import process$2 from 'node:process';
import readline from 'node:readline';
import * as WorkerThreads from 'node:worker_threads';
import require$$2, { strictEqual, notStrictEqual } from 'assert';
import require$$0$4, { resolve as resolve$2, dirname, normalize, join, relative, extname, basename } from 'path';
import require$$0$3, { statSync, readdirSync, readFileSync, writeFile } from 'fs';
import require$$0$2, { format as format$5, inspect } from 'util';
import require$$5, { fileURLToPath } from 'url';
import { createRequire } from 'node:module';
import fs, { readdirSync as readdirSync$1, readFileSync as readFileSync$1, accessSync, existsSync } from 'node:fs';
import require$$1 from 'tty';
import require$$0$1 from 'os';
import require$$0$5 from 'child_process';
import { PassThrough } from 'node:stream';
import { mkdtemp, unlink, rename, readFile } from 'node:fs/promises';
import os, { tmpdir } from 'node:os';
import path$1, { join as join$1, dirname as dirname$1 } from 'node:path';
import childProcess, { execSync, spawnSync, spawn as spawn$1 } from 'node:child_process';
import { EventEmitter as EventEmitter$1 } from 'node:events';
import * as http$1 from 'node:http';
import * as https$1 from 'node:https';
import { urlToHttpOptions, URL as URL$1 } from 'node:url';
import require$$0$6 from 'http';
import require$$1$1 from 'https';
import require$$0$7 from 'net';
import require$$1$2 from 'tls';
import require$$0$8 from 'events';
import require$$0$9 from 'buffer';
import require$$1$3 from 'stream';
import require$$3$3 from 'dns';
import require$$2$1 from 'crypto';
import 'node:assert';
import require$$0$a from 'zlib';
import { generateReport as generateReport$1, navigation as navigation$1, snapshot as snapshot$1 } from './lighthouse-devtools-mcp-bundle.js';

function _mergeNamespaces(n, m) {
	m.forEach(function (e) {
		e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
			if (k !== 'default' && !(k in n)) {
				var d = Object.getOwnPropertyDescriptor(e, k);
				Object.defineProperty(n, k, d.get ? d : {
					enumerable: true,
					get: function () { return e[k]; }
				});
			}
		});
	});
	return Object.freeze(n);
}

var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

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

function getAugmentedNamespace(n) {
  if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  var f = n.default;
	if (typeof f == "function") {
		var a = function a () {
			var isInstance = false;
      try {
        isInstance = this instanceof a;
      } catch {}
			if (isInstance) {
        return Reflect.construct(f, arguments, this.constructor);
			}
			return f.apply(this, arguments);
		};
		a.prototype = f.prototype;
  } else a = {};
  Object.defineProperty(a, '__esModule', {value: true});
	Object.keys(n).forEach(function (k) {
		var d = Object.getOwnPropertyDescriptor(n, k);
		Object.defineProperty(a, k, d.get ? d : {
			enumerable: true,
			get: function () {
				return n[k];
			}
		});
	});
	return a;
}

var es_promise_withResolvers = {};

var globalThis_1;
var hasRequiredGlobalThis;

function requireGlobalThis () {
	if (hasRequiredGlobalThis) return globalThis_1;
	hasRequiredGlobalThis = 1;
	var check = function (it) {
	  return it && it.Math === Math && it;
	};
	globalThis_1 =
	  check(typeof globalThis == 'object' && globalThis) ||
	  check(typeof window == 'object' && window) ||
	  check(typeof self == 'object' && self) ||
	  check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
	  check(typeof globalThis_1 == 'object' && globalThis_1) ||
	  (function () { return this; })() || Function('return this')();
	return globalThis_1;
}

var objectGetOwnPropertyDescriptor = {};

var fails;
var hasRequiredFails;

function requireFails () {
	if (hasRequiredFails) return fails;
	hasRequiredFails = 1;
	fails = function (exec) {
	  try {
	    return !!exec();
	  } catch (error) {
	    return true;
	  }
	};
	return fails;
}

var descriptors;
var hasRequiredDescriptors;

function requireDescriptors () {
	if (hasRequiredDescriptors) return descriptors;
	hasRequiredDescriptors = 1;
	var fails = requireFails();
	descriptors = !fails(function () {
	  return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;
	});
	return descriptors;
}

var functionBindNative;
var hasRequiredFunctionBindNative;

function requireFunctionBindNative () {
	if (hasRequiredFunctionBindNative) return functionBindNative;
	hasRequiredFunctionBindNative = 1;
	var fails = requireFails();
	functionBindNative = !fails(function () {
	  var test = (function () {  }).bind();
	  return typeof test != 'function' || test.hasOwnProperty('prototype');
	});
	return functionBindNative;
}

var functionCall;
var hasRequiredFunctionCall;

function requireFunctionCall () {
	if (hasRequiredFunctionCall) return functionCall;
	hasRequiredFunctionCall = 1;
	var NATIVE_BIND = requireFunctionBindNative();
	var call = Function.prototype.call;
	functionCall = NATIVE_BIND ? call.bind(call) : function () {
	  return call.apply(call, arguments);
	};
	return functionCall;
}

var objectPropertyIsEnumerable = {};

var hasRequiredObjectPropertyIsEnumerable;

function requireObjectPropertyIsEnumerable () {
	if (hasRequiredObjectPropertyIsEnumerable) return objectPropertyIsEnumerable;
	hasRequiredObjectPropertyIsEnumerable = 1;
	var $propertyIsEnumerable = {}.propertyIsEnumerable;
	var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
	var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
	objectPropertyIsEnumerable.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
	  var descriptor = getOwnPropertyDescriptor(this, V);
	  return !!descriptor && descriptor.enumerable;
	} : $propertyIsEnumerable;
	return objectPropertyIsEnumerable;
}

var createPropertyDescriptor;
var hasRequiredCreatePropertyDescriptor;

function requireCreatePropertyDescriptor () {
	if (hasRequiredCreatePropertyDescriptor) return createPropertyDescriptor;
	hasRequiredCreatePropertyDescriptor = 1;
	createPropertyDescriptor = function (bitmap, value) {
	  return {
	    enumerable: !(bitmap & 1),
	    configurable: !(bitmap & 2),
	    writable: !(bitmap & 4),
	    value: value
	  };
	};
	return createPropertyDescriptor;
}

var functionUncurryThis;
var hasRequiredFunctionUncurryThis;

function requireFunctionUncurryThis () {
	if (hasRequiredFunctionUncurryThis) return functionUncurryThis;
	hasRequiredFunctionUncurryThis = 1;
	var NATIVE_BIND = requireFunctionBindNative();
	var FunctionPrototype = Function.prototype;
	var call = FunctionPrototype.call;
	var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);
	functionUncurryThis = NATIVE_BIND ? uncurryThisWithBind : function (fn) {
	  return function () {
	    return call.apply(fn, arguments);
	  };
	};
	return functionUncurryThis;
}

var classofRaw;
var hasRequiredClassofRaw;

function requireClassofRaw () {
	if (hasRequiredClassofRaw) return classofRaw;
	hasRequiredClassofRaw = 1;
	var uncurryThis = requireFunctionUncurryThis();
	var toString = uncurryThis({}.toString);
	var stringSlice = uncurryThis(''.slice);
	classofRaw = function (it) {
	  return stringSlice(toString(it), 8, -1);
	};
	return classofRaw;
}

var indexedObject;
var hasRequiredIndexedObject;

function requireIndexedObject () {
	if (hasRequiredIndexedObject) return indexedObject;
	hasRequiredIndexedObject = 1;
	var uncurryThis = requireFunctionUncurryThis();
	var fails = requireFails();
	var classof = requireClassofRaw();
	var $Object = Object;
	var split = uncurryThis(''.split);
	indexedObject = fails(function () {
	  return !$Object('z').propertyIsEnumerable(0);
	}) ? function (it) {
	  return classof(it) === 'String' ? split(it, '') : $Object(it);
	} : $Object;
	return indexedObject;
}

var isNullOrUndefined;
var hasRequiredIsNullOrUndefined;

function requireIsNullOrUndefined () {
	if (hasRequiredIsNullOrUndefined) return isNullOrUndefined;
	hasRequiredIsNullOrUndefined = 1;
	isNullOrUndefined = function (it) {
	  return it === null || it === undefined;
	};
	return isNullOrUndefined;
}

var requireObjectCoercible;
var hasRequiredRequireObjectCoercible;

function requireRequireObjectCoercible () {
	if (hasRequiredRequireObjectCoercible) return requireObjectCoercible;
	hasRequiredRequireObjectCoercible = 1;
	var isNullOrUndefined = requireIsNullOrUndefined();
	var $TypeError = TypeError;
	requireObjectCoercible = function (it) {
	  if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it);
	  return it;
	};
	return requireObjectCoercible;
}

var toIndexedObject;
var hasRequiredToIndexedObject;

function requireToIndexedObject () {
	if (hasRequiredToIndexedObject) return toIndexedObject;
	hasRequiredToIndexedObject = 1;
	var IndexedObject = requireIndexedObject();
	var requireObjectCoercible = requireRequireObjectCoercible();
	toIndexedObject = function (it) {
	  return IndexedObject(requireObjectCoercible(it));
	};
	return toIndexedObject;
}

var isCallable;
var hasRequiredIsCallable;

function requireIsCallable () {
	if (hasRequiredIsCallable) return isCallable;
	hasRequiredIsCallable = 1;
	var documentAll = typeof document == 'object' && document.all;
	isCallable = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) {
	  return typeof argument == 'function' || argument === documentAll;
	} : function (argument) {
	  return typeof argument == 'function';
	};
	return isCallable;
}

var isObject$1;
var hasRequiredIsObject;

function requireIsObject () {
	if (hasRequiredIsObject) return isObject$1;
	hasRequiredIsObject = 1;
	var isCallable = requireIsCallable();
	isObject$1 = function (it) {
	  return typeof it == 'object' ? it !== null : isCallable(it);
	};
	return isObject$1;
}

var getBuiltIn;
var hasRequiredGetBuiltIn;

function requireGetBuiltIn () {
	if (hasRequiredGetBuiltIn) return getBuiltIn;
	hasRequiredGetBuiltIn = 1;
	var globalThis = requireGlobalThis();
	var isCallable = requireIsCallable();
	var aFunction = function (argument) {
	  return isCallable(argument) ? argument : undefined;
	};
	getBuiltIn = function (namespace, method) {
	  return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method];
	};
	return getBuiltIn;
}

var objectIsPrototypeOf;
var hasRequiredObjectIsPrototypeOf;

function requireObjectIsPrototypeOf () {
	if (hasRequiredObjectIsPrototypeOf) return objectIsPrototypeOf;
	hasRequiredObjectIsPrototypeOf = 1;
	var uncurryThis = requireFunctionUncurryThis();
	objectIsPrototypeOf = uncurryThis({}.isPrototypeOf);
	return objectIsPrototypeOf;
}

var environmentUserAgent;
var hasRequiredEnvironmentUserAgent;

function requireEnvironmentUserAgent () {
	if (hasRequiredEnvironmentUserAgent) return environmentUserAgent;
	hasRequiredEnvironmentUserAgent = 1;
	var globalThis = requireGlobalThis();
	var navigator = globalThis.navigator;
	var userAgent = navigator && navigator.userAgent;
	environmentUserAgent = userAgent ? String(userAgent) : '';
	return environmentUserAgent;
}

var environmentV8Version;
var hasRequiredEnvironmentV8Version;

function requireEnvironmentV8Version () {
	if (hasRequiredEnvironmentV8Version) return environmentV8Version;
	hasRequiredEnvironmentV8Version = 1;
	var globalThis = requireGlobalThis();
	var userAgent = requireEnvironmentUserAgent();
	var process = globalThis.process;
	var Deno = globalThis.Deno;
	var versions = process && process.versions || Deno && Deno.version;
	var v8 = versions && versions.v8;
	var match, version;
	if (v8) {
	  match = v8.split('.');
	  version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
	}
	if (!version && userAgent) {
	  match = userAgent.match(/Edge\/(\d+)/);
	  if (!match || match[1] >= 74) {
	    match = userAgent.match(/Chrome\/(\d+)/);
	    if (match) version = +match[1];
	  }
	}
	environmentV8Version = version;
	return environmentV8Version;
}

var symbolConstructorDetection;
var hasRequiredSymbolConstructorDetection;

function requireSymbolConstructorDetection () {
	if (hasRequiredSymbolConstructorDetection) return symbolConstructorDetection;
	hasRequiredSymbolConstructorDetection = 1;
	var V8_VERSION = requireEnvironmentV8Version();
	var fails = requireFails();
	var globalThis = requireGlobalThis();
	var $String = globalThis.String;
	symbolConstructorDetection = !!Object.getOwnPropertySymbols && !fails(function () {
	  var symbol = Symbol('symbol detection');
	  return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||
	    !Symbol.sham && V8_VERSION && V8_VERSION < 41;
	});
	return symbolConstructorDetection;
}

var useSymbolAsUid;
var hasRequiredUseSymbolAsUid;

function requireUseSymbolAsUid () {
	if (hasRequiredUseSymbolAsUid) return useSymbolAsUid;
	hasRequiredUseSymbolAsUid = 1;
	var NATIVE_SYMBOL = requireSymbolConstructorDetection();
	useSymbolAsUid = NATIVE_SYMBOL &&
	  !Symbol.sham &&
	  typeof Symbol.iterator == 'symbol';
	return useSymbolAsUid;
}

var isSymbol;
var hasRequiredIsSymbol;

function requireIsSymbol () {
	if (hasRequiredIsSymbol) return isSymbol;
	hasRequiredIsSymbol = 1;
	var getBuiltIn = requireGetBuiltIn();
	var isCallable = requireIsCallable();
	var isPrototypeOf = requireObjectIsPrototypeOf();
	var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
	var $Object = Object;
	isSymbol = USE_SYMBOL_AS_UID ? function (it) {
	  return typeof it == 'symbol';
	} : function (it) {
	  var $Symbol = getBuiltIn('Symbol');
	  return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));
	};
	return isSymbol;
}

var tryToString;
var hasRequiredTryToString;

function requireTryToString () {
	if (hasRequiredTryToString) return tryToString;
	hasRequiredTryToString = 1;
	var $String = String;
	tryToString = function (argument) {
	  try {
	    return $String(argument);
	  } catch (error) {
	    return 'Object';
	  }
	};
	return tryToString;
}

var aCallable;
var hasRequiredACallable;

function requireACallable () {
	if (hasRequiredACallable) return aCallable;
	hasRequiredACallable = 1;
	var isCallable = requireIsCallable();
	var tryToString = requireTryToString();
	var $TypeError = TypeError;
	aCallable = function (argument) {
	  if (isCallable(argument)) return argument;
	  throw new $TypeError(tryToString(argument) + ' is not a function');
	};
	return aCallable;
}

var getMethod;
var hasRequiredGetMethod;

function requireGetMethod () {
	if (hasRequiredGetMethod) return getMethod;
	hasRequiredGetMethod = 1;
	var aCallable = requireACallable();
	var isNullOrUndefined = requireIsNullOrUndefined();
	getMethod = function (V, P) {
	  var func = V[P];
	  return isNullOrUndefined(func) ? undefined : aCallable(func);
	};
	return getMethod;
}

var ordinaryToPrimitive;
var hasRequiredOrdinaryToPrimitive;

function requireOrdinaryToPrimitive () {
	if (hasRequiredOrdinaryToPrimitive) return ordinaryToPrimitive;
	hasRequiredOrdinaryToPrimitive = 1;
	var call = requireFunctionCall();
	var isCallable = requireIsCallable();
	var isObject = requireIsObject();
	var $TypeError = TypeError;
	ordinaryToPrimitive = function (input, pref) {
	  var fn, val;
	  if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
	  if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
	  if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
	  throw new $TypeError("Can't convert object to primitive value");
	};
	return ordinaryToPrimitive;
}

var sharedStore = {exports: {}};

var isPure;
var hasRequiredIsPure;

function requireIsPure () {
	if (hasRequiredIsPure) return isPure;
	hasRequiredIsPure = 1;
	isPure = false;
	return isPure;
}

var defineGlobalProperty;
var hasRequiredDefineGlobalProperty;

function requireDefineGlobalProperty () {
	if (hasRequiredDefineGlobalProperty) return defineGlobalProperty;
	hasRequiredDefineGlobalProperty = 1;
	var globalThis = requireGlobalThis();
	var defineProperty = Object.defineProperty;
	defineGlobalProperty = function (key, value) {
	  try {
	    defineProperty(globalThis, key, { value: value, configurable: true, writable: true });
	  } catch (error) {
	    globalThis[key] = value;
	  } return value;
	};
	return defineGlobalProperty;
}

var hasRequiredSharedStore;

function requireSharedStore () {
	if (hasRequiredSharedStore) return sharedStore.exports;
	hasRequiredSharedStore = 1;
	var IS_PURE = requireIsPure();
	var globalThis = requireGlobalThis();
	var defineGlobalProperty = requireDefineGlobalProperty();
	var SHARED = '__core-js_shared__';
	var store = sharedStore.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {});
	(store.versions || (store.versions = [])).push({
	  version: '3.48.0',
	  mode: IS_PURE ? 'pure' : 'global',
	  copyright: '© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.',
	  license: 'https://github.com/zloirock/core-js/blob/v3.48.0/LICENSE',
	  source: 'https://github.com/zloirock/core-js'
	});
	return sharedStore.exports;
}

var shared$1;
var hasRequiredShared$1;

function requireShared$1 () {
	if (hasRequiredShared$1) return shared$1;
	hasRequiredShared$1 = 1;
	var store = requireSharedStore();
	shared$1 = function (key, value) {
	  return store[key] || (store[key] = value || {});
	};
	return shared$1;
}

var toObject;
var hasRequiredToObject;

function requireToObject () {
	if (hasRequiredToObject) return toObject;
	hasRequiredToObject = 1;
	var requireObjectCoercible = requireRequireObjectCoercible();
	var $Object = Object;
	toObject = function (argument) {
	  return $Object(requireObjectCoercible(argument));
	};
	return toObject;
}

var hasOwnProperty_1;
var hasRequiredHasOwnProperty;

function requireHasOwnProperty () {
	if (hasRequiredHasOwnProperty) return hasOwnProperty_1;
	hasRequiredHasOwnProperty = 1;
	var uncurryThis = requireFunctionUncurryThis();
	var toObject = requireToObject();
	var hasOwnProperty = uncurryThis({}.hasOwnProperty);
	hasOwnProperty_1 = Object.hasOwn || function hasOwn(it, key) {
	  return hasOwnProperty(toObject(it), key);
	};
	return hasOwnProperty_1;
}

var uid;
var hasRequiredUid;

function requireUid () {
	if (hasRequiredUid) return uid;
	hasRequiredUid = 1;
	var uncurryThis = requireFunctionUncurryThis();
	var id = 0;
	var postfix = Math.random();
	var toString = uncurryThis(1.1.toString);
	uid = function (key) {
	  return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
	};
	return uid;
}

var wellKnownSymbol;
var hasRequiredWellKnownSymbol;

function requireWellKnownSymbol () {
	if (hasRequiredWellKnownSymbol) return wellKnownSymbol;
	hasRequiredWellKnownSymbol = 1;
	var globalThis = requireGlobalThis();
	var shared = requireShared$1();
	var hasOwn = requireHasOwnProperty();
	var uid = requireUid();
	var NATIVE_SYMBOL = requireSymbolConstructorDetection();
	var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
	var Symbol = globalThis.Symbol;
	var WellKnownSymbolsStore = shared('wks');
	var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid;
	wellKnownSymbol = function (name) {
	  if (!hasOwn(WellKnownSymbolsStore, name)) {
	    WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)
	      ? Symbol[name]
	      : createWellKnownSymbol('Symbol.' + name);
	  } return WellKnownSymbolsStore[name];
	};
	return wellKnownSymbol;
}

var toPrimitive;
var hasRequiredToPrimitive;

function requireToPrimitive () {
	if (hasRequiredToPrimitive) return toPrimitive;
	hasRequiredToPrimitive = 1;
	var call = requireFunctionCall();
	var isObject = requireIsObject();
	var isSymbol = requireIsSymbol();
	var getMethod = requireGetMethod();
	var ordinaryToPrimitive = requireOrdinaryToPrimitive();
	var wellKnownSymbol = requireWellKnownSymbol();
	var $TypeError = TypeError;
	var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
	toPrimitive = function (input, pref) {
	  if (!isObject(input) || isSymbol(input)) return input;
	  var exoticToPrim = getMethod(input, TO_PRIMITIVE);
	  var result;
	  if (exoticToPrim) {
	    if (pref === undefined) pref = 'default';
	    result = call(exoticToPrim, input, pref);
	    if (!isObject(result) || isSymbol(result)) return result;
	    throw new $TypeError("Can't convert object to primitive value");
	  }
	  if (pref === undefined) pref = 'number';
	  return ordinaryToPrimitive(input, pref);
	};
	return toPrimitive;
}

var toPropertyKey;
var hasRequiredToPropertyKey;

function requireToPropertyKey () {
	if (hasRequiredToPropertyKey) return toPropertyKey;
	hasRequiredToPropertyKey = 1;
	var toPrimitive = requireToPrimitive();
	var isSymbol = requireIsSymbol();
	toPropertyKey = function (argument) {
	  var key = toPrimitive(argument, 'string');
	  return isSymbol(key) ? key : key + '';
	};
	return toPropertyKey;
}

var documentCreateElement;
var hasRequiredDocumentCreateElement;

function requireDocumentCreateElement () {
	if (hasRequiredDocumentCreateElement) return documentCreateElement;
	hasRequiredDocumentCreateElement = 1;
	var globalThis = requireGlobalThis();
	var isObject = requireIsObject();
	var document = globalThis.document;
	var EXISTS = isObject(document) && isObject(document.createElement);
	documentCreateElement = function (it) {
	  return EXISTS ? document.createElement(it) : {};
	};
	return documentCreateElement;
}

var ie8DomDefine;
var hasRequiredIe8DomDefine;

function requireIe8DomDefine () {
	if (hasRequiredIe8DomDefine) return ie8DomDefine;
	hasRequiredIe8DomDefine = 1;
	var DESCRIPTORS = requireDescriptors();
	var fails = requireFails();
	var createElement = requireDocumentCreateElement();
	ie8DomDefine = !DESCRIPTORS && !fails(function () {
	  return Object.defineProperty(createElement('div'), 'a', {
	    get: function () { return 7; }
	  }).a !== 7;
	});
	return ie8DomDefine;
}

var hasRequiredObjectGetOwnPropertyDescriptor;

function requireObjectGetOwnPropertyDescriptor () {
	if (hasRequiredObjectGetOwnPropertyDescriptor) return objectGetOwnPropertyDescriptor;
	hasRequiredObjectGetOwnPropertyDescriptor = 1;
	var DESCRIPTORS = requireDescriptors();
	var call = requireFunctionCall();
	var propertyIsEnumerableModule = requireObjectPropertyIsEnumerable();
	var createPropertyDescriptor = requireCreatePropertyDescriptor();
	var toIndexedObject = requireToIndexedObject();
	var toPropertyKey = requireToPropertyKey();
	var hasOwn = requireHasOwnProperty();
	var IE8_DOM_DEFINE = requireIe8DomDefine();
	var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
	objectGetOwnPropertyDescriptor.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
	  O = toIndexedObject(O);
	  P = toPropertyKey(P);
	  if (IE8_DOM_DEFINE) try {
	    return $getOwnPropertyDescriptor(O, P);
	  } catch (error) {  }
	  if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
	};
	return objectGetOwnPropertyDescriptor;
}

var objectDefineProperty = {};

var v8PrototypeDefineBug;
var hasRequiredV8PrototypeDefineBug;

function requireV8PrototypeDefineBug () {
	if (hasRequiredV8PrototypeDefineBug) return v8PrototypeDefineBug;
	hasRequiredV8PrototypeDefineBug = 1;
	var DESCRIPTORS = requireDescriptors();
	var fails = requireFails();
	v8PrototypeDefineBug = DESCRIPTORS && fails(function () {
	  return Object.defineProperty(function () {  }, 'prototype', {
	    value: 42,
	    writable: false
	  }).prototype !== 42;
	});
	return v8PrototypeDefineBug;
}

var anObject;
var hasRequiredAnObject;

function requireAnObject () {
	if (hasRequiredAnObject) return anObject;
	hasRequiredAnObject = 1;
	var isObject = requireIsObject();
	var $String = String;
	var $TypeError = TypeError;
	anObject = function (argument) {
	  if (isObject(argument)) return argument;
	  throw new $TypeError($String(argument) + ' is not an object');
	};
	return anObject;
}

var hasRequiredObjectDefineProperty;

function requireObjectDefineProperty () {
	if (hasRequiredObjectDefineProperty) return objectDefineProperty;
	hasRequiredObjectDefineProperty = 1;
	var DESCRIPTORS = requireDescriptors();
	var IE8_DOM_DEFINE = requireIe8DomDefine();
	var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
	var anObject = requireAnObject();
	var toPropertyKey = requireToPropertyKey();
	var $TypeError = TypeError;
	var $defineProperty = Object.defineProperty;
	var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
	var ENUMERABLE = 'enumerable';
	var CONFIGURABLE = 'configurable';
	var WRITABLE = 'writable';
	objectDefineProperty.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
	  anObject(O);
	  P = toPropertyKey(P);
	  anObject(Attributes);
	  if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
	    var current = $getOwnPropertyDescriptor(O, P);
	    if (current && current[WRITABLE]) {
	      O[P] = Attributes.value;
	      Attributes = {
	        configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
	        enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
	        writable: false
	      };
	    }
	  } return $defineProperty(O, P, Attributes);
	} : $defineProperty : function defineProperty(O, P, Attributes) {
	  anObject(O);
	  P = toPropertyKey(P);
	  anObject(Attributes);
	  if (IE8_DOM_DEFINE) try {
	    return $defineProperty(O, P, Attributes);
	  } catch (error) {  }
	  if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported');
	  if ('value' in Attributes) O[P] = Attributes.value;
	  return O;
	};
	return objectDefineProperty;
}

var createNonEnumerableProperty;
var hasRequiredCreateNonEnumerableProperty;

function requireCreateNonEnumerableProperty () {
	if (hasRequiredCreateNonEnumerableProperty) return createNonEnumerableProperty;
	hasRequiredCreateNonEnumerableProperty = 1;
	var DESCRIPTORS = requireDescriptors();
	var definePropertyModule = requireObjectDefineProperty();
	var createPropertyDescriptor = requireCreatePropertyDescriptor();
	createNonEnumerableProperty = DESCRIPTORS ? function (object, key, value) {
	  return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
	} : function (object, key, value) {
	  object[key] = value;
	  return object;
	};
	return createNonEnumerableProperty;
}

var makeBuiltIn = {exports: {}};

var functionName;
var hasRequiredFunctionName;

function requireFunctionName () {
	if (hasRequiredFunctionName) return functionName;
	hasRequiredFunctionName = 1;
	var DESCRIPTORS = requireDescriptors();
	var hasOwn = requireHasOwnProperty();
	var FunctionPrototype = Function.prototype;
	var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
	var EXISTS = hasOwn(FunctionPrototype, 'name');
	var PROPER = EXISTS && (function something() {  }).name === 'something';
	var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
	functionName = {
	  EXISTS: EXISTS,
	  PROPER: PROPER,
	  CONFIGURABLE: CONFIGURABLE
	};
	return functionName;
}

var inspectSource;
var hasRequiredInspectSource;

function requireInspectSource () {
	if (hasRequiredInspectSource) return inspectSource;
	hasRequiredInspectSource = 1;
	var uncurryThis = requireFunctionUncurryThis();
	var isCallable = requireIsCallable();
	var store = requireSharedStore();
	var functionToString = uncurryThis(Function.toString);
	if (!isCallable(store.inspectSource)) {
	  store.inspectSource = function (it) {
	    return functionToString(it);
	  };
	}
	inspectSource = store.inspectSource;
	return inspectSource;
}

var weakMapBasicDetection;
var hasRequiredWeakMapBasicDetection;

function requireWeakMapBasicDetection () {
	if (hasRequiredWeakMapBasicDetection) return weakMapBasicDetection;
	hasRequiredWeakMapBasicDetection = 1;
	var globalThis = requireGlobalThis();
	var isCallable = requireIsCallable();
	var WeakMap = globalThis.WeakMap;
	weakMapBasicDetection = isCallable(WeakMap) && /native code/.test(String(WeakMap));
	return weakMapBasicDetection;
}

var sharedKey;
var hasRequiredSharedKey;

function requireSharedKey () {
	if (hasRequiredSharedKey) return sharedKey;
	hasRequiredSharedKey = 1;
	var shared = requireShared$1();
	var uid = requireUid();
	var keys = shared('keys');
	sharedKey = function (key) {
	  return keys[key] || (keys[key] = uid(key));
	};
	return sharedKey;
}

var hiddenKeys;
var hasRequiredHiddenKeys;

function requireHiddenKeys () {
	if (hasRequiredHiddenKeys) return hiddenKeys;
	hasRequiredHiddenKeys = 1;
	hiddenKeys = {};
	return hiddenKeys;
}

var internalState;
var hasRequiredInternalState;

function requireInternalState () {
	if (hasRequiredInternalState) return internalState;
	hasRequiredInternalState = 1;
	var NATIVE_WEAK_MAP = requireWeakMapBasicDetection();
	var globalThis = requireGlobalThis();
	var isObject = requireIsObject();
	var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
	var hasOwn = requireHasOwnProperty();
	var shared = requireSharedStore();
	var sharedKey = requireSharedKey();
	var hiddenKeys = requireHiddenKeys();
	var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
	var TypeError = globalThis.TypeError;
	var WeakMap = globalThis.WeakMap;
	var set, get, has;
	var enforce = function (it) {
	  return has(it) ? get(it) : set(it, {});
	};
	var getterFor = function (TYPE) {
	  return function (it) {
	    var state;
	    if (!isObject(it) || (state = get(it)).type !== TYPE) {
	      throw new TypeError('Incompatible receiver, ' + TYPE + ' required');
	    } return state;
	  };
	};
	if (NATIVE_WEAK_MAP || shared.state) {
	  var store = shared.state || (shared.state = new WeakMap());
	  store.get = store.get;
	  store.has = store.has;
	  store.set = store.set;
	  set = function (it, metadata) {
	    if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
	    metadata.facade = it;
	    store.set(it, metadata);
	    return metadata;
	  };
	  get = function (it) {
	    return store.get(it) || {};
	  };
	  has = function (it) {
	    return store.has(it);
	  };
	} else {
	  var STATE = sharedKey('state');
	  hiddenKeys[STATE] = true;
	  set = function (it, metadata) {
	    if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
	    metadata.facade = it;
	    createNonEnumerableProperty(it, STATE, metadata);
	    return metadata;
	  };
	  get = function (it) {
	    return hasOwn(it, STATE) ? it[STATE] : {};
	  };
	  has = function (it) {
	    return hasOwn(it, STATE);
	  };
	}
	internalState = {
	  set: set,
	  get: get,
	  has: has,
	  enforce: enforce,
	  getterFor: getterFor
	};
	return internalState;
}

var hasRequiredMakeBuiltIn;

function requireMakeBuiltIn () {
	if (hasRequiredMakeBuiltIn) return makeBuiltIn.exports;
	hasRequiredMakeBuiltIn = 1;
	var uncurryThis = requireFunctionUncurryThis();
	var fails = requireFails();
	var isCallable = requireIsCallable();
	var hasOwn = requireHasOwnProperty();
	var DESCRIPTORS = requireDescriptors();
	var CONFIGURABLE_FUNCTION_NAME = requireFunctionName().CONFIGURABLE;
	var inspectSource = requireInspectSource();
	var InternalStateModule = requireInternalState();
	var enforceInternalState = InternalStateModule.enforce;
	var getInternalState = InternalStateModule.get;
	var $String = String;
	var defineProperty = Object.defineProperty;
	var stringSlice = uncurryThis(''.slice);
	var replace = uncurryThis(''.replace);
	var join = uncurryThis([].join);
	var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {
	  return defineProperty(function () {  }, 'length', { value: 8 }).length !== 8;
	});
	var TEMPLATE = String(String).split('String');
	var makeBuiltIn$1 = makeBuiltIn.exports = function (value, name, options) {
	  if (stringSlice($String(name), 0, 7) === 'Symbol(') {
	    name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
	  }
	  if (options && options.getter) name = 'get ' + name;
	  if (options && options.setter) name = 'set ' + name;
	  if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
	    if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true });
	    else value.name = name;
	  }
	  if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) {
	    defineProperty(value, 'length', { value: options.arity });
	  }
	  try {
	    if (options && hasOwn(options, 'constructor') && options.constructor) {
	      if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false });
	    } else if (value.prototype) value.prototype = undefined;
	  } catch (error) {  }
	  var state = enforceInternalState(value);
	  if (!hasOwn(state, 'source')) {
	    state.source = join(TEMPLATE, typeof name == 'string' ? name : '');
	  } return value;
	};
	Function.prototype.toString = makeBuiltIn$1(function toString() {
	  return isCallable(this) && getInternalState(this).source || inspectSource(this);
	}, 'toString');
	return makeBuiltIn.exports;
}

var defineBuiltIn;
var hasRequiredDefineBuiltIn;

function requireDefineBuiltIn () {
	if (hasRequiredDefineBuiltIn) return defineBuiltIn;
	hasRequiredDefineBuiltIn = 1;
	var isCallable = requireIsCallable();
	var definePropertyModule = requireObjectDefineProperty();
	var makeBuiltIn = requireMakeBuiltIn();
	var defineGlobalProperty = requireDefineGlobalProperty();
	defineBuiltIn = function (O, key, value, options) {
	  if (!options) options = {};
	  var simple = options.enumerable;
	  var name = options.name !== undefined ? options.name : key;
	  if (isCallable(value)) makeBuiltIn(value, name, options);
	  if (options.global) {
	    if (simple) O[key] = value;
	    else defineGlobalProperty(key, value);
	  } else {
	    try {
	      if (!options.unsafe) delete O[key];
	      else if (O[key]) simple = true;
	    } catch (error) {  }
	    if (simple) O[key] = value;
	    else definePropertyModule.f(O, key, {
	      value: value,
	      enumerable: false,
	      configurable: !options.nonConfigurable,
	      writable: !options.nonWritable
	    });
	  } return O;
	};
	return defineBuiltIn;
}

var objectGetOwnPropertyNames = {};

var mathTrunc;
var hasRequiredMathTrunc;

function requireMathTrunc () {
	if (hasRequiredMathTrunc) return mathTrunc;
	hasRequiredMathTrunc = 1;
	var ceil = Math.ceil;
	var floor = Math.floor;
	mathTrunc = Math.trunc || function trunc(x) {
	  var n = +x;
	  return (n > 0 ? floor : ceil)(n);
	};
	return mathTrunc;
}

var toIntegerOrInfinity;
var hasRequiredToIntegerOrInfinity;

function requireToIntegerOrInfinity () {
	if (hasRequiredToIntegerOrInfinity) return toIntegerOrInfinity;
	hasRequiredToIntegerOrInfinity = 1;
	var trunc = requireMathTrunc();
	toIntegerOrInfinity = function (argument) {
	  var number = +argument;
	  return number !== number || number === 0 ? 0 : trunc(number);
	};
	return toIntegerOrInfinity;
}

var toAbsoluteIndex;
var hasRequiredToAbsoluteIndex;

function requireToAbsoluteIndex () {
	if (hasRequiredToAbsoluteIndex) return toAbsoluteIndex;
	hasRequiredToAbsoluteIndex = 1;
	var toIntegerOrInfinity = requireToIntegerOrInfinity();
	var max = Math.max;
	var min = Math.min;
	toAbsoluteIndex = function (index, length) {
	  var integer = toIntegerOrInfinity(index);
	  return integer < 0 ? max(integer + length, 0) : min(integer, length);
	};
	return toAbsoluteIndex;
}

var toLength;
var hasRequiredToLength;

function requireToLength () {
	if (hasRequiredToLength) return toLength;
	hasRequiredToLength = 1;
	var toIntegerOrInfinity = requireToIntegerOrInfinity();
	var min = Math.min;
	toLength = function (argument) {
	  var len = toIntegerOrInfinity(argument);
	  return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0;
	};
	return toLength;
}

var lengthOfArrayLike;
var hasRequiredLengthOfArrayLike;

function requireLengthOfArrayLike () {
	if (hasRequiredLengthOfArrayLike) return lengthOfArrayLike;
	hasRequiredLengthOfArrayLike = 1;
	var toLength = requireToLength();
	lengthOfArrayLike = function (obj) {
	  return toLength(obj.length);
	};
	return lengthOfArrayLike;
}

var arrayIncludes;
var hasRequiredArrayIncludes;

function requireArrayIncludes () {
	if (hasRequiredArrayIncludes) return arrayIncludes;
	hasRequiredArrayIncludes = 1;
	var toIndexedObject = requireToIndexedObject();
	var toAbsoluteIndex = requireToAbsoluteIndex();
	var lengthOfArrayLike = requireLengthOfArrayLike();
	var createMethod = function (IS_INCLUDES) {
	  return function ($this, el, fromIndex) {
	    var O = toIndexedObject($this);
	    var length = lengthOfArrayLike(O);
	    if (length === 0) return !IS_INCLUDES && -1;
	    var index = toAbsoluteIndex(fromIndex, length);
	    var value;
	    if (IS_INCLUDES && el !== el) while (length > index) {
	      value = O[index++];
	      if (value !== value) return true;
	    } else for (;length > index; index++) {
	      if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
	    } return !IS_INCLUDES && -1;
	  };
	};
	arrayIncludes = {
	  includes: createMethod(true),
	  indexOf: createMethod(false)
	};
	return arrayIncludes;
}

var objectKeysInternal;
var hasRequiredObjectKeysInternal;

function requireObjectKeysInternal () {
	if (hasRequiredObjectKeysInternal) return objectKeysInternal;
	hasRequiredObjectKeysInternal = 1;
	var uncurryThis = requireFunctionUncurryThis();
	var hasOwn = requireHasOwnProperty();
	var toIndexedObject = requireToIndexedObject();
	var indexOf = requireArrayIncludes().indexOf;
	var hiddenKeys = requireHiddenKeys();
	var push = uncurryThis([].push);
	objectKeysInternal = function (object, names) {
	  var O = toIndexedObject(object);
	  var i = 0;
	  var result = [];
	  var key;
	  for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
	  while (names.length > i) if (hasOwn(O, key = names[i++])) {
	    ~indexOf(result, key) || push(result, key);
	  }
	  return result;
	};
	return objectKeysInternal;
}

var enumBugKeys;
var hasRequiredEnumBugKeys;

function requireEnumBugKeys () {
	if (hasRequiredEnumBugKeys) return enumBugKeys;
	hasRequiredEnumBugKeys = 1;
	enumBugKeys = [
	  'constructor',
	  'hasOwnProperty',
	  'isPrototypeOf',
	  'propertyIsEnumerable',
	  'toLocaleString',
	  'toString',
	  'valueOf'
	];
	return enumBugKeys;
}

var hasRequiredObjectGetOwnPropertyNames;

function requireObjectGetOwnPropertyNames () {
	if (hasRequiredObjectGetOwnPropertyNames) return objectGetOwnPropertyNames;
	hasRequiredObjectGetOwnPropertyNames = 1;
	var internalObjectKeys = requireObjectKeysInternal();
	var enumBugKeys = requireEnumBugKeys();
	var hiddenKeys = enumBugKeys.concat('length', 'prototype');
	objectGetOwnPropertyNames.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
	  return internalObjectKeys(O, hiddenKeys);
	};
	return objectGetOwnPropertyNames;
}

var objectGetOwnPropertySymbols = {};

var hasRequiredObjectGetOwnPropertySymbols;

function requireObjectGetOwnPropertySymbols () {
	if (hasRequiredObjectGetOwnPropertySymbols) return objectGetOwnPropertySymbols;
	hasRequiredObjectGetOwnPropertySymbols = 1;
	objectGetOwnPropertySymbols.f = Object.getOwnPropertySymbols;
	return objectGetOwnPropertySymbols;
}

var ownKeys$1;
var hasRequiredOwnKeys;

function requireOwnKeys () {
	if (hasRequiredOwnKeys) return ownKeys$1;
	hasRequiredOwnKeys = 1;
	var getBuiltIn = requireGetBuiltIn();
	var uncurryThis = requireFunctionUncurryThis();
	var getOwnPropertyNamesModule = requireObjectGetOwnPropertyNames();
	var getOwnPropertySymbolsModule = requireObjectGetOwnPropertySymbols();
	var anObject = requireAnObject();
	var concat = uncurryThis([].concat);
	ownKeys$1 = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
	  var keys = getOwnPropertyNamesModule.f(anObject(it));
	  var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
	  return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
	};
	return ownKeys$1;
}

var copyConstructorProperties;
var hasRequiredCopyConstructorProperties;

function requireCopyConstructorProperties () {
	if (hasRequiredCopyConstructorProperties) return copyConstructorProperties;
	hasRequiredCopyConstructorProperties = 1;
	var hasOwn = requireHasOwnProperty();
	var ownKeys = requireOwnKeys();
	var getOwnPropertyDescriptorModule = requireObjectGetOwnPropertyDescriptor();
	var definePropertyModule = requireObjectDefineProperty();
	copyConstructorProperties = function (target, source, exceptions) {
	  var keys = ownKeys(source);
	  var defineProperty = definePropertyModule.f;
	  var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
	  for (var i = 0; i < keys.length; i++) {
	    var key = keys[i];
	    if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
	      defineProperty(target, key, getOwnPropertyDescriptor(source, key));
	    }
	  }
	};
	return copyConstructorProperties;
}

var isForced_1;
var hasRequiredIsForced;

function requireIsForced () {
	if (hasRequiredIsForced) return isForced_1;
	hasRequiredIsForced = 1;
	var fails = requireFails();
	var isCallable = requireIsCallable();
	var replacement = /#|\.prototype\./;
	var isForced = function (feature, detection) {
	  var value = data[normalize(feature)];
	  return value === POLYFILL ? true
	    : value === NATIVE ? false
	    : isCallable(detection) ? fails(detection)
	    : !!detection;
	};
	var normalize = isForced.normalize = function (string) {
	  return String(string).replace(replacement, '.').toLowerCase();
	};
	var data = isForced.data = {};
	var NATIVE = isForced.NATIVE = 'N';
	var POLYFILL = isForced.POLYFILL = 'P';
	isForced_1 = isForced;
	return isForced_1;
}

var _export;
var hasRequired_export;

function require_export () {
	if (hasRequired_export) return _export;
	hasRequired_export = 1;
	var globalThis = requireGlobalThis();
	var getOwnPropertyDescriptor = requireObjectGetOwnPropertyDescriptor().f;
	var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
	var defineBuiltIn = requireDefineBuiltIn();
	var defineGlobalProperty = requireDefineGlobalProperty();
	var copyConstructorProperties = requireCopyConstructorProperties();
	var isForced = requireIsForced();
	_export = function (options, source) {
	  var TARGET = options.target;
	  var GLOBAL = options.global;
	  var STATIC = options.stat;
	  var FORCED, target, key, targetProperty, sourceProperty, descriptor;
	  if (GLOBAL) {
	    target = globalThis;
	  } else if (STATIC) {
	    target = globalThis[TARGET] || defineGlobalProperty(TARGET, {});
	  } else {
	    target = globalThis[TARGET] && globalThis[TARGET].prototype;
	  }
	  if (target) for (key in source) {
	    sourceProperty = source[key];
	    if (options.dontCallGetSet) {
	      descriptor = getOwnPropertyDescriptor(target, key);
	      targetProperty = descriptor && descriptor.value;
	    } else targetProperty = target[key];
	    FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
	    if (!FORCED && targetProperty !== undefined) {
	      if (typeof sourceProperty == typeof targetProperty) continue;
	      copyConstructorProperties(sourceProperty, targetProperty);
	    }
	    if (options.sham || (targetProperty && targetProperty.sham)) {
	      createNonEnumerableProperty(sourceProperty, 'sham', true);
	    }
	    defineBuiltIn(target, key, sourceProperty, options);
	  }
	};
	return _export;
}

var newPromiseCapability = {};

var hasRequiredNewPromiseCapability;

function requireNewPromiseCapability () {
	if (hasRequiredNewPromiseCapability) return newPromiseCapability;
	hasRequiredNewPromiseCapability = 1;
	var aCallable = requireACallable();
	var $TypeError = TypeError;
	var PromiseCapability = function (C) {
	  var resolve, reject;
	  this.promise = new C(function ($$resolve, $$reject) {
	    if (resolve !== undefined || reject !== undefined) throw new $TypeError('Bad Promise constructor');
	    resolve = $$resolve;
	    reject = $$reject;
	  });
	  this.resolve = aCallable(resolve);
	  this.reject = aCallable(reject);
	};
	newPromiseCapability.f = function (C) {
	  return new PromiseCapability(C);
	};
	return newPromiseCapability;
}

var hasRequiredEs_promise_withResolvers;

function requireEs_promise_withResolvers () {
	if (hasRequiredEs_promise_withResolvers) return es_promise_withResolvers;
	hasRequiredEs_promise_withResolvers = 1;
	var $ = require_export();
	var newPromiseCapabilityModule = requireNewPromiseCapability();
	$({ target: 'Promise', stat: true }, {
	  withResolvers: function withResolvers() {
	    var promiseCapability = newPromiseCapabilityModule.f(this);
	    return {
	      promise: promiseCapability.promise,
	      resolve: promiseCapability.resolve,
	      reject: promiseCapability.reject
	    };
	  }
	});
	return es_promise_withResolvers;
}

requireEs_promise_withResolvers();

var es_set_union_v2 = {};

var setHelpers;
var hasRequiredSetHelpers;

function requireSetHelpers () {
	if (hasRequiredSetHelpers) return setHelpers;
	hasRequiredSetHelpers = 1;
	var uncurryThis = requireFunctionUncurryThis();
	var SetPrototype = Set.prototype;
	setHelpers = {
	  Set: Set,
	  add: uncurryThis(SetPrototype.add),
	  has: uncurryThis(SetPrototype.has),
	  remove: uncurryThis(SetPrototype['delete']),
	  proto: SetPrototype
	};
	return setHelpers;
}

var aSet;
var hasRequiredASet;

function requireASet () {
	if (hasRequiredASet) return aSet;
	hasRequiredASet = 1;
	var has = requireSetHelpers().has;
	aSet = function (it) {
	  has(it);
	  return it;
	};
	return aSet;
}

var iterateSimple;
var hasRequiredIterateSimple;

function requireIterateSimple () {
	if (hasRequiredIterateSimple) return iterateSimple;
	hasRequiredIterateSimple = 1;
	var call = requireFunctionCall();
	iterateSimple = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) {
	  var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator;
	  var next = record.next;
	  var step, result;
	  while (!(step = call(next, iterator)).done) {
	    result = fn(step.value);
	    if (result !== undefined) return result;
	  }
	};
	return iterateSimple;
}

var setIterate;
var hasRequiredSetIterate;

function requireSetIterate () {
	if (hasRequiredSetIterate) return setIterate;
	hasRequiredSetIterate = 1;
	var uncurryThis = requireFunctionUncurryThis();
	var iterateSimple = requireIterateSimple();
	var SetHelpers = requireSetHelpers();
	var Set = SetHelpers.Set;
	var SetPrototype = SetHelpers.proto;
	var forEach = uncurryThis(SetPrototype.forEach);
	var keys = uncurryThis(SetPrototype.keys);
	var next = keys(new Set()).next;
	setIterate = function (set, fn, interruptible) {
	  return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn);
	};
	return setIterate;
}

var setClone;
var hasRequiredSetClone;

function requireSetClone () {
	if (hasRequiredSetClone) return setClone;
	hasRequiredSetClone = 1;
	var SetHelpers = requireSetHelpers();
	var iterate = requireSetIterate();
	var Set = SetHelpers.Set;
	var add = SetHelpers.add;
	setClone = function (set) {
	  var result = new Set();
	  iterate(set, function (it) {
	    add(result, it);
	  });
	  return result;
	};
	return setClone;
}

var getIteratorDirect;
var hasRequiredGetIteratorDirect;

function requireGetIteratorDirect () {
	if (hasRequiredGetIteratorDirect) return getIteratorDirect;
	hasRequiredGetIteratorDirect = 1;
	getIteratorDirect = function (obj) {
	  return {
	    iterator: obj,
	    next: obj.next,
	    done: false
	  };
	};
	return getIteratorDirect;
}

var getSetRecord;
var hasRequiredGetSetRecord;

function requireGetSetRecord () {
	if (hasRequiredGetSetRecord) return getSetRecord;
	hasRequiredGetSetRecord = 1;
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var call = requireFunctionCall();
	var toIntegerOrInfinity = requireToIntegerOrInfinity();
	var getIteratorDirect = requireGetIteratorDirect();
	var INVALID_SIZE = 'Invalid size';
	var $RangeError = RangeError;
	var $TypeError = TypeError;
	var max = Math.max;
	var SetRecord = function (set, intSize) {
	  this.set = set;
	  this.size = max(intSize, 0);
	  this.has = aCallable(set.has);
	  this.keys = aCallable(set.keys);
	};
	SetRecord.prototype = {
	  getIterator: function () {
	    return getIteratorDirect(anObject(call(this.keys, this.set)));
	  },
	  includes: function (it) {
	    return call(this.has, this.set, it);
	  }
	};
	getSetRecord = function (obj) {
	  anObject(obj);
	  var numSize = +obj.size;
	  if (numSize !== numSize) throw new $TypeError(INVALID_SIZE);
	  var intSize = toIntegerOrInfinity(numSize);
	  if (intSize < 0) throw new $RangeError(INVALID_SIZE);
	  return new SetRecord(obj, intSize);
	};
	return getSetRecord;
}

var setUnion;
var hasRequiredSetUnion;

function requireSetUnion () {
	if (hasRequiredSetUnion) return setUnion;
	hasRequiredSetUnion = 1;
	var aSet = requireASet();
	var add = requireSetHelpers().add;
	var clone = requireSetClone();
	var getSetRecord = requireGetSetRecord();
	var iterateSimple = requireIterateSimple();
	setUnion = function union(other) {
	  var O = aSet(this);
	  var keysIter = getSetRecord(other).getIterator();
	  var result = clone(O);
	  iterateSimple(keysIter, function (it) {
	    add(result, it);
	  });
	  return result;
	};
	return setUnion;
}

var setMethodGetKeysBeforeCloningDetection;
var hasRequiredSetMethodGetKeysBeforeCloningDetection;

function requireSetMethodGetKeysBeforeCloningDetection () {
	if (hasRequiredSetMethodGetKeysBeforeCloningDetection) return setMethodGetKeysBeforeCloningDetection;
	hasRequiredSetMethodGetKeysBeforeCloningDetection = 1;
	setMethodGetKeysBeforeCloningDetection = function (METHOD_NAME) {
	  try {
	    var baseSet = new Set();
	    var setLike = {
	      size: 0,
	      has: function () { return true; },
	      keys: function () {
	        return Object.defineProperty({}, 'next', {
	          get: function () {
	            baseSet.clear();
	            baseSet.add(4);
	            return function () {
	              return { done: true };
	            };
	          }
	        });
	      }
	    };
	    var result = baseSet[METHOD_NAME](setLike);
	    return result.size === 1 && result.values().next().value === 4;
	  } catch (error) {
	    return false;
	  }
	};
	return setMethodGetKeysBeforeCloningDetection;
}

var setMethodAcceptSetLike;
var hasRequiredSetMethodAcceptSetLike;

function requireSetMethodAcceptSetLike () {
	if (hasRequiredSetMethodAcceptSetLike) return setMethodAcceptSetLike;
	hasRequiredSetMethodAcceptSetLike = 1;
	var getBuiltIn = requireGetBuiltIn();
	var createSetLike = function (size) {
	  return {
	    size: size,
	    has: function () {
	      return false;
	    },
	    keys: function () {
	      return {
	        next: function () {
	          return { done: true };
	        }
	      };
	    }
	  };
	};
	var createSetLikeWithInfinitySize = function (size) {
	  return {
	    size: size,
	    has: function () {
	      return true;
	    },
	    keys: function () {
	      throw new Error('e');
	    }
	  };
	};
	setMethodAcceptSetLike = function (name, callback) {
	  var Set = getBuiltIn('Set');
	  try {
	    new Set()[name](createSetLike(0));
	    try {
	      new Set()[name](createSetLike(-1));
	      return false;
	    } catch (error2) {
	      if (!callback) return true;
	      try {
	        new Set()[name](createSetLikeWithInfinitySize(-Infinity));
	        return false;
	      } catch (error) {
	        var set = new Set([1, 2]);
	        return callback(set[name](createSetLikeWithInfinitySize(Infinity)));
	      }
	    }
	  } catch (error) {
	    return false;
	  }
	};
	return setMethodAcceptSetLike;
}

var hasRequiredEs_set_union_v2;

function requireEs_set_union_v2 () {
	if (hasRequiredEs_set_union_v2) return es_set_union_v2;
	hasRequiredEs_set_union_v2 = 1;
	var $ = require_export();
	var union = requireSetUnion();
	var setMethodGetKeysBeforeCloning = requireSetMethodGetKeysBeforeCloningDetection();
	var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
	var FORCED = !setMethodAcceptSetLike('union') || !setMethodGetKeysBeforeCloning('union');
	$({ target: 'Set', proto: true, real: true, forced: FORCED }, {
	  union: union
	});
	return es_set_union_v2;
}

requireEs_set_union_v2();

var iteratorHelpers = {};

var iteratorHelpersStage3 = {};

var esnext_asyncIterator_constructor = {};

var anInstance;
var hasRequiredAnInstance;

function requireAnInstance () {
	if (hasRequiredAnInstance) return anInstance;
	hasRequiredAnInstance = 1;
	var isPrototypeOf = requireObjectIsPrototypeOf();
	var $TypeError = TypeError;
	anInstance = function (it, Prototype) {
	  if (isPrototypeOf(Prototype, it)) return it;
	  throw new $TypeError('Incorrect invocation');
	};
	return anInstance;
}

var correctPrototypeGetter;
var hasRequiredCorrectPrototypeGetter;

function requireCorrectPrototypeGetter () {
	if (hasRequiredCorrectPrototypeGetter) return correctPrototypeGetter;
	hasRequiredCorrectPrototypeGetter = 1;
	var fails = requireFails();
	correctPrototypeGetter = !fails(function () {
	  function F() {  }
	  F.prototype.constructor = null;
	  return Object.getPrototypeOf(new F()) !== F.prototype;
	});
	return correctPrototypeGetter;
}

var objectGetPrototypeOf;
var hasRequiredObjectGetPrototypeOf;

function requireObjectGetPrototypeOf () {
	if (hasRequiredObjectGetPrototypeOf) return objectGetPrototypeOf;
	hasRequiredObjectGetPrototypeOf = 1;
	var hasOwn = requireHasOwnProperty();
	var isCallable = requireIsCallable();
	var toObject = requireToObject();
	var sharedKey = requireSharedKey();
	var CORRECT_PROTOTYPE_GETTER = requireCorrectPrototypeGetter();
	var IE_PROTO = sharedKey('IE_PROTO');
	var $Object = Object;
	var ObjectPrototype = $Object.prototype;
	objectGetPrototypeOf = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {
	  var object = toObject(O);
	  if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
	  var constructor = object.constructor;
	  if (isCallable(constructor) && object instanceof constructor) {
	    return constructor.prototype;
	  } return object instanceof $Object ? ObjectPrototype : null;
	};
	return objectGetPrototypeOf;
}

var objectDefineProperties = {};

var objectKeys$1;
var hasRequiredObjectKeys;

function requireObjectKeys () {
	if (hasRequiredObjectKeys) return objectKeys$1;
	hasRequiredObjectKeys = 1;
	var internalObjectKeys = requireObjectKeysInternal();
	var enumBugKeys = requireEnumBugKeys();
	objectKeys$1 = Object.keys || function keys(O) {
	  return internalObjectKeys(O, enumBugKeys);
	};
	return objectKeys$1;
}

var hasRequiredObjectDefineProperties;

function requireObjectDefineProperties () {
	if (hasRequiredObjectDefineProperties) return objectDefineProperties;
	hasRequiredObjectDefineProperties = 1;
	var DESCRIPTORS = requireDescriptors();
	var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
	var definePropertyModule = requireObjectDefineProperty();
	var anObject = requireAnObject();
	var toIndexedObject = requireToIndexedObject();
	var objectKeys = requireObjectKeys();
	objectDefineProperties.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
	  anObject(O);
	  var props = toIndexedObject(Properties);
	  var keys = objectKeys(Properties);
	  var length = keys.length;
	  var index = 0;
	  var key;
	  while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
	  return O;
	};
	return objectDefineProperties;
}

var html$1;
var hasRequiredHtml;

function requireHtml () {
	if (hasRequiredHtml) return html$1;
	hasRequiredHtml = 1;
	var getBuiltIn = requireGetBuiltIn();
	html$1 = getBuiltIn('document', 'documentElement');
	return html$1;
}

var objectCreate;
var hasRequiredObjectCreate;

function requireObjectCreate () {
	if (hasRequiredObjectCreate) return objectCreate;
	hasRequiredObjectCreate = 1;
	var anObject = requireAnObject();
	var definePropertiesModule = requireObjectDefineProperties();
	var enumBugKeys = requireEnumBugKeys();
	var hiddenKeys = requireHiddenKeys();
	var html = requireHtml();
	var documentCreateElement = requireDocumentCreateElement();
	var sharedKey = requireSharedKey();
	var GT = '>';
	var LT = '<';
	var PROTOTYPE = 'prototype';
	var SCRIPT = 'script';
	var IE_PROTO = sharedKey('IE_PROTO');
	var EmptyConstructor = function () {  };
	var scriptTag = function (content) {
	  return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
	};
	var NullProtoObjectViaActiveX = function (activeXDocument) {
	  activeXDocument.write(scriptTag(''));
	  activeXDocument.close();
	  var temp = activeXDocument.parentWindow.Object;
	  activeXDocument = null;
	  return temp;
	};
	var NullProtoObjectViaIFrame = function () {
	  var iframe = documentCreateElement('iframe');
	  var JS = 'java' + SCRIPT + ':';
	  var iframeDocument;
	  iframe.style.display = 'none';
	  html.appendChild(iframe);
	  iframe.src = String(JS);
	  iframeDocument = iframe.contentWindow.document;
	  iframeDocument.open();
	  iframeDocument.write(scriptTag('document.F=Object'));
	  iframeDocument.close();
	  return iframeDocument.F;
	};
	var activeXDocument;
	var NullProtoObject = function () {
	  try {
	    activeXDocument = new ActiveXObject('htmlfile');
	  } catch (error) {  }
	  NullProtoObject = typeof document != 'undefined'
	    ? document.domain && activeXDocument
	      ? NullProtoObjectViaActiveX(activeXDocument)
	      : NullProtoObjectViaIFrame()
	    : NullProtoObjectViaActiveX(activeXDocument);
	  var length = enumBugKeys.length;
	  while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
	  return NullProtoObject();
	};
	hiddenKeys[IE_PROTO] = true;
	objectCreate = Object.create || function create(O, Properties) {
	  var result;
	  if (O !== null) {
	    EmptyConstructor[PROTOTYPE] = anObject(O);
	    result = new EmptyConstructor();
	    EmptyConstructor[PROTOTYPE] = null;
	    result[IE_PROTO] = O;
	  } else result = NullProtoObject();
	  return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
	};
	return objectCreate;
}

var asyncIteratorPrototype;
var hasRequiredAsyncIteratorPrototype;

function requireAsyncIteratorPrototype () {
	if (hasRequiredAsyncIteratorPrototype) return asyncIteratorPrototype;
	hasRequiredAsyncIteratorPrototype = 1;
	var globalThis = requireGlobalThis();
	var shared = requireSharedStore();
	var isCallable = requireIsCallable();
	var create = requireObjectCreate();
	var getPrototypeOf = requireObjectGetPrototypeOf();
	var defineBuiltIn = requireDefineBuiltIn();
	var wellKnownSymbol = requireWellKnownSymbol();
	var IS_PURE = requireIsPure();
	var USE_FUNCTION_CONSTRUCTOR = 'USE_FUNCTION_CONSTRUCTOR';
	var ASYNC_ITERATOR = wellKnownSymbol('asyncIterator');
	var AsyncIterator = globalThis.AsyncIterator;
	var PassedAsyncIteratorPrototype = shared.AsyncIteratorPrototype;
	var AsyncIteratorPrototype, prototype;
	if (PassedAsyncIteratorPrototype) {
	  AsyncIteratorPrototype = PassedAsyncIteratorPrototype;
	} else if (isCallable(AsyncIterator)) {
	  AsyncIteratorPrototype = AsyncIterator.prototype;
	} else if (shared[USE_FUNCTION_CONSTRUCTOR] || globalThis[USE_FUNCTION_CONSTRUCTOR]) {
	  try {
	    prototype = getPrototypeOf(getPrototypeOf(getPrototypeOf(Function('return async function*(){}()')())));
	    if (getPrototypeOf(prototype) === Object.prototype) AsyncIteratorPrototype = prototype;
	  } catch (error) {  }
	}
	if (!AsyncIteratorPrototype) AsyncIteratorPrototype = {};
	else if (IS_PURE) AsyncIteratorPrototype = create(AsyncIteratorPrototype);
	if (!isCallable(AsyncIteratorPrototype[ASYNC_ITERATOR])) {
	  defineBuiltIn(AsyncIteratorPrototype, ASYNC_ITERATOR, function () {
	    return this;
	  });
	}
	asyncIteratorPrototype = AsyncIteratorPrototype;
	return asyncIteratorPrototype;
}

var hasRequiredEsnext_asyncIterator_constructor;

function requireEsnext_asyncIterator_constructor () {
	if (hasRequiredEsnext_asyncIterator_constructor) return esnext_asyncIterator_constructor;
	hasRequiredEsnext_asyncIterator_constructor = 1;
	var $ = require_export();
	var anInstance = requireAnInstance();
	var getPrototypeOf = requireObjectGetPrototypeOf();
	var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
	var hasOwn = requireHasOwnProperty();
	var wellKnownSymbol = requireWellKnownSymbol();
	var AsyncIteratorPrototype = requireAsyncIteratorPrototype();
	var IS_PURE = requireIsPure();
	var TO_STRING_TAG = wellKnownSymbol('toStringTag');
	var $TypeError = TypeError;
	var AsyncIteratorConstructor = function AsyncIterator() {
	  anInstance(this, AsyncIteratorPrototype);
	  if (getPrototypeOf(this) === AsyncIteratorPrototype) throw new $TypeError('Abstract class AsyncIterator not directly constructable');
	};
	AsyncIteratorConstructor.prototype = AsyncIteratorPrototype;
	if (!hasOwn(AsyncIteratorPrototype, TO_STRING_TAG)) {
	  createNonEnumerableProperty(AsyncIteratorPrototype, TO_STRING_TAG, 'AsyncIterator');
	}
	if (IS_PURE || !hasOwn(AsyncIteratorPrototype, 'constructor') || AsyncIteratorPrototype.constructor === Object) {
	  createNonEnumerableProperty(AsyncIteratorPrototype, 'constructor', AsyncIteratorConstructor);
	}
	$({ global: true, constructor: true, forced: IS_PURE }, {
	  AsyncIterator: AsyncIteratorConstructor
	});
	return esnext_asyncIterator_constructor;
}

var esnext_asyncIterator_drop = {};

var notANan;
var hasRequiredNotANan;

function requireNotANan () {
	if (hasRequiredNotANan) return notANan;
	hasRequiredNotANan = 1;
	var $RangeError = RangeError;
	notANan = function (it) {
	  if (it === it) return it;
	  throw new $RangeError('NaN is not allowed');
	};
	return notANan;
}

var toPositiveInteger;
var hasRequiredToPositiveInteger;

function requireToPositiveInteger () {
	if (hasRequiredToPositiveInteger) return toPositiveInteger;
	hasRequiredToPositiveInteger = 1;
	var toIntegerOrInfinity = requireToIntegerOrInfinity();
	var $RangeError = RangeError;
	toPositiveInteger = function (it) {
	  var result = toIntegerOrInfinity(it);
	  if (result < 0) throw new $RangeError("The argument can't be less than 0");
	  return result;
	};
	return toPositiveInteger;
}

var perform;
var hasRequiredPerform;

function requirePerform () {
	if (hasRequiredPerform) return perform;
	hasRequiredPerform = 1;
	perform = function (exec) {
	  try {
	    return { error: false, value: exec() };
	  } catch (error) {
	    return { error: true, value: error };
	  }
	};
	return perform;
}

var defineBuiltIns;
var hasRequiredDefineBuiltIns;

function requireDefineBuiltIns () {
	if (hasRequiredDefineBuiltIns) return defineBuiltIns;
	hasRequiredDefineBuiltIns = 1;
	var defineBuiltIn = requireDefineBuiltIn();
	defineBuiltIns = function (target, src, options) {
	  for (var key in src) defineBuiltIn(target, key, src[key], options);
	  return target;
	};
	return defineBuiltIns;
}

var createIterResultObject;
var hasRequiredCreateIterResultObject;

function requireCreateIterResultObject () {
	if (hasRequiredCreateIterResultObject) return createIterResultObject;
	hasRequiredCreateIterResultObject = 1;
	createIterResultObject = function (value, done) {
	  return { value: value, done: done };
	};
	return createIterResultObject;
}

var iteratorClose;
var hasRequiredIteratorClose;

function requireIteratorClose () {
	if (hasRequiredIteratorClose) return iteratorClose;
	hasRequiredIteratorClose = 1;
	var call = requireFunctionCall();
	var anObject = requireAnObject();
	var getMethod = requireGetMethod();
	iteratorClose = function (iterator, kind, value) {
	  var innerResult, innerError;
	  anObject(iterator);
	  try {
	    innerResult = getMethod(iterator, 'return');
	    if (!innerResult) {
	      if (kind === 'throw') throw value;
	      return value;
	    }
	    innerResult = call(innerResult, iterator);
	  } catch (error) {
	    innerError = true;
	    innerResult = error;
	  }
	  if (kind === 'throw') throw value;
	  if (innerError) throw innerResult;
	  anObject(innerResult);
	  return value;
	};
	return iteratorClose;
}

var asyncIteratorCreateProxy;
var hasRequiredAsyncIteratorCreateProxy;

function requireAsyncIteratorCreateProxy () {
	if (hasRequiredAsyncIteratorCreateProxy) return asyncIteratorCreateProxy;
	hasRequiredAsyncIteratorCreateProxy = 1;
	var call = requireFunctionCall();
	var perform = requirePerform();
	var anObject = requireAnObject();
	var create = requireObjectCreate();
	var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
	var defineBuiltIns = requireDefineBuiltIns();
	var wellKnownSymbol = requireWellKnownSymbol();
	var InternalStateModule = requireInternalState();
	var getBuiltIn = requireGetBuiltIn();
	var getMethod = requireGetMethod();
	var AsyncIteratorPrototype = requireAsyncIteratorPrototype();
	var createIterResultObject = requireCreateIterResultObject();
	var iteratorClose = requireIteratorClose();
	var Promise = getBuiltIn('Promise');
	var TO_STRING_TAG = wellKnownSymbol('toStringTag');
	var ASYNC_ITERATOR_HELPER = 'AsyncIteratorHelper';
	var WRAP_FOR_VALID_ASYNC_ITERATOR = 'WrapForValidAsyncIterator';
	var setInternalState = InternalStateModule.set;
	var createAsyncIteratorProxyPrototype = function (IS_ITERATOR) {
	  var IS_GENERATOR = !IS_ITERATOR;
	  var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ASYNC_ITERATOR : ASYNC_ITERATOR_HELPER);
	  var getStateOrEarlyExit = function (that) {
	    var stateCompletion = perform(function () {
	      return getInternalState(that);
	    });
	    var stateError = stateCompletion.error;
	    var state = stateCompletion.value;
	    if (stateError || (IS_GENERATOR && state.done)) {
	      return { exit: true, value: stateError ? Promise.reject(state) : Promise.resolve(createIterResultObject(undefined, true)) };
	    } return { exit: false, value: state };
	  };
	  return defineBuiltIns(create(AsyncIteratorPrototype), {
	    next: function next() {
	      var stateCompletion = getStateOrEarlyExit(this);
	      var state = stateCompletion.value;
	      if (stateCompletion.exit) return state;
	      var handlerCompletion = perform(function () {
	        return anObject(state.nextHandler(Promise));
	      });
	      var handlerError = handlerCompletion.error;
	      var value = handlerCompletion.value;
	      if (handlerError) state.done = true;
	      return handlerError ? Promise.reject(value) : Promise.resolve(value);
	    },
	    'return': function () {
	      var stateCompletion = getStateOrEarlyExit(this);
	      var state = stateCompletion.value;
	      if (stateCompletion.exit) return state;
	      state.done = true;
	      var iterator = state.iterator;
	      var returnMethod, result;
	      var completion = perform(function () {
	        if (state.inner) try {
	          iteratorClose(state.inner.iterator, 'normal');
	        } catch (error) {
	          return iteratorClose(iterator, 'throw', error);
	        }
	        return getMethod(iterator, 'return');
	      });
	      returnMethod = result = completion.value;
	      if (completion.error) return Promise.reject(result);
	      if (returnMethod === undefined) return Promise.resolve(createIterResultObject(undefined, true));
	      completion = perform(function () {
	        return call(returnMethod, iterator);
	      });
	      result = completion.value;
	      if (completion.error) return Promise.reject(result);
	      return IS_ITERATOR ? Promise.resolve(result) : Promise.resolve(result).then(function (resolved) {
	        anObject(resolved);
	        return createIterResultObject(undefined, true);
	      });
	    }
	  });
	};
	var WrapForValidAsyncIteratorPrototype = createAsyncIteratorProxyPrototype(true);
	var AsyncIteratorHelperPrototype = createAsyncIteratorProxyPrototype(false);
	createNonEnumerableProperty(AsyncIteratorHelperPrototype, TO_STRING_TAG, 'Async Iterator Helper');
	asyncIteratorCreateProxy = function (nextHandler, IS_ITERATOR) {
	  var AsyncIteratorProxy = function AsyncIterator(record, state) {
	    if (state) {
	      state.iterator = record.iterator;
	      state.next = record.next;
	    } else state = record;
	    state.type = IS_ITERATOR ? WRAP_FOR_VALID_ASYNC_ITERATOR : ASYNC_ITERATOR_HELPER;
	    state.nextHandler = nextHandler;
	    state.counter = 0;
	    state.done = false;
	    setInternalState(this, state);
	  };
	  AsyncIteratorProxy.prototype = IS_ITERATOR ? WrapForValidAsyncIteratorPrototype : AsyncIteratorHelperPrototype;
	  return AsyncIteratorProxy;
	};
	return asyncIteratorCreateProxy;
}

var hasRequiredEsnext_asyncIterator_drop;

function requireEsnext_asyncIterator_drop () {
	if (hasRequiredEsnext_asyncIterator_drop) return esnext_asyncIterator_drop;
	hasRequiredEsnext_asyncIterator_drop = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var notANaN = requireNotANan();
	var toPositiveInteger = requireToPositiveInteger();
	var createAsyncIteratorProxy = requireAsyncIteratorCreateProxy();
	var createIterResultObject = requireCreateIterResultObject();
	var AsyncIteratorProxy = createAsyncIteratorProxy(function (Promise) {
	  var state = this;
	  return new Promise(function (resolve, reject) {
	    var doneAndReject = function (error) {
	      state.done = true;
	      reject(error);
	    };
	    var loop = function () {
	      try {
	        Promise.resolve(anObject(call(state.next, state.iterator))).then(function (step) {
	          try {
	            if (anObject(step).done) {
	              state.done = true;
	              resolve(createIterResultObject(undefined, true));
	            } else if (state.remaining) {
	              state.remaining--;
	              loop();
	            } else resolve(createIterResultObject(step.value, false));
	          } catch (err) { doneAndReject(err); }
	        }, doneAndReject);
	      } catch (error) { doneAndReject(error); }
	    };
	    loop();
	  });
	});
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  drop: function drop(limit) {
	    anObject(this);
	    var remaining = toPositiveInteger(notANaN(+limit));
	    return new AsyncIteratorProxy(getIteratorDirect(this), {
	      remaining: remaining
	    });
	  }
	});
	return esnext_asyncIterator_drop;
}

var esnext_asyncIterator_every = {};

var doesNotExceedSafeInteger;
var hasRequiredDoesNotExceedSafeInteger;

function requireDoesNotExceedSafeInteger () {
	if (hasRequiredDoesNotExceedSafeInteger) return doesNotExceedSafeInteger;
	hasRequiredDoesNotExceedSafeInteger = 1;
	var $TypeError = TypeError;
	var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
	doesNotExceedSafeInteger = function (it) {
	  if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded');
	  return it;
	};
	return doesNotExceedSafeInteger;
}

var createProperty;
var hasRequiredCreateProperty;

function requireCreateProperty () {
	if (hasRequiredCreateProperty) return createProperty;
	hasRequiredCreateProperty = 1;
	var DESCRIPTORS = requireDescriptors();
	var definePropertyModule = requireObjectDefineProperty();
	var createPropertyDescriptor = requireCreatePropertyDescriptor();
	createProperty = function (object, key, value) {
	  if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value));
	  else object[key] = value;
	};
	return createProperty;
}

var isArray$1;
var hasRequiredIsArray;

function requireIsArray () {
	if (hasRequiredIsArray) return isArray$1;
	hasRequiredIsArray = 1;
	var classof = requireClassofRaw();
	isArray$1 = Array.isArray || function isArray(argument) {
	  return classof(argument) === 'Array';
	};
	return isArray$1;
}

var arraySetLength;
var hasRequiredArraySetLength;

function requireArraySetLength () {
	if (hasRequiredArraySetLength) return arraySetLength;
	hasRequiredArraySetLength = 1;
	var DESCRIPTORS = requireDescriptors();
	var isArray = requireIsArray();
	var $TypeError = TypeError;
	var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
	var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {
	  if (this !== undefined) return true;
	  try {
	    Object.defineProperty([], 'length', { writable: false }).length = 1;
	  } catch (error) {
	    return error instanceof TypeError;
	  }
	}();
	arraySetLength = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
	  if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) {
	    throw new $TypeError('Cannot set read only .length');
	  } return O.length = length;
	} : function (O, length) {
	  return O.length = length;
	};
	return arraySetLength;
}

var asyncIteratorClose;
var hasRequiredAsyncIteratorClose;

function requireAsyncIteratorClose () {
	if (hasRequiredAsyncIteratorClose) return asyncIteratorClose;
	hasRequiredAsyncIteratorClose = 1;
	var call = requireFunctionCall();
	var getBuiltIn = requireGetBuiltIn();
	var getMethod = requireGetMethod();
	asyncIteratorClose = function (iterator, method, argument, reject) {
	  try {
	    var returnMethod = getMethod(iterator, 'return');
	    if (returnMethod) {
	      return getBuiltIn('Promise').resolve(call(returnMethod, iterator)).then(function () {
	        method(argument);
	      }, function (error) {
	        reject(error);
	      });
	    }
	  } catch (error2) {
	    return reject(error2);
	  } method(argument);
	};
	return asyncIteratorClose;
}

var asyncIteratorIteration;
var hasRequiredAsyncIteratorIteration;

function requireAsyncIteratorIteration () {
	if (hasRequiredAsyncIteratorIteration) return asyncIteratorIteration;
	hasRequiredAsyncIteratorIteration = 1;
	var call = requireFunctionCall();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var isObject = requireIsObject();
	var doesNotExceedSafeInteger = requireDoesNotExceedSafeInteger();
	var getBuiltIn = requireGetBuiltIn();
	var createProperty = requireCreateProperty();
	var setArrayLength = requireArraySetLength();
	var getIteratorDirect = requireGetIteratorDirect();
	var closeAsyncIteration = requireAsyncIteratorClose();
	var createMethod = function (TYPE) {
	  var IS_TO_ARRAY = TYPE === 0;
	  var IS_FOR_EACH = TYPE === 1;
	  var IS_EVERY = TYPE === 2;
	  var IS_SOME = TYPE === 3;
	  return function (object, fn, target) {
	    anObject(object);
	    var MAPPING = fn !== undefined;
	    if (MAPPING || !IS_TO_ARRAY) aCallable(fn);
	    var record = getIteratorDirect(object);
	    var Promise = getBuiltIn('Promise');
	    var iterator = record.iterator;
	    var next = record.next;
	    var counter = 0;
	    return new Promise(function (resolve, reject) {
	      var ifAbruptCloseAsyncIterator = function (error) {
	        closeAsyncIteration(iterator, reject, error, reject);
	      };
	      var loop = function () {
	        try {
	          if (MAPPING) try {
	            doesNotExceedSafeInteger(counter);
	          } catch (error5) { ifAbruptCloseAsyncIterator(error5); }
	          Promise.resolve(anObject(call(next, iterator))).then(function (step) {
	            try {
	              if (anObject(step).done) {
	                if (IS_TO_ARRAY) {
	                  setArrayLength(target, counter);
	                  resolve(target);
	                } else resolve(IS_SOME ? false : IS_EVERY || undefined);
	              } else {
	                var value = step.value;
	                try {
	                  if (MAPPING) {
	                    var result = fn(value, counter);
	                    var handler = function ($result) {
	                      if (IS_FOR_EACH) {
	                        loop();
	                      } else if (IS_EVERY) {
	                        $result ? loop() : closeAsyncIteration(iterator, resolve, false, reject);
	                      } else if (IS_TO_ARRAY) {
	                        try {
	                          createProperty(target, counter++, $result);
	                          loop();
	                        } catch (error4) { ifAbruptCloseAsyncIterator(error4); }
	                      } else {
	                        $result ? closeAsyncIteration(iterator, resolve, IS_SOME || value, reject) : loop();
	                      }
	                    };
	                    if (isObject(result)) Promise.resolve(result).then(handler, ifAbruptCloseAsyncIterator);
	                    else handler(result);
	                  } else {
	                    createProperty(target, counter++, value);
	                    loop();
	                  }
	                } catch (error3) { ifAbruptCloseAsyncIterator(error3); }
	              }
	            } catch (error2) { reject(error2); }
	          }, reject);
	        } catch (error) { reject(error); }
	      };
	      loop();
	    });
	  };
	};
	asyncIteratorIteration = {
	  toArray: createMethod(0),
	  forEach: createMethod(1),
	  every: createMethod(2),
	  some: createMethod(3),
	  find: createMethod(4)
	};
	return asyncIteratorIteration;
}

var hasRequiredEsnext_asyncIterator_every;

function requireEsnext_asyncIterator_every () {
	if (hasRequiredEsnext_asyncIterator_every) return esnext_asyncIterator_every;
	hasRequiredEsnext_asyncIterator_every = 1;
	var $ = require_export();
	var $every = requireAsyncIteratorIteration().every;
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  every: function every(predicate) {
	    return $every(this, predicate);
	  }
	});
	return esnext_asyncIterator_every;
}

var esnext_asyncIterator_filter = {};

var hasRequiredEsnext_asyncIterator_filter;

function requireEsnext_asyncIterator_filter () {
	if (hasRequiredEsnext_asyncIterator_filter) return esnext_asyncIterator_filter;
	hasRequiredEsnext_asyncIterator_filter = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var isObject = requireIsObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var createAsyncIteratorProxy = requireAsyncIteratorCreateProxy();
	var createIterResultObject = requireCreateIterResultObject();
	var closeAsyncIteration = requireAsyncIteratorClose();
	var AsyncIteratorProxy = createAsyncIteratorProxy(function (Promise) {
	  var state = this;
	  var iterator = state.iterator;
	  var predicate = state.predicate;
	  return new Promise(function (resolve, reject) {
	    var doneAndReject = function (error) {
	      state.done = true;
	      reject(error);
	    };
	    var ifAbruptCloseAsyncIterator = function (error) {
	      closeAsyncIteration(iterator, doneAndReject, error, doneAndReject);
	    };
	    var loop = function () {
	      try {
	        Promise.resolve(anObject(call(state.next, iterator))).then(function (step) {
	          try {
	            if (anObject(step).done) {
	              state.done = true;
	              resolve(createIterResultObject(undefined, true));
	            } else {
	              var value = step.value;
	              try {
	                var result = predicate(value, state.counter++);
	                var handler = function (selected) {
	                  selected ? resolve(createIterResultObject(value, false)) : loop();
	                };
	                if (isObject(result)) Promise.resolve(result).then(handler, ifAbruptCloseAsyncIterator);
	                else handler(result);
	              } catch (error3) { ifAbruptCloseAsyncIterator(error3); }
	            }
	          } catch (error2) { doneAndReject(error2); }
	        }, doneAndReject);
	      } catch (error) { doneAndReject(error); }
	    };
	    loop();
	  });
	});
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  filter: function filter(predicate) {
	    anObject(this);
	    aCallable(predicate);
	    return new AsyncIteratorProxy(getIteratorDirect(this), {
	      predicate: predicate
	    });
	  }
	});
	return esnext_asyncIterator_filter;
}

var esnext_asyncIterator_find = {};

var hasRequiredEsnext_asyncIterator_find;

function requireEsnext_asyncIterator_find () {
	if (hasRequiredEsnext_asyncIterator_find) return esnext_asyncIterator_find;
	hasRequiredEsnext_asyncIterator_find = 1;
	var $ = require_export();
	var $find = requireAsyncIteratorIteration().find;
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  find: function find(predicate) {
	    return $find(this, predicate);
	  }
	});
	return esnext_asyncIterator_find;
}

var esnext_asyncIterator_flatMap = {};

var toStringTagSupport;
var hasRequiredToStringTagSupport;

function requireToStringTagSupport () {
	if (hasRequiredToStringTagSupport) return toStringTagSupport;
	hasRequiredToStringTagSupport = 1;
	var wellKnownSymbol = requireWellKnownSymbol();
	var TO_STRING_TAG = wellKnownSymbol('toStringTag');
	var test = {};
	test[TO_STRING_TAG] = 'z';
	toStringTagSupport = String(test) === '[object z]';
	return toStringTagSupport;
}

var classof;
var hasRequiredClassof;

function requireClassof () {
	if (hasRequiredClassof) return classof;
	hasRequiredClassof = 1;
	var TO_STRING_TAG_SUPPORT = requireToStringTagSupport();
	var isCallable = requireIsCallable();
	var classofRaw = requireClassofRaw();
	var wellKnownSymbol = requireWellKnownSymbol();
	var TO_STRING_TAG = wellKnownSymbol('toStringTag');
	var $Object = Object;
	var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments';
	var tryGet = function (it, key) {
	  try {
	    return it[key];
	  } catch (error) {  }
	};
	classof = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
	  var O, tag, result;
	  return it === undefined ? 'Undefined' : it === null ? 'Null'
	    : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag
	    : CORRECT_ARGUMENTS ? classofRaw(O)
	    : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result;
	};
	return classof;
}

var iterators;
var hasRequiredIterators;

function requireIterators () {
	if (hasRequiredIterators) return iterators;
	hasRequiredIterators = 1;
	iterators = {};
	return iterators;
}

var getIteratorMethod;
var hasRequiredGetIteratorMethod;

function requireGetIteratorMethod () {
	if (hasRequiredGetIteratorMethod) return getIteratorMethod;
	hasRequiredGetIteratorMethod = 1;
	var classof = requireClassof();
	var getMethod = requireGetMethod();
	var isNullOrUndefined = requireIsNullOrUndefined();
	var Iterators = requireIterators();
	var wellKnownSymbol = requireWellKnownSymbol();
	var ITERATOR = wellKnownSymbol('iterator');
	getIteratorMethod = function (it) {
	  if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR)
	    || getMethod(it, '@@iterator')
	    || Iterators[classof(it)];
	};
	return getIteratorMethod;
}

var asyncFromSyncIterator;
var hasRequiredAsyncFromSyncIterator;

function requireAsyncFromSyncIterator () {
	if (hasRequiredAsyncFromSyncIterator) return asyncFromSyncIterator;
	hasRequiredAsyncFromSyncIterator = 1;
	var call = requireFunctionCall();
	var anObject = requireAnObject();
	var create = requireObjectCreate();
	var getMethod = requireGetMethod();
	var defineBuiltIns = requireDefineBuiltIns();
	var InternalStateModule = requireInternalState();
	var iteratorClose = requireIteratorClose();
	var getBuiltIn = requireGetBuiltIn();
	var AsyncIteratorPrototype = requireAsyncIteratorPrototype();
	var createIterResultObject = requireCreateIterResultObject();
	var Promise = getBuiltIn('Promise');
	var ASYNC_FROM_SYNC_ITERATOR = 'AsyncFromSyncIterator';
	var setInternalState = InternalStateModule.set;
	var getInternalState = InternalStateModule.getterFor(ASYNC_FROM_SYNC_ITERATOR);
	var asyncFromSyncIteratorContinuation = function (result, resolve, reject, syncIterator, closeOnRejection) {
	  var done = result.done;
	  Promise.resolve(result.value).then(function (value) {
	    resolve(createIterResultObject(value, done));
	  }, function (error) {
	    if (!done && closeOnRejection) {
	      try {
	        iteratorClose(syncIterator, 'throw', error);
	      } catch (error2) {
	        error = error2;
	      }
	    }
	    reject(error);
	  });
	};
	var AsyncFromSyncIterator = function AsyncIterator(iteratorRecord) {
	  iteratorRecord.type = ASYNC_FROM_SYNC_ITERATOR;
	  setInternalState(this, iteratorRecord);
	};
	AsyncFromSyncIterator.prototype = defineBuiltIns(create(AsyncIteratorPrototype), {
	  next: function next() {
	    var state = getInternalState(this);
	    return new Promise(function (resolve, reject) {
	      var result = anObject(call(state.next, state.iterator));
	      asyncFromSyncIteratorContinuation(result, resolve, reject, state.iterator, true);
	    });
	  },
	  'return': function () {
	    var iterator = getInternalState(this).iterator;
	    return new Promise(function (resolve, reject) {
	      var $return = getMethod(iterator, 'return');
	      if ($return === undefined) return resolve(createIterResultObject(undefined, true));
	      var result = anObject(call($return, iterator));
	      asyncFromSyncIteratorContinuation(result, resolve, reject, iterator);
	    });
	  }
	});
	asyncFromSyncIterator = AsyncFromSyncIterator;
	return asyncFromSyncIterator;
}

var getAsyncIteratorFlattenable;
var hasRequiredGetAsyncIteratorFlattenable;

function requireGetAsyncIteratorFlattenable () {
	if (hasRequiredGetAsyncIteratorFlattenable) return getAsyncIteratorFlattenable;
	hasRequiredGetAsyncIteratorFlattenable = 1;
	var call = requireFunctionCall();
	var isCallable = requireIsCallable();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var getIteratorMethod = requireGetIteratorMethod();
	var getMethod = requireGetMethod();
	var wellKnownSymbol = requireWellKnownSymbol();
	var AsyncFromSyncIterator = requireAsyncFromSyncIterator();
	var ASYNC_ITERATOR = wellKnownSymbol('asyncIterator');
	getAsyncIteratorFlattenable = function (obj) {
	  var object = anObject(obj);
	  var alreadyAsync = true;
	  var method = getMethod(object, ASYNC_ITERATOR);
	  var iterator;
	  if (!isCallable(method)) {
	    method = getIteratorMethod(object);
	    alreadyAsync = false;
	  }
	  if (method !== undefined) {
	    iterator = call(method, object);
	  } else {
	    iterator = object;
	    alreadyAsync = true;
	  }
	  anObject(iterator);
	  return getIteratorDirect(alreadyAsync ? iterator : new AsyncFromSyncIterator(getIteratorDirect(iterator)));
	};
	return getAsyncIteratorFlattenable;
}

var hasRequiredEsnext_asyncIterator_flatMap;

function requireEsnext_asyncIterator_flatMap () {
	if (hasRequiredEsnext_asyncIterator_flatMap) return esnext_asyncIterator_flatMap;
	hasRequiredEsnext_asyncIterator_flatMap = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var isObject = requireIsObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var createAsyncIteratorProxy = requireAsyncIteratorCreateProxy();
	var createIterResultObject = requireCreateIterResultObject();
	var getAsyncIteratorFlattenable = requireGetAsyncIteratorFlattenable();
	var closeAsyncIteration = requireAsyncIteratorClose();
	var AsyncIteratorProxy = createAsyncIteratorProxy(function (Promise) {
	  var state = this;
	  var iterator = state.iterator;
	  var mapper = state.mapper;
	  return new Promise(function (resolve, reject) {
	    var doneAndReject = function (error) {
	      state.done = true;
	      reject(error);
	    };
	    var ifAbruptCloseAsyncIterator = function (error) {
	      closeAsyncIteration(iterator, doneAndReject, error, doneAndReject);
	    };
	    var outerLoop = function () {
	      try {
	        Promise.resolve(anObject(call(state.next, iterator))).then(function (step) {
	          try {
	            if (anObject(step).done) {
	              state.done = true;
	              resolve(createIterResultObject(undefined, true));
	            } else {
	              var value = step.value;
	              try {
	                var result = mapper(value, state.counter++);
	                var handler = function (mapped) {
	                  try {
	                    state.inner = getAsyncIteratorFlattenable(mapped);
	                    innerLoop();
	                  } catch (error4) { ifAbruptCloseAsyncIterator(error4); }
	                };
	                if (isObject(result)) Promise.resolve(result).then(handler, ifAbruptCloseAsyncIterator);
	                else handler(result);
	              } catch (error3) { ifAbruptCloseAsyncIterator(error3); }
	            }
	          } catch (error2) { doneAndReject(error2); }
	        }, doneAndReject);
	      } catch (error) { doneAndReject(error); }
	    };
	    var innerLoop = function () {
	      var inner = state.inner;
	      if (inner) {
	        try {
	          Promise.resolve(anObject(call(inner.next, inner.iterator))).then(function (result) {
	            try {
	              if (anObject(result).done) {
	                state.inner = null;
	                outerLoop();
	              } else resolve(createIterResultObject(result.value, false));
	            } catch (error1) { ifAbruptCloseAsyncIterator(error1); }
	          }, ifAbruptCloseAsyncIterator);
	        } catch (error) { ifAbruptCloseAsyncIterator(error); }
	      } else outerLoop();
	    };
	    innerLoop();
	  });
	});
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  flatMap: function flatMap(mapper) {
	    anObject(this);
	    aCallable(mapper);
	    return new AsyncIteratorProxy(getIteratorDirect(this), {
	      mapper: mapper,
	      inner: null
	    });
	  }
	});
	return esnext_asyncIterator_flatMap;
}

var esnext_asyncIterator_forEach = {};

var hasRequiredEsnext_asyncIterator_forEach;

function requireEsnext_asyncIterator_forEach () {
	if (hasRequiredEsnext_asyncIterator_forEach) return esnext_asyncIterator_forEach;
	hasRequiredEsnext_asyncIterator_forEach = 1;
	var $ = require_export();
	var $forEach = requireAsyncIteratorIteration().forEach;
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  forEach: function forEach(fn) {
	    return $forEach(this, fn);
	  }
	});
	return esnext_asyncIterator_forEach;
}

var esnext_asyncIterator_from = {};

var asyncIteratorWrap;
var hasRequiredAsyncIteratorWrap;

function requireAsyncIteratorWrap () {
	if (hasRequiredAsyncIteratorWrap) return asyncIteratorWrap;
	hasRequiredAsyncIteratorWrap = 1;
	var call = requireFunctionCall();
	var createAsyncIteratorProxy = requireAsyncIteratorCreateProxy();
	asyncIteratorWrap = createAsyncIteratorProxy(function () {
	  return call(this.next, this.iterator);
	}, true);
	return asyncIteratorWrap;
}

var hasRequiredEsnext_asyncIterator_from;

function requireEsnext_asyncIterator_from () {
	if (hasRequiredEsnext_asyncIterator_from) return esnext_asyncIterator_from;
	hasRequiredEsnext_asyncIterator_from = 1;
	var $ = require_export();
	var toObject = requireToObject();
	var isPrototypeOf = requireObjectIsPrototypeOf();
	var getAsyncIteratorFlattenable = requireGetAsyncIteratorFlattenable();
	var AsyncIteratorPrototype = requireAsyncIteratorPrototype();
	var WrapAsyncIterator = requireAsyncIteratorWrap();
	$({ target: 'AsyncIterator', stat: true, forced: true }, {
	  from: function from(O) {
	    var iteratorRecord = getAsyncIteratorFlattenable(typeof O == 'string' ? toObject(O) : O);
	    return isPrototypeOf(AsyncIteratorPrototype, iteratorRecord.iterator)
	      ? iteratorRecord.iterator
	      : new WrapAsyncIterator(iteratorRecord);
	  }
	});
	return esnext_asyncIterator_from;
}

var esnext_asyncIterator_map = {};

var asyncIteratorMap;
var hasRequiredAsyncIteratorMap;

function requireAsyncIteratorMap () {
	if (hasRequiredAsyncIteratorMap) return asyncIteratorMap;
	hasRequiredAsyncIteratorMap = 1;
	var call = requireFunctionCall();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var isObject = requireIsObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var createAsyncIteratorProxy = requireAsyncIteratorCreateProxy();
	var createIterResultObject = requireCreateIterResultObject();
	var closeAsyncIteration = requireAsyncIteratorClose();
	var AsyncIteratorProxy = createAsyncIteratorProxy(function (Promise) {
	  var state = this;
	  var iterator = state.iterator;
	  var mapper = state.mapper;
	  return new Promise(function (resolve, reject) {
	    var doneAndReject = function (error) {
	      state.done = true;
	      reject(error);
	    };
	    var ifAbruptCloseAsyncIterator = function (error) {
	      closeAsyncIteration(iterator, doneAndReject, error, doneAndReject);
	    };
	    Promise.resolve(anObject(call(state.next, iterator))).then(function (step) {
	      try {
	        if (anObject(step).done) {
	          state.done = true;
	          resolve(createIterResultObject(undefined, true));
	        } else {
	          var value = step.value;
	          try {
	            var result = mapper(value, state.counter++);
	            var handler = function (mapped) {
	              resolve(createIterResultObject(mapped, false));
	            };
	            if (isObject(result)) Promise.resolve(result).then(handler, ifAbruptCloseAsyncIterator);
	            else handler(result);
	          } catch (error2) { ifAbruptCloseAsyncIterator(error2); }
	        }
	      } catch (error) { doneAndReject(error); }
	    }, doneAndReject);
	  });
	});
	asyncIteratorMap = function map(mapper) {
	  anObject(this);
	  aCallable(mapper);
	  return new AsyncIteratorProxy(getIteratorDirect(this), {
	    mapper: mapper
	  });
	};
	return asyncIteratorMap;
}

var hasRequiredEsnext_asyncIterator_map;

function requireEsnext_asyncIterator_map () {
	if (hasRequiredEsnext_asyncIterator_map) return esnext_asyncIterator_map;
	hasRequiredEsnext_asyncIterator_map = 1;
	var $ = require_export();
	var map = requireAsyncIteratorMap();
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  map: map
	});
	return esnext_asyncIterator_map;
}

var esnext_asyncIterator_reduce = {};

var hasRequiredEsnext_asyncIterator_reduce;

function requireEsnext_asyncIterator_reduce () {
	if (hasRequiredEsnext_asyncIterator_reduce) return esnext_asyncIterator_reduce;
	hasRequiredEsnext_asyncIterator_reduce = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var isObject = requireIsObject();
	var getBuiltIn = requireGetBuiltIn();
	var getIteratorDirect = requireGetIteratorDirect();
	var closeAsyncIteration = requireAsyncIteratorClose();
	var Promise = getBuiltIn('Promise');
	var $TypeError = TypeError;
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  reduce: function reduce(reducer ) {
	    anObject(this);
	    aCallable(reducer);
	    var record = getIteratorDirect(this);
	    var iterator = record.iterator;
	    var next = record.next;
	    var noInitial = arguments.length < 2;
	    var accumulator = noInitial ? undefined : arguments[1];
	    var counter = 0;
	    return new Promise(function (resolve, reject) {
	      var ifAbruptCloseAsyncIterator = function (error) {
	        closeAsyncIteration(iterator, reject, error, reject);
	      };
	      var loop = function () {
	        try {
	          Promise.resolve(anObject(call(next, iterator))).then(function (step) {
	            try {
	              if (anObject(step).done) {
	                noInitial ? reject(new $TypeError('Reduce of empty iterator with no initial value')) : resolve(accumulator);
	              } else {
	                var value = step.value;
	                if (noInitial) {
	                  noInitial = false;
	                  accumulator = value;
	                  loop();
	                } else try {
	                  var result = reducer(accumulator, value, counter);
	                  var handler = function ($result) {
	                    accumulator = $result;
	                    loop();
	                  };
	                  if (isObject(result)) Promise.resolve(result).then(handler, ifAbruptCloseAsyncIterator);
	                  else handler(result);
	                } catch (error3) { ifAbruptCloseAsyncIterator(error3); }
	              }
	              counter++;
	            } catch (error2) { reject(error2); }
	          }, reject);
	        } catch (error) { reject(error); }
	      };
	      loop();
	    });
	  }
	});
	return esnext_asyncIterator_reduce;
}

var esnext_asyncIterator_some = {};

var hasRequiredEsnext_asyncIterator_some;

function requireEsnext_asyncIterator_some () {
	if (hasRequiredEsnext_asyncIterator_some) return esnext_asyncIterator_some;
	hasRequiredEsnext_asyncIterator_some = 1;
	var $ = require_export();
	var $some = requireAsyncIteratorIteration().some;
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  some: function some(predicate) {
	    return $some(this, predicate);
	  }
	});
	return esnext_asyncIterator_some;
}

var esnext_asyncIterator_take = {};

var hasRequiredEsnext_asyncIterator_take;

function requireEsnext_asyncIterator_take () {
	if (hasRequiredEsnext_asyncIterator_take) return esnext_asyncIterator_take;
	hasRequiredEsnext_asyncIterator_take = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var notANaN = requireNotANan();
	var toPositiveInteger = requireToPositiveInteger();
	var createAsyncIteratorProxy = requireAsyncIteratorCreateProxy();
	var createIterResultObject = requireCreateIterResultObject();
	var AsyncIteratorProxy = createAsyncIteratorProxy(function (Promise) {
	  var state = this;
	  var iterator = state.iterator;
	  var returnMethod;
	  if (!state.remaining--) {
	    var resultDone = createIterResultObject(undefined, true);
	    state.done = true;
	    returnMethod = iterator['return'];
	    if (returnMethod !== undefined) {
	      return Promise.resolve(call(returnMethod, iterator, undefined)).then(function () {
	        return resultDone;
	      });
	    }
	    return resultDone;
	  } return Promise.resolve(call(state.next, iterator)).then(function (step) {
	    if (anObject(step).done) {
	      state.done = true;
	      return createIterResultObject(undefined, true);
	    } return createIterResultObject(step.value, false);
	  }).then(null, function (error) {
	    state.done = true;
	    throw error;
	  });
	});
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  take: function take(limit) {
	    anObject(this);
	    var remaining = toPositiveInteger(notANaN(+limit));
	    return new AsyncIteratorProxy(getIteratorDirect(this), {
	      remaining: remaining
	    });
	  }
	});
	return esnext_asyncIterator_take;
}

var esnext_asyncIterator_toArray = {};

var hasRequiredEsnext_asyncIterator_toArray;

function requireEsnext_asyncIterator_toArray () {
	if (hasRequiredEsnext_asyncIterator_toArray) return esnext_asyncIterator_toArray;
	hasRequiredEsnext_asyncIterator_toArray = 1;
	var $ = require_export();
	var $toArray = requireAsyncIteratorIteration().toArray;
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  toArray: function toArray() {
	    return $toArray(this, undefined, []);
	  }
	});
	return esnext_asyncIterator_toArray;
}

var esnext_iterator_constructor = {};

var es_iterator_constructor = {};

var defineBuiltInAccessor;
var hasRequiredDefineBuiltInAccessor;

function requireDefineBuiltInAccessor () {
	if (hasRequiredDefineBuiltInAccessor) return defineBuiltInAccessor;
	hasRequiredDefineBuiltInAccessor = 1;
	var makeBuiltIn = requireMakeBuiltIn();
	var defineProperty = requireObjectDefineProperty();
	defineBuiltInAccessor = function (target, name, descriptor) {
	  if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
	  if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
	  return defineProperty.f(target, name, descriptor);
	};
	return defineBuiltInAccessor;
}

var iteratorsCore;
var hasRequiredIteratorsCore;

function requireIteratorsCore () {
	if (hasRequiredIteratorsCore) return iteratorsCore;
	hasRequiredIteratorsCore = 1;
	var fails = requireFails();
	var isCallable = requireIsCallable();
	var isObject = requireIsObject();
	var create = requireObjectCreate();
	var getPrototypeOf = requireObjectGetPrototypeOf();
	var defineBuiltIn = requireDefineBuiltIn();
	var wellKnownSymbol = requireWellKnownSymbol();
	var IS_PURE = requireIsPure();
	var ITERATOR = wellKnownSymbol('iterator');
	var BUGGY_SAFARI_ITERATORS = false;
	var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
	if ([].keys) {
	  arrayIterator = [].keys();
	  if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
	  else {
	    PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
	    if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
	  }
	}
	var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () {
	  var test = {};
	  return IteratorPrototype[ITERATOR].call(test) !== test;
	});
	if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
	else if (IS_PURE) IteratorPrototype = create(IteratorPrototype);
	if (!isCallable(IteratorPrototype[ITERATOR])) {
	  defineBuiltIn(IteratorPrototype, ITERATOR, function () {
	    return this;
	  });
	}
	iteratorsCore = {
	  IteratorPrototype: IteratorPrototype,
	  BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
	};
	return iteratorsCore;
}

var hasRequiredEs_iterator_constructor;

function requireEs_iterator_constructor () {
	if (hasRequiredEs_iterator_constructor) return es_iterator_constructor;
	hasRequiredEs_iterator_constructor = 1;
	var $ = require_export();
	var globalThis = requireGlobalThis();
	var anInstance = requireAnInstance();
	var anObject = requireAnObject();
	var isCallable = requireIsCallable();
	var getPrototypeOf = requireObjectGetPrototypeOf();
	var defineBuiltInAccessor = requireDefineBuiltInAccessor();
	var createProperty = requireCreateProperty();
	var fails = requireFails();
	var hasOwn = requireHasOwnProperty();
	var wellKnownSymbol = requireWellKnownSymbol();
	var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
	var DESCRIPTORS = requireDescriptors();
	var IS_PURE = requireIsPure();
	var CONSTRUCTOR = 'constructor';
	var ITERATOR = 'Iterator';
	var TO_STRING_TAG = wellKnownSymbol('toStringTag');
	var $TypeError = TypeError;
	var NativeIterator = globalThis[ITERATOR];
	var FORCED = IS_PURE
	  || !isCallable(NativeIterator)
	  || NativeIterator.prototype !== IteratorPrototype
	  || !fails(function () { NativeIterator({}); });
	var IteratorConstructor = function Iterator() {
	  anInstance(this, IteratorPrototype);
	  if (getPrototypeOf(this) === IteratorPrototype) throw new $TypeError('Abstract class Iterator not directly constructable');
	};
	var defineIteratorPrototypeAccessor = function (key, value) {
	  if (DESCRIPTORS) {
	    defineBuiltInAccessor(IteratorPrototype, key, {
	      configurable: true,
	      get: function () {
	        return value;
	      },
	      set: function (replacement) {
	        anObject(this);
	        if (this === IteratorPrototype) throw new $TypeError("You can't redefine this property");
	        if (hasOwn(this, key)) this[key] = replacement;
	        else createProperty(this, key, replacement);
	      }
	    });
	  } else IteratorPrototype[key] = value;
	};
	if (!hasOwn(IteratorPrototype, TO_STRING_TAG)) defineIteratorPrototypeAccessor(TO_STRING_TAG, ITERATOR);
	if (FORCED || !hasOwn(IteratorPrototype, CONSTRUCTOR) || IteratorPrototype[CONSTRUCTOR] === Object) {
	  defineIteratorPrototypeAccessor(CONSTRUCTOR, IteratorConstructor);
	}
	IteratorConstructor.prototype = IteratorPrototype;
	$({ global: true, constructor: true, forced: FORCED }, {
	  Iterator: IteratorConstructor
	});
	return es_iterator_constructor;
}

var hasRequiredEsnext_iterator_constructor;

function requireEsnext_iterator_constructor () {
	if (hasRequiredEsnext_iterator_constructor) return esnext_iterator_constructor;
	hasRequiredEsnext_iterator_constructor = 1;
	requireEs_iterator_constructor();
	return esnext_iterator_constructor;
}

var esnext_iterator_drop = {};

var es_iterator_drop = {};

var iteratorCloseAll;
var hasRequiredIteratorCloseAll;

function requireIteratorCloseAll () {
	if (hasRequiredIteratorCloseAll) return iteratorCloseAll;
	hasRequiredIteratorCloseAll = 1;
	var iteratorClose = requireIteratorClose();
	iteratorCloseAll = function (iters, kind, value) {
	  for (var i = iters.length - 1; i >= 0; i--) {
	    if (iters[i] === undefined) continue;
	    try {
	      value = iteratorClose(iters[i].iterator, kind, value);
	    } catch (error) {
	      kind = 'throw';
	      value = error;
	    }
	  }
	  if (kind === 'throw') throw value;
	  return value;
	};
	return iteratorCloseAll;
}

var iteratorCreateProxy;
var hasRequiredIteratorCreateProxy;

function requireIteratorCreateProxy () {
	if (hasRequiredIteratorCreateProxy) return iteratorCreateProxy;
	hasRequiredIteratorCreateProxy = 1;
	var call = requireFunctionCall();
	var create = requireObjectCreate();
	var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
	var defineBuiltIns = requireDefineBuiltIns();
	var wellKnownSymbol = requireWellKnownSymbol();
	var InternalStateModule = requireInternalState();
	var getMethod = requireGetMethod();
	var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
	var createIterResultObject = requireCreateIterResultObject();
	var iteratorClose = requireIteratorClose();
	var iteratorCloseAll = requireIteratorCloseAll();
	var TO_STRING_TAG = wellKnownSymbol('toStringTag');
	var ITERATOR_HELPER = 'IteratorHelper';
	var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator';
	var NORMAL = 'normal';
	var THROW = 'throw';
	var setInternalState = InternalStateModule.set;
	var createIteratorProxyPrototype = function (IS_ITERATOR) {
	  var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER);
	  return defineBuiltIns(create(IteratorPrototype), {
	    next: function next() {
	      var state = getInternalState(this);
	      if (IS_ITERATOR) return state.nextHandler();
	      if (state.done) return createIterResultObject(undefined, true);
	      try {
	        var result = state.nextHandler();
	        return state.returnHandlerResult ? result : createIterResultObject(result, state.done);
	      } catch (error) {
	        state.done = true;
	        throw error;
	      }
	    },
	    'return': function () {
	      var state = getInternalState(this);
	      var iterator = state.iterator;
	      state.done = true;
	      if (IS_ITERATOR) {
	        var returnMethod = getMethod(iterator, 'return');
	        return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true);
	      }
	      if (state.inner) try {
	        iteratorClose(state.inner.iterator, NORMAL);
	      } catch (error) {
	        return iteratorClose(iterator, THROW, error);
	      }
	      if (state.openIters) try {
	        iteratorCloseAll(state.openIters, NORMAL);
	      } catch (error) {
	        return iteratorClose(iterator, THROW, error);
	      }
	      if (iterator) iteratorClose(iterator, NORMAL);
	      return createIterResultObject(undefined, true);
	    }
	  });
	};
	var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true);
	var IteratorHelperPrototype = createIteratorProxyPrototype(false);
	createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper');
	iteratorCreateProxy = function (nextHandler, IS_ITERATOR, RETURN_HANDLER_RESULT) {
	  var IteratorProxy = function Iterator(record, state) {
	    if (state) {
	      state.iterator = record.iterator;
	      state.next = record.next;
	    } else state = record;
	    state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER;
	    state.returnHandlerResult = !!RETURN_HANDLER_RESULT;
	    state.nextHandler = nextHandler;
	    state.counter = 0;
	    state.done = false;
	    setInternalState(this, state);
	  };
	  IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype;
	  return IteratorProxy;
	};
	return iteratorCreateProxy;
}

var iteratorHelperThrowsOnInvalidIterator;
var hasRequiredIteratorHelperThrowsOnInvalidIterator;

function requireIteratorHelperThrowsOnInvalidIterator () {
	if (hasRequiredIteratorHelperThrowsOnInvalidIterator) return iteratorHelperThrowsOnInvalidIterator;
	hasRequiredIteratorHelperThrowsOnInvalidIterator = 1;
	iteratorHelperThrowsOnInvalidIterator = function (methodName, argument) {
	  var method = typeof Iterator == 'function' && Iterator.prototype[methodName];
	  if (method) try {
	    method.call({ next: null }, argument).next();
	  } catch (error) {
	    return true;
	  }
	};
	return iteratorHelperThrowsOnInvalidIterator;
}

var iteratorHelperWithoutClosingOnEarlyError;
var hasRequiredIteratorHelperWithoutClosingOnEarlyError;

function requireIteratorHelperWithoutClosingOnEarlyError () {
	if (hasRequiredIteratorHelperWithoutClosingOnEarlyError) return iteratorHelperWithoutClosingOnEarlyError;
	hasRequiredIteratorHelperWithoutClosingOnEarlyError = 1;
	var globalThis = requireGlobalThis();
	iteratorHelperWithoutClosingOnEarlyError = function (METHOD_NAME, ExpectedError) {
	  var Iterator = globalThis.Iterator;
	  var IteratorPrototype = Iterator && Iterator.prototype;
	  var method = IteratorPrototype && IteratorPrototype[METHOD_NAME];
	  var CLOSED = false;
	  if (method) try {
	    method.call({
	      next: function () { return { done: true }; },
	      'return': function () { CLOSED = true; }
	    }, -1);
	  } catch (error) {
	    if (!(error instanceof ExpectedError)) CLOSED = false;
	  }
	  if (!CLOSED) return method;
	};
	return iteratorHelperWithoutClosingOnEarlyError;
}

var hasRequiredEs_iterator_drop;

function requireEs_iterator_drop () {
	if (hasRequiredEs_iterator_drop) return es_iterator_drop;
	hasRequiredEs_iterator_drop = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var notANaN = requireNotANan();
	var toPositiveInteger = requireToPositiveInteger();
	var iteratorClose = requireIteratorClose();
	var createIteratorProxy = requireIteratorCreateProxy();
	var iteratorHelperThrowsOnInvalidIterator = requireIteratorHelperThrowsOnInvalidIterator();
	var iteratorHelperWithoutClosingOnEarlyError = requireIteratorHelperWithoutClosingOnEarlyError();
	var IS_PURE = requireIsPure();
	var DROP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator('drop', 0);
	var dropWithoutClosingOnEarlyError = !IS_PURE && !DROP_WITHOUT_THROWING_ON_INVALID_ITERATOR
	  && iteratorHelperWithoutClosingOnEarlyError('drop', RangeError);
	var FORCED = IS_PURE || DROP_WITHOUT_THROWING_ON_INVALID_ITERATOR || dropWithoutClosingOnEarlyError;
	var IteratorProxy = createIteratorProxy(function () {
	  var iterator = this.iterator;
	  var next = this.next;
	  var result, done;
	  while (this.remaining) {
	    this.remaining--;
	    result = anObject(call(next, iterator));
	    done = this.done = !!result.done;
	    if (done) return;
	  }
	  result = anObject(call(next, iterator));
	  done = this.done = !!result.done;
	  if (!done) return result.value;
	});
	$({ target: 'Iterator', proto: true, real: true, forced: FORCED }, {
	  drop: function drop(limit) {
	    anObject(this);
	    var remaining;
	    try {
	      remaining = toPositiveInteger(notANaN(+limit));
	    } catch (error) {
	      iteratorClose(this, 'throw', error);
	    }
	    if (dropWithoutClosingOnEarlyError) return call(dropWithoutClosingOnEarlyError, this, remaining);
	    return new IteratorProxy(getIteratorDirect(this), {
	      remaining: remaining
	    });
	  }
	});
	return es_iterator_drop;
}

var hasRequiredEsnext_iterator_drop;

function requireEsnext_iterator_drop () {
	if (hasRequiredEsnext_iterator_drop) return esnext_iterator_drop;
	hasRequiredEsnext_iterator_drop = 1;
	requireEs_iterator_drop();
	return esnext_iterator_drop;
}

var esnext_iterator_every = {};

var es_iterator_every = {};

var functionUncurryThisClause;
var hasRequiredFunctionUncurryThisClause;

function requireFunctionUncurryThisClause () {
	if (hasRequiredFunctionUncurryThisClause) return functionUncurryThisClause;
	hasRequiredFunctionUncurryThisClause = 1;
	var classofRaw = requireClassofRaw();
	var uncurryThis = requireFunctionUncurryThis();
	functionUncurryThisClause = function (fn) {
	  if (classofRaw(fn) === 'Function') return uncurryThis(fn);
	};
	return functionUncurryThisClause;
}

var functionBindContext;
var hasRequiredFunctionBindContext;

function requireFunctionBindContext () {
	if (hasRequiredFunctionBindContext) return functionBindContext;
	hasRequiredFunctionBindContext = 1;
	var uncurryThis = requireFunctionUncurryThisClause();
	var aCallable = requireACallable();
	var NATIVE_BIND = requireFunctionBindNative();
	var bind = uncurryThis(uncurryThis.bind);
	functionBindContext = function (fn, that) {
	  aCallable(fn);
	  return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function () {
	    return fn.apply(that, arguments);
	  };
	};
	return functionBindContext;
}

var isArrayIteratorMethod;
var hasRequiredIsArrayIteratorMethod;

function requireIsArrayIteratorMethod () {
	if (hasRequiredIsArrayIteratorMethod) return isArrayIteratorMethod;
	hasRequiredIsArrayIteratorMethod = 1;
	var wellKnownSymbol = requireWellKnownSymbol();
	var Iterators = requireIterators();
	var ITERATOR = wellKnownSymbol('iterator');
	var ArrayPrototype = Array.prototype;
	isArrayIteratorMethod = function (it) {
	  return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
	};
	return isArrayIteratorMethod;
}

var getIterator;
var hasRequiredGetIterator;

function requireGetIterator () {
	if (hasRequiredGetIterator) return getIterator;
	hasRequiredGetIterator = 1;
	var call = requireFunctionCall();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var tryToString = requireTryToString();
	var getIteratorMethod = requireGetIteratorMethod();
	var $TypeError = TypeError;
	getIterator = function (argument, usingIterator) {
	  var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
	  if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));
	  throw new $TypeError(tryToString(argument) + ' is not iterable');
	};
	return getIterator;
}

var iterate;
var hasRequiredIterate;

function requireIterate () {
	if (hasRequiredIterate) return iterate;
	hasRequiredIterate = 1;
	var bind = requireFunctionBindContext();
	var call = requireFunctionCall();
	var anObject = requireAnObject();
	var tryToString = requireTryToString();
	var isArrayIteratorMethod = requireIsArrayIteratorMethod();
	var lengthOfArrayLike = requireLengthOfArrayLike();
	var isPrototypeOf = requireObjectIsPrototypeOf();
	var getIterator = requireGetIterator();
	var getIteratorMethod = requireGetIteratorMethod();
	var iteratorClose = requireIteratorClose();
	var $TypeError = TypeError;
	var Result = function (stopped, result) {
	  this.stopped = stopped;
	  this.result = result;
	};
	var ResultPrototype = Result.prototype;
	iterate = function (iterable, unboundFunction, options) {
	  var that = options && options.that;
	  var AS_ENTRIES = !!(options && options.AS_ENTRIES);
	  var IS_RECORD = !!(options && options.IS_RECORD);
	  var IS_ITERATOR = !!(options && options.IS_ITERATOR);
	  var INTERRUPTED = !!(options && options.INTERRUPTED);
	  var fn = bind(unboundFunction, that);
	  var iterator, iterFn, index, length, result, next, step;
	  var stop = function (condition) {
	    if (iterator) iteratorClose(iterator, 'normal');
	    return new Result(true, condition);
	  };
	  var callFn = function (value) {
	    if (AS_ENTRIES) {
	      anObject(value);
	      return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
	    } return INTERRUPTED ? fn(value, stop) : fn(value);
	  };
	  if (IS_RECORD) {
	    iterator = iterable.iterator;
	  } else if (IS_ITERATOR) {
	    iterator = iterable;
	  } else {
	    iterFn = getIteratorMethod(iterable);
	    if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable');
	    if (isArrayIteratorMethod(iterFn)) {
	      for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
	        result = callFn(iterable[index]);
	        if (result && isPrototypeOf(ResultPrototype, result)) return result;
	      } return new Result(false);
	    }
	    iterator = getIterator(iterable, iterFn);
	  }
	  next = IS_RECORD ? iterable.next : iterator.next;
	  while (!(step = call(next, iterator)).done) {
	    try {
	      result = callFn(step.value);
	    } catch (error) {
	      iteratorClose(iterator, 'throw', error);
	    }
	    if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
	  } return new Result(false);
	};
	return iterate;
}

var hasRequiredEs_iterator_every;

function requireEs_iterator_every () {
	if (hasRequiredEs_iterator_every) return es_iterator_every;
	hasRequiredEs_iterator_every = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var iterate = requireIterate();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var iteratorClose = requireIteratorClose();
	var iteratorHelperWithoutClosingOnEarlyError = requireIteratorHelperWithoutClosingOnEarlyError();
	var everyWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('every', TypeError);
	$({ target: 'Iterator', proto: true, real: true, forced: everyWithoutClosingOnEarlyError }, {
	  every: function every(predicate) {
	    anObject(this);
	    try {
	      aCallable(predicate);
	    } catch (error) {
	      iteratorClose(this, 'throw', error);
	    }
	    if (everyWithoutClosingOnEarlyError) return call(everyWithoutClosingOnEarlyError, this, predicate);
	    var record = getIteratorDirect(this);
	    var counter = 0;
	    return !iterate(record, function (value, stop) {
	      if (!predicate(value, counter++)) return stop();
	    }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
	  }
	});
	return es_iterator_every;
}

var hasRequiredEsnext_iterator_every;

function requireEsnext_iterator_every () {
	if (hasRequiredEsnext_iterator_every) return esnext_iterator_every;
	hasRequiredEsnext_iterator_every = 1;
	requireEs_iterator_every();
	return esnext_iterator_every;
}

var esnext_iterator_filter = {};

var es_iterator_filter = {};

var callWithSafeIterationClosing;
var hasRequiredCallWithSafeIterationClosing;

function requireCallWithSafeIterationClosing () {
	if (hasRequiredCallWithSafeIterationClosing) return callWithSafeIterationClosing;
	hasRequiredCallWithSafeIterationClosing = 1;
	var anObject = requireAnObject();
	var iteratorClose = requireIteratorClose();
	callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) {
	  try {
	    return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
	  } catch (error) {
	    iteratorClose(iterator, 'throw', error);
	  }
	};
	return callWithSafeIterationClosing;
}

var hasRequiredEs_iterator_filter;

function requireEs_iterator_filter () {
	if (hasRequiredEs_iterator_filter) return es_iterator_filter;
	hasRequiredEs_iterator_filter = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var createIteratorProxy = requireIteratorCreateProxy();
	var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
	var IS_PURE = requireIsPure();
	var iteratorClose = requireIteratorClose();
	var iteratorHelperThrowsOnInvalidIterator = requireIteratorHelperThrowsOnInvalidIterator();
	var iteratorHelperWithoutClosingOnEarlyError = requireIteratorHelperWithoutClosingOnEarlyError();
	var FILTER_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator('filter', function () {  });
	var filterWithoutClosingOnEarlyError = !IS_PURE && !FILTER_WITHOUT_THROWING_ON_INVALID_ITERATOR
	  && iteratorHelperWithoutClosingOnEarlyError('filter', TypeError);
	var FORCED = IS_PURE || FILTER_WITHOUT_THROWING_ON_INVALID_ITERATOR || filterWithoutClosingOnEarlyError;
	var IteratorProxy = createIteratorProxy(function () {
	  var iterator = this.iterator;
	  var predicate = this.predicate;
	  var next = this.next;
	  var result, done, value;
	  while (true) {
	    result = anObject(call(next, iterator));
	    done = this.done = !!result.done;
	    if (done) return;
	    value = result.value;
	    if (callWithSafeIterationClosing(iterator, predicate, [value, this.counter++], true)) return value;
	  }
	});
	$({ target: 'Iterator', proto: true, real: true, forced: FORCED }, {
	  filter: function filter(predicate) {
	    anObject(this);
	    try {
	      aCallable(predicate);
	    } catch (error) {
	      iteratorClose(this, 'throw', error);
	    }
	    if (filterWithoutClosingOnEarlyError) return call(filterWithoutClosingOnEarlyError, this, predicate);
	    return new IteratorProxy(getIteratorDirect(this), {
	      predicate: predicate
	    });
	  }
	});
	return es_iterator_filter;
}

var hasRequiredEsnext_iterator_filter;

function requireEsnext_iterator_filter () {
	if (hasRequiredEsnext_iterator_filter) return esnext_iterator_filter;
	hasRequiredEsnext_iterator_filter = 1;
	requireEs_iterator_filter();
	return esnext_iterator_filter;
}

var esnext_iterator_find = {};

var es_iterator_find = {};

var hasRequiredEs_iterator_find;

function requireEs_iterator_find () {
	if (hasRequiredEs_iterator_find) return es_iterator_find;
	hasRequiredEs_iterator_find = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var iterate = requireIterate();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var iteratorClose = requireIteratorClose();
	var iteratorHelperWithoutClosingOnEarlyError = requireIteratorHelperWithoutClosingOnEarlyError();
	var findWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('find', TypeError);
	$({ target: 'Iterator', proto: true, real: true, forced: findWithoutClosingOnEarlyError }, {
	  find: function find(predicate) {
	    anObject(this);
	    try {
	      aCallable(predicate);
	    } catch (error) {
	      iteratorClose(this, 'throw', error);
	    }
	    if (findWithoutClosingOnEarlyError) return call(findWithoutClosingOnEarlyError, this, predicate);
	    var record = getIteratorDirect(this);
	    var counter = 0;
	    return iterate(record, function (value, stop) {
	      if (predicate(value, counter++)) return stop(value);
	    }, { IS_RECORD: true, INTERRUPTED: true }).result;
	  }
	});
	return es_iterator_find;
}

var hasRequiredEsnext_iterator_find;

function requireEsnext_iterator_find () {
	if (hasRequiredEsnext_iterator_find) return esnext_iterator_find;
	hasRequiredEsnext_iterator_find = 1;
	requireEs_iterator_find();
	return esnext_iterator_find;
}

var esnext_iterator_flatMap = {};

var es_iterator_flatMap = {};

var getIteratorFlattenable;
var hasRequiredGetIteratorFlattenable;

function requireGetIteratorFlattenable () {
	if (hasRequiredGetIteratorFlattenable) return getIteratorFlattenable;
	hasRequiredGetIteratorFlattenable = 1;
	var call = requireFunctionCall();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var getIteratorMethod = requireGetIteratorMethod();
	getIteratorFlattenable = function (obj, stringHandling) {
	  if (!stringHandling || typeof obj !== 'string') anObject(obj);
	  var method = getIteratorMethod(obj);
	  return getIteratorDirect(anObject(method !== undefined ? call(method, obj) : obj));
	};
	return getIteratorFlattenable;
}

var hasRequiredEs_iterator_flatMap;

function requireEs_iterator_flatMap () {
	if (hasRequiredEs_iterator_flatMap) return es_iterator_flatMap;
	hasRequiredEs_iterator_flatMap = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var getIteratorFlattenable = requireGetIteratorFlattenable();
	var createIteratorProxy = requireIteratorCreateProxy();
	var iteratorClose = requireIteratorClose();
	var IS_PURE = requireIsPure();
	var iteratorHelperThrowsOnInvalidIterator = requireIteratorHelperThrowsOnInvalidIterator();
	var iteratorHelperWithoutClosingOnEarlyError = requireIteratorHelperWithoutClosingOnEarlyError();
	function throwsOnIteratorWithoutReturn() {
	  try {
	    var it = Iterator.prototype.flatMap.call(new Map([[4, 5]]).entries(), function (v) { return v; });
	    it.next();
	    it['return']();
	  } catch (error) {
	    return true;
	  }
	}
	var FLAT_MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE
	  && !iteratorHelperThrowsOnInvalidIterator('flatMap', function () {  });
	var flatMapWithoutClosingOnEarlyError = !IS_PURE && !FLAT_MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR
	  && iteratorHelperWithoutClosingOnEarlyError('flatMap', TypeError);
	var FORCED = IS_PURE || FLAT_MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR || flatMapWithoutClosingOnEarlyError
	  || throwsOnIteratorWithoutReturn();
	var IteratorProxy = createIteratorProxy(function () {
	  var iterator = this.iterator;
	  var mapper = this.mapper;
	  var result, inner;
	  while (true) {
	    if (inner = this.inner) try {
	      result = anObject(call(inner.next, inner.iterator));
	      if (!result.done) return result.value;
	      this.inner = null;
	    } catch (error) { iteratorClose(iterator, 'throw', error); }
	    result = anObject(call(this.next, iterator));
	    if (this.done = !!result.done) return;
	    try {
	      this.inner = getIteratorFlattenable(mapper(result.value, this.counter++), false);
	    } catch (error) { iteratorClose(iterator, 'throw', error); }
	  }
	});
	$({ target: 'Iterator', proto: true, real: true, forced: FORCED }, {
	  flatMap: function flatMap(mapper) {
	    anObject(this);
	    try {
	      aCallable(mapper);
	    } catch (error) {
	      iteratorClose(this, 'throw', error);
	    }
	    if (flatMapWithoutClosingOnEarlyError) return call(flatMapWithoutClosingOnEarlyError, this, mapper);
	    return new IteratorProxy(getIteratorDirect(this), {
	      mapper: mapper,
	      inner: null
	    });
	  }
	});
	return es_iterator_flatMap;
}

var hasRequiredEsnext_iterator_flatMap;

function requireEsnext_iterator_flatMap () {
	if (hasRequiredEsnext_iterator_flatMap) return esnext_iterator_flatMap;
	hasRequiredEsnext_iterator_flatMap = 1;
	requireEs_iterator_flatMap();
	return esnext_iterator_flatMap;
}

var esnext_iterator_forEach = {};

var es_iterator_forEach = {};

var hasRequiredEs_iterator_forEach;

function requireEs_iterator_forEach () {
	if (hasRequiredEs_iterator_forEach) return es_iterator_forEach;
	hasRequiredEs_iterator_forEach = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var iterate = requireIterate();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var iteratorClose = requireIteratorClose();
	var iteratorHelperWithoutClosingOnEarlyError = requireIteratorHelperWithoutClosingOnEarlyError();
	var forEachWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('forEach', TypeError);
	$({ target: 'Iterator', proto: true, real: true, forced: forEachWithoutClosingOnEarlyError }, {
	  forEach: function forEach(fn) {
	    anObject(this);
	    try {
	      aCallable(fn);
	    } catch (error) {
	      iteratorClose(this, 'throw', error);
	    }
	    if (forEachWithoutClosingOnEarlyError) return call(forEachWithoutClosingOnEarlyError, this, fn);
	    var record = getIteratorDirect(this);
	    var counter = 0;
	    iterate(record, function (value) {
	      fn(value, counter++);
	    }, { IS_RECORD: true });
	  }
	});
	return es_iterator_forEach;
}

var hasRequiredEsnext_iterator_forEach;

function requireEsnext_iterator_forEach () {
	if (hasRequiredEsnext_iterator_forEach) return esnext_iterator_forEach;
	hasRequiredEsnext_iterator_forEach = 1;
	requireEs_iterator_forEach();
	return esnext_iterator_forEach;
}

var esnext_iterator_from = {};

var es_iterator_from = {};

var hasRequiredEs_iterator_from;

function requireEs_iterator_from () {
	if (hasRequiredEs_iterator_from) return es_iterator_from;
	hasRequiredEs_iterator_from = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var toObject = requireToObject();
	var isPrototypeOf = requireObjectIsPrototypeOf();
	var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
	var createIteratorProxy = requireIteratorCreateProxy();
	var getIteratorFlattenable = requireGetIteratorFlattenable();
	var IS_PURE = requireIsPure();
	var FORCED = IS_PURE || function () {
	  try {
	    Iterator.from({ 'return': null })['return']();
	  } catch (error) {
	    return true;
	  }
	}();
	var IteratorProxy = createIteratorProxy(function () {
	  return call(this.next, this.iterator);
	}, true);
	$({ target: 'Iterator', stat: true, forced: FORCED }, {
	  from: function from(O) {
	    var iteratorRecord = getIteratorFlattenable(typeof O == 'string' ? toObject(O) : O, true);
	    return isPrototypeOf(IteratorPrototype, iteratorRecord.iterator)
	      ? iteratorRecord.iterator
	      : new IteratorProxy(iteratorRecord);
	  }
	});
	return es_iterator_from;
}

var hasRequiredEsnext_iterator_from;

function requireEsnext_iterator_from () {
	if (hasRequiredEsnext_iterator_from) return esnext_iterator_from;
	hasRequiredEsnext_iterator_from = 1;
	requireEs_iterator_from();
	return esnext_iterator_from;
}

var esnext_iterator_map = {};

var es_iterator_map = {};

var hasRequiredEs_iterator_map;

function requireEs_iterator_map () {
	if (hasRequiredEs_iterator_map) return es_iterator_map;
	hasRequiredEs_iterator_map = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var createIteratorProxy = requireIteratorCreateProxy();
	var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
	var iteratorClose = requireIteratorClose();
	var iteratorHelperThrowsOnInvalidIterator = requireIteratorHelperThrowsOnInvalidIterator();
	var iteratorHelperWithoutClosingOnEarlyError = requireIteratorHelperWithoutClosingOnEarlyError();
	var IS_PURE = requireIsPure();
	var MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR = !IS_PURE && !iteratorHelperThrowsOnInvalidIterator('map', function () {  });
	var mapWithoutClosingOnEarlyError = !IS_PURE && !MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR
	  && iteratorHelperWithoutClosingOnEarlyError('map', TypeError);
	var FORCED = IS_PURE || MAP_WITHOUT_THROWING_ON_INVALID_ITERATOR || mapWithoutClosingOnEarlyError;
	var IteratorProxy = createIteratorProxy(function () {
	  var iterator = this.iterator;
	  var result = anObject(call(this.next, iterator));
	  var done = this.done = !!result.done;
	  if (!done) return callWithSafeIterationClosing(iterator, this.mapper, [result.value, this.counter++], true);
	});
	$({ target: 'Iterator', proto: true, real: true, forced: FORCED }, {
	  map: function map(mapper) {
	    anObject(this);
	    try {
	      aCallable(mapper);
	    } catch (error) {
	      iteratorClose(this, 'throw', error);
	    }
	    if (mapWithoutClosingOnEarlyError) return call(mapWithoutClosingOnEarlyError, this, mapper);
	    return new IteratorProxy(getIteratorDirect(this), {
	      mapper: mapper
	    });
	  }
	});
	return es_iterator_map;
}

var hasRequiredEsnext_iterator_map;

function requireEsnext_iterator_map () {
	if (hasRequiredEsnext_iterator_map) return esnext_iterator_map;
	hasRequiredEsnext_iterator_map = 1;
	requireEs_iterator_map();
	return esnext_iterator_map;
}

var esnext_iterator_reduce = {};

var es_iterator_reduce = {};

var functionApply;
var hasRequiredFunctionApply;

function requireFunctionApply () {
	if (hasRequiredFunctionApply) return functionApply;
	hasRequiredFunctionApply = 1;
	var NATIVE_BIND = requireFunctionBindNative();
	var FunctionPrototype = Function.prototype;
	var apply = FunctionPrototype.apply;
	var call = FunctionPrototype.call;
	functionApply = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () {
	  return call.apply(apply, arguments);
	});
	return functionApply;
}

var hasRequiredEs_iterator_reduce;

function requireEs_iterator_reduce () {
	if (hasRequiredEs_iterator_reduce) return es_iterator_reduce;
	hasRequiredEs_iterator_reduce = 1;
	var $ = require_export();
	var iterate = requireIterate();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var iteratorClose = requireIteratorClose();
	var iteratorHelperWithoutClosingOnEarlyError = requireIteratorHelperWithoutClosingOnEarlyError();
	var apply = requireFunctionApply();
	var fails = requireFails();
	var $TypeError = TypeError;
	var FAILS_ON_INITIAL_UNDEFINED = fails(function () {
	  [].keys().reduce(function () {  }, undefined);
	});
	var reduceWithoutClosingOnEarlyError = !FAILS_ON_INITIAL_UNDEFINED && iteratorHelperWithoutClosingOnEarlyError('reduce', $TypeError);
	$({ target: 'Iterator', proto: true, real: true, forced: FAILS_ON_INITIAL_UNDEFINED || reduceWithoutClosingOnEarlyError }, {
	  reduce: function reduce(reducer ) {
	    anObject(this);
	    try {
	      aCallable(reducer);
	    } catch (error) {
	      iteratorClose(this, 'throw', error);
	    }
	    var noInitial = arguments.length < 2;
	    var accumulator = noInitial ? undefined : arguments[1];
	    if (reduceWithoutClosingOnEarlyError) {
	      return apply(reduceWithoutClosingOnEarlyError, this, noInitial ? [reducer] : [reducer, accumulator]);
	    }
	    var record = getIteratorDirect(this);
	    var counter = 0;
	    iterate(record, function (value) {
	      if (noInitial) {
	        noInitial = false;
	        accumulator = value;
	      } else {
	        accumulator = reducer(accumulator, value, counter);
	      }
	      counter++;
	    }, { IS_RECORD: true });
	    if (noInitial) throw new $TypeError('Reduce of empty iterator with no initial value');
	    return accumulator;
	  }
	});
	return es_iterator_reduce;
}

var hasRequiredEsnext_iterator_reduce;

function requireEsnext_iterator_reduce () {
	if (hasRequiredEsnext_iterator_reduce) return esnext_iterator_reduce;
	hasRequiredEsnext_iterator_reduce = 1;
	requireEs_iterator_reduce();
	return esnext_iterator_reduce;
}

var esnext_iterator_some = {};

var es_iterator_some = {};

var hasRequiredEs_iterator_some;

function requireEs_iterator_some () {
	if (hasRequiredEs_iterator_some) return es_iterator_some;
	hasRequiredEs_iterator_some = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var iterate = requireIterate();
	var aCallable = requireACallable();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var iteratorClose = requireIteratorClose();
	var iteratorHelperWithoutClosingOnEarlyError = requireIteratorHelperWithoutClosingOnEarlyError();
	var someWithoutClosingOnEarlyError = iteratorHelperWithoutClosingOnEarlyError('some', TypeError);
	$({ target: 'Iterator', proto: true, real: true, forced: someWithoutClosingOnEarlyError }, {
	  some: function some(predicate) {
	    anObject(this);
	    try {
	      aCallable(predicate);
	    } catch (error) {
	      iteratorClose(this, 'throw', error);
	    }
	    if (someWithoutClosingOnEarlyError) return call(someWithoutClosingOnEarlyError, this, predicate);
	    var record = getIteratorDirect(this);
	    var counter = 0;
	    return iterate(record, function (value, stop) {
	      if (predicate(value, counter++)) return stop();
	    }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
	  }
	});
	return es_iterator_some;
}

var hasRequiredEsnext_iterator_some;

function requireEsnext_iterator_some () {
	if (hasRequiredEsnext_iterator_some) return esnext_iterator_some;
	hasRequiredEsnext_iterator_some = 1;
	requireEs_iterator_some();
	return esnext_iterator_some;
}

var esnext_iterator_take = {};

var es_iterator_take = {};

var hasRequiredEs_iterator_take;

function requireEs_iterator_take () {
	if (hasRequiredEs_iterator_take) return es_iterator_take;
	hasRequiredEs_iterator_take = 1;
	var $ = require_export();
	var call = requireFunctionCall();
	var anObject = requireAnObject();
	var getIteratorDirect = requireGetIteratorDirect();
	var notANaN = requireNotANan();
	var toPositiveInteger = requireToPositiveInteger();
	var createIteratorProxy = requireIteratorCreateProxy();
	var iteratorClose = requireIteratorClose();
	var iteratorHelperWithoutClosingOnEarlyError = requireIteratorHelperWithoutClosingOnEarlyError();
	var IS_PURE = requireIsPure();
	var takeWithoutClosingOnEarlyError = !IS_PURE && iteratorHelperWithoutClosingOnEarlyError('take', RangeError);
	var IteratorProxy = createIteratorProxy(function () {
	  var iterator = this.iterator;
	  if (!this.remaining--) {
	    this.done = true;
	    return iteratorClose(iterator, 'normal', undefined);
	  }
	  var result = anObject(call(this.next, iterator));
	  var done = this.done = !!result.done;
	  if (!done) return result.value;
	});
	$({ target: 'Iterator', proto: true, real: true, forced: IS_PURE || takeWithoutClosingOnEarlyError }, {
	  take: function take(limit) {
	    anObject(this);
	    var remaining;
	    try {
	      remaining = toPositiveInteger(notANaN(+limit));
	    } catch (error) {
	      iteratorClose(this, 'throw', error);
	    }
	    if (takeWithoutClosingOnEarlyError) return call(takeWithoutClosingOnEarlyError, this, remaining);
	    return new IteratorProxy(getIteratorDirect(this), {
	      remaining: remaining
	    });
	  }
	});
	return es_iterator_take;
}

var hasRequiredEsnext_iterator_take;

function requireEsnext_iterator_take () {
	if (hasRequiredEsnext_iterator_take) return esnext_iterator_take;
	hasRequiredEsnext_iterator_take = 1;
	requireEs_iterator_take();
	return esnext_iterator_take;
}

var esnext_iterator_toArray = {};

var es_iterator_toArray = {};

var hasRequiredEs_iterator_toArray;

function requireEs_iterator_toArray () {
	if (hasRequiredEs_iterator_toArray) return es_iterator_toArray;
	hasRequiredEs_iterator_toArray = 1;
	var $ = require_export();
	var anObject = requireAnObject();
	var createProperty = requireCreateProperty();
	var iterate = requireIterate();
	var getIteratorDirect = requireGetIteratorDirect();
	$({ target: 'Iterator', proto: true, real: true }, {
	  toArray: function toArray() {
	    var result = [];
	    var index = 0;
	    iterate(getIteratorDirect(anObject(this)), function (element) {
	      createProperty(result, index++, element);
	    }, { IS_RECORD: true });
	    return result;
	  }
	});
	return es_iterator_toArray;
}

var hasRequiredEsnext_iterator_toArray;

function requireEsnext_iterator_toArray () {
	if (hasRequiredEsnext_iterator_toArray) return esnext_iterator_toArray;
	hasRequiredEsnext_iterator_toArray = 1;
	requireEs_iterator_toArray();
	return esnext_iterator_toArray;
}

var esnext_iterator_toAsync = {};

var hasRequiredEsnext_iterator_toAsync;

function requireEsnext_iterator_toAsync () {
	if (hasRequiredEsnext_iterator_toAsync) return esnext_iterator_toAsync;
	hasRequiredEsnext_iterator_toAsync = 1;
	var $ = require_export();
	var anObject = requireAnObject();
	var AsyncFromSyncIterator = requireAsyncFromSyncIterator();
	var WrapAsyncIterator = requireAsyncIteratorWrap();
	var getIteratorDirect = requireGetIteratorDirect();
	$({ target: 'Iterator', proto: true, real: true, forced: true }, {
	  toAsync: function toAsync() {
	    return new WrapAsyncIterator(getIteratorDirect(new AsyncFromSyncIterator(getIteratorDirect(anObject(this)))));
	  }
	});
	return esnext_iterator_toAsync;
}

var hasRequiredIteratorHelpersStage3;

function requireIteratorHelpersStage3 () {
	if (hasRequiredIteratorHelpersStage3) return iteratorHelpersStage3;
	hasRequiredIteratorHelpersStage3 = 1;
	requireEsnext_asyncIterator_constructor();
	requireEsnext_asyncIterator_drop();
	requireEsnext_asyncIterator_every();
	requireEsnext_asyncIterator_filter();
	requireEsnext_asyncIterator_find();
	requireEsnext_asyncIterator_flatMap();
	requireEsnext_asyncIterator_forEach();
	requireEsnext_asyncIterator_from();
	requireEsnext_asyncIterator_map();
	requireEsnext_asyncIterator_reduce();
	requireEsnext_asyncIterator_some();
	requireEsnext_asyncIterator_take();
	requireEsnext_asyncIterator_toArray();
	requireEsnext_iterator_constructor();
	requireEsnext_iterator_drop();
	requireEsnext_iterator_every();
	requireEsnext_iterator_filter();
	requireEsnext_iterator_find();
	requireEsnext_iterator_flatMap();
	requireEsnext_iterator_forEach();
	requireEsnext_iterator_from();
	requireEsnext_iterator_map();
	requireEsnext_iterator_reduce();
	requireEsnext_iterator_some();
	requireEsnext_iterator_take();
	requireEsnext_iterator_toArray();
	requireEsnext_iterator_toAsync();
	return iteratorHelpersStage3;
}

var esnext_asyncIterator_asIndexedPairs = {};

var asyncIteratorIndexed;
var hasRequiredAsyncIteratorIndexed;

function requireAsyncIteratorIndexed () {
	if (hasRequiredAsyncIteratorIndexed) return asyncIteratorIndexed;
	hasRequiredAsyncIteratorIndexed = 1;
	var call = requireFunctionCall();
	var map = requireAsyncIteratorMap();
	var callback = function (value, counter) {
	  return [counter, value];
	};
	asyncIteratorIndexed = function indexed() {
	  return call(map, this, callback);
	};
	return asyncIteratorIndexed;
}

var hasRequiredEsnext_asyncIterator_asIndexedPairs;

function requireEsnext_asyncIterator_asIndexedPairs () {
	if (hasRequiredEsnext_asyncIterator_asIndexedPairs) return esnext_asyncIterator_asIndexedPairs;
	hasRequiredEsnext_asyncIterator_asIndexedPairs = 1;
	var $ = require_export();
	var indexed = requireAsyncIteratorIndexed();
	$({ target: 'AsyncIterator', name: 'indexed', proto: true, real: true, forced: true }, {
	  asIndexedPairs: indexed
	});
	return esnext_asyncIterator_asIndexedPairs;
}

var esnext_asyncIterator_indexed = {};

var hasRequiredEsnext_asyncIterator_indexed;

function requireEsnext_asyncIterator_indexed () {
	if (hasRequiredEsnext_asyncIterator_indexed) return esnext_asyncIterator_indexed;
	hasRequiredEsnext_asyncIterator_indexed = 1;
	var $ = require_export();
	var indexed = requireAsyncIteratorIndexed();
	$({ target: 'AsyncIterator', proto: true, real: true, forced: true }, {
	  indexed: indexed
	});
	return esnext_asyncIterator_indexed;
}

var esnext_iterator_asIndexedPairs = {};

var iteratorIndexed;
var hasRequiredIteratorIndexed;

function requireIteratorIndexed () {
	if (hasRequiredIteratorIndexed) return iteratorIndexed;
	hasRequiredIteratorIndexed = 1;
	requireEs_iterator_map();
	var call = requireFunctionCall();
	var map = requireIteratorsCore().IteratorPrototype.map;
	var callback = function (value, counter) {
	  return [counter, value];
	};
	iteratorIndexed = function indexed() {
	  return call(map, this, callback);
	};
	return iteratorIndexed;
}

var hasRequiredEsnext_iterator_asIndexedPairs;

function requireEsnext_iterator_asIndexedPairs () {
	if (hasRequiredEsnext_iterator_asIndexedPairs) return esnext_iterator_asIndexedPairs;
	hasRequiredEsnext_iterator_asIndexedPairs = 1;
	var $ = require_export();
	var indexed = requireIteratorIndexed();
	$({ target: 'Iterator', name: 'indexed', proto: true, real: true, forced: true }, {
	  asIndexedPairs: indexed
	});
	return esnext_iterator_asIndexedPairs;
}

var esnext_iterator_indexed = {};

var hasRequiredEsnext_iterator_indexed;

function requireEsnext_iterator_indexed () {
	if (hasRequiredEsnext_iterator_indexed) return esnext_iterator_indexed;
	hasRequiredEsnext_iterator_indexed = 1;
	var $ = require_export();
	var indexed = requireIteratorIndexed();
	$({ target: 'Iterator', proto: true, real: true, forced: true }, {
	  indexed: indexed
	});
	return esnext_iterator_indexed;
}

var hasRequiredIteratorHelpers;

function requireIteratorHelpers () {
	if (hasRequiredIteratorHelpers) return iteratorHelpers;
	hasRequiredIteratorHelpers = 1;
	requireIteratorHelpersStage3();
	requireEsnext_asyncIterator_asIndexedPairs();
	requireEsnext_asyncIterator_indexed();
	requireEsnext_iterator_asIndexedPairs();
	requireEsnext_iterator_indexed();
	return iteratorHelpers;
}

requireIteratorHelpers();

const align = {
    right: alignRight,
    center: alignCenter
};
const top = 0;
const right = 1;
const bottom = 2;
const left = 3;
class UI {
    constructor(opts) {
        var _a;
        this.width = opts.width;
        this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true;
        this.rows = [];
    }
    span(...args) {
        const cols = this.div(...args);
        cols.span = true;
    }
    resetOutput() {
        this.rows = [];
    }
    div(...args) {
        if (args.length === 0) {
            this.div('');
        }
        if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') {
            return this.applyLayoutDSL(args[0]);
        }
        const cols = args.map(arg => {
            if (typeof arg === 'string') {
                return this.colFromString(arg);
            }
            return arg;
        });
        this.rows.push(cols);
        return cols;
    }
    shouldApplyLayoutDSL(...args) {
        return args.length === 1 && typeof args[0] === 'string' &&
            /[\t\n]/.test(args[0]);
    }
    applyLayoutDSL(str) {
        const rows = str.split('\n').map(row => row.split('\t'));
        let leftColumnWidth = 0;
        rows.forEach(columns => {
            if (columns.length > 1 && mixin$1.stringWidth(columns[0]) > leftColumnWidth) {
                leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin$1.stringWidth(columns[0]));
            }
        });
        rows.forEach(columns => {
            this.div(...columns.map((r, i) => {
                return {
                    text: r.trim(),
                    padding: this.measurePadding(r),
                    width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
                };
            }));
        });
        return this.rows[this.rows.length - 1];
    }
    colFromString(text) {
        return {
            text,
            padding: this.measurePadding(text)
        };
    }
    measurePadding(str) {
        const noAnsi = mixin$1.stripAnsi(str);
        return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
    }
    toString() {
        const lines = [];
        this.rows.forEach(row => {
            this.rowToString(row, lines);
        });
        return lines
            .filter(line => !line.hidden)
            .map(line => line.text)
            .join('\n');
    }
    rowToString(row, lines) {
        this.rasterize(row).forEach((rrow, r) => {
            let str = '';
            rrow.forEach((col, c) => {
                const { width } = row[c];
                const wrapWidth = this.negatePadding(row[c]);
                let ts = col;
                if (wrapWidth > mixin$1.stringWidth(col)) {
                    ts += ' '.repeat(wrapWidth - mixin$1.stringWidth(col));
                }
                if (row[c].align && row[c].align !== 'left' && this.wrap) {
                    const fn = align[row[c].align];
                    ts = fn(ts, wrapWidth);
                    if (mixin$1.stringWidth(ts) < wrapWidth) {
                        ts += ' '.repeat((width || 0) - mixin$1.stringWidth(ts) - 1);
                    }
                }
                const padding = row[c].padding || [0, 0, 0, 0];
                if (padding[left]) {
                    str += ' '.repeat(padding[left]);
                }
                str += addBorder(row[c], ts, '| ');
                str += ts;
                str += addBorder(row[c], ts, ' |');
                if (padding[right]) {
                    str += ' '.repeat(padding[right]);
                }
                if (r === 0 && lines.length > 0) {
                    str = this.renderInline(str, lines[lines.length - 1]);
                }
            });
            lines.push({
                text: str.replace(/ +$/, ''),
                span: row.span
            });
        });
        return lines;
    }
    renderInline(source, previousLine) {
        const match = source.match(/^ */);
        const leadingWhitespace = match ? match[0].length : 0;
        const target = previousLine.text;
        const targetTextWidth = mixin$1.stringWidth(target.trimRight());
        if (!previousLine.span) {
            return source;
        }
        if (!this.wrap) {
            previousLine.hidden = true;
            return target + source;
        }
        if (leadingWhitespace < targetTextWidth) {
            return source;
        }
        previousLine.hidden = true;
        return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
    }
    rasterize(row) {
        const rrows = [];
        const widths = this.columnWidths(row);
        let wrapped;
        row.forEach((col, c) => {
            col.width = widths[c];
            if (this.wrap) {
                wrapped = mixin$1.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n');
            }
            else {
                wrapped = col.text.split('\n');
            }
            if (col.border) {
                wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.');
                wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'");
            }
            if (col.padding) {
                wrapped.unshift(...new Array(col.padding[top] || 0).fill(''));
                wrapped.push(...new Array(col.padding[bottom] || 0).fill(''));
            }
            wrapped.forEach((str, r) => {
                if (!rrows[r]) {
                    rrows.push([]);
                }
                const rrow = rrows[r];
                for (let i = 0; i < c; i++) {
                    if (rrow[i] === undefined) {
                        rrow.push('');
                    }
                }
                rrow.push(str);
            });
        });
        return rrows;
    }
    negatePadding(col) {
        let wrapWidth = col.width || 0;
        if (col.padding) {
            wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
        }
        if (col.border) {
            wrapWidth -= 4;
        }
        return wrapWidth;
    }
    columnWidths(row) {
        if (!this.wrap) {
            return row.map(col => {
                return col.width || mixin$1.stringWidth(col.text);
            });
        }
        let unset = row.length;
        let remainingWidth = this.width;
        const widths = row.map(col => {
            if (col.width) {
                unset--;
                remainingWidth -= col.width;
                return col.width;
            }
            return undefined;
        });
        const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
        return widths.map((w, i) => {
            if (w === undefined) {
                return Math.max(unsetWidth, _minWidth(row[i]));
            }
            return w;
        });
    }
}
function addBorder(col, ts, style) {
    if (col.border) {
        if (/[.']-+[.']/.test(ts)) {
            return '';
        }
        if (ts.trim().length !== 0) {
            return style;
        }
        return '  ';
    }
    return '';
}
function _minWidth(col) {
    const padding = col.padding || [];
    const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
    if (col.border) {
        return minWidth + 4;
    }
    return minWidth;
}
function getWindowWidth() {
    if (typeof process === 'object' && process.stdout && process.stdout.columns) {
        return process.stdout.columns;
    }
    return 80;
}
function alignRight(str, width) {
    str = str.trim();
    const strWidth = mixin$1.stringWidth(str);
    if (strWidth < width) {
        return ' '.repeat(width - strWidth) + str;
    }
    return str;
}
function alignCenter(str, width) {
    str = str.trim();
    const strWidth = mixin$1.stringWidth(str);
    if (strWidth >= width) {
        return str;
    }
    return ' '.repeat((width - strWidth) >> 1) + str;
}
let mixin$1;
function cliui(opts, _mixin) {
    mixin$1 = _mixin;
    return new UI({
        width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
        wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
    });
}

function ansiRegex({onlyFirst = false} = {}) {
	const ST = '(?:\\u0007|\\u001B\\u005C|\\u009C)';
	const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`;
	const csi = '[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]';
	const pattern = `${osc}|${csi}`;
	return new RegExp(pattern, onlyFirst ? undefined : 'g');
}

const regex = ansiRegex();
function stripAnsi(string) {
	if (typeof string !== 'string') {
		throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
	}
	return string.replace(regex, '');
}

function isAmbiguous(x) {
	return x === 0xA1
		|| x === 0xA4
		|| x === 0xA7
		|| x === 0xA8
		|| x === 0xAA
		|| x === 0xAD
		|| x === 0xAE
		|| x >= 0xB0 && x <= 0xB4
		|| x >= 0xB6 && x <= 0xBA
		|| x >= 0xBC && x <= 0xBF
		|| x === 0xC6
		|| x === 0xD0
		|| x === 0xD7
		|| x === 0xD8
		|| x >= 0xDE && x <= 0xE1
		|| x === 0xE6
		|| x >= 0xE8 && x <= 0xEA
		|| x === 0xEC
		|| x === 0xED
		|| x === 0xF0
		|| x === 0xF2
		|| x === 0xF3
		|| x >= 0xF7 && x <= 0xFA
		|| x === 0xFC
		|| x === 0xFE
		|| x === 0x101
		|| x === 0x111
		|| x === 0x113
		|| x === 0x11B
		|| x === 0x126
		|| x === 0x127
		|| x === 0x12B
		|| x >= 0x131 && x <= 0x133
		|| x === 0x138
		|| x >= 0x13F && x <= 0x142
		|| x === 0x144
		|| x >= 0x148 && x <= 0x14B
		|| x === 0x14D
		|| x === 0x152
		|| x === 0x153
		|| x === 0x166
		|| x === 0x167
		|| x === 0x16B
		|| x === 0x1CE
		|| x === 0x1D0
		|| x === 0x1D2
		|| x === 0x1D4
		|| x === 0x1D6
		|| x === 0x1D8
		|| x === 0x1DA
		|| x === 0x1DC
		|| x === 0x251
		|| x === 0x261
		|| x === 0x2C4
		|| x === 0x2C7
		|| x >= 0x2C9 && x <= 0x2CB
		|| x === 0x2CD
		|| x === 0x2D0
		|| x >= 0x2D8 && x <= 0x2DB
		|| x === 0x2DD
		|| x === 0x2DF
		|| x >= 0x300 && x <= 0x36F
		|| x >= 0x391 && x <= 0x3A1
		|| x >= 0x3A3 && x <= 0x3A9
		|| x >= 0x3B1 && x <= 0x3C1
		|| x >= 0x3C3 && x <= 0x3C9
		|| x === 0x401
		|| x >= 0x410 && x <= 0x44F
		|| x === 0x451
		|| x === 0x2010
		|| x >= 0x2013 && x <= 0x2016
		|| x === 0x2018
		|| x === 0x2019
		|| x === 0x201C
		|| x === 0x201D
		|| x >= 0x2020 && x <= 0x2022
		|| x >= 0x2024 && x <= 0x2027
		|| x === 0x2030
		|| x === 0x2032
		|| x === 0x2033
		|| x === 0x2035
		|| x === 0x203B
		|| x === 0x203E
		|| x === 0x2074
		|| x === 0x207F
		|| x >= 0x2081 && x <= 0x2084
		|| x === 0x20AC
		|| x === 0x2103
		|| x === 0x2105
		|| x === 0x2109
		|| x === 0x2113
		|| x === 0x2116
		|| x === 0x2121
		|| x === 0x2122
		|| x === 0x2126
		|| x === 0x212B
		|| x === 0x2153
		|| x === 0x2154
		|| x >= 0x215B && x <= 0x215E
		|| x >= 0x2160 && x <= 0x216B
		|| x >= 0x2170 && x <= 0x2179
		|| x === 0x2189
		|| x >= 0x2190 && x <= 0x2199
		|| x === 0x21B8
		|| x === 0x21B9
		|| x === 0x21D2
		|| x === 0x21D4
		|| x === 0x21E7
		|| x === 0x2200
		|| x === 0x2202
		|| x === 0x2203
		|| x === 0x2207
		|| x === 0x2208
		|| x === 0x220B
		|| x === 0x220F
		|| x === 0x2211
		|| x === 0x2215
		|| x === 0x221A
		|| x >= 0x221D && x <= 0x2220
		|| x === 0x2223
		|| x === 0x2225
		|| x >= 0x2227 && x <= 0x222C
		|| x === 0x222E
		|| x >= 0x2234 && x <= 0x2237
		|| x === 0x223C
		|| x === 0x223D
		|| x === 0x2248
		|| x === 0x224C
		|| x === 0x2252
		|| x === 0x2260
		|| x === 0x2261
		|| x >= 0x2264 && x <= 0x2267
		|| x === 0x226A
		|| x === 0x226B
		|| x === 0x226E
		|| x === 0x226F
		|| x === 0x2282
		|| x === 0x2283
		|| x === 0x2286
		|| x === 0x2287
		|| x === 0x2295
		|| x === 0x2299
		|| x === 0x22A5
		|| x === 0x22BF
		|| x === 0x2312
		|| x >= 0x2460 && x <= 0x24E9
		|| x >= 0x24EB && x <= 0x254B
		|| x >= 0x2550 && x <= 0x2573
		|| x >= 0x2580 && x <= 0x258F
		|| x >= 0x2592 && x <= 0x2595
		|| x === 0x25A0
		|| x === 0x25A1
		|| x >= 0x25A3 && x <= 0x25A9
		|| x === 0x25B2
		|| x === 0x25B3
		|| x === 0x25B6
		|| x === 0x25B7
		|| x === 0x25BC
		|| x === 0x25BD
		|| x === 0x25C0
		|| x === 0x25C1
		|| x >= 0x25C6 && x <= 0x25C8
		|| x === 0x25CB
		|| x >= 0x25CE && x <= 0x25D1
		|| x >= 0x25E2 && x <= 0x25E5
		|| x === 0x25EF
		|| x === 0x2605
		|| x === 0x2606
		|| x === 0x2609
		|| x === 0x260E
		|| x === 0x260F
		|| x === 0x261C
		|| x === 0x261E
		|| x === 0x2640
		|| x === 0x2642
		|| x === 0x2660
		|| x === 0x2661
		|| x >= 0x2663 && x <= 0x2665
		|| x >= 0x2667 && x <= 0x266A
		|| x === 0x266C
		|| x === 0x266D
		|| x === 0x266F
		|| x === 0x269E
		|| x === 0x269F
		|| x === 0x26BF
		|| x >= 0x26C6 && x <= 0x26CD
		|| x >= 0x26CF && x <= 0x26D3
		|| x >= 0x26D5 && x <= 0x26E1
		|| x === 0x26E3
		|| x === 0x26E8
		|| x === 0x26E9
		|| x >= 0x26EB && x <= 0x26F1
		|| x === 0x26F4
		|| x >= 0x26F6 && x <= 0x26F9
		|| x === 0x26FB
		|| x === 0x26FC
		|| x === 0x26FE
		|| x === 0x26FF
		|| x === 0x273D
		|| x >= 0x2776 && x <= 0x277F
		|| x >= 0x2B56 && x <= 0x2B59
		|| x >= 0x3248 && x <= 0x324F
		|| x >= 0xE000 && x <= 0xF8FF
		|| x >= 0xFE00 && x <= 0xFE0F
		|| x === 0xFFFD
		|| x >= 0x1F100 && x <= 0x1F10A
		|| x >= 0x1F110 && x <= 0x1F12D
		|| x >= 0x1F130 && x <= 0x1F169
		|| x >= 0x1F170 && x <= 0x1F18D
		|| x === 0x1F18F
		|| x === 0x1F190
		|| x >= 0x1F19B && x <= 0x1F1AC
		|| x >= 0xE0100 && x <= 0xE01EF
		|| x >= 0xF0000 && x <= 0xFFFFD
		|| x >= 0x100000 && x <= 0x10FFFD;
}
function isFullWidth(x) {
	return x === 0x3000
		|| x >= 0xFF01 && x <= 0xFF60
		|| x >= 0xFFE0 && x <= 0xFFE6;
}
function isWide(x) {
	return x >= 0x1100 && x <= 0x115F
		|| x === 0x231A
		|| x === 0x231B
		|| x === 0x2329
		|| x === 0x232A
		|| x >= 0x23E9 && x <= 0x23EC
		|| x === 0x23F0
		|| x === 0x23F3
		|| x === 0x25FD
		|| x === 0x25FE
		|| x === 0x2614
		|| x === 0x2615
		|| x >= 0x2630 && x <= 0x2637
		|| x >= 0x2648 && x <= 0x2653
		|| x === 0x267F
		|| x >= 0x268A && x <= 0x268F
		|| x === 0x2693
		|| x === 0x26A1
		|| x === 0x26AA
		|| x === 0x26AB
		|| x === 0x26BD
		|| x === 0x26BE
		|| x === 0x26C4
		|| x === 0x26C5
		|| x === 0x26CE
		|| x === 0x26D4
		|| x === 0x26EA
		|| x === 0x26F2
		|| x === 0x26F3
		|| x === 0x26F5
		|| x === 0x26FA
		|| x === 0x26FD
		|| x === 0x2705
		|| x === 0x270A
		|| x === 0x270B
		|| x === 0x2728
		|| x === 0x274C
		|| x === 0x274E
		|| x >= 0x2753 && x <= 0x2755
		|| x === 0x2757
		|| x >= 0x2795 && x <= 0x2797
		|| x === 0x27B0
		|| x === 0x27BF
		|| x === 0x2B1B
		|| x === 0x2B1C
		|| x === 0x2B50
		|| x === 0x2B55
		|| x >= 0x2E80 && x <= 0x2E99
		|| x >= 0x2E9B && x <= 0x2EF3
		|| x >= 0x2F00 && x <= 0x2FD5
		|| x >= 0x2FF0 && x <= 0x2FFF
		|| x >= 0x3001 && x <= 0x303E
		|| x >= 0x3041 && x <= 0x3096
		|| x >= 0x3099 && x <= 0x30FF
		|| x >= 0x3105 && x <= 0x312F
		|| x >= 0x3131 && x <= 0x318E
		|| x >= 0x3190 && x <= 0x31E5
		|| x >= 0x31EF && x <= 0x321E
		|| x >= 0x3220 && x <= 0x3247
		|| x >= 0x3250 && x <= 0xA48C
		|| x >= 0xA490 && x <= 0xA4C6
		|| x >= 0xA960 && x <= 0xA97C
		|| x >= 0xAC00 && x <= 0xD7A3
		|| x >= 0xF900 && x <= 0xFAFF
		|| x >= 0xFE10 && x <= 0xFE19
		|| x >= 0xFE30 && x <= 0xFE52
		|| x >= 0xFE54 && x <= 0xFE66
		|| x >= 0xFE68 && x <= 0xFE6B
		|| x >= 0x16FE0 && x <= 0x16FE4
		|| x >= 0x16FF0 && x <= 0x16FF6
		|| x >= 0x17000 && x <= 0x18CD5
		|| x >= 0x18CFF && x <= 0x18D1E
		|| x >= 0x18D80 && x <= 0x18DF2
		|| x >= 0x1AFF0 && x <= 0x1AFF3
		|| x >= 0x1AFF5 && x <= 0x1AFFB
		|| x === 0x1AFFD
		|| x === 0x1AFFE
		|| x >= 0x1B000 && x <= 0x1B122
		|| x === 0x1B132
		|| x >= 0x1B150 && x <= 0x1B152
		|| x === 0x1B155
		|| x >= 0x1B164 && x <= 0x1B167
		|| x >= 0x1B170 && x <= 0x1B2FB
		|| x >= 0x1D300 && x <= 0x1D356
		|| x >= 0x1D360 && x <= 0x1D376
		|| x === 0x1F004
		|| x === 0x1F0CF
		|| x === 0x1F18E
		|| x >= 0x1F191 && x <= 0x1F19A
		|| x >= 0x1F200 && x <= 0x1F202
		|| x >= 0x1F210 && x <= 0x1F23B
		|| x >= 0x1F240 && x <= 0x1F248
		|| x === 0x1F250
		|| x === 0x1F251
		|| x >= 0x1F260 && x <= 0x1F265
		|| x >= 0x1F300 && x <= 0x1F320
		|| x >= 0x1F32D && x <= 0x1F335
		|| x >= 0x1F337 && x <= 0x1F37C
		|| x >= 0x1F37E && x <= 0x1F393
		|| x >= 0x1F3A0 && x <= 0x1F3CA
		|| x >= 0x1F3CF && x <= 0x1F3D3
		|| x >= 0x1F3E0 && x <= 0x1F3F0
		|| x === 0x1F3F4
		|| x >= 0x1F3F8 && x <= 0x1F43E
		|| x === 0x1F440
		|| x >= 0x1F442 && x <= 0x1F4FC
		|| x >= 0x1F4FF && x <= 0x1F53D
		|| x >= 0x1F54B && x <= 0x1F54E
		|| x >= 0x1F550 && x <= 0x1F567
		|| x === 0x1F57A
		|| x === 0x1F595
		|| x === 0x1F596
		|| x === 0x1F5A4
		|| x >= 0x1F5FB && x <= 0x1F64F
		|| x >= 0x1F680 && x <= 0x1F6C5
		|| x === 0x1F6CC
		|| x >= 0x1F6D0 && x <= 0x1F6D2
		|| x >= 0x1F6D5 && x <= 0x1F6D8
		|| x >= 0x1F6DC && x <= 0x1F6DF
		|| x === 0x1F6EB
		|| x === 0x1F6EC
		|| x >= 0x1F6F4 && x <= 0x1F6FC
		|| x >= 0x1F7E0 && x <= 0x1F7EB
		|| x === 0x1F7F0
		|| x >= 0x1F90C && x <= 0x1F93A
		|| x >= 0x1F93C && x <= 0x1F945
		|| x >= 0x1F947 && x <= 0x1F9FF
		|| x >= 0x1FA70 && x <= 0x1FA7C
		|| x >= 0x1FA80 && x <= 0x1FA8A
		|| x >= 0x1FA8E && x <= 0x1FAC6
		|| x === 0x1FAC8
		|| x >= 0x1FACD && x <= 0x1FADC
		|| x >= 0x1FADF && x <= 0x1FAEA
		|| x >= 0x1FAEF && x <= 0x1FAF8
		|| x >= 0x20000 && x <= 0x2FFFD
		|| x >= 0x30000 && x <= 0x3FFFD;
}

function validate$2(codePoint) {
	if (!Number.isSafeInteger(codePoint)) {
		throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
	}
}
function eastAsianWidth(codePoint, {ambiguousAsWide = false} = {}) {
	validate$2(codePoint);
	if (
		isFullWidth(codePoint)
		|| isWide(codePoint)
		|| (ambiguousAsWide && isAmbiguous(codePoint))
	) {
		return 2;
	}
	return 1;
}

var emojiRegex$2 = () => {
	return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
};

const segmenter = new Intl.Segmenter();
const defaultIgnorableCodePointRegex = /^\p{Default_Ignorable_Code_Point}$/u;
function stringWidth(string, options = {}) {
	if (typeof string !== 'string' || string.length === 0) {
		return 0;
	}
	const {
		ambiguousIsNarrow = true,
		countAnsiEscapeCodes = false,
	} = options;
	if (!countAnsiEscapeCodes) {
		string = stripAnsi(string);
	}
	if (string.length === 0) {
		return 0;
	}
	let width = 0;
	const eastAsianWidthOptions = {ambiguousAsWide: !ambiguousIsNarrow};
	for (const {segment: character} of segmenter.segment(string)) {
		const codePoint = character.codePointAt(0);
		if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) {
			continue;
		}
		if (
			(codePoint >= 0x20_0B && codePoint <= 0x20_0F)
			|| codePoint === 0xFE_FF
		) {
			continue;
		}
		if (
			(codePoint >= 0x3_00 && codePoint <= 0x3_6F)
			|| (codePoint >= 0x1A_B0 && codePoint <= 0x1A_FF)
			|| (codePoint >= 0x1D_C0 && codePoint <= 0x1D_FF)
			|| (codePoint >= 0x20_D0 && codePoint <= 0x20_FF)
			|| (codePoint >= 0xFE_20 && codePoint <= 0xFE_2F)
		) {
			continue;
		}
		if (codePoint >= 0xD8_00 && codePoint <= 0xDF_FF) {
			continue;
		}
		if (codePoint >= 0xFE_00 && codePoint <= 0xFE_0F) {
			continue;
		}
		if (defaultIgnorableCodePointRegex.test(character)) {
			continue;
		}
		if (emojiRegex$2().test(character)) {
			width += 2;
			continue;
		}
		width += eastAsianWidth(codePoint, eastAsianWidthOptions);
	}
	return width;
}

const ANSI_BACKGROUND_OFFSET = 10;
const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`;
const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`;
const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`;
const styles = {
	modifier: {
		reset: [0, 0],
		bold: [1, 22],
		dim: [2, 22],
		italic: [3, 23],
		underline: [4, 24],
		overline: [53, 55],
		inverse: [7, 27],
		hidden: [8, 28],
		strikethrough: [9, 29],
	},
	color: {
		black: [30, 39],
		red: [31, 39],
		green: [32, 39],
		yellow: [33, 39],
		blue: [34, 39],
		magenta: [35, 39],
		cyan: [36, 39],
		white: [37, 39],
		blackBright: [90, 39],
		gray: [90, 39],
		grey: [90, 39],
		redBright: [91, 39],
		greenBright: [92, 39],
		yellowBright: [93, 39],
		blueBright: [94, 39],
		magentaBright: [95, 39],
		cyanBright: [96, 39],
		whiteBright: [97, 39],
	},
	bgColor: {
		bgBlack: [40, 49],
		bgRed: [41, 49],
		bgGreen: [42, 49],
		bgYellow: [43, 49],
		bgBlue: [44, 49],
		bgMagenta: [45, 49],
		bgCyan: [46, 49],
		bgWhite: [47, 49],
		bgBlackBright: [100, 49],
		bgGray: [100, 49],
		bgGrey: [100, 49],
		bgRedBright: [101, 49],
		bgGreenBright: [102, 49],
		bgYellowBright: [103, 49],
		bgBlueBright: [104, 49],
		bgMagentaBright: [105, 49],
		bgCyanBright: [106, 49],
		bgWhiteBright: [107, 49],
	},
};
Object.keys(styles.modifier);
const foregroundColorNames = Object.keys(styles.color);
const backgroundColorNames = Object.keys(styles.bgColor);
[...foregroundColorNames, ...backgroundColorNames];
function assembleStyles() {
	const codes = new Map();
	for (const [groupName, group] of Object.entries(styles)) {
		for (const [styleName, style] of Object.entries(group)) {
			styles[styleName] = {
				open: `\u001B[${style[0]}m`,
				close: `\u001B[${style[1]}m`,
			};
			group[styleName] = styles[styleName];
			codes.set(style[0], style[1]);
		}
		Object.defineProperty(styles, groupName, {
			value: group,
			enumerable: false,
		});
	}
	Object.defineProperty(styles, 'codes', {
		value: codes,
		enumerable: false,
	});
	styles.color.close = '\u001B[39m';
	styles.bgColor.close = '\u001B[49m';
	styles.color.ansi = wrapAnsi16();
	styles.color.ansi256 = wrapAnsi256();
	styles.color.ansi16m = wrapAnsi16m();
	styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
	styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
	styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
	Object.defineProperties(styles, {
		rgbToAnsi256: {
			value(red, green, blue) {
				if (red === green && green === blue) {
					if (red < 8) {
						return 16;
					}
					if (red > 248) {
						return 231;
					}
					return Math.round(((red - 8) / 247) * 24) + 232;
				}
				return 16
					+ (36 * Math.round(red / 255 * 5))
					+ (6 * Math.round(green / 255 * 5))
					+ Math.round(blue / 255 * 5);
			},
			enumerable: false,
		},
		hexToRgb: {
			value(hex) {
				const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
				if (!matches) {
					return [0, 0, 0];
				}
				let [colorString] = matches;
				if (colorString.length === 3) {
					colorString = [...colorString].map(character => character + character).join('');
				}
				const integer = Number.parseInt(colorString, 16);
				return [
					(integer >> 16) & 0xFF,
					(integer >> 8) & 0xFF,
					integer & 0xFF,
				];
			},
			enumerable: false,
		},
		hexToAnsi256: {
			value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
			enumerable: false,
		},
		ansi256ToAnsi: {
			value(code) {
				if (code < 8) {
					return 30 + code;
				}
				if (code < 16) {
					return 90 + (code - 8);
				}
				let red;
				let green;
				let blue;
				if (code >= 232) {
					red = (((code - 232) * 10) + 8) / 255;
					green = red;
					blue = red;
				} else {
					code -= 16;
					const remainder = code % 36;
					red = Math.floor(code / 36) / 5;
					green = Math.floor(remainder / 6) / 5;
					blue = (remainder % 6) / 5;
				}
				const value = Math.max(red, green, blue) * 2;
				if (value === 0) {
					return 30;
				}
				let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));
				if (value === 2) {
					result += 60;
				}
				return result;
			},
			enumerable: false,
		},
		rgbToAnsi: {
			value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
			enumerable: false,
		},
		hexToAnsi: {
			value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
			enumerable: false,
		},
	});
	return styles;
}
const ansiStyles = assembleStyles();

const ESCAPES = new Set([
	'\u001B',
	'\u009B',
]);
const END_CODE = 39;
const ANSI_ESCAPE_BELL = '\u0007';
const ANSI_CSI = '[';
const ANSI_OSC = ']';
const ANSI_SGR_TERMINATOR = 'm';
const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
const wrapAnsiHyperlink = url => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;
const wordLengths = string => string.split(' ').map(character => stringWidth(character));
const wrapWord = (rows, word, columns) => {
	const characters = [...word];
	let isInsideEscape = false;
	let isInsideLinkEscape = false;
	let visible = stringWidth(stripAnsi(rows.at(-1)));
	for (const [index, character] of characters.entries()) {
		const characterLength = stringWidth(character);
		if (visible + characterLength <= columns) {
			rows[rows.length - 1] += character;
		} else {
			rows.push(character);
			visible = 0;
		}
		if (ESCAPES.has(character)) {
			isInsideEscape = true;
			const ansiEscapeLinkCandidate = characters.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK.length).join('');
			isInsideLinkEscape = ansiEscapeLinkCandidate === ANSI_ESCAPE_LINK;
		}
		if (isInsideEscape) {
			if (isInsideLinkEscape) {
				if (character === ANSI_ESCAPE_BELL) {
					isInsideEscape = false;
					isInsideLinkEscape = false;
				}
			} else if (character === ANSI_SGR_TERMINATOR) {
				isInsideEscape = false;
			}
			continue;
		}
		visible += characterLength;
		if (visible === columns && index < characters.length - 1) {
			rows.push('');
			visible = 0;
		}
	}
	if (!visible && rows.at(-1).length > 0 && rows.length > 1) {
		rows[rows.length - 2] += rows.pop();
	}
};
const stringVisibleTrimSpacesRight = string => {
	const words = string.split(' ');
	let last = words.length;
	while (last > 0) {
		if (stringWidth(words[last - 1]) > 0) {
			break;
		}
		last--;
	}
	if (last === words.length) {
		return string;
	}
	return words.slice(0, last).join(' ') + words.slice(last).join('');
};
const exec = (string, columns, options = {}) => {
	if (options.trim !== false && string.trim() === '') {
		return '';
	}
	let returnValue = '';
	let escapeCode;
	let escapeUrl;
	const lengths = wordLengths(string);
	let rows = [''];
	for (const [index, word] of string.split(' ').entries()) {
		if (options.trim !== false) {
			rows[rows.length - 1] = rows.at(-1).trimStart();
		}
		let rowLength = stringWidth(rows.at(-1));
		if (index !== 0) {
			if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
				rows.push('');
				rowLength = 0;
			}
			if (rowLength > 0 || options.trim === false) {
				rows[rows.length - 1] += ' ';
				rowLength++;
			}
		}
		if (options.hard && lengths[index] > columns) {
			const remainingColumns = (columns - rowLength);
			const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
			const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
			if (breaksStartingNextLine < breaksStartingThisLine) {
				rows.push('');
			}
			wrapWord(rows, word, columns);
			continue;
		}
		if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
			if (options.wordWrap === false && rowLength < columns) {
				wrapWord(rows, word, columns);
				continue;
			}
			rows.push('');
		}
		if (rowLength + lengths[index] > columns && options.wordWrap === false) {
			wrapWord(rows, word, columns);
			continue;
		}
		rows[rows.length - 1] += word;
	}
	if (options.trim !== false) {
		rows = rows.map(row => stringVisibleTrimSpacesRight(row));
	}
	const preString = rows.join('\n');
	const pre = [...preString];
	let preStringIndex = 0;
	for (const [index, character] of pre.entries()) {
		returnValue += character;
		if (ESCAPES.has(character)) {
			const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(preString.slice(preStringIndex)) || {groups: {}};
			if (groups.code !== undefined) {
				const code = Number.parseFloat(groups.code);
				escapeCode = code === END_CODE ? undefined : code;
			} else if (groups.uri !== undefined) {
				escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;
			}
		}
		const code = ansiStyles.codes.get(Number(escapeCode));
		if (pre[index + 1] === '\n') {
			if (escapeUrl) {
				returnValue += wrapAnsiHyperlink('');
			}
			if (escapeCode && code) {
				returnValue += wrapAnsiCode(code);
			}
		} else if (character === '\n') {
			if (escapeCode && code) {
				returnValue += wrapAnsiCode(escapeCode);
			}
			if (escapeUrl) {
				returnValue += wrapAnsiHyperlink(escapeUrl);
			}
		}
		preStringIndex += character.length;
	}
	return returnValue;
};
function wrapAnsi(string, columns, options) {
	return String(string)
		.normalize()
		.replaceAll('\r\n', '\n')
		.split('\n')
		.map(line => exec(line, columns, options))
		.join('\n');
}

function ui (opts) {
  return cliui(opts, {
    stringWidth,
    stripAnsi,
    wrap: wrapAnsi
  })
}

function escalade (start, callback) {
	let dir = resolve$2('.', start);
	let tmp, stats = statSync(dir);
	if (!stats.isDirectory()) {
		dir = dirname(dir);
	}
	while (true) {
		tmp = callback(dir, readdirSync(dir));
		if (tmp) return resolve$2(dir, tmp);
		dir = dirname(tmp = dir);
		if (tmp === dir) break;
	}
}

/**
 * @license
 * Copyright (c) 2016, Contributors
 * SPDX-License-Identifier: ISC
 */
function camelCase(str) {
    const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
    if (!isCamelCase) {
        str = str.toLowerCase();
    }
    if (str.indexOf('-') === -1 && str.indexOf('_') === -1) {
        return str;
    }
    else {
        let camelcase = '';
        let nextChrUpper = false;
        const leadingHyphens = str.match(/^-+/);
        for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
            let chr = str.charAt(i);
            if (nextChrUpper) {
                nextChrUpper = false;
                chr = chr.toUpperCase();
            }
            if (i !== 0 && (chr === '-' || chr === '_')) {
                nextChrUpper = true;
            }
            else if (chr !== '-' && chr !== '_') {
                camelcase += chr;
            }
        }
        return camelcase;
    }
}
function decamelize(str, joinString) {
    const lowercase = str.toLowerCase();
    joinString = joinString || '-';
    let notCamelcase = '';
    for (let i = 0; i < str.length; i++) {
        const chrLower = lowercase.charAt(i);
        const chrString = str.charAt(i);
        if (chrLower !== chrString && i > 0) {
            notCamelcase += `${joinString}${lowercase.charAt(i)}`;
        }
        else {
            notCamelcase += chrString;
        }
    }
    return notCamelcase;
}
function looksLikeNumber(x) {
    if (x === null || x === undefined)
        return false;
    if (typeof x === 'number')
        return true;
    if (/^0x[0-9a-f]+$/i.test(x))
        return true;
    if (/^0[^.]/.test(x))
        return false;
    return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}

/**
 * @license
 * Copyright (c) 2016, Contributors
 * SPDX-License-Identifier: ISC
 */
function tokenizeArgString(argString) {
    if (Array.isArray(argString)) {
        return argString.map(e => typeof e !== 'string' ? e + '' : e);
    }
    argString = argString.trim();
    let i = 0;
    let prevC = null;
    let c = null;
    let opening = null;
    const args = [];
    for (let ii = 0; ii < argString.length; ii++) {
        prevC = c;
        c = argString.charAt(ii);
        if (c === ' ' && !opening) {
            if (!(prevC === ' ')) {
                i++;
            }
            continue;
        }
        if (c === opening) {
            opening = null;
        }
        else if ((c === "'" || c === '"') && !opening) {
            opening = c;
        }
        if (!args[i])
            args[i] = '';
        args[i] += c;
    }
    return args;
}

/**
 * @license
 * Copyright (c) 2016, Contributors
 * SPDX-License-Identifier: ISC
 */
var DefaultValuesForTypeKey;
(function (DefaultValuesForTypeKey) {
    DefaultValuesForTypeKey["BOOLEAN"] = "boolean";
    DefaultValuesForTypeKey["STRING"] = "string";
    DefaultValuesForTypeKey["NUMBER"] = "number";
    DefaultValuesForTypeKey["ARRAY"] = "array";
})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));

/**
 * @license
 * Copyright (c) 2016, Contributors
 * SPDX-License-Identifier: ISC
 */
let mixin;
class YargsParser {
    constructor(_mixin) {
        mixin = _mixin;
    }
    parse(argsInput, options) {
        const opts = Object.assign({
            alias: undefined,
            array: undefined,
            boolean: undefined,
            config: undefined,
            configObjects: undefined,
            configuration: undefined,
            coerce: undefined,
            count: undefined,
            default: undefined,
            envPrefix: undefined,
            narg: undefined,
            normalize: undefined,
            string: undefined,
            number: undefined,
            __: undefined,
            key: undefined
        }, options);
        const args = tokenizeArgString(argsInput);
        const inputIsString = typeof argsInput === 'string';
        const aliases = combineAliases(Object.assign(Object.create(null), opts.alias));
        const configuration = Object.assign({
            'boolean-negation': true,
            'camel-case-expansion': true,
            'combine-arrays': false,
            'dot-notation': true,
            'duplicate-arguments-array': true,
            'flatten-duplicate-arrays': true,
            'greedy-arrays': true,
            'halt-at-non-option': false,
            'nargs-eats-options': false,
            'negation-prefix': 'no-',
            'parse-numbers': true,
            'parse-positional-numbers': true,
            'populate--': false,
            'set-placeholder-key': false,
            'short-option-groups': true,
            'strip-aliased': false,
            'strip-dashed': false,
            'unknown-options-as-args': false
        }, opts.configuration);
        const defaults = Object.assign(Object.create(null), opts.default);
        const configObjects = opts.configObjects || [];
        const envPrefix = opts.envPrefix;
        const notFlagsOption = configuration['populate--'];
        const notFlagsArgv = notFlagsOption ? '--' : '_';
        const newAliases = Object.create(null);
        const defaulted = Object.create(null);
        const __ = opts.__ || mixin.format;
        const flags = {
            aliases: Object.create(null),
            arrays: Object.create(null),
            bools: Object.create(null),
            strings: Object.create(null),
            numbers: Object.create(null),
            counts: Object.create(null),
            normalize: Object.create(null),
            configs: Object.create(null),
            nargs: Object.create(null),
            coercions: Object.create(null),
            keys: []
        };
        const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
        const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)');
        [].concat(opts.array || []).filter(Boolean).forEach(function (opt) {
            const key = typeof opt === 'object' ? opt.key : opt;
            const assignment = Object.keys(opt).map(function (key) {
                const arrayFlagKeys = {
                    boolean: 'bools',
                    string: 'strings',
                    number: 'numbers'
                };
                return arrayFlagKeys[key];
            }).filter(Boolean).pop();
            if (assignment) {
                flags[assignment][key] = true;
            }
            flags.arrays[key] = true;
            flags.keys.push(key);
        });
        [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) {
            flags.bools[key] = true;
            flags.keys.push(key);
        });
        [].concat(opts.string || []).filter(Boolean).forEach(function (key) {
            flags.strings[key] = true;
            flags.keys.push(key);
        });
        [].concat(opts.number || []).filter(Boolean).forEach(function (key) {
            flags.numbers[key] = true;
            flags.keys.push(key);
        });
        [].concat(opts.count || []).filter(Boolean).forEach(function (key) {
            flags.counts[key] = true;
            flags.keys.push(key);
        });
        [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) {
            flags.normalize[key] = true;
            flags.keys.push(key);
        });
        if (typeof opts.narg === 'object') {
            Object.entries(opts.narg).forEach(([key, value]) => {
                if (typeof value === 'number') {
                    flags.nargs[key] = value;
                    flags.keys.push(key);
                }
            });
        }
        if (typeof opts.coerce === 'object') {
            Object.entries(opts.coerce).forEach(([key, value]) => {
                if (typeof value === 'function') {
                    flags.coercions[key] = value;
                    flags.keys.push(key);
                }
            });
        }
        if (typeof opts.config !== 'undefined') {
            if (Array.isArray(opts.config) || typeof opts.config === 'string') {
                [].concat(opts.config).filter(Boolean).forEach(function (key) {
                    flags.configs[key] = true;
                });
            }
            else if (typeof opts.config === 'object') {
                Object.entries(opts.config).forEach(([key, value]) => {
                    if (typeof value === 'boolean' || typeof value === 'function') {
                        flags.configs[key] = value;
                    }
                });
            }
        }
        extendAliases(opts.key, aliases, opts.default, flags.arrays);
        Object.keys(defaults).forEach(function (key) {
            (flags.aliases[key] || []).forEach(function (alias) {
                defaults[alias] = defaults[key];
            });
        });
        let error = null;
        checkConfiguration();
        let notFlags = [];
        const argv = Object.assign(Object.create(null), { _: [] });
        const argvReturn = {};
        for (let i = 0; i < args.length; i++) {
            const arg = args[i];
            const truncatedArg = arg.replace(/^-{3,}/, '---');
            let broken;
            let key;
            let letters;
            let m;
            let next;
            let value;
            if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) {
                pushPositional(arg);
            }
            else if (truncatedArg.match(/^---+(=|$)/)) {
                pushPositional(arg);
                continue;
            }
            else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) {
                m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
                if (m !== null && Array.isArray(m) && m.length >= 3) {
                    if (checkAllAliases(m[1], flags.arrays)) {
                        i = eatArray(i, m[1], args, m[2]);
                    }
                    else if (checkAllAliases(m[1], flags.nargs) !== false) {
                        i = eatNargs(i, m[1], args, m[2]);
                    }
                    else {
                        setArg(m[1], m[2], true);
                    }
                }
            }
            else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
                m = arg.match(negatedBoolean);
                if (m !== null && Array.isArray(m) && m.length >= 2) {
                    key = m[1];
                    setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
                }
            }
            else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) {
                m = arg.match(/^--?(.+)/);
                if (m !== null && Array.isArray(m) && m.length >= 2) {
                    key = m[1];
                    if (checkAllAliases(key, flags.arrays)) {
                        i = eatArray(i, key, args);
                    }
                    else if (checkAllAliases(key, flags.nargs) !== false) {
                        i = eatNargs(i, key, args);
                    }
                    else {
                        next = args[i + 1];
                        if (next !== undefined && (!next.match(/^-/) ||
                            next.match(negative)) &&
                            !checkAllAliases(key, flags.bools) &&
                            !checkAllAliases(key, flags.counts)) {
                            setArg(key, next);
                            i++;
                        }
                        else if (/^(true|false)$/.test(next)) {
                            setArg(key, next);
                            i++;
                        }
                        else {
                            setArg(key, defaultValue(key));
                        }
                    }
                }
            }
            else if (arg.match(/^-.\..+=/)) {
                m = arg.match(/^-([^=]+)=([\s\S]*)$/);
                if (m !== null && Array.isArray(m) && m.length >= 3) {
                    setArg(m[1], m[2]);
                }
            }
            else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
                next = args[i + 1];
                m = arg.match(/^-(.\..+)/);
                if (m !== null && Array.isArray(m) && m.length >= 2) {
                    key = m[1];
                    if (next !== undefined && !next.match(/^-/) &&
                        !checkAllAliases(key, flags.bools) &&
                        !checkAllAliases(key, flags.counts)) {
                        setArg(key, next);
                        i++;
                    }
                    else {
                        setArg(key, defaultValue(key));
                    }
                }
            }
            else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
                letters = arg.slice(1, -1).split('');
                broken = false;
                for (let j = 0; j < letters.length; j++) {
                    next = arg.slice(j + 2);
                    if (letters[j + 1] && letters[j + 1] === '=') {
                        value = arg.slice(j + 3);
                        key = letters[j];
                        if (checkAllAliases(key, flags.arrays)) {
                            i = eatArray(i, key, args, value);
                        }
                        else if (checkAllAliases(key, flags.nargs) !== false) {
                            i = eatNargs(i, key, args, value);
                        }
                        else {
                            setArg(key, value);
                        }
                        broken = true;
                        break;
                    }
                    if (next === '-') {
                        setArg(letters[j], next);
                        continue;
                    }
                    if (/[A-Za-z]/.test(letters[j]) &&
                        /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) &&
                        checkAllAliases(next, flags.bools) === false) {
                        setArg(letters[j], next);
                        broken = true;
                        break;
                    }
                    if (letters[j + 1] && letters[j + 1].match(/\W/)) {
                        setArg(letters[j], next);
                        broken = true;
                        break;
                    }
                    else {
                        setArg(letters[j], defaultValue(letters[j]));
                    }
                }
                key = arg.slice(-1)[0];
                if (!broken && key !== '-') {
                    if (checkAllAliases(key, flags.arrays)) {
                        i = eatArray(i, key, args);
                    }
                    else if (checkAllAliases(key, flags.nargs) !== false) {
                        i = eatNargs(i, key, args);
                    }
                    else {
                        next = args[i + 1];
                        if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
                            next.match(negative)) &&
                            !checkAllAliases(key, flags.bools) &&
                            !checkAllAliases(key, flags.counts)) {
                            setArg(key, next);
                            i++;
                        }
                        else if (/^(true|false)$/.test(next)) {
                            setArg(key, next);
                            i++;
                        }
                        else {
                            setArg(key, defaultValue(key));
                        }
                    }
                }
            }
            else if (arg.match(/^-[0-9]$/) &&
                arg.match(negative) &&
                checkAllAliases(arg.slice(1), flags.bools)) {
                key = arg.slice(1);
                setArg(key, defaultValue(key));
            }
            else if (arg === '--') {
                notFlags = args.slice(i + 1);
                break;
            }
            else if (configuration['halt-at-non-option']) {
                notFlags = args.slice(i);
                break;
            }
            else {
                pushPositional(arg);
            }
        }
        applyEnvVars(argv, true);
        applyEnvVars(argv, false);
        setConfig(argv);
        setConfigObjects();
        applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
        applyCoercions(argv);
        if (configuration['set-placeholder-key'])
            setPlaceholderKeys(argv);
        Object.keys(flags.counts).forEach(function (key) {
            if (!hasKey(argv, key.split('.')))
                setArg(key, 0);
        });
        if (notFlagsOption && notFlags.length)
            argv[notFlagsArgv] = [];
        notFlags.forEach(function (key) {
            argv[notFlagsArgv].push(key);
        });
        if (configuration['camel-case-expansion'] && configuration['strip-dashed']) {
            Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => {
                delete argv[key];
            });
        }
        if (configuration['strip-aliased']) {
            [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => {
                if (configuration['camel-case-expansion'] && alias.includes('-')) {
                    delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')];
                }
                delete argv[alias];
            });
        }
        function pushPositional(arg) {
            const maybeCoercedNumber = maybeCoerceNumber('_', arg);
            if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') {
                argv._.push(maybeCoercedNumber);
            }
        }
        function eatNargs(i, key, args, argAfterEqualSign) {
            let ii;
            let toEat = checkAllAliases(key, flags.nargs);
            toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat;
            if (toEat === 0) {
                if (!isUndefined(argAfterEqualSign)) {
                    error = Error(__('Argument unexpected for: %s', key));
                }
                setArg(key, defaultValue(key));
                return i;
            }
            let available = isUndefined(argAfterEqualSign) ? 0 : 1;
            if (configuration['nargs-eats-options']) {
                if (args.length - (i + 1) + available < toEat) {
                    error = Error(__('Not enough arguments following: %s', key));
                }
                available = toEat;
            }
            else {
                for (ii = i + 1; ii < args.length; ii++) {
                    if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii]))
                        available++;
                    else
                        break;
                }
                if (available < toEat)
                    error = Error(__('Not enough arguments following: %s', key));
            }
            let consumed = Math.min(available, toEat);
            if (!isUndefined(argAfterEqualSign) && consumed > 0) {
                setArg(key, argAfterEqualSign);
                consumed--;
            }
            for (ii = i + 1; ii < (consumed + i + 1); ii++) {
                setArg(key, args[ii]);
            }
            return (i + consumed);
        }
        function eatArray(i, key, args, argAfterEqualSign) {
            let argsToSet = [];
            let next = argAfterEqualSign || args[i + 1];
            const nargsCount = checkAllAliases(key, flags.nargs);
            if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) {
                argsToSet.push(true);
            }
            else if (isUndefined(next) ||
                (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) {
                if (defaults[key] !== undefined) {
                    const defVal = defaults[key];
                    argsToSet = Array.isArray(defVal) ? defVal : [defVal];
                }
            }
            else {
                if (!isUndefined(argAfterEqualSign)) {
                    argsToSet.push(processValue(key, argAfterEqualSign, true));
                }
                for (let ii = i + 1; ii < args.length; ii++) {
                    if ((!configuration['greedy-arrays'] && argsToSet.length > 0) ||
                        (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount))
                        break;
                    next = args[ii];
                    if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
                        break;
                    i = ii;
                    argsToSet.push(processValue(key, next, inputIsString));
                }
            }
            if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) ||
                (isNaN(nargsCount) && argsToSet.length === 0))) {
                error = Error(__('Not enough arguments following: %s', key));
            }
            setArg(key, argsToSet);
            return i;
        }
        function setArg(key, val, shouldStripQuotes = inputIsString) {
            if (/-/.test(key) && configuration['camel-case-expansion']) {
                const alias = key.split('.').map(function (prop) {
                    return camelCase(prop);
                }).join('.');
                addNewAlias(key, alias);
            }
            const value = processValue(key, val, shouldStripQuotes);
            const splitKey = key.split('.');
            setKey(argv, splitKey, value);
            if (flags.aliases[key]) {
                flags.aliases[key].forEach(function (x) {
                    const keyProperties = x.split('.');
                    setKey(argv, keyProperties, value);
                });
            }
            if (splitKey.length > 1 && configuration['dot-notation']) {
                (flags.aliases[splitKey[0]] || []).forEach(function (x) {
                    let keyProperties = x.split('.');
                    const a = [].concat(splitKey);
                    a.shift();
                    keyProperties = keyProperties.concat(a);
                    if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) {
                        setKey(argv, keyProperties, value);
                    }
                });
            }
            if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
                const keys = [key].concat(flags.aliases[key] || []);
                keys.forEach(function (key) {
                    Object.defineProperty(argvReturn, key, {
                        enumerable: true,
                        get() {
                            return val;
                        },
                        set(value) {
                            val = typeof value === 'string' ? mixin.normalize(value) : value;
                        }
                    });
                });
            }
        }
        function addNewAlias(key, alias) {
            if (!(flags.aliases[key] && flags.aliases[key].length)) {
                flags.aliases[key] = [alias];
                newAliases[alias] = true;
            }
            if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
                addNewAlias(alias, key);
            }
        }
        function processValue(key, val, shouldStripQuotes) {
            if (shouldStripQuotes) {
                val = stripQuotes(val);
            }
            if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
                if (typeof val === 'string')
                    val = val === 'true';
            }
            let value = Array.isArray(val)
                ? val.map(function (v) { return maybeCoerceNumber(key, v); })
                : maybeCoerceNumber(key, val);
            if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
                value = increment();
            }
            if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
                if (Array.isArray(val))
                    value = val.map((val) => { return mixin.normalize(val); });
                else
                    value = mixin.normalize(val);
            }
            return value;
        }
        function maybeCoerceNumber(key, value) {
            if (!configuration['parse-positional-numbers'] && key === '_')
                return value;
            if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
                const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`))));
                if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) {
                    value = Number(value);
                }
            }
            return value;
        }
        function setConfig(argv) {
            const configLookup = Object.create(null);
            applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
            Object.keys(flags.configs).forEach(function (configKey) {
                const configPath = argv[configKey] || configLookup[configKey];
                if (configPath) {
                    try {
                        let config = null;
                        const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath);
                        const resolveConfig = flags.configs[configKey];
                        if (typeof resolveConfig === 'function') {
                            try {
                                config = resolveConfig(resolvedConfigPath);
                            }
                            catch (e) {
                                config = e;
                            }
                            if (config instanceof Error) {
                                error = config;
                                return;
                            }
                        }
                        else {
                            config = mixin.require(resolvedConfigPath);
                        }
                        setConfigObject(config);
                    }
                    catch (ex) {
                        if (ex.name === 'PermissionDenied')
                            error = ex;
                        else if (argv[configKey])
                            error = Error(__('Invalid JSON config file: %s', configPath));
                    }
                }
            });
        }
        function setConfigObject(config, prev) {
            Object.keys(config).forEach(function (key) {
                const value = config[key];
                const fullKey = prev ? prev + '.' + key : key;
                if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
                    setConfigObject(value, fullKey);
                }
                else {
                    if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) {
                        setArg(fullKey, value);
                    }
                }
            });
        }
        function setConfigObjects() {
            if (typeof configObjects !== 'undefined') {
                configObjects.forEach(function (configObject) {
                    setConfigObject(configObject);
                });
            }
        }
        function applyEnvVars(argv, configOnly) {
            if (typeof envPrefix === 'undefined')
                return;
            const prefix = typeof envPrefix === 'string' ? envPrefix : '';
            const env = mixin.env();
            Object.keys(env).forEach(function (envVar) {
                if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
                    const keys = envVar.split('__').map(function (key, i) {
                        if (i === 0) {
                            key = key.substring(prefix.length);
                        }
                        return camelCase(key);
                    });
                    if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) {
                        setArg(keys.join('.'), env[envVar]);
                    }
                }
            });
        }
        function applyCoercions(argv) {
            let coerce;
            const applied = new Set();
            Object.keys(argv).forEach(function (key) {
                if (!applied.has(key)) {
                    coerce = checkAllAliases(key, flags.coercions);
                    if (typeof coerce === 'function') {
                        try {
                            const value = maybeCoerceNumber(key, coerce(argv[key]));
                            ([].concat(flags.aliases[key] || [], key)).forEach(ali => {
                                applied.add(ali);
                                argv[ali] = value;
                            });
                        }
                        catch (err) {
                            error = err;
                        }
                    }
                }
            });
        }
        function setPlaceholderKeys(argv) {
            flags.keys.forEach((key) => {
                if (~key.indexOf('.'))
                    return;
                if (typeof argv[key] === 'undefined')
                    argv[key] = undefined;
            });
            return argv;
        }
        function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) {
            Object.keys(defaults).forEach(function (key) {
                if (!hasKey(obj, key.split('.'))) {
                    setKey(obj, key.split('.'), defaults[key]);
                    if (canLog)
                        defaulted[key] = true;
                    (aliases[key] || []).forEach(function (x) {
                        if (hasKey(obj, x.split('.')))
                            return;
                        setKey(obj, x.split('.'), defaults[key]);
                    });
                }
            });
        }
        function hasKey(obj, keys) {
            let o = obj;
            if (!configuration['dot-notation'])
                keys = [keys.join('.')];
            keys.slice(0, -1).forEach(function (key) {
                o = (o[key] || {});
            });
            const key = keys[keys.length - 1];
            if (typeof o !== 'object')
                return false;
            else
                return key in o;
        }
        function setKey(obj, keys, value) {
            let o = obj;
            if (!configuration['dot-notation'])
                keys = [keys.join('.')];
            keys.slice(0, -1).forEach(function (key) {
                key = sanitizeKey(key);
                if (typeof o === 'object' && o[key] === undefined) {
                    o[key] = {};
                }
                if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
                    if (Array.isArray(o[key])) {
                        o[key].push({});
                    }
                    else {
                        o[key] = [o[key], {}];
                    }
                    o = o[key][o[key].length - 1];
                }
                else {
                    o = o[key];
                }
            });
            const key = sanitizeKey(keys[keys.length - 1]);
            const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays);
            const isValueArray = Array.isArray(value);
            let duplicate = configuration['duplicate-arguments-array'];
            if (!duplicate && checkAllAliases(key, flags.nargs)) {
                duplicate = true;
                if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) {
                    o[key] = undefined;
                }
            }
            if (value === increment()) {
                o[key] = increment(o[key]);
            }
            else if (Array.isArray(o[key])) {
                if (duplicate && isTypeArray && isValueArray) {
                    o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
                }
                else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
                    o[key] = value;
                }
                else {
                    o[key] = o[key].concat([value]);
                }
            }
            else if (o[key] === undefined && isTypeArray) {
                o[key] = isValueArray ? value : [value];
            }
            else if (duplicate && !(o[key] === undefined ||
                checkAllAliases(key, flags.counts) ||
                checkAllAliases(key, flags.bools))) {
                o[key] = [o[key], value];
            }
            else {
                o[key] = value;
            }
        }
        function extendAliases(...args) {
            args.forEach(function (obj) {
                Object.keys(obj || {}).forEach(function (key) {
                    if (flags.aliases[key])
                        return;
                    flags.aliases[key] = [].concat(aliases[key] || []);
                    flags.aliases[key].concat(key).forEach(function (x) {
                        if (/-/.test(x) && configuration['camel-case-expansion']) {
                            const c = camelCase(x);
                            if (c !== key && flags.aliases[key].indexOf(c) === -1) {
                                flags.aliases[key].push(c);
                                newAliases[c] = true;
                            }
                        }
                    });
                    flags.aliases[key].concat(key).forEach(function (x) {
                        if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
                            const c = decamelize(x, '-');
                            if (c !== key && flags.aliases[key].indexOf(c) === -1) {
                                flags.aliases[key].push(c);
                                newAliases[c] = true;
                            }
                        }
                    });
                    flags.aliases[key].forEach(function (x) {
                        flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
                            return x !== y;
                        }));
                    });
                });
            });
        }
        function checkAllAliases(key, flag) {
            const toCheck = [].concat(flags.aliases[key] || [], key);
            const keys = Object.keys(flag);
            const setAlias = toCheck.find(key => keys.includes(key));
            return setAlias ? flag[setAlias] : false;
        }
        function hasAnyFlag(key) {
            const flagsKeys = Object.keys(flags);
            const toCheck = [].concat(flagsKeys.map(k => flags[k]));
            return toCheck.some(function (flag) {
                return Array.isArray(flag) ? flag.includes(key) : flag[key];
            });
        }
        function hasFlagsMatching(arg, ...patterns) {
            const toCheck = [].concat(...patterns);
            return toCheck.some(function (pattern) {
                const match = arg.match(pattern);
                return match && hasAnyFlag(match[1]);
            });
        }
        function hasAllShortFlags(arg) {
            if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
                return false;
            }
            let hasAllFlags = true;
            let next;
            const letters = arg.slice(1).split('');
            for (let j = 0; j < letters.length; j++) {
                next = arg.slice(j + 2);
                if (!hasAnyFlag(letters[j])) {
                    hasAllFlags = false;
                    break;
                }
                if ((letters[j + 1] && letters[j + 1] === '=') ||
                    next === '-' ||
                    (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) ||
                    (letters[j + 1] && letters[j + 1].match(/\W/))) {
                    break;
                }
            }
            return hasAllFlags;
        }
        function isUnknownOptionAsArg(arg) {
            return configuration['unknown-options-as-args'] && isUnknownOption(arg);
        }
        function isUnknownOption(arg) {
            arg = arg.replace(/^-{3,}/, '--');
            if (arg.match(negative)) {
                return false;
            }
            if (hasAllShortFlags(arg)) {
                return false;
            }
            const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
            const normalFlag = /^-+([^=]+?)$/;
            const flagEndingInHyphen = /^-+([^=]+?)-$/;
            const flagEndingInDigits = /^-+([^=]+?\d+)$/;
            const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
            return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
        }
        function defaultValue(key) {
            if (!checkAllAliases(key, flags.bools) &&
                !checkAllAliases(key, flags.counts) &&
                `${key}` in defaults) {
                return defaults[key];
            }
            else {
                return defaultForType(guessType(key));
            }
        }
        function defaultForType(type) {
            const def = {
                [DefaultValuesForTypeKey.BOOLEAN]: true,
                [DefaultValuesForTypeKey.STRING]: '',
                [DefaultValuesForTypeKey.NUMBER]: undefined,
                [DefaultValuesForTypeKey.ARRAY]: []
            };
            return def[type];
        }
        function guessType(key) {
            let type = DefaultValuesForTypeKey.BOOLEAN;
            if (checkAllAliases(key, flags.strings))
                type = DefaultValuesForTypeKey.STRING;
            else if (checkAllAliases(key, flags.numbers))
                type = DefaultValuesForTypeKey.NUMBER;
            else if (checkAllAliases(key, flags.bools))
                type = DefaultValuesForTypeKey.BOOLEAN;
            else if (checkAllAliases(key, flags.arrays))
                type = DefaultValuesForTypeKey.ARRAY;
            return type;
        }
        function isUndefined(num) {
            return num === undefined;
        }
        function checkConfiguration() {
            Object.keys(flags.counts).find(key => {
                if (checkAllAliases(key, flags.arrays)) {
                    error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key));
                    return true;
                }
                else if (checkAllAliases(key, flags.nargs)) {
                    error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key));
                    return true;
                }
                return false;
            });
        }
        return {
            aliases: Object.assign({}, flags.aliases),
            argv: Object.assign(argvReturn, argv),
            configuration: configuration,
            defaulted: Object.assign({}, defaulted),
            error: error,
            newAliases: Object.assign({}, newAliases)
        };
    }
}
function combineAliases(aliases) {
    const aliasArrays = [];
    const combined = Object.create(null);
    let change = true;
    Object.keys(aliases).forEach(function (key) {
        aliasArrays.push([].concat(aliases[key], key));
    });
    while (change) {
        change = false;
        for (let i = 0; i < aliasArrays.length; i++) {
            for (let ii = i + 1; ii < aliasArrays.length; ii++) {
                const intersect = aliasArrays[i].filter(function (v) {
                    return aliasArrays[ii].indexOf(v) !== -1;
                });
                if (intersect.length) {
                    aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
                    aliasArrays.splice(ii, 1);
                    change = true;
                    break;
                }
            }
        }
    }
    aliasArrays.forEach(function (aliasArray) {
        aliasArray = aliasArray.filter(function (v, i, self) {
            return self.indexOf(v) === i;
        });
        const lastAlias = aliasArray.pop();
        if (lastAlias !== undefined && typeof lastAlias === 'string') {
            combined[lastAlias] = aliasArray;
        }
    });
    return combined;
}
function increment(orig) {
    return orig !== undefined ? orig + 1 : 1;
}
function sanitizeKey(key) {
    if (key === '__proto__')
        return '___proto___';
    return key;
}
function stripQuotes(val) {
    return (typeof val === 'string' &&
        (val[0] === "'" || val[0] === '"') &&
        val[val.length - 1] === val[0])
        ? val.substring(1, val.length - 1)
        : val;
}

/**
 * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
 *
 * @license
 * Copyright (c) 2016, Contributors
 * SPDX-License-Identifier: ISC
 */
var _a$7, _b, _c;
const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION)
    ? Number(process.env.YARGS_MIN_NODE_VERSION)
    : 20;
const nodeVersion = (_b = (_a$7 = process === null || process === void 0 ? void 0 : process.versions) === null || _a$7 === void 0 ? void 0 : _a$7.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);
if (nodeVersion) {
    const major = Number(nodeVersion.match(/^([^.]+)/)[1]);
    if (major < minNodeVersion) {
        throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
    }
}
const env = process ? process.env : {};
const require$2 = createRequire ? createRequire(import.meta.url) : undefined;
const parser$1 = new YargsParser({
    cwd: process.cwd,
    env: () => {
        return env;
    },
    format: format$5,
    normalize,
    resolve: resolve$2,
    require: (path) => {
        if (typeof require$2 !== 'undefined') {
            return require$2(path);
        }
        else if (path.match(/\.json$/)) {
            return JSON.parse(readFileSync(path, 'utf8'));
        }
        else {
            throw Error('only .json config files are supported in ESM');
        }
    }
});
const yargsParser = function Parser(args, opts) {
    const result = parser$1.parse(args.slice(), opts);
    return result.argv;
};
yargsParser.detailed = function (args, opts) {
    return parser$1.parse(args.slice(), opts);
};
yargsParser.camelCase = camelCase;
yargsParser.decamelize = decamelize;
yargsParser.looksLikeNumber = looksLikeNumber;

function getProcessArgvBinIndex() {
    if (isBundledElectronApp())
        return 0;
    return 1;
}
function isBundledElectronApp() {
    return isElectronApp() && !process.defaultApp;
}
function isElectronApp() {
    return !!process.versions.electron;
}
function hideBin(argv) {
    return argv.slice(getProcessArgvBinIndex() + 1);
}
function getProcessArgvBin() {
    return process.argv[getProcessArgvBinIndex()];
}

var shim$3 = {
    fs: {
        readFileSync,
        writeFile
    },
    format: format$5,
    resolve: resolve$2,
    exists: (file) => {
        try {
            return statSync(file).isFile();
        }
        catch (err) {
            return false;
        }
    }
};

let shim$2;
class Y18N {
    constructor(opts) {
        opts = opts || {};
        this.directory = opts.directory || './locales';
        this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true;
        this.locale = opts.locale || 'en';
        this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true;
        this.cache = Object.create(null);
        this.writeQueue = [];
    }
    __(...args) {
        if (typeof arguments[0] !== 'string') {
            return this._taggedLiteral(arguments[0], ...arguments);
        }
        const str = args.shift();
        let cb = function () { };
        if (typeof args[args.length - 1] === 'function')
            cb = args.pop();
        cb = cb || function () { };
        if (!this.cache[this.locale])
            this._readLocaleFile();
        if (!this.cache[this.locale][str] && this.updateFiles) {
            this.cache[this.locale][str] = str;
            this._enqueueWrite({
                directory: this.directory,
                locale: this.locale,
                cb
            });
        }
        else {
            cb();
        }
        return shim$2.format.apply(shim$2.format, [this.cache[this.locale][str] || str].concat(args));
    }
    __n() {
        const args = Array.prototype.slice.call(arguments);
        const singular = args.shift();
        const plural = args.shift();
        const quantity = args.shift();
        let cb = function () { };
        if (typeof args[args.length - 1] === 'function')
            cb = args.pop();
        if (!this.cache[this.locale])
            this._readLocaleFile();
        let str = quantity === 1 ? singular : plural;
        if (this.cache[this.locale][singular]) {
            const entry = this.cache[this.locale][singular];
            str = entry[quantity === 1 ? 'one' : 'other'];
        }
        if (!this.cache[this.locale][singular] && this.updateFiles) {
            this.cache[this.locale][singular] = {
                one: singular,
                other: plural
            };
            this._enqueueWrite({
                directory: this.directory,
                locale: this.locale,
                cb
            });
        }
        else {
            cb();
        }
        const values = [str];
        if (~str.indexOf('%d'))
            values.push(quantity);
        return shim$2.format.apply(shim$2.format, values.concat(args));
    }
    setLocale(locale) {
        this.locale = locale;
    }
    getLocale() {
        return this.locale;
    }
    updateLocale(obj) {
        if (!this.cache[this.locale])
            this._readLocaleFile();
        for (const key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                this.cache[this.locale][key] = obj[key];
            }
        }
    }
    _taggedLiteral(parts, ...args) {
        let str = '';
        parts.forEach(function (part, i) {
            const arg = args[i + 1];
            str += part;
            if (typeof arg !== 'undefined') {
                str += '%s';
            }
        });
        return this.__.apply(this, [str].concat([].slice.call(args, 1)));
    }
    _enqueueWrite(work) {
        this.writeQueue.push(work);
        if (this.writeQueue.length === 1)
            this._processWriteQueue();
    }
    _processWriteQueue() {
        const _this = this;
        const work = this.writeQueue[0];
        const directory = work.directory;
        const locale = work.locale;
        const cb = work.cb;
        const languageFile = this._resolveLocaleFile(directory, locale);
        const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
        shim$2.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {
            _this.writeQueue.shift();
            if (_this.writeQueue.length > 0)
                _this._processWriteQueue();
            cb(err);
        });
    }
    _readLocaleFile() {
        let localeLookup = {};
        const languageFile = this._resolveLocaleFile(this.directory, this.locale);
        try {
            if (shim$2.fs.readFileSync) {
                localeLookup = JSON.parse(shim$2.fs.readFileSync(languageFile, 'utf-8'));
            }
        }
        catch (err) {
            if (err instanceof SyntaxError) {
                err.message = 'syntax error in ' + languageFile;
            }
            if (err.code === 'ENOENT')
                localeLookup = {};
            else
                throw err;
        }
        this.cache[this.locale] = localeLookup;
    }
    _resolveLocaleFile(directory, locale) {
        let file = shim$2.resolve(directory, './', locale + '.json');
        if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
            const languageFile = shim$2.resolve(directory, './', locale.split('_')[0] + '.json');
            if (this._fileExistsSync(languageFile))
                file = languageFile;
        }
        return file;
    }
    _fileExistsSync(file) {
        return shim$2.exists(file);
    }
}
function y18n$1(opts, _shim) {
    shim$2 = _shim;
    const y18n = new Y18N(opts);
    return {
        __: y18n.__.bind(y18n),
        __n: y18n.__n.bind(y18n),
        setLocale: y18n.setLocale.bind(y18n),
        getLocale: y18n.getLocale.bind(y18n),
        updateLocale: y18n.updateLocale.bind(y18n),
        locale: y18n.locale
    };
}

const y18n = (opts) => {
  return y18n$1(opts, shim$3)
};

var getCallerFile$1;
var hasRequiredGetCallerFile;

function requireGetCallerFile () {
	if (hasRequiredGetCallerFile) return getCallerFile$1;
	hasRequiredGetCallerFile = 1;
	getCallerFile$1 = function getCallerFile(position) {
	    if (position === void 0) { position = 2; }
	    if (position >= Error.stackTraceLimit) {
	        throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`');
	    }
	    var oldPrepareStackTrace = Error.prepareStackTrace;
	    Error.prepareStackTrace = function (_, stack) { return stack; };
	    var stack = new Error().stack;
	    Error.prepareStackTrace = oldPrepareStackTrace;
	    if (stack !== null && typeof stack === 'object') {
	        return stack[position] ? stack[position].getFileName() : undefined;
	    }
	};
	return getCallerFile$1;
}

var getCallerFileExports = requireGetCallerFile();
var getCallerFile = /*@__PURE__*/getDefaultExportFromCjs(getCallerFileExports);

const __dirname$1 = fileURLToPath(import.meta.url);
const mainFilename = __dirname$1.substring(0, __dirname$1.lastIndexOf('node_modules'));
const require$1 = createRequire(import.meta.url);
var shim$1 = {
  assert: {
    notStrictEqual,
    strictEqual
  },
  cliui: ui,
  findUp: escalade,
  getEnv: (key) => {
    return process.env[key]
  },
  inspect,
  getProcessArgvBin,
  mainFilename: mainFilename || process.cwd(),
  Parser: yargsParser,
  path: {
    basename,
    dirname,
    extname,
    relative,
    resolve: resolve$2,
    join
  },
  process: {
    argv: () => process.argv,
    cwd: process.cwd,
    emitWarning: (warning, type) => process.emitWarning(warning, type),
    execPath: () => process.execPath,
    exit: (code) => {
      process.exit(code);
    },
    nextTick: process.nextTick,
    stdColumns: typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null
  },
  readFileSync: readFileSync$1,
  readdirSync: readdirSync$1,
  require: require$1,
  getCallerFile: () => {
    const callerFile = getCallerFile(3);
    return callerFile.match(/^file:\/\//) ? fileURLToPath(callerFile) : callerFile;
  },
  stringWidth,
  y18n: y18n({
    directory: resolve$2(__dirname$1, '../../../locales'),
    updateFiles: false
  })
};

function assertNotStrictEqual(actual, expected, shim, message) {
    shim.assert.notStrictEqual(actual, expected, message);
}
function assertSingleKey(actual, shim) {
    shim.assert.strictEqual(typeof actual, 'string');
}
function objectKeys(object) {
    return Object.keys(object);
}

function isPromise$1(maybePromise) {
    return (!!maybePromise &&
        !!maybePromise.then &&
        typeof maybePromise.then === 'function');
}

class YError extends Error {
    constructor(msg) {
        super(msg || 'yargs error');
        this.name = 'YError';
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, YError);
        }
    }
}

function parseCommand(cmd) {
    const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ');
    const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
    const bregex = /\.*[\][<>]/g;
    const firstCommand = splitCommand.shift();
    if (!firstCommand)
        throw new Error(`No command found in: ${cmd}`);
    const parsedCommand = {
        cmd: firstCommand.replace(bregex, ''),
        demanded: [],
        optional: [],
    };
    splitCommand.forEach((cmd, i) => {
        let variadic = false;
        cmd = cmd.replace(/\s/g, '');
        if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1)
            variadic = true;
        if (/^\[/.test(cmd)) {
            parsedCommand.optional.push({
                cmd: cmd.replace(bregex, '').split('|'),
                variadic,
            });
        }
        else {
            parsedCommand.demanded.push({
                cmd: cmd.replace(bregex, '').split('|'),
                variadic,
            });
        }
    });
    return parsedCommand;
}

const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
function argsert(arg1, arg2, arg3) {
    function parseArgs() {
        return typeof arg1 === 'object'
            ? [{ demanded: [], optional: [] }, arg1, arg2]
            : [
                parseCommand(`cmd ${arg1}`),
                arg2,
                arg3,
            ];
    }
    try {
        let position = 0;
        const [parsed, callerArguments, _length] = parseArgs();
        const args = [].slice.call(callerArguments);
        while (args.length && args[args.length - 1] === undefined)
            args.pop();
        const length = _length || args.length;
        if (length < parsed.demanded.length) {
            throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
        }
        const totalCommands = parsed.demanded.length + parsed.optional.length;
        if (length > totalCommands) {
            throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
        }
        parsed.demanded.forEach(demanded => {
            const arg = args.shift();
            const observedType = guessType(arg);
            const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*');
            if (matchingTypes.length === 0)
                argumentTypeError(observedType, demanded.cmd, position);
            position += 1;
        });
        parsed.optional.forEach(optional => {
            if (args.length === 0)
                return;
            const arg = args.shift();
            const observedType = guessType(arg);
            const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*');
            if (matchingTypes.length === 0)
                argumentTypeError(observedType, optional.cmd, position);
            position += 1;
        });
    }
    catch (err) {
        console.warn(err.stack);
    }
}
function guessType(arg) {
    if (Array.isArray(arg)) {
        return 'array';
    }
    else if (arg === null) {
        return 'null';
    }
    return typeof arg;
}
function argumentTypeError(observedType, allowedTypes, position) {
    throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`);
}

class GlobalMiddleware {
    constructor(yargs) {
        this.globalMiddleware = [];
        this.frozens = [];
        this.yargs = yargs;
    }
    addMiddleware(callback, applyBeforeValidation, global = true, mutates = false) {
        argsert('<array|function> [boolean] [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length);
        if (Array.isArray(callback)) {
            for (let i = 0; i < callback.length; i++) {
                if (typeof callback[i] !== 'function') {
                    throw Error('middleware must be a function');
                }
                const m = callback[i];
                m.applyBeforeValidation = applyBeforeValidation;
                m.global = global;
            }
            Array.prototype.push.apply(this.globalMiddleware, callback);
        }
        else if (typeof callback === 'function') {
            const m = callback;
            m.applyBeforeValidation = applyBeforeValidation;
            m.global = global;
            m.mutates = mutates;
            this.globalMiddleware.push(callback);
        }
        return this.yargs;
    }
    addCoerceMiddleware(callback, option) {
        const aliases = this.yargs.getAliases();
        this.globalMiddleware = this.globalMiddleware.filter(m => {
            const toCheck = [...(aliases[option] || []), option];
            if (!m.option)
                return true;
            else
                return !toCheck.includes(m.option);
        });
        callback.option = option;
        return this.addMiddleware(callback, true, true, true);
    }
    getMiddleware() {
        return this.globalMiddleware;
    }
    freeze() {
        this.frozens.push([...this.globalMiddleware]);
    }
    unfreeze() {
        const frozen = this.frozens.pop();
        if (frozen !== undefined)
            this.globalMiddleware = frozen;
    }
    reset() {
        this.globalMiddleware = this.globalMiddleware.filter(m => m.global);
    }
}
function commandMiddlewareFactory(commandMiddleware) {
    if (!commandMiddleware)
        return [];
    return commandMiddleware.map(middleware => {
        middleware.applyBeforeValidation = false;
        return middleware;
    });
}
function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
    return middlewares.reduce((acc, middleware) => {
        if (middleware.applyBeforeValidation !== beforeValidation) {
            return acc;
        }
        if (middleware.mutates) {
            if (middleware.applied)
                return acc;
            middleware.applied = true;
        }
        if (isPromise$1(acc)) {
            return acc
                .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)]))
                .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
        }
        else {
            const result = middleware(acc, yargs);
            return isPromise$1(result)
                ? result.then(middlewareObj => Object.assign(acc, middlewareObj))
                : Object.assign(acc, result);
        }
    }, argv);
}

function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => {
    throw err;
}) {
    try {
        const result = isFunction$1(getResult) ? getResult() : getResult;
        return isPromise$1(result)
            ? result.then((result) => resultHandler(result))
            : resultHandler(result);
    }
    catch (err) {
        return errorHandler(err);
    }
}
function isFunction$1(arg) {
    return typeof arg === 'function';
}

const DEFAULT_MARKER = /(^\*)|(^\$0)/;
class CommandInstance {
    constructor(usage, validation, globalMiddleware, shim) {
        this.requireCache = new Set();
        this.handlers = {};
        this.aliasMap = {};
        this.frozens = [];
        this.shim = shim;
        this.usage = usage;
        this.globalMiddleware = globalMiddleware;
        this.validation = validation;
    }
    addDirectory(dir, req, callerFile, opts) {
        opts = opts || {};
        this.requireCache.add(callerFile);
        const fullDirPath = this.shim.path.resolve(this.shim.path.dirname(callerFile), dir);
        const files = this.shim.readdirSync(fullDirPath, {
            recursive: opts.recurse ? true : false,
        });
        if (!Array.isArray(opts.extensions))
            opts.extensions = ['js'];
        const visit = typeof opts.visit === 'function' ? opts.visit : (o) => o;
        for (const fileb of files) {
            const file = fileb.toString();
            if (opts.exclude) {
                let exclude = false;
                if (typeof opts.exclude === 'function') {
                    exclude = opts.exclude(file);
                }
                else {
                    exclude = opts.exclude.test(file);
                }
                if (exclude)
                    continue;
            }
            if (opts.include) {
                let include = false;
                if (typeof opts.include === 'function') {
                    include = opts.include(file);
                }
                else {
                    include = opts.include.test(file);
                }
                if (!include)
                    continue;
            }
            let supportedExtension = false;
            for (const ext of opts.extensions) {
                if (file.endsWith(ext))
                    supportedExtension = true;
            }
            if (supportedExtension) {
                const joined = this.shim.path.join(fullDirPath, file);
                const module = req(joined);
                const extendableModule = Object.create(null, Object.getOwnPropertyDescriptors({ ...module }));
                const visited = visit(extendableModule, joined, file);
                if (visited) {
                    if (this.requireCache.has(joined))
                        continue;
                    else
                        this.requireCache.add(joined);
                    if (!extendableModule.command) {
                        extendableModule.command = this.shim.path.basename(joined, this.shim.path.extname(joined));
                    }
                    this.addHandler(extendableModule);
                }
            }
        }
    }
    addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) {
        let aliases = [];
        const middlewares = commandMiddlewareFactory(commandMiddleware);
        handler = handler || (() => { });
        if (Array.isArray(cmd)) {
            if (isCommandAndAliases(cmd)) {
                [cmd, ...aliases] = cmd;
            }
            else {
                for (const command of cmd) {
                    this.addHandler(command);
                }
            }
        }
        else if (isCommandHandlerDefinition(cmd)) {
            let command = Array.isArray(cmd.command) || typeof cmd.command === 'string'
                ? cmd.command
                : null;
            if (command === null) {
                throw new Error(`No command name given for module: ${this.shim.inspect(cmd)}`);
            }
            if (cmd.aliases)
                command = [].concat(command).concat(cmd.aliases);
            this.addHandler(command, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
            return;
        }
        else if (isCommandBuilderDefinition(builder)) {
            this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
            return;
        }
        if (typeof cmd === 'string') {
            const parsedCommand = parseCommand(cmd);
            aliases = aliases.map(alias => parseCommand(alias).cmd);
            let isDefault = false;
            const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => {
                if (DEFAULT_MARKER.test(c)) {
                    isDefault = true;
                    return false;
                }
                return true;
            });
            if (parsedAliases.length === 0 && isDefault)
                parsedAliases.push('$0');
            if (isDefault) {
                parsedCommand.cmd = parsedAliases[0];
                aliases = parsedAliases.slice(1);
                cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
            }
            aliases.forEach(alias => {
                this.aliasMap[alias] = parsedCommand.cmd;
            });
            if (description !== false) {
                this.usage.command(cmd, description, isDefault, aliases, deprecated);
            }
            this.handlers[parsedCommand.cmd] = {
                original: cmd,
                description,
                handler,
                builder: builder || {},
                middlewares,
                deprecated,
                demanded: parsedCommand.demanded,
                optional: parsedCommand.optional,
            };
            if (isDefault)
                this.defaultCommand = this.handlers[parsedCommand.cmd];
        }
    }
    getCommandHandlers() {
        return this.handlers;
    }
    getCommands() {
        return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
    }
    hasDefaultCommand() {
        return !!this.defaultCommand;
    }
    runCommand(command, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) {
        const commandHandler = this.handlers[command] ||
            this.handlers[this.aliasMap[command]] ||
            this.defaultCommand;
        const currentContext = yargs.getInternalMethods().getContext();
        const parentCommands = currentContext.commands.slice();
        const isDefaultCommand = !command;
        if (command) {
            currentContext.commands.push(command);
            currentContext.fullCommands.push(commandHandler.original);
        }
        const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet);
        return isPromise$1(builderResult)
            ? builderResult.then(result => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs))
            : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs);
    }
    applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) {
        const builder = commandHandler.builder;
        let innerYargs = yargs;
        if (isCommandBuilderCallback(builder)) {
            yargs.getInternalMethods().getUsageInstance().freeze();
            const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet);
            if (isPromise$1(builderOutput)) {
                return builderOutput.then(output => {
                    innerYargs = isYargsInstance(output) ? output : yargs;
                    return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
                });
            }
        }
        else if (isCommandBuilderOptionDefinitions(builder)) {
            yargs.getInternalMethods().getUsageInstance().freeze();
            innerYargs = yargs.getInternalMethods().reset(aliases);
            Object.keys(commandHandler.builder).forEach(key => {
                innerYargs.option(key, builder[key]);
            });
        }
        return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
    }
    parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) {
        if (isDefaultCommand)
            innerYargs.getInternalMethods().getUsageInstance().unfreeze(true);
        if (this.shouldUpdateUsage(innerYargs)) {
            innerYargs
                .getInternalMethods()
                .getUsageInstance()
                .usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
        }
        const innerArgv = innerYargs
            .getInternalMethods()
            .runYargsParserAndExecuteCommands(null, undefined, true, commandIndex, helpOnly);
        return isPromise$1(innerArgv)
            ? innerArgv.then(argv => ({
                aliases: innerYargs.parsed.aliases,
                innerArgv: argv,
            }))
            : {
                aliases: innerYargs.parsed.aliases,
                innerArgv: innerArgv,
            };
    }
    shouldUpdateUsage(yargs) {
        return (!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() &&
            yargs.getInternalMethods().getUsageInstance().getUsage().length === 0);
    }
    usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
        const c = DEFAULT_MARKER.test(commandHandler.original)
            ? commandHandler.original.replace(DEFAULT_MARKER, '').trim()
            : commandHandler.original;
        const pc = parentCommands.filter(c => {
            return !DEFAULT_MARKER.test(c);
        });
        pc.push(c);
        return `$0 ${pc.join(' ')}`;
    }
    handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) {
        if (!yargs.getInternalMethods().getHasOutput()) {
            const validation = yargs
                .getInternalMethods()
                .runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand);
            innerArgv = maybeAsyncResult(innerArgv, result => {
                validation(result);
                return result;
            });
        }
        if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) {
            yargs.getInternalMethods().setHasOutput();
            const populateDoubleDash = !!yargs.getOptions().configuration['populate--'];
            yargs
                .getInternalMethods()
                .postProcess(innerArgv, populateDoubleDash, false, false);
            innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
            innerArgv = maybeAsyncResult(innerArgv, result => {
                const handlerResult = commandHandler.handler(result);
                return isPromise$1(handlerResult)
                    ? handlerResult.then(() => result)
                    : result;
            });
            if (!isDefaultCommand) {
                yargs.getInternalMethods().getUsageInstance().cacheHelpMessage();
            }
            if (isPromise$1(innerArgv) &&
                !yargs.getInternalMethods().hasParseCallback()) {
                innerArgv.catch(error => {
                    try {
                        yargs.getInternalMethods().getUsageInstance().fail(null, error);
                    }
                    catch (_err) {
                    }
                });
            }
        }
        if (!isDefaultCommand) {
            currentContext.commands.pop();
            currentContext.fullCommands.pop();
        }
        return innerArgv;
    }
    applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) {
        let positionalMap = {};
        if (helpOnly)
            return innerArgv;
        if (!yargs.getInternalMethods().getHasOutput()) {
            positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs);
        }
        const middlewares = this.globalMiddleware
            .getMiddleware()
            .slice(0)
            .concat(commandHandler.middlewares);
        const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true);
        return isPromise$1(maybePromiseArgv)
            ? maybePromiseArgv.then(resolvedInnerArgv => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap))
            : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap);
    }
    populatePositionals(commandHandler, argv, context, yargs) {
        argv._ = argv._.slice(context.commands.length);
        const demanded = commandHandler.demanded.slice(0);
        const optional = commandHandler.optional.slice(0);
        const positionalMap = {};
        this.validation.positionalCount(demanded.length, argv._.length);
        while (demanded.length) {
            const demand = demanded.shift();
            this.populatePositional(demand, argv, positionalMap);
        }
        while (optional.length) {
            const maybe = optional.shift();
            this.populatePositional(maybe, argv, positionalMap);
        }
        argv._ = context.commands.concat(argv._.map(a => '' + a));
        this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs);
        return positionalMap;
    }
    populatePositional(positional, argv, positionalMap) {
        const cmd = positional.cmd[0];
        if (positional.variadic) {
            positionalMap[cmd] = argv._.splice(0).map(String);
        }
        else {
            if (argv._.length)
                positionalMap[cmd] = [String(argv._.shift())];
        }
    }
    cmdToParseOptions(cmdString) {
        const parseOptions = {
            array: [],
            default: {},
            alias: {},
            demand: {},
        };
        const parsed = parseCommand(cmdString);
        parsed.demanded.forEach(d => {
            const [cmd, ...aliases] = d.cmd;
            if (d.variadic) {
                parseOptions.array.push(cmd);
                parseOptions.default[cmd] = [];
            }
            parseOptions.alias[cmd] = aliases;
            parseOptions.demand[cmd] = true;
        });
        parsed.optional.forEach(o => {
            const [cmd, ...aliases] = o.cmd;
            if (o.variadic) {
                parseOptions.array.push(cmd);
                parseOptions.default[cmd] = [];
            }
            parseOptions.alias[cmd] = aliases;
        });
        return parseOptions;
    }
    postProcessPositionals(argv, positionalMap, parseOptions, yargs) {
        const options = Object.assign({}, yargs.getOptions());
        options.default = Object.assign(parseOptions.default, options.default);
        for (const key of Object.keys(parseOptions.alias)) {
            options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]);
        }
        options.array = options.array.concat(parseOptions.array);
        options.config = {};
        const unparsed = [];
        Object.keys(positionalMap).forEach(key => {
            positionalMap[key].map(value => {
                if (options.configuration['unknown-options-as-args'])
                    options.key[key] = true;
                unparsed.push(`--${key}`);
                unparsed.push(value);
            });
        });
        if (!unparsed.length)
            return;
        const config = Object.assign({}, options.configuration, {
            'populate--': false,
        });
        const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, {
            configuration: config,
        }));
        if (parsed.error) {
            yargs
                .getInternalMethods()
                .getUsageInstance()
                .fail(parsed.error.message, parsed.error);
        }
        else {
            const positionalKeys = Object.keys(positionalMap);
            Object.keys(positionalMap).forEach(key => {
                positionalKeys.push(...parsed.aliases[key]);
            });
            Object.keys(parsed.argv).forEach(key => {
                if (positionalKeys.includes(key)) {
                    if (!positionalMap[key])
                        positionalMap[key] = parsed.argv[key];
                    if (!this.isInConfigs(yargs, key) &&
                        !this.isDefaulted(yargs, key) &&
                        Object.prototype.hasOwnProperty.call(argv, key) &&
                        Object.prototype.hasOwnProperty.call(parsed.argv, key) &&
                        (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) {
                        argv[key] = [].concat(argv[key], parsed.argv[key]);
                    }
                    else {
                        argv[key] = parsed.argv[key];
                    }
                }
            });
        }
    }
    isDefaulted(yargs, key) {
        const { default: defaults } = yargs.getOptions();
        return (Object.prototype.hasOwnProperty.call(defaults, key) ||
            Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key)));
    }
    isInConfigs(yargs, key) {
        const { configObjects } = yargs.getOptions();
        return (configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) ||
            configObjects.some(c => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key))));
    }
    runDefaultBuilderOn(yargs) {
        if (!this.defaultCommand)
            return;
        if (this.shouldUpdateUsage(yargs)) {
            const commandString = DEFAULT_MARKER.test(this.defaultCommand.original)
                ? this.defaultCommand.original
                : this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
            yargs
                .getInternalMethods()
                .getUsageInstance()
                .usage(commandString, this.defaultCommand.description);
        }
        const builder = this.defaultCommand.builder;
        if (isCommandBuilderCallback(builder)) {
            return builder(yargs, true);
        }
        else if (!isCommandBuilderDefinition(builder)) {
            Object.keys(builder).forEach(key => {
                yargs.option(key, builder[key]);
            });
        }
        return undefined;
    }
    extractDesc({ describe, description, desc }) {
        for (const test of [describe, description, desc]) {
            if (typeof test === 'string' || test === false)
                return test;
            assertNotStrictEqual(test, true, this.shim);
        }
        return false;
    }
    freeze() {
        this.frozens.push({
            handlers: this.handlers,
            aliasMap: this.aliasMap,
            defaultCommand: this.defaultCommand,
        });
    }
    unfreeze() {
        const frozen = this.frozens.pop();
        assertNotStrictEqual(frozen, undefined, this.shim);
        ({
            handlers: this.handlers,
            aliasMap: this.aliasMap,
            defaultCommand: this.defaultCommand,
        } = frozen);
    }
    reset() {
        this.handlers = {};
        this.aliasMap = {};
        this.defaultCommand = undefined;
        this.requireCache = new Set();
        return this;
    }
}
function command(usage, validation, globalMiddleware, shim) {
    return new CommandInstance(usage, validation, globalMiddleware, shim);
}
function isCommandBuilderDefinition(builder) {
    return (typeof builder === 'object' &&
        !!builder.builder &&
        typeof builder.handler === 'function');
}
function isCommandAndAliases(cmd) {
    return cmd.every(c => typeof c === 'string');
}
function isCommandBuilderCallback(builder) {
    return typeof builder === 'function';
}
function isCommandBuilderOptionDefinitions(builder) {
    return typeof builder === 'object';
}
function isCommandHandlerDefinition(cmd) {
    return typeof cmd === 'object' && !Array.isArray(cmd);
}

function objFilter(original = {}, filter = () => true) {
    const obj = {};
    objectKeys(original).forEach(key => {
        if (filter(key, original[key])) {
            obj[key] = original[key];
        }
    });
    return obj;
}

function setBlocking(blocking) {
    if (typeof process === 'undefined')
        return;
    [process.stdout, process.stderr].forEach(_stream => {
        const stream = _stream;
        if (stream._handle &&
            stream.isTTY &&
            typeof stream._handle.setBlocking === 'function') {
            stream._handle.setBlocking(blocking);
        }
    });
}

function isBoolean(fail) {
    return typeof fail === 'boolean';
}
function usage(yargs, shim) {
    const __ = shim.y18n.__;
    const self = {};
    const fails = [];
    self.failFn = function failFn(f) {
        fails.push(f);
    };
    let failMessage = null;
    let globalFailMessage = null;
    let showHelpOnFail = true;
    self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) {
        const [enabled, message] = typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2];
        if (yargs.getInternalMethods().isGlobalContext()) {
            globalFailMessage = message;
        }
        failMessage = message;
        showHelpOnFail = enabled;
        return self;
    };
    let failureOutput = false;
    self.fail = function fail(msg, err) {
        const logger = yargs.getInternalMethods().getLoggerInstance();
        if (fails.length) {
            for (let i = fails.length - 1; i >= 0; --i) {
                const fail = fails[i];
                if (isBoolean(fail)) {
                    if (err)
                        throw err;
                    else if (msg)
                        throw Error(msg);
                }
                else {
                    fail(msg, err, self);
                }
            }
        }
        else {
            if (yargs.getExitProcess())
                setBlocking(true);
            if (!failureOutput) {
                failureOutput = true;
                if (showHelpOnFail) {
                    yargs.showHelp('error');
                    logger.error();
                }
                if (msg || err)
                    logger.error(msg || err);
                const globalOrCommandFailMessage = failMessage || globalFailMessage;
                if (globalOrCommandFailMessage) {
                    if (msg || err)
                        logger.error('');
                    logger.error(globalOrCommandFailMessage);
                }
            }
            err = err || new YError(msg);
            if (yargs.getExitProcess()) {
                return yargs.exit(1);
            }
            else if (yargs.getInternalMethods().hasParseCallback()) {
                return yargs.exit(1, err);
            }
            else {
                throw err;
            }
        }
    };
    let usages = [];
    let usageDisabled = false;
    self.usage = (msg, description) => {
        if (msg === null) {
            usageDisabled = true;
            usages = [];
            return self;
        }
        usageDisabled = false;
        usages.push([msg, description || '']);
        return self;
    };
    self.getUsage = () => {
        return usages;
    };
    self.getUsageDisabled = () => {
        return usageDisabled;
    };
    self.getPositionalGroupName = () => {
        return __('Positionals:');
    };
    let examples = [];
    self.example = (cmd, description) => {
        examples.push([cmd, description || '']);
    };
    let commands = [];
    self.command = function command(cmd, description, isDefault, aliases, deprecated = false) {
        if (isDefault) {
            commands = commands.map(cmdArray => {
                cmdArray[2] = false;
                return cmdArray;
            });
        }
        commands.push([cmd, description || '', isDefault, aliases, deprecated]);
    };
    self.getCommands = () => commands;
    let descriptions = {};
    self.describe = function describe(keyOrKeys, desc) {
        if (Array.isArray(keyOrKeys)) {
            keyOrKeys.forEach(k => {
                self.describe(k, desc);
            });
        }
        else if (typeof keyOrKeys === 'object') {
            Object.keys(keyOrKeys).forEach(k => {
                self.describe(k, keyOrKeys[k]);
            });
        }
        else {
            descriptions[keyOrKeys] = desc;
        }
    };
    self.getDescriptions = () => descriptions;
    let epilogs = [];
    self.epilog = msg => {
        epilogs.push(msg);
    };
    let wrapSet = false;
    let wrap;
    self.wrap = cols => {
        wrapSet = true;
        wrap = cols;
    };
    self.getWrap = () => {
        if (shim.getEnv('YARGS_DISABLE_WRAP')) {
            return null;
        }
        if (!wrapSet) {
            wrap = windowWidth();
            wrapSet = true;
        }
        return wrap;
    };
    const deferY18nLookupPrefix = '__yargsString__:';
    self.deferY18nLookup = str => deferY18nLookupPrefix + str;
    self.help = function help() {
        if (cachedHelpMessage)
            return cachedHelpMessage;
        normalizeAliases();
        const base$0 = yargs.customScriptName
            ? yargs.$0
            : shim.path.basename(yargs.$0);
        const demandedOptions = yargs.getDemandedOptions();
        const demandedCommands = yargs.getDemandedCommands();
        const deprecatedOptions = yargs.getDeprecatedOptions();
        const groups = yargs.getGroups();
        const options = yargs.getOptions();
        let keys = [];
        keys = keys.concat(Object.keys(descriptions));
        keys = keys.concat(Object.keys(demandedOptions));
        keys = keys.concat(Object.keys(demandedCommands));
        keys = keys.concat(Object.keys(options.default));
        keys = keys.filter(filterHiddenOptions);
        keys = Object.keys(keys.reduce((acc, key) => {
            if (key !== '_')
                acc[key] = true;
            return acc;
        }, {}));
        const theWrap = self.getWrap();
        const ui = shim.cliui({
            width: theWrap,
            wrap: !!theWrap,
        });
        if (!usageDisabled) {
            if (usages.length) {
                usages.forEach(usage => {
                    ui.div({ text: `${usage[0].replace(/\$0/g, base$0)}` });
                    if (usage[1]) {
                        ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] });
                    }
                });
                ui.div();
            }
            else if (commands.length) {
                let u = null;
                if (demandedCommands._) {
                    u = `${base$0} <${__('command')}>\n`;
                }
                else {
                    u = `${base$0} [${__('command')}]\n`;
                }
                ui.div(`${u}`);
            }
        }
        if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) {
            ui.div(__('Commands:'));
            const context = yargs.getInternalMethods().getContext();
            const parentCommands = context.commands.length
                ? `${context.commands.join(' ')} `
                : '';
            if (yargs.getInternalMethods().getParserConfiguration()['sort-commands'] ===
                true) {
                commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
            }
            const prefix = base$0 ? `${base$0} ` : '';
            commands.forEach(command => {
                const commandString = `${prefix}${parentCommands}${command[0].replace(/^\$0 ?/, '')}`;
                ui.span({
                    text: commandString,
                    padding: [0, 2, 0, 2],
                    width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4,
                }, { text: command[1] });
                const hints = [];
                if (command[2])
                    hints.push(`[${__('default')}]`);
                if (command[3] && command[3].length) {
                    hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`);
                }
                if (command[4]) {
                    if (typeof command[4] === 'string') {
                        hints.push(`[${__('deprecated: %s', command[4])}]`);
                    }
                    else {
                        hints.push(`[${__('deprecated')}]`);
                    }
                }
                if (hints.length) {
                    ui.div({
                        text: hints.join(' '),
                        padding: [0, 0, 0, 2],
                        align: 'right',
                    });
                }
                else {
                    ui.div();
                }
            });
            ui.div();
        }
        const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
        keys = keys.filter(key => !yargs.parsed.newAliases[key] &&
            aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1));
        const defaultGroup = __('Options:');
        if (!groups[defaultGroup])
            groups[defaultGroup] = [];
        addUngroupedKeys(keys, options.alias, groups, defaultGroup);
        const isLongSwitch = (sw) => /^--/.test(getText$1(sw));
        const displayedGroups = Object.keys(groups)
            .filter(groupName => groups[groupName].length > 0)
            .map(groupName => {
            const normalizedKeys = groups[groupName]
                .filter(filterHiddenOptions)
                .map(key => {
                if (aliasKeys.includes(key))
                    return key;
                for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
                    if ((options.alias[aliasKey] || []).includes(key))
                        return aliasKey;
                }
                return key;
            });
            return { groupName, normalizedKeys };
        })
            .filter(({ normalizedKeys }) => normalizedKeys.length > 0)
            .map(({ groupName, normalizedKeys }) => {
            const switches = normalizedKeys.reduce((acc, key) => {
                acc[key] = [key]
                    .concat(options.alias[key] || [])
                    .map(sw => {
                    if (groupName === self.getPositionalGroupName())
                        return sw;
                    else {
                        return ((/^[0-9]$/.test(sw)
                            ? options.boolean.includes(key)
                                ? '-'
                                : '--'
                            : sw.length > 1
                                ? '--'
                                : '-') + sw);
                    }
                })
                    .sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2)
                    ? 0
                    : isLongSwitch(sw1)
                        ? 1
                        : -1)
                    .join(', ');
                return acc;
            }, {});
            return { groupName, normalizedKeys, switches };
        });
        const shortSwitchesUsed = displayedGroups
            .filter(({ groupName }) => groupName !== self.getPositionalGroupName())
            .some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key])));
        if (shortSwitchesUsed) {
            displayedGroups
                .filter(({ groupName }) => groupName !== self.getPositionalGroupName())
                .forEach(({ normalizedKeys, switches }) => {
                normalizedKeys.forEach(key => {
                    if (isLongSwitch(switches[key])) {
                        switches[key] = addIndentation(switches[key], '-x, '.length);
                    }
                });
            });
        }
        displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
            ui.div(groupName);
            normalizedKeys.forEach(key => {
                const kswitch = switches[key];
                let desc = descriptions[key] || '';
                let type = null;
                if (desc.includes(deferY18nLookupPrefix))
                    desc = __(desc.substring(deferY18nLookupPrefix.length));
                if (options.boolean.includes(key))
                    type = `[${__('boolean')}]`;
                if (options.count.includes(key))
                    type = `[${__('count')}]`;
                if (options.string.includes(key))
                    type = `[${__('string')}]`;
                if (options.normalize.includes(key))
                    type = `[${__('string')}]`;
                if (options.array.includes(key))
                    type = `[${__('array')}]`;
                if (options.number.includes(key))
                    type = `[${__('number')}]`;
                const deprecatedExtra = (deprecated) => typeof deprecated === 'string'
                    ? `[${__('deprecated: %s', deprecated)}]`
                    : `[${__('deprecated')}]`;
                const extra = [
                    key in deprecatedOptions
                        ? deprecatedExtra(deprecatedOptions[key])
                        : null,
                    type,
                    key in demandedOptions ? `[${__('required')}]` : null,
                    options.choices && options.choices[key]
                        ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]`
                        : null,
                    defaultString(options.default[key], options.defaultDescription[key]),
                ]
                    .filter(Boolean)
                    .join(' ');
                ui.span({
                    text: getText$1(kswitch),
                    padding: [0, 2, 0, 2 + getIndentation(kswitch)],
                    width: maxWidth(switches, theWrap) + 4,
                }, desc);
                const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()['hide-types'] ===
                    true;
                if (extra && !shouldHideOptionExtras)
                    ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' });
                else
                    ui.div();
            });
            ui.div();
        });
        if (examples.length) {
            ui.div(__('Examples:'));
            examples.forEach(example => {
                example[0] = example[0].replace(/\$0/g, base$0);
            });
            examples.forEach(example => {
                if (example[1] === '') {
                    ui.div({
                        text: example[0],
                        padding: [0, 2, 0, 2],
                    });
                }
                else {
                    ui.div({
                        text: example[0],
                        padding: [0, 2, 0, 2],
                        width: maxWidth(examples, theWrap) + 4,
                    }, {
                        text: example[1],
                    });
                }
            });
            ui.div();
        }
        if (epilogs.length > 0) {
            const e = epilogs
                .map(epilog => epilog.replace(/\$0/g, base$0))
                .join('\n');
            ui.div(`${e}\n`);
        }
        return ui.toString().replace(/\s*$/, '');
    };
    function maxWidth(table, theWrap, modifier) {
        let width = 0;
        if (!Array.isArray(table)) {
            table = Object.values(table).map(v => [v]);
        }
        table.forEach(v => {
            width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText$1(v[0])}` : getText$1(v[0])) + getIndentation(v[0]), width);
        });
        if (theWrap)
            width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
        return width;
    }
    function normalizeAliases() {
        const demandedOptions = yargs.getDemandedOptions();
        const options = yargs.getOptions();
        (Object.keys(options.alias) || []).forEach(key => {
            options.alias[key].forEach(alias => {
                if (descriptions[alias])
                    self.describe(key, descriptions[alias]);
                if (alias in demandedOptions)
                    yargs.demandOption(key, demandedOptions[alias]);
                if (options.boolean.includes(alias))
                    yargs.boolean(key);
                if (options.count.includes(alias))
                    yargs.count(key);
                if (options.string.includes(alias))
                    yargs.string(key);
                if (options.normalize.includes(alias))
                    yargs.normalize(key);
                if (options.array.includes(alias))
                    yargs.array(key);
                if (options.number.includes(alias))
                    yargs.number(key);
            });
        });
    }
    let cachedHelpMessage;
    self.cacheHelpMessage = function () {
        cachedHelpMessage = this.help();
    };
    self.clearCachedHelpMessage = function () {
        cachedHelpMessage = undefined;
    };
    self.hasCachedHelpMessage = function () {
        return !!cachedHelpMessage;
    };
    function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
        let groupedKeys = [];
        let toCheck = null;
        Object.keys(groups).forEach(group => {
            groupedKeys = groupedKeys.concat(groups[group]);
        });
        keys.forEach(key => {
            toCheck = [key].concat(aliases[key]);
            if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
                groups[defaultGroup].push(key);
            }
        });
        return groupedKeys;
    }
    function filterHiddenOptions(key) {
        return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 ||
            yargs.parsed.argv[yargs.getOptions().showHiddenOpt]);
    }
    self.showHelp = (level) => {
        const logger = yargs.getInternalMethods().getLoggerInstance();
        if (!level)
            level = 'error';
        const emit = typeof level === 'function' ? level : logger[level];
        emit(self.help());
    };
    self.functionDescription = fn => {
        const description = fn.name
            ? shim.Parser.decamelize(fn.name, '-')
            : __('generated-value');
        return ['(', description, ')'].join('');
    };
    self.stringifiedValues = function stringifiedValues(values, separator) {
        let string = '';
        const sep = separator || ', ';
        const array = [].concat(values);
        if (!values || !array.length)
            return string;
        array.forEach(value => {
            if (string.length)
                string += sep;
            string += JSON.stringify(value);
        });
        return string;
    };
    function defaultString(value, defaultDescription) {
        let string = `[${__('default:')} `;
        if (value === undefined && !defaultDescription)
            return null;
        if (defaultDescription) {
            string += defaultDescription;
        }
        else {
            switch (typeof value) {
                case 'string':
                    string += `"${value}"`;
                    break;
                case 'object':
                    string += JSON.stringify(value);
                    break;
                default:
                    string += value;
            }
        }
        return `${string}]`;
    }
    function windowWidth() {
        const maxWidth = 80;
        if (shim.process.stdColumns) {
            return Math.min(maxWidth, shim.process.stdColumns);
        }
        else {
            return maxWidth;
        }
    }
    let version = null;
    self.version = ver => {
        version = ver;
    };
    self.showVersion = level => {
        const logger = yargs.getInternalMethods().getLoggerInstance();
        if (!level)
            level = 'error';
        const emit = typeof level === 'function' ? level : logger[level];
        emit(version);
    };
    self.reset = function reset(localLookup) {
        failMessage = null;
        failureOutput = false;
        usages = [];
        usageDisabled = false;
        epilogs = [];
        examples = [];
        commands = [];
        descriptions = objFilter(descriptions, k => !localLookup[k]);
        return self;
    };
    const frozens = [];
    self.freeze = function freeze() {
        frozens.push({
            failMessage,
            failureOutput,
            usages,
            usageDisabled,
            epilogs,
            examples,
            commands,
            descriptions,
        });
    };
    self.unfreeze = function unfreeze(defaultCommand = false) {
        const frozen = frozens.pop();
        if (!frozen)
            return;
        if (defaultCommand) {
            descriptions = { ...frozen.descriptions, ...descriptions };
            commands = [...frozen.commands, ...commands];
            usages = [...frozen.usages, ...usages];
            examples = [...frozen.examples, ...examples];
            epilogs = [...frozen.epilogs, ...epilogs];
        }
        else {
            ({
                failMessage,
                failureOutput,
                usages,
                usageDisabled,
                epilogs,
                examples,
                commands,
                descriptions,
            } = frozen);
        }
    };
    return self;
}
function isIndentedText(text) {
    return typeof text === 'object';
}
function addIndentation(text, indent) {
    return isIndentedText(text)
        ? { text: text.text, indentation: text.indentation + indent }
        : { text, indentation: indent };
}
function getIndentation(text) {
    return isIndentedText(text) ? text.indentation : 0;
}
function getText$1(text) {
    return isIndentedText(text) ? text.text : text;
}

const completionShTemplate = `###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
#    or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
#
_{{app_name}}_yargs_completions()
{
    local cur_word args type_list

    cur_word="\${COMP_WORDS[COMP_CWORD]}"
    args=("\${COMP_WORDS[@]}")

    # ask yargs to generate completions.
    # see https://stackoverflow.com/a/40944195/7080036 for the spaces-handling awk
    mapfile -t type_list < <({{app_path}} --get-yargs-completions "\${args[@]}")
    mapfile -t COMPREPLY < <(compgen -W "$( printf '%q ' "\${type_list[@]}" )" -- "\${cur_word}" |
        awk '/ / { print "\\""$0"\\"" } /^[^ ]+$/ { print $0 }')

    # if no match was found, fall back to filename completion
    if [ \${#COMPREPLY[@]} -eq 0 ]; then
      COMPREPLY=()
    fi

    return 0
}
complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
`;
const completionZshTemplate = `#compdef {{app_name}}
###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
#    or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
#
_{{app_name}}_yargs_completions()
{
  local reply
  local si=$IFS
  IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
  IFS=$si
  if [[ \${#reply} -gt 0 ]]; then
    _describe 'values' reply
  else
    _default
  fi
}
if [[ "'\${zsh_eval_context[-1]}" == "loadautofunc" ]]; then
  _{{app_name}}_yargs_completions "$@"
else
  compdef _{{app_name}}_yargs_completions {{app_name}}
fi
###-end-{{app_name}}-completions-###
`;

class Completion {
    constructor(yargs, usage, command, shim) {
        var _a, _b, _c;
        this.yargs = yargs;
        this.usage = usage;
        this.command = command;
        this.shim = shim;
        this.completionKey = 'get-yargs-completions';
        this.aliases = null;
        this.customCompletionFunction = null;
        this.indexAfterLastReset = 0;
        this.zshShell =
            (_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) ||
                ((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false;
    }
    defaultCompletion(args, argv, current, done) {
        const handlers = this.command.getCommandHandlers();
        for (let i = 0, ii = args.length; i < ii; ++i) {
            if (handlers[args[i]] && handlers[args[i]].builder) {
                const builder = handlers[args[i]].builder;
                if (isCommandBuilderCallback(builder)) {
                    this.indexAfterLastReset = i + 1;
                    const y = this.yargs.getInternalMethods().reset();
                    builder(y, true);
                    return y.argv;
                }
            }
        }
        const completions = [];
        this.commandCompletions(completions, args, current);
        this.optionCompletions(completions, args, argv, current);
        this.choicesFromOptionsCompletions(completions, args, argv, current);
        this.choicesFromPositionalsCompletions(completions, args, argv, current);
        done(null, completions);
    }
    commandCompletions(completions, args, current) {
        const parentCommands = this.yargs
            .getInternalMethods()
            .getContext().commands;
        if (!current.match(/^-/) &&
            parentCommands[parentCommands.length - 1] !== current &&
            !this.previousArgHasChoices(args)) {
            this.usage.getCommands().forEach(usageCommand => {
                const commandName = parseCommand(usageCommand[0]).cmd;
                if (args.indexOf(commandName) === -1) {
                    if (!this.zshShell) {
                        completions.push(commandName);
                    }
                    else {
                        const desc = usageCommand[1] || '';
                        completions.push(commandName.replace(/:/g, '\\:') + ':' + desc);
                    }
                }
            });
        }
    }
    optionCompletions(completions, args, argv, current) {
        if ((current.match(/^-/) || (current === '' && completions.length === 0)) &&
            !this.previousArgHasChoices(args)) {
            const options = this.yargs.getOptions();
            const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
            Object.keys(options.key).forEach(key => {
                const negable = !!options.configuration['boolean-negation'] &&
                    options.boolean.includes(key);
                const isPositionalKey = positionalKeys.includes(key);
                if (!isPositionalKey &&
                    !options.hiddenOptions.includes(key) &&
                    !this.argsContainKey(args, key, negable)) {
                    this.completeOptionKey(key, completions, current, negable && !!options.default[key]);
                }
            });
        }
    }
    choicesFromOptionsCompletions(completions, args, argv, current) {
        if (this.previousArgHasChoices(args)) {
            const choices = this.getPreviousArgChoices(args);
            if (choices && choices.length > 0) {
                completions.push(...choices.map(c => c.replace(/:/g, '\\:')));
            }
        }
    }
    choicesFromPositionalsCompletions(completions, args, argv, current) {
        if (current === '' &&
            completions.length > 0 &&
            this.previousArgHasChoices(args)) {
            return;
        }
        const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
        const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length +
            1);
        const positionalKey = positionalKeys[argv._.length - offset - 1];
        if (!positionalKey) {
            return;
        }
        const choices = this.yargs.getOptions().choices[positionalKey] || [];
        for (const choice of choices) {
            if (choice.startsWith(current)) {
                completions.push(choice.replace(/:/g, '\\:'));
            }
        }
    }
    getPreviousArgChoices(args) {
        if (args.length < 1)
            return;
        let previousArg = args[args.length - 1];
        let filter = '';
        if (!previousArg.startsWith('-') && args.length > 1) {
            filter = previousArg;
            previousArg = args[args.length - 2];
        }
        if (!previousArg.startsWith('-'))
            return;
        const previousArgKey = previousArg.replace(/^-+/, '');
        const options = this.yargs.getOptions();
        const possibleAliases = [
            previousArgKey,
            ...(this.yargs.getAliases()[previousArgKey] || []),
        ];
        let choices;
        for (const possibleAlias of possibleAliases) {
            if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) &&
                Array.isArray(options.choices[possibleAlias])) {
                choices = options.choices[possibleAlias];
                break;
            }
        }
        if (choices) {
            return choices.filter(choice => !filter || choice.startsWith(filter));
        }
    }
    previousArgHasChoices(args) {
        const choices = this.getPreviousArgChoices(args);
        return choices !== undefined && choices.length > 0;
    }
    argsContainKey(args, key, negable) {
        const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1;
        if (argsContains(key))
            return true;
        if (negable && argsContains(`no-${key}`))
            return true;
        if (this.aliases) {
            for (const alias of this.aliases[key]) {
                if (argsContains(alias))
                    return true;
            }
        }
        return false;
    }
    completeOptionKey(key, completions, current, negable) {
        var _a, _b, _c, _d;
        let keyWithDesc = key;
        if (this.zshShell) {
            const descs = this.usage.getDescriptions();
            const aliasKey = (_b = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b.find(alias => {
                const desc = descs[alias];
                return typeof desc === 'string' && desc.length > 0;
            });
            const descFromAlias = aliasKey ? descs[aliasKey] : undefined;
            const desc = (_d = (_c = descs[key]) !== null && _c !== void 0 ? _c : descFromAlias) !== null && _d !== void 0 ? _d : '';
            keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc
                .replace('__yargsString__:', '')
                .replace(/(\r\n|\n|\r)/gm, ' ')}`;
        }
        const startsByTwoDashes = (s) => /^--/.test(s);
        const isShortOption = (s) => /^[^0-9]$/.test(s);
        const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--';
        completions.push(dashes + keyWithDesc);
        if (negable) {
            completions.push(dashes + 'no-' + keyWithDesc);
        }
    }
    customCompletion(args, argv, current, done) {
        assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
        if (isSyncCompletionFunction(this.customCompletionFunction)) {
            const result = this.customCompletionFunction(current, argv);
            if (isPromise$1(result)) {
                return result
                    .then(list => {
                    this.shim.process.nextTick(() => {
                        done(null, list);
                    });
                })
                    .catch(err => {
                    this.shim.process.nextTick(() => {
                        done(err, undefined);
                    });
                });
            }
            return done(null, result);
        }
        else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
            return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => {
                done(null, completions);
            });
        }
        else {
            return this.customCompletionFunction(current, argv, completions => {
                done(null, completions);
            });
        }
    }
    getCompletion(args, done) {
        const current = args.length ? args[args.length - 1] : '';
        const argv = this.yargs.parse(args, true);
        const completionFunction = this.customCompletionFunction
            ? (argv) => this.customCompletion(args, argv, current, done)
            : (argv) => this.defaultCompletion(args, argv, current, done);
        return isPromise$1(argv)
            ? argv.then(completionFunction)
            : completionFunction(argv);
    }
    generateCompletionScript($0, cmd) {
        let script = this.zshShell
            ? completionZshTemplate
            : completionShTemplate;
        const name = this.shim.path.basename($0);
        if ($0.match(/\.js$/))
            $0 = `./${$0}`;
        script = script.replace(/{{app_name}}/g, name);
        script = script.replace(/{{completion_command}}/g, cmd);
        return script.replace(/{{app_path}}/g, $0);
    }
    registerFunction(fn) {
        this.customCompletionFunction = fn;
    }
    setParsed(parsed) {
        this.aliases = parsed.aliases;
    }
}
function completion(yargs, usage, command, shim) {
    return new Completion(yargs, usage, command, shim);
}
function isSyncCompletionFunction(completionFunction) {
    return completionFunction.length < 3;
}
function isFallbackCompletionFunction(completionFunction) {
    return completionFunction.length > 3;
}

function levenshtein(a, b) {
    if (a.length === 0)
        return b.length;
    if (b.length === 0)
        return a.length;
    const matrix = [];
    let i;
    for (i = 0; i <= b.length; i++) {
        matrix[i] = [i];
    }
    let j;
    for (j = 0; j <= a.length; j++) {
        matrix[0][j] = j;
    }
    for (i = 1; i <= b.length; i++) {
        for (j = 1; j <= a.length; j++) {
            if (b.charAt(i - 1) === a.charAt(j - 1)) {
                matrix[i][j] = matrix[i - 1][j - 1];
            }
            else {
                if (i > 1 &&
                    j > 1 &&
                    b.charAt(i - 2) === a.charAt(j - 1) &&
                    b.charAt(i - 1) === a.charAt(j - 2)) {
                    matrix[i][j] = matrix[i - 2][j - 2] + 1;
                }
                else {
                    matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
                }
            }
        }
    }
    return matrix[b.length][a.length];
}

const specialKeys = ['$0', '--', '_'];
function validation$3(yargs, usage, shim) {
    const __ = shim.y18n.__;
    const __n = shim.y18n.__n;
    const self = {};
    self.nonOptionCount = function nonOptionCount(argv) {
        const demandedCommands = yargs.getDemandedCommands();
        const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0);
        const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length;
        if (demandedCommands._ &&
            (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
            if (_s < demandedCommands._.min) {
                if (demandedCommands._.minMsg !== undefined) {
                    usage.fail(demandedCommands._.minMsg
                        ? demandedCommands._.minMsg
                            .replace(/\$0/g, _s.toString())
                            .replace(/\$1/, demandedCommands._.min.toString())
                        : null);
                }
                else {
                    usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString()));
                }
            }
            else if (_s > demandedCommands._.max) {
                if (demandedCommands._.maxMsg !== undefined) {
                    usage.fail(demandedCommands._.maxMsg
                        ? demandedCommands._.maxMsg
                            .replace(/\$0/g, _s.toString())
                            .replace(/\$1/, demandedCommands._.max.toString())
                        : null);
                }
                else {
                    usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString()));
                }
            }
        }
    };
    self.positionalCount = function positionalCount(required, observed) {
        if (observed < required) {
            usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + ''));
        }
    };
    self.requiredArguments = function requiredArguments(argv, demandedOptions) {
        let missing = null;
        for (const key of Object.keys(demandedOptions)) {
            if (!Object.prototype.hasOwnProperty.call(argv, key) ||
                typeof argv[key] === 'undefined') {
                missing = missing || {};
                missing[key] = demandedOptions[key];
            }
        }
        if (missing) {
            const customMsgs = [];
            for (const key of Object.keys(missing)) {
                const msg = missing[key];
                if (msg && customMsgs.indexOf(msg) < 0) {
                    customMsgs.push(msg);
                }
            }
            const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : '';
            usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg));
        }
    };
    self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) {
        var _a;
        const commandKeys = yargs
            .getInternalMethods()
            .getCommandInstance()
            .getCommands();
        const unknown = [];
        const currentContext = yargs.getInternalMethods().getContext();
        Object.keys(argv).forEach(key => {
            if (!specialKeys.includes(key) &&
                !Object.prototype.hasOwnProperty.call(positionalMap, key) &&
                !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) &&
                !self.isValidAndSomeAliasIsNotNew(key, aliases)) {
                unknown.push(key);
            }
        });
        if (checkPositionals &&
            (currentContext.commands.length > 0 ||
                commandKeys.length > 0 ||
                isDefaultCommand)) {
            argv._.slice(currentContext.commands.length).forEach(key => {
                if (!commandKeys.includes('' + key)) {
                    unknown.push('' + key);
                }
            });
        }
        if (checkPositionals) {
            const demandedCommands = yargs.getDemandedCommands();
            const maxNonOptDemanded = ((_a = demandedCommands._) === null || _a === void 0 ? void 0 : _a.max) || 0;
            const expected = currentContext.commands.length + maxNonOptDemanded;
            if (expected < argv._.length) {
                argv._.slice(expected).forEach(key => {
                    key = String(key);
                    if (!currentContext.commands.includes(key) &&
                        !unknown.includes(key)) {
                        unknown.push(key);
                    }
                });
            }
        }
        if (unknown.length) {
            usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', ')));
        }
    };
    self.unknownCommands = function unknownCommands(argv) {
        const commandKeys = yargs
            .getInternalMethods()
            .getCommandInstance()
            .getCommands();
        const unknown = [];
        const currentContext = yargs.getInternalMethods().getContext();
        if (currentContext.commands.length > 0 || commandKeys.length > 0) {
            argv._.slice(currentContext.commands.length).forEach(key => {
                if (!commandKeys.includes('' + key)) {
                    unknown.push('' + key);
                }
            });
        }
        if (unknown.length > 0) {
            usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', ')));
            return true;
        }
        else {
            return false;
        }
    };
    self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) {
        if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
            return false;
        }
        const newAliases = yargs.parsed.newAliases;
        return [key, ...aliases[key]].some(a => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]);
    };
    self.limitedChoices = function limitedChoices(argv) {
        const options = yargs.getOptions();
        const invalid = {};
        if (!Object.keys(options.choices).length)
            return;
        Object.keys(argv).forEach(key => {
            if (specialKeys.indexOf(key) === -1 &&
                Object.prototype.hasOwnProperty.call(options.choices, key)) {
                [].concat(argv[key]).forEach(value => {
                    if (options.choices[key].indexOf(value) === -1 &&
                        value !== undefined) {
                        invalid[key] = (invalid[key] || []).concat(value);
                    }
                });
            }
        });
        const invalidKeys = Object.keys(invalid);
        if (!invalidKeys.length)
            return;
        let msg = __('Invalid values:');
        invalidKeys.forEach(key => {
            msg += `\n  ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`;
        });
        usage.fail(msg);
    };
    let implied = {};
    self.implies = function implies(key, value) {
        argsert('<string|object> [array|number|string]', [key, value], arguments.length);
        if (typeof key === 'object') {
            Object.keys(key).forEach(k => {
                self.implies(k, key[k]);
            });
        }
        else {
            yargs.global(key);
            if (!implied[key]) {
                implied[key] = [];
            }
            if (Array.isArray(value)) {
                value.forEach(i => self.implies(key, i));
            }
            else {
                assertNotStrictEqual(value, undefined, shim);
                implied[key].push(value);
            }
        }
    };
    self.getImplied = function getImplied() {
        return implied;
    };
    function keyExists(argv, val) {
        const num = Number(val);
        val = isNaN(num) ? val : num;
        if (typeof val === 'number') {
            val = argv._.length >= val;
        }
        else if (val.match(/^--no-.+/)) {
            val = val.match(/^--no-(.+)/)[1];
            val = !Object.prototype.hasOwnProperty.call(argv, val);
        }
        else {
            val = Object.prototype.hasOwnProperty.call(argv, val);
        }
        return val;
    }
    self.implications = function implications(argv) {
        const implyFail = [];
        Object.keys(implied).forEach(key => {
            const origKey = key;
            (implied[key] || []).forEach(value => {
                let key = origKey;
                const origValue = value;
                key = keyExists(argv, key);
                value = keyExists(argv, value);
                if (key && !value) {
                    implyFail.push(` ${origKey} -> ${origValue}`);
                }
            });
        });
        if (implyFail.length) {
            let msg = `${__('Implications failed:')}\n`;
            implyFail.forEach(value => {
                msg += value;
            });
            usage.fail(msg);
        }
    };
    let conflicting = {};
    self.conflicts = function conflicts(key, value) {
        argsert('<string|object> [array|string]', [key, value], arguments.length);
        if (typeof key === 'object') {
            Object.keys(key).forEach(k => {
                self.conflicts(k, key[k]);
            });
        }
        else {
            yargs.global(key);
            if (!conflicting[key]) {
                conflicting[key] = [];
            }
            if (Array.isArray(value)) {
                value.forEach(i => self.conflicts(key, i));
            }
            else {
                conflicting[key].push(value);
            }
        }
    };
    self.getConflicting = () => conflicting;
    self.conflicting = function conflictingFn(argv) {
        Object.keys(argv).forEach(key => {
            if (conflicting[key]) {
                conflicting[key].forEach(value => {
                    if (value && argv[key] !== undefined && argv[value] !== undefined) {
                        usage.fail(__('Arguments %s and %s are mutually exclusive', key, value));
                    }
                });
            }
        });
        if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) {
            Object.keys(conflicting).forEach(key => {
                conflicting[key].forEach(value => {
                    if (value &&
                        argv[shim.Parser.camelCase(key)] !== undefined &&
                        argv[shim.Parser.camelCase(value)] !== undefined) {
                        usage.fail(__('Arguments %s and %s are mutually exclusive', key, value));
                    }
                });
            });
        }
    };
    self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
        const threshold = 3;
        potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
        let recommended = null;
        let bestDistance = Infinity;
        for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
            const d = levenshtein(cmd, candidate);
            if (d <= threshold && d < bestDistance) {
                bestDistance = d;
                recommended = candidate;
            }
        }
        if (recommended)
            usage.fail(__('Did you mean %s?', recommended));
    };
    self.reset = function reset(localLookup) {
        implied = objFilter(implied, k => !localLookup[k]);
        conflicting = objFilter(conflicting, k => !localLookup[k]);
        return self;
    };
    const frozens = [];
    self.freeze = function freeze() {
        frozens.push({
            implied,
            conflicting,
        });
    };
    self.unfreeze = function unfreeze() {
        const frozen = frozens.pop();
        assertNotStrictEqual(frozen, undefined, shim);
        ({ implied, conflicting } = frozen);
    };
    return self;
}

let previouslyVisitedConfigs = [];
let shim;
function applyExtends(config, cwd, mergeExtends, _shim) {
    shim = _shim;
    let defaultConfig = {};
    if (Object.prototype.hasOwnProperty.call(config, 'extends')) {
        if (typeof config.extends !== 'string')
            return defaultConfig;
        const isPath = /\.json|\..*rc$/.test(config.extends);
        let pathToDefault = null;
        if (!isPath) {
            try {
                pathToDefault = import.meta.resolve(config.extends);
            }
            catch (_err) {
                return config;
            }
        }
        else {
            pathToDefault = getPathToDefaultConfig(cwd, config.extends);
        }
        checkForCircularExtends(pathToDefault);
        previouslyVisitedConfigs.push(pathToDefault);
        defaultConfig = isPath
            ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8'))
            : _shim.require(config.extends);
        delete config.extends;
        defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim);
    }
    previouslyVisitedConfigs = [];
    return mergeExtends
        ? mergeDeep(defaultConfig, config)
        : Object.assign({}, defaultConfig, config);
}
function checkForCircularExtends(cfgPath) {
    if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
        throw new YError(`Circular extended configurations: '${cfgPath}'.`);
    }
}
function getPathToDefaultConfig(cwd, pathToExtend) {
    return shim.path.resolve(cwd, pathToExtend);
}
function mergeDeep(config1, config2) {
    const target = {};
    function isObject(obj) {
        return obj && typeof obj === 'object' && !Array.isArray(obj);
    }
    Object.assign(target, config1);
    for (const key of Object.keys(config2)) {
        if (isObject(config2[key]) && isObject(target[key])) {
            target[key] = mergeDeep(config1[key], config2[key]);
        }
        else {
            target[key] = config2[key];
        }
    }
    return target;
}

var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _YargsInstance_command, _YargsInstance_cwd, _YargsInstance_context, _YargsInstance_completion, _YargsInstance_completionCommand, _YargsInstance_defaultShowHiddenOpt, _YargsInstance_exitError, _YargsInstance_detectLocale, _YargsInstance_emittedWarnings, _YargsInstance_exitProcess, _YargsInstance_frozens, _YargsInstance_globalMiddleware, _YargsInstance_groups, _YargsInstance_hasOutput, _YargsInstance_helpOpt, _YargsInstance_isGlobalContext, _YargsInstance_logger, _YargsInstance_output, _YargsInstance_options, _YargsInstance_parentRequire, _YargsInstance_parserConfig, _YargsInstance_parseFn, _YargsInstance_parseContext, _YargsInstance_pkgs, _YargsInstance_preservedGroups, _YargsInstance_processArgs, _YargsInstance_recommendCommands, _YargsInstance_shim, _YargsInstance_strict, _YargsInstance_strictCommands, _YargsInstance_strictOptions, _YargsInstance_usage, _YargsInstance_usageConfig, _YargsInstance_versionOpt, _YargsInstance_validation;
function YargsFactory(_shim) {
    return (processArgs = [], cwd = _shim.process.cwd(), parentRequire) => {
        const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim);
        Object.defineProperty(yargs, 'argv', {
            get: () => {
                return yargs.parse();
            },
            enumerable: true,
        });
        yargs.help();
        yargs.version();
        return yargs;
    };
}
const kCopyDoubleDash = Symbol('copyDoubleDash');
const kCreateLogger = Symbol('copyDoubleDash');
const kDeleteFromParserHintObject = Symbol('deleteFromParserHintObject');
const kEmitWarning = Symbol('emitWarning');
const kFreeze = Symbol('freeze');
const kGetDollarZero = Symbol('getDollarZero');
const kGetParserConfiguration = Symbol('getParserConfiguration');
const kGetUsageConfiguration = Symbol('getUsageConfiguration');
const kGuessLocale = Symbol('guessLocale');
const kGuessVersion = Symbol('guessVersion');
const kParsePositionalNumbers = Symbol('parsePositionalNumbers');
const kPkgUp = Symbol('pkgUp');
const kPopulateParserHintArray = Symbol('populateParserHintArray');
const kPopulateParserHintSingleValueDictionary = Symbol('populateParserHintSingleValueDictionary');
const kPopulateParserHintArrayDictionary = Symbol('populateParserHintArrayDictionary');
const kPopulateParserHintDictionary = Symbol('populateParserHintDictionary');
const kSanitizeKey = Symbol('sanitizeKey');
const kSetKey = Symbol('setKey');
const kUnfreeze = Symbol('unfreeze');
const kValidateAsync = Symbol('validateAsync');
const kGetCommandInstance = Symbol('getCommandInstance');
const kGetContext = Symbol('getContext');
const kGetHasOutput = Symbol('getHasOutput');
const kGetLoggerInstance = Symbol('getLoggerInstance');
const kGetParseContext = Symbol('getParseContext');
const kGetUsageInstance = Symbol('getUsageInstance');
const kGetValidationInstance = Symbol('getValidationInstance');
const kHasParseCallback = Symbol('hasParseCallback');
const kIsGlobalContext = Symbol('isGlobalContext');
const kPostProcess = Symbol('postProcess');
const kRebase = Symbol('rebase');
const kReset = Symbol('reset');
const kRunYargsParserAndExecuteCommands = Symbol('runYargsParserAndExecuteCommands');
const kRunValidation = Symbol('runValidation');
const kSetHasOutput = Symbol('setHasOutput');
const kTrackManuallySetKeys = Symbol('kTrackManuallySetKeys');
const DEFAULT_LOCALE$1 = 'en_US';
class YargsInstance {
    constructor(processArgs = [], cwd, parentRequire, shim) {
        this.customScriptName = false;
        this.parsed = false;
        _YargsInstance_command.set(this, void 0);
        _YargsInstance_cwd.set(this, void 0);
        _YargsInstance_context.set(this, { commands: [], fullCommands: [] });
        _YargsInstance_completion.set(this, null);
        _YargsInstance_completionCommand.set(this, null);
        _YargsInstance_defaultShowHiddenOpt.set(this, 'show-hidden');
        _YargsInstance_exitError.set(this, null);
        _YargsInstance_detectLocale.set(this, true);
        _YargsInstance_emittedWarnings.set(this, {});
        _YargsInstance_exitProcess.set(this, true);
        _YargsInstance_frozens.set(this, []);
        _YargsInstance_globalMiddleware.set(this, void 0);
        _YargsInstance_groups.set(this, {});
        _YargsInstance_hasOutput.set(this, false);
        _YargsInstance_helpOpt.set(this, null);
        _YargsInstance_isGlobalContext.set(this, true);
        _YargsInstance_logger.set(this, void 0);
        _YargsInstance_output.set(this, '');
        _YargsInstance_options.set(this, void 0);
        _YargsInstance_parentRequire.set(this, void 0);
        _YargsInstance_parserConfig.set(this, {});
        _YargsInstance_parseFn.set(this, null);
        _YargsInstance_parseContext.set(this, null);
        _YargsInstance_pkgs.set(this, {});
        _YargsInstance_preservedGroups.set(this, {});
        _YargsInstance_processArgs.set(this, void 0);
        _YargsInstance_recommendCommands.set(this, false);
        _YargsInstance_shim.set(this, void 0);
        _YargsInstance_strict.set(this, false);
        _YargsInstance_strictCommands.set(this, false);
        _YargsInstance_strictOptions.set(this, false);
        _YargsInstance_usage.set(this, void 0);
        _YargsInstance_usageConfig.set(this, {});
        _YargsInstance_versionOpt.set(this, null);
        _YargsInstance_validation.set(this, void 0);
        __classPrivateFieldSet$1(this, _YargsInstance_shim, shim, "f");
        __classPrivateFieldSet$1(this, _YargsInstance_processArgs, processArgs, "f");
        __classPrivateFieldSet$1(this, _YargsInstance_cwd, cwd, "f");
        __classPrivateFieldSet$1(this, _YargsInstance_parentRequire, parentRequire, "f");
        __classPrivateFieldSet$1(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f");
        this.$0 = this[kGetDollarZero]();
        this[kReset]();
        __classPrivateFieldSet$1(this, _YargsInstance_command, __classPrivateFieldGet$1(this, _YargsInstance_command, "f"), "f");
        __classPrivateFieldSet$1(this, _YargsInstance_usage, __classPrivateFieldGet$1(this, _YargsInstance_usage, "f"), "f");
        __classPrivateFieldSet$1(this, _YargsInstance_validation, __classPrivateFieldGet$1(this, _YargsInstance_validation, "f"), "f");
        __classPrivateFieldSet$1(this, _YargsInstance_options, __classPrivateFieldGet$1(this, _YargsInstance_options, "f"), "f");
        __classPrivateFieldGet$1(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet$1(this, _YargsInstance_defaultShowHiddenOpt, "f");
        __classPrivateFieldSet$1(this, _YargsInstance_logger, this[kCreateLogger](), "f");
        __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").y18n.setLocale(DEFAULT_LOCALE$1);
    }
    addHelpOpt(opt, msg) {
        const defaultHelpOpt = 'help';
        argsert('[string|boolean] [string]', [opt, msg], arguments.length);
        if (__classPrivateFieldGet$1(this, _YargsInstance_helpOpt, "f")) {
            this[kDeleteFromParserHintObject](__classPrivateFieldGet$1(this, _YargsInstance_helpOpt, "f"));
            __classPrivateFieldSet$1(this, _YargsInstance_helpOpt, null, "f");
        }
        if (opt === false && msg === undefined)
            return this;
        __classPrivateFieldSet$1(this, _YargsInstance_helpOpt, typeof opt === 'string' ? opt : defaultHelpOpt, "f");
        this.boolean(__classPrivateFieldGet$1(this, _YargsInstance_helpOpt, "f"));
        this.describe(__classPrivateFieldGet$1(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").deferY18nLookup('Show help'));
        return this;
    }
    help(opt, msg) {
        return this.addHelpOpt(opt, msg);
    }
    addShowHiddenOpt(opt, msg) {
        argsert('[string|boolean] [string]', [opt, msg], arguments.length);
        if (opt === false && msg === undefined)
            return this;
        const showHiddenOpt = typeof opt === 'string' ? opt : __classPrivateFieldGet$1(this, _YargsInstance_defaultShowHiddenOpt, "f");
        this.boolean(showHiddenOpt);
        this.describe(showHiddenOpt, msg || __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").deferY18nLookup('Show hidden options'));
        __classPrivateFieldGet$1(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt;
        return this;
    }
    showHidden(opt, msg) {
        return this.addShowHiddenOpt(opt, msg);
    }
    alias(key, value) {
        argsert('<object|string|array> [string|array]', [key, value], arguments.length);
        this[kPopulateParserHintArrayDictionary](this.alias.bind(this), 'alias', key, value);
        return this;
    }
    array(keys) {
        argsert('<array|string>', [keys], arguments.length);
        this[kPopulateParserHintArray]('array', keys);
        this[kTrackManuallySetKeys](keys);
        return this;
    }
    boolean(keys) {
        argsert('<array|string>', [keys], arguments.length);
        this[kPopulateParserHintArray]('boolean', keys);
        this[kTrackManuallySetKeys](keys);
        return this;
    }
    check(f, global) {
        argsert('<function> [boolean]', [f, global], arguments.length);
        this.middleware((argv, _yargs) => {
            return maybeAsyncResult(() => {
                return f(argv, _yargs.getOptions());
            }, (result) => {
                if (!result) {
                    __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet$1(this, _YargsInstance_shim, "f").y18n.__('Argument check failed: %s', f.toString()));
                }
                else if (typeof result === 'string' || result instanceof Error) {
                    __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").fail(result.toString(), result);
                }
                return argv;
            }, (err) => {
                __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err);
                return argv;
            });
        }, false, global);
        return this;
    }
    choices(key, value) {
        argsert('<object|string|array> [string|array]', [key, value], arguments.length);
        this[kPopulateParserHintArrayDictionary](this.choices.bind(this), 'choices', key, value);
        return this;
    }
    coerce(keys, value) {
        argsert('<object|string|array> [function]', [keys, value], arguments.length);
        if (Array.isArray(keys)) {
            if (!value) {
                throw new YError('coerce callback must be provided');
            }
            for (const key of keys) {
                this.coerce(key, value);
            }
            return this;
        }
        else if (typeof keys === 'object') {
            for (const key of Object.keys(keys)) {
                this.coerce(key, keys[key]);
            }
            return this;
        }
        if (!value) {
            throw new YError('coerce callback must be provided');
        }
        const coerceKey = keys;
        __classPrivateFieldGet$1(this, _YargsInstance_options, "f").key[coerceKey] = true;
        __classPrivateFieldGet$1(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => {
            var _a;
            const coerceKeyAliases = (_a = yargs.getAliases()[coerceKey]) !== null && _a !== void 0 ? _a : [];
            const argvKeys = [coerceKey, ...coerceKeyAliases].filter(key => Object.prototype.hasOwnProperty.call(argv, key));
            if (argvKeys.length === 0) {
                return argv;
            }
            return maybeAsyncResult(() => {
                return value(argv[argvKeys[0]]);
            }, (result) => {
                argvKeys.forEach(key => {
                    argv[key] = result;
                });
                return argv;
            }, (err) => {
                throw new YError(err.message);
            });
        }, coerceKey);
        return this;
    }
    conflicts(key1, key2) {
        argsert('<string|object> [string|array]', [key1, key2], arguments.length);
        __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").conflicts(key1, key2);
        return this;
    }
    config(key = 'config', msg, parseFn) {
        argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length);
        if (typeof key === 'object' && !Array.isArray(key)) {
            key = applyExtends(key, __classPrivateFieldGet$1(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f"));
            __classPrivateFieldGet$1(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet$1(this, _YargsInstance_options, "f").configObjects || []).concat(key);
            return this;
        }
        if (typeof msg === 'function') {
            parseFn = msg;
            msg = undefined;
        }
        this.describe(key, msg || __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").deferY18nLookup('Path to JSON config file'));
        (Array.isArray(key) ? key : [key]).forEach(k => {
            __classPrivateFieldGet$1(this, _YargsInstance_options, "f").config[k] = parseFn || true;
        });
        return this;
    }
    completion(cmd, desc, fn) {
        argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length);
        if (typeof desc === 'function') {
            fn = desc;
            desc = undefined;
        }
        __classPrivateFieldSet$1(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet$1(this, _YargsInstance_completionCommand, "f") || 'completion', "f");
        if (!desc && desc !== false) {
            desc = 'generate completion script';
        }
        this.command(__classPrivateFieldGet$1(this, _YargsInstance_completionCommand, "f"), desc);
        if (fn)
            __classPrivateFieldGet$1(this, _YargsInstance_completion, "f").registerFunction(fn);
        return this;
    }
    command(cmd, description, builder, handler, middlewares, deprecated) {
        argsert('<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length);
        __classPrivateFieldGet$1(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated);
        return this;
    }
    commands(cmd, description, builder, handler, middlewares, deprecated) {
        return this.command(cmd, description, builder, handler, middlewares, deprecated);
    }
    commandDir(dir, opts) {
        argsert('<string> [object]', [dir, opts], arguments.length);
        const req = __classPrivateFieldGet$1(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").require;
        __classPrivateFieldGet$1(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").getCallerFile(), opts);
        return this;
    }
    count(keys) {
        argsert('<array|string>', [keys], arguments.length);
        this[kPopulateParserHintArray]('count', keys);
        this[kTrackManuallySetKeys](keys);
        return this;
    }
    default(key, value, defaultDescription) {
        argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length);
        if (defaultDescription) {
            assertSingleKey(key, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f"));
            __classPrivateFieldGet$1(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription;
        }
        if (typeof value === 'function') {
            assertSingleKey(key, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f"));
            if (!__classPrivateFieldGet$1(this, _YargsInstance_options, "f").defaultDescription[key])
                __classPrivateFieldGet$1(this, _YargsInstance_options, "f").defaultDescription[key] =
                    __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").functionDescription(value);
            value = value.call();
        }
        this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), 'default', key, value);
        return this;
    }
    defaults(key, value, defaultDescription) {
        return this.default(key, value, defaultDescription);
    }
    demandCommand(min = 1, max, minMsg, maxMsg) {
        argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length);
        if (typeof max !== 'number') {
            minMsg = max;
            max = Infinity;
        }
        this.global('_', false);
        __classPrivateFieldGet$1(this, _YargsInstance_options, "f").demandedCommands._ = {
            min,
            max,
            minMsg,
            maxMsg,
        };
        return this;
    }
    demand(keys, max, msg) {
        if (Array.isArray(max)) {
            max.forEach(key => {
                assertNotStrictEqual(msg, true, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f"));
                this.demandOption(key, msg);
            });
            max = Infinity;
        }
        else if (typeof max !== 'number') {
            msg = max;
            max = Infinity;
        }
        if (typeof keys === 'number') {
            assertNotStrictEqual(msg, true, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f"));
            this.demandCommand(keys, max, msg, msg);
        }
        else if (Array.isArray(keys)) {
            keys.forEach(key => {
                assertNotStrictEqual(msg, true, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f"));
                this.demandOption(key, msg);
            });
        }
        else {
            if (typeof msg === 'string') {
                this.demandOption(keys, msg);
            }
            else if (msg === true || typeof msg === 'undefined') {
                this.demandOption(keys);
            }
        }
        return this;
    }
    demandOption(keys, msg) {
        argsert('<object|string|array> [string]', [keys, msg], arguments.length);
        this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), 'demandedOptions', keys, msg);
        return this;
    }
    deprecateOption(option, message) {
        argsert('<string> [string|boolean]', [option, message], arguments.length);
        __classPrivateFieldGet$1(this, _YargsInstance_options, "f").deprecatedOptions[option] = message;
        return this;
    }
    describe(keys, description) {
        argsert('<object|string|array> [string]', [keys, description], arguments.length);
        this[kSetKey](keys, true);
        __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").describe(keys, description);
        return this;
    }
    detectLocale(detect) {
        argsert('<boolean>', [detect], arguments.length);
        __classPrivateFieldSet$1(this, _YargsInstance_detectLocale, detect, "f");
        return this;
    }
    env(prefix) {
        argsert('[string|boolean]', [prefix], arguments.length);
        if (prefix === false)
            delete __classPrivateFieldGet$1(this, _YargsInstance_options, "f").envPrefix;
        else
            __classPrivateFieldGet$1(this, _YargsInstance_options, "f").envPrefix = prefix || '';
        return this;
    }
    epilogue(msg) {
        argsert('<string>', [msg], arguments.length);
        __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").epilog(msg);
        return this;
    }
    epilog(msg) {
        return this.epilogue(msg);
    }
    example(cmd, description) {
        argsert('<string|array> [string]', [cmd, description], arguments.length);
        if (Array.isArray(cmd)) {
            cmd.forEach(exampleParams => this.example(...exampleParams));
        }
        else {
            __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").example(cmd, description);
        }
        return this;
    }
    exit(code, err) {
        __classPrivateFieldSet$1(this, _YargsInstance_hasOutput, true, "f");
        __classPrivateFieldSet$1(this, _YargsInstance_exitError, err, "f");
        if (__classPrivateFieldGet$1(this, _YargsInstance_exitProcess, "f"))
            __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").process.exit(code);
    }
    exitProcess(enabled = true) {
        argsert('[boolean]', [enabled], arguments.length);
        __classPrivateFieldSet$1(this, _YargsInstance_exitProcess, enabled, "f");
        return this;
    }
    fail(f) {
        argsert('<function|boolean>', [f], arguments.length);
        if (typeof f === 'boolean' && f !== false) {
            throw new YError("Invalid first argument. Expected function or boolean 'false'");
        }
        __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").failFn(f);
        return this;
    }
    getAliases() {
        return this.parsed ? this.parsed.aliases : {};
    }
    async getCompletion(args, done) {
        argsert('<array> [function]', [args, done], arguments.length);
        if (!done) {
            return new Promise((resolve, reject) => {
                __classPrivateFieldGet$1(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => {
                    if (err)
                        reject(err);
                    else
                        resolve(completions);
                });
            });
        }
        else {
            return __classPrivateFieldGet$1(this, _YargsInstance_completion, "f").getCompletion(args, done);
        }
    }
    getDemandedOptions() {
        argsert([], 0);
        return __classPrivateFieldGet$1(this, _YargsInstance_options, "f").demandedOptions;
    }
    getDemandedCommands() {
        argsert([], 0);
        return __classPrivateFieldGet$1(this, _YargsInstance_options, "f").demandedCommands;
    }
    getDeprecatedOptions() {
        argsert([], 0);
        return __classPrivateFieldGet$1(this, _YargsInstance_options, "f").deprecatedOptions;
    }
    getDetectLocale() {
        return __classPrivateFieldGet$1(this, _YargsInstance_detectLocale, "f");
    }
    getExitProcess() {
        return __classPrivateFieldGet$1(this, _YargsInstance_exitProcess, "f");
    }
    getGroups() {
        return Object.assign({}, __classPrivateFieldGet$1(this, _YargsInstance_groups, "f"), __classPrivateFieldGet$1(this, _YargsInstance_preservedGroups, "f"));
    }
    getHelp() {
        __classPrivateFieldSet$1(this, _YargsInstance_hasOutput, true, "f");
        if (!__classPrivateFieldGet$1(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
            if (!this.parsed) {
                const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet$1(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true);
                if (isPromise$1(parse)) {
                    return parse.then(() => {
                        return __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").help();
                    });
                }
            }
            const builderResponse = __classPrivateFieldGet$1(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
            if (isPromise$1(builderResponse)) {
                return builderResponse.then(() => {
                    return __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").help();
                });
            }
        }
        return Promise.resolve(__classPrivateFieldGet$1(this, _YargsInstance_usage, "f").help());
    }
    getOptions() {
        return __classPrivateFieldGet$1(this, _YargsInstance_options, "f");
    }
    getStrict() {
        return __classPrivateFieldGet$1(this, _YargsInstance_strict, "f");
    }
    getStrictCommands() {
        return __classPrivateFieldGet$1(this, _YargsInstance_strictCommands, "f");
    }
    getStrictOptions() {
        return __classPrivateFieldGet$1(this, _YargsInstance_strictOptions, "f");
    }
    global(globals, global) {
        argsert('<string|array> [boolean]', [globals, global], arguments.length);
        globals = [].concat(globals);
        if (global !== false) {
            __classPrivateFieldGet$1(this, _YargsInstance_options, "f").local = __classPrivateFieldGet$1(this, _YargsInstance_options, "f").local.filter(l => globals.indexOf(l) === -1);
        }
        else {
            globals.forEach(g => {
                if (!__classPrivateFieldGet$1(this, _YargsInstance_options, "f").local.includes(g))
                    __classPrivateFieldGet$1(this, _YargsInstance_options, "f").local.push(g);
            });
        }
        return this;
    }
    group(opts, groupName) {
        argsert('<string|array> <string>', [opts, groupName], arguments.length);
        const existing = __classPrivateFieldGet$1(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet$1(this, _YargsInstance_groups, "f")[groupName];
        if (__classPrivateFieldGet$1(this, _YargsInstance_preservedGroups, "f")[groupName]) {
            delete __classPrivateFieldGet$1(this, _YargsInstance_preservedGroups, "f")[groupName];
        }
        const seen = {};
        __classPrivateFieldGet$1(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter(key => {
            if (seen[key])
                return false;
            return (seen[key] = true);
        });
        return this;
    }
    hide(key) {
        argsert('<string>', [key], arguments.length);
        __classPrivateFieldGet$1(this, _YargsInstance_options, "f").hiddenOptions.push(key);
        return this;
    }
    implies(key, value) {
        argsert('<string|object> [number|string|array]', [key, value], arguments.length);
        __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").implies(key, value);
        return this;
    }
    locale(locale) {
        argsert('[string]', [locale], arguments.length);
        if (locale === undefined) {
            this[kGuessLocale]();
            return __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").y18n.getLocale();
        }
        __classPrivateFieldSet$1(this, _YargsInstance_detectLocale, false, "f");
        __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").y18n.setLocale(locale);
        return this;
    }
    middleware(callback, applyBeforeValidation, global) {
        return __classPrivateFieldGet$1(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global);
    }
    nargs(key, value) {
        argsert('<string|object|array> [number]', [key, value], arguments.length);
        this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), 'narg', key, value);
        return this;
    }
    normalize(keys) {
        argsert('<array|string>', [keys], arguments.length);
        this[kPopulateParserHintArray]('normalize', keys);
        return this;
    }
    number(keys) {
        argsert('<array|string>', [keys], arguments.length);
        this[kPopulateParserHintArray]('number', keys);
        this[kTrackManuallySetKeys](keys);
        return this;
    }
    option(key, opt) {
        argsert('<string|object> [object]', [key, opt], arguments.length);
        if (typeof key === 'object') {
            Object.keys(key).forEach(k => {
                this.options(k, key[k]);
            });
        }
        else {
            if (typeof opt !== 'object') {
                opt = {};
            }
            this[kTrackManuallySetKeys](key);
            if (__classPrivateFieldGet$1(this, _YargsInstance_versionOpt, "f") && (key === 'version' || (opt === null || opt === void 0 ? void 0 : opt.alias) === 'version')) {
                this[kEmitWarning]([
                    '"version" is a reserved word.',
                    'Please do one of the following:',
                    '- Disable version with `yargs.version(false)` if using "version" as an option',
                    '- Use the built-in `yargs.version` method instead (if applicable)',
                    '- Use a different option key',
                    'https://yargs.js.org/docs/#api-reference-version',
                ].join('\n'), undefined, 'versionWarning');
            }
            __classPrivateFieldGet$1(this, _YargsInstance_options, "f").key[key] = true;
            if (opt.alias)
                this.alias(key, opt.alias);
            const deprecate = opt.deprecate || opt.deprecated;
            if (deprecate) {
                this.deprecateOption(key, deprecate);
            }
            const demand = opt.demand || opt.required || opt.require;
            if (demand) {
                this.demand(key, demand);
            }
            if (opt.demandOption) {
                this.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined);
            }
            if (opt.conflicts) {
                this.conflicts(key, opt.conflicts);
            }
            if ('default' in opt) {
                this.default(key, opt.default);
            }
            if (opt.implies !== undefined) {
                this.implies(key, opt.implies);
            }
            if (opt.nargs !== undefined) {
                this.nargs(key, opt.nargs);
            }
            if (opt.config) {
                this.config(key, opt.configParser);
            }
            if (opt.normalize) {
                this.normalize(key);
            }
            if (opt.choices) {
                this.choices(key, opt.choices);
            }
            if (opt.coerce) {
                this.coerce(key, opt.coerce);
            }
            if (opt.group) {
                this.group(key, opt.group);
            }
            if (opt.boolean || opt.type === 'boolean') {
                this.boolean(key);
                if (opt.alias)
                    this.boolean(opt.alias);
            }
            if (opt.array || opt.type === 'array') {
                this.array(key);
                if (opt.alias)
                    this.array(opt.alias);
            }
            if (opt.number || opt.type === 'number') {
                this.number(key);
                if (opt.alias)
                    this.number(opt.alias);
            }
            if (opt.string || opt.type === 'string') {
                this.string(key);
                if (opt.alias)
                    this.string(opt.alias);
            }
            if (opt.count || opt.type === 'count') {
                this.count(key);
            }
            if (typeof opt.global === 'boolean') {
                this.global(key, opt.global);
            }
            if (opt.defaultDescription) {
                __classPrivateFieldGet$1(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription;
            }
            if (opt.skipValidation) {
                this.skipValidation(key);
            }
            const desc = opt.describe || opt.description || opt.desc;
            const descriptions = __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").getDescriptions();
            if (!Object.prototype.hasOwnProperty.call(descriptions, key) ||
                typeof desc === 'string') {
                this.describe(key, desc);
            }
            if (opt.hidden) {
                this.hide(key);
            }
            if (opt.requiresArg) {
                this.requiresArg(key);
            }
        }
        return this;
    }
    options(key, opt) {
        return this.option(key, opt);
    }
    parse(args, shortCircuit, _parseFn) {
        argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length);
        this[kFreeze]();
        if (typeof args === 'undefined') {
            args = __classPrivateFieldGet$1(this, _YargsInstance_processArgs, "f");
        }
        if (typeof shortCircuit === 'object') {
            __classPrivateFieldSet$1(this, _YargsInstance_parseContext, shortCircuit, "f");
            shortCircuit = _parseFn;
        }
        if (typeof shortCircuit === 'function') {
            __classPrivateFieldSet$1(this, _YargsInstance_parseFn, shortCircuit, "f");
            shortCircuit = false;
        }
        if (!shortCircuit)
            __classPrivateFieldSet$1(this, _YargsInstance_processArgs, args, "f");
        if (__classPrivateFieldGet$1(this, _YargsInstance_parseFn, "f"))
            __classPrivateFieldSet$1(this, _YargsInstance_exitProcess, false, "f");
        const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit);
        const tmpParsed = this.parsed;
        __classPrivateFieldGet$1(this, _YargsInstance_completion, "f").setParsed(this.parsed);
        if (isPromise$1(parsed)) {
            return parsed
                .then(argv => {
                if (__classPrivateFieldGet$1(this, _YargsInstance_parseFn, "f"))
                    __classPrivateFieldGet$1(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet$1(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet$1(this, _YargsInstance_output, "f"));
                return argv;
            })
                .catch(err => {
                if (__classPrivateFieldGet$1(this, _YargsInstance_parseFn, "f")) {
                    __classPrivateFieldGet$1(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet$1(this, _YargsInstance_output, "f"));
                }
                throw err;
            })
                .finally(() => {
                this[kUnfreeze]();
                this.parsed = tmpParsed;
            });
        }
        else {
            if (__classPrivateFieldGet$1(this, _YargsInstance_parseFn, "f"))
                __classPrivateFieldGet$1(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet$1(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet$1(this, _YargsInstance_output, "f"));
            this[kUnfreeze]();
            this.parsed = tmpParsed;
        }
        return parsed;
    }
    parseAsync(args, shortCircuit, _parseFn) {
        const maybePromise = this.parse(args, shortCircuit, _parseFn);
        return !isPromise$1(maybePromise)
            ? Promise.resolve(maybePromise)
            : maybePromise;
    }
    parseSync(args, shortCircuit, _parseFn) {
        const maybePromise = this.parse(args, shortCircuit, _parseFn);
        if (isPromise$1(maybePromise)) {
            throw new YError('.parseSync() must not be used with asynchronous builders, handlers, or middleware');
        }
        return maybePromise;
    }
    parserConfiguration(config) {
        argsert('<object>', [config], arguments.length);
        __classPrivateFieldSet$1(this, _YargsInstance_parserConfig, config, "f");
        return this;
    }
    pkgConf(key, rootPath) {
        argsert('<string> [string]', [key, rootPath], arguments.length);
        let conf = null;
        const obj = this[kPkgUp](rootPath || __classPrivateFieldGet$1(this, _YargsInstance_cwd, "f"));
        if (obj[key] && typeof obj[key] === 'object') {
            conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet$1(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f"));
            __classPrivateFieldGet$1(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet$1(this, _YargsInstance_options, "f").configObjects || []).concat(conf);
        }
        return this;
    }
    positional(key, opts) {
        argsert('<string> <object>', [key, opts], arguments.length);
        const supportedOpts = [
            'default',
            'defaultDescription',
            'implies',
            'normalize',
            'choices',
            'conflicts',
            'coerce',
            'type',
            'describe',
            'desc',
            'description',
            'alias',
        ];
        opts = objFilter(opts, (k, v) => {
            if (k === 'type' && !['string', 'number', 'boolean'].includes(v))
                return false;
            return supportedOpts.includes(k);
        });
        const fullCommand = __classPrivateFieldGet$1(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet$1(this, _YargsInstance_context, "f").fullCommands.length - 1];
        const parseOptions = fullCommand
            ? __classPrivateFieldGet$1(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand)
            : {
                array: [],
                alias: {},
                default: {},
                demand: {},
            };
        objectKeys(parseOptions).forEach(pk => {
            const parseOption = parseOptions[pk];
            if (Array.isArray(parseOption)) {
                if (parseOption.indexOf(key) !== -1)
                    opts[pk] = true;
            }
            else {
                if (parseOption[key] && !(pk in opts))
                    opts[pk] = parseOption[key];
            }
        });
        this.group(key, __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").getPositionalGroupName());
        return this.option(key, opts);
    }
    recommendCommands(recommend = true) {
        argsert('[boolean]', [recommend], arguments.length);
        __classPrivateFieldSet$1(this, _YargsInstance_recommendCommands, recommend, "f");
        return this;
    }
    required(keys, max, msg) {
        return this.demand(keys, max, msg);
    }
    require(keys, max, msg) {
        return this.demand(keys, max, msg);
    }
    requiresArg(keys) {
        argsert('<array|string|object> [number]', [keys], arguments.length);
        if (typeof keys === 'string' && __classPrivateFieldGet$1(this, _YargsInstance_options, "f").narg[keys]) {
            return this;
        }
        else {
            this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), 'narg', keys, NaN);
        }
        return this;
    }
    showCompletionScript($0, cmd) {
        argsert('[string] [string]', [$0, cmd], arguments.length);
        $0 = $0 || this.$0;
        __classPrivateFieldGet$1(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet$1(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet$1(this, _YargsInstance_completionCommand, "f") || 'completion'));
        return this;
    }
    showHelp(level) {
        argsert('[string|function]', [level], arguments.length);
        __classPrivateFieldSet$1(this, _YargsInstance_hasOutput, true, "f");
        if (!__classPrivateFieldGet$1(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
            if (!this.parsed) {
                const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet$1(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true);
                if (isPromise$1(parse)) {
                    parse.then(() => {
                        __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").showHelp(level);
                    });
                    return this;
                }
            }
            const builderResponse = __classPrivateFieldGet$1(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
            if (isPromise$1(builderResponse)) {
                builderResponse.then(() => {
                    __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").showHelp(level);
                });
                return this;
            }
        }
        __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").showHelp(level);
        return this;
    }
    scriptName(scriptName) {
        this.customScriptName = true;
        this.$0 = scriptName;
        return this;
    }
    showHelpOnFail(enabled, message) {
        argsert('[boolean|string] [string]', [enabled, message], arguments.length);
        __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message);
        return this;
    }
    showVersion(level) {
        argsert('[string|function]', [level], arguments.length);
        __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").showVersion(level);
        return this;
    }
    skipValidation(keys) {
        argsert('<array|string>', [keys], arguments.length);
        this[kPopulateParserHintArray]('skipValidation', keys);
        return this;
    }
    strict(enabled) {
        argsert('[boolean]', [enabled], arguments.length);
        __classPrivateFieldSet$1(this, _YargsInstance_strict, enabled !== false, "f");
        return this;
    }
    strictCommands(enabled) {
        argsert('[boolean]', [enabled], arguments.length);
        __classPrivateFieldSet$1(this, _YargsInstance_strictCommands, enabled !== false, "f");
        return this;
    }
    strictOptions(enabled) {
        argsert('[boolean]', [enabled], arguments.length);
        __classPrivateFieldSet$1(this, _YargsInstance_strictOptions, enabled !== false, "f");
        return this;
    }
    string(keys) {
        argsert('<array|string>', [keys], arguments.length);
        this[kPopulateParserHintArray]('string', keys);
        this[kTrackManuallySetKeys](keys);
        return this;
    }
    terminalWidth() {
        argsert([], 0);
        return __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").process.stdColumns;
    }
    updateLocale(obj) {
        return this.updateStrings(obj);
    }
    updateStrings(obj) {
        argsert('<object>', [obj], arguments.length);
        __classPrivateFieldSet$1(this, _YargsInstance_detectLocale, false, "f");
        __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").y18n.updateLocale(obj);
        return this;
    }
    usage(msg, description, builder, handler) {
        argsert('<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length);
        if (description !== undefined) {
            assertNotStrictEqual(msg, null, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f"));
            if ((msg || '').match(/^\$0( |$)/)) {
                return this.command(msg, description, builder, handler);
            }
            else {
                throw new YError('.usage() description must start with $0 if being used as alias for .command()');
            }
        }
        else {
            __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").usage(msg);
            return this;
        }
    }
    usageConfiguration(config) {
        argsert('<object>', [config], arguments.length);
        __classPrivateFieldSet$1(this, _YargsInstance_usageConfig, config, "f");
        return this;
    }
    version(opt, msg, ver) {
        const defaultVersionOpt = 'version';
        argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length);
        if (__classPrivateFieldGet$1(this, _YargsInstance_versionOpt, "f")) {
            this[kDeleteFromParserHintObject](__classPrivateFieldGet$1(this, _YargsInstance_versionOpt, "f"));
            __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").version(undefined);
            __classPrivateFieldSet$1(this, _YargsInstance_versionOpt, null, "f");
        }
        if (arguments.length === 0) {
            ver = this[kGuessVersion]();
            opt = defaultVersionOpt;
        }
        else if (arguments.length === 1) {
            if (opt === false) {
                return this;
            }
            ver = opt;
            opt = defaultVersionOpt;
        }
        else if (arguments.length === 2) {
            ver = msg;
            msg = undefined;
        }
        __classPrivateFieldSet$1(this, _YargsInstance_versionOpt, typeof opt === 'string' ? opt : defaultVersionOpt, "f");
        msg = msg || __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").deferY18nLookup('Show version number');
        __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").version(ver || undefined);
        this.boolean(__classPrivateFieldGet$1(this, _YargsInstance_versionOpt, "f"));
        this.describe(__classPrivateFieldGet$1(this, _YargsInstance_versionOpt, "f"), msg);
        return this;
    }
    wrap(cols) {
        argsert('<number|null|undefined>', [cols], arguments.length);
        __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").wrap(cols);
        return this;
    }
    [(_YargsInstance_command = new WeakMap(), _YargsInstance_cwd = new WeakMap(), _YargsInstance_context = new WeakMap(), _YargsInstance_completion = new WeakMap(), _YargsInstance_completionCommand = new WeakMap(), _YargsInstance_defaultShowHiddenOpt = new WeakMap(), _YargsInstance_exitError = new WeakMap(), _YargsInstance_detectLocale = new WeakMap(), _YargsInstance_emittedWarnings = new WeakMap(), _YargsInstance_exitProcess = new WeakMap(), _YargsInstance_frozens = new WeakMap(), _YargsInstance_globalMiddleware = new WeakMap(), _YargsInstance_groups = new WeakMap(), _YargsInstance_hasOutput = new WeakMap(), _YargsInstance_helpOpt = new WeakMap(), _YargsInstance_isGlobalContext = new WeakMap(), _YargsInstance_logger = new WeakMap(), _YargsInstance_output = new WeakMap(), _YargsInstance_options = new WeakMap(), _YargsInstance_parentRequire = new WeakMap(), _YargsInstance_parserConfig = new WeakMap(), _YargsInstance_parseFn = new WeakMap(), _YargsInstance_parseContext = new WeakMap(), _YargsInstance_pkgs = new WeakMap(), _YargsInstance_preservedGroups = new WeakMap(), _YargsInstance_processArgs = new WeakMap(), _YargsInstance_recommendCommands = new WeakMap(), _YargsInstance_shim = new WeakMap(), _YargsInstance_strict = new WeakMap(), _YargsInstance_strictCommands = new WeakMap(), _YargsInstance_strictOptions = new WeakMap(), _YargsInstance_usage = new WeakMap(), _YargsInstance_usageConfig = new WeakMap(), _YargsInstance_versionOpt = new WeakMap(), _YargsInstance_validation = new WeakMap(), kCopyDoubleDash)](argv) {
        if (!argv._ || !argv['--'])
            return argv;
        argv._.push.apply(argv._, argv['--']);
        try {
            delete argv['--'];
        }
        catch (_err) { }
        return argv;
    }
    [kCreateLogger]() {
        return {
            log: (...args) => {
                if (!this[kHasParseCallback]())
                    console.log(...args);
                __classPrivateFieldSet$1(this, _YargsInstance_hasOutput, true, "f");
                if (__classPrivateFieldGet$1(this, _YargsInstance_output, "f").length)
                    __classPrivateFieldSet$1(this, _YargsInstance_output, __classPrivateFieldGet$1(this, _YargsInstance_output, "f") + '\n', "f");
                __classPrivateFieldSet$1(this, _YargsInstance_output, __classPrivateFieldGet$1(this, _YargsInstance_output, "f") + args.join(' '), "f");
            },
            error: (...args) => {
                if (!this[kHasParseCallback]())
                    console.error(...args);
                __classPrivateFieldSet$1(this, _YargsInstance_hasOutput, true, "f");
                if (__classPrivateFieldGet$1(this, _YargsInstance_output, "f").length)
                    __classPrivateFieldSet$1(this, _YargsInstance_output, __classPrivateFieldGet$1(this, _YargsInstance_output, "f") + '\n', "f");
                __classPrivateFieldSet$1(this, _YargsInstance_output, __classPrivateFieldGet$1(this, _YargsInstance_output, "f") + args.join(' '), "f");
            },
        };
    }
    [kDeleteFromParserHintObject](optionKey) {
        objectKeys(__classPrivateFieldGet$1(this, _YargsInstance_options, "f")).forEach((hintKey) => {
            if (((key) => key === 'configObjects')(hintKey))
                return;
            const hint = __classPrivateFieldGet$1(this, _YargsInstance_options, "f")[hintKey];
            if (Array.isArray(hint)) {
                if (hint.includes(optionKey))
                    hint.splice(hint.indexOf(optionKey), 1);
            }
            else if (typeof hint === 'object') {
                delete hint[optionKey];
            }
        });
        delete __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").getDescriptions()[optionKey];
    }
    [kEmitWarning](warning, type, deduplicationId) {
        if (!__classPrivateFieldGet$1(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) {
            __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").process.emitWarning(warning, type);
            __classPrivateFieldGet$1(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true;
        }
    }
    [kFreeze]() {
        __classPrivateFieldGet$1(this, _YargsInstance_frozens, "f").push({
            options: __classPrivateFieldGet$1(this, _YargsInstance_options, "f"),
            configObjects: __classPrivateFieldGet$1(this, _YargsInstance_options, "f").configObjects.slice(0),
            exitProcess: __classPrivateFieldGet$1(this, _YargsInstance_exitProcess, "f"),
            groups: __classPrivateFieldGet$1(this, _YargsInstance_groups, "f"),
            strict: __classPrivateFieldGet$1(this, _YargsInstance_strict, "f"),
            strictCommands: __classPrivateFieldGet$1(this, _YargsInstance_strictCommands, "f"),
            strictOptions: __classPrivateFieldGet$1(this, _YargsInstance_strictOptions, "f"),
            completionCommand: __classPrivateFieldGet$1(this, _YargsInstance_completionCommand, "f"),
            output: __classPrivateFieldGet$1(this, _YargsInstance_output, "f"),
            exitError: __classPrivateFieldGet$1(this, _YargsInstance_exitError, "f"),
            hasOutput: __classPrivateFieldGet$1(this, _YargsInstance_hasOutput, "f"),
            parsed: this.parsed,
            parseFn: __classPrivateFieldGet$1(this, _YargsInstance_parseFn, "f"),
            parseContext: __classPrivateFieldGet$1(this, _YargsInstance_parseContext, "f"),
        });
        __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").freeze();
        __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").freeze();
        __classPrivateFieldGet$1(this, _YargsInstance_command, "f").freeze();
        __classPrivateFieldGet$1(this, _YargsInstance_globalMiddleware, "f").freeze();
    }
    [kGetDollarZero]() {
        let $0 = '';
        let default$0;
        if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet$1(this, _YargsInstance_shim, "f").process.argv()[0])) {
            default$0 = __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").process.argv().slice(1, 2);
        }
        else {
            default$0 = __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").process.argv().slice(0, 1);
        }
        $0 = default$0
            .map(x => {
            const b = this[kRebase](__classPrivateFieldGet$1(this, _YargsInstance_cwd, "f"), x);
            return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
        })
            .join(' ')
            .trim();
        if (__classPrivateFieldGet$1(this, _YargsInstance_shim, "f").getEnv('_') &&
            __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").getEnv('_')) {
            $0 = __classPrivateFieldGet$1(this, _YargsInstance_shim, "f")
                .getEnv('_')
                .replace(`${__classPrivateFieldGet$1(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet$1(this, _YargsInstance_shim, "f").process.execPath())}/`, '');
        }
        return $0;
    }
    [kGetParserConfiguration]() {
        return __classPrivateFieldGet$1(this, _YargsInstance_parserConfig, "f");
    }
    [kGetUsageConfiguration]() {
        return __classPrivateFieldGet$1(this, _YargsInstance_usageConfig, "f");
    }
    [kGuessLocale]() {
        if (!__classPrivateFieldGet$1(this, _YargsInstance_detectLocale, "f"))
            return;
        const locale = __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").getEnv('LC_ALL') ||
            __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").getEnv('LC_MESSAGES') ||
            __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").getEnv('LANG') ||
            __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").getEnv('LANGUAGE') ||
            'en_US';
        this.locale(locale.replace(/[.:].*/, ''));
    }
    [kGuessVersion]() {
        const obj = this[kPkgUp]();
        return obj.version || 'unknown';
    }
    [kParsePositionalNumbers](argv) {
        const args = argv['--'] ? argv['--'] : argv._;
        for (let i = 0, arg; (arg = args[i]) !== undefined; i++) {
            if (__classPrivateFieldGet$1(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) &&
                Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
                args[i] = Number(arg);
            }
        }
        return argv;
    }
    [kPkgUp](rootPath) {
        const npath = rootPath || '*';
        if (__classPrivateFieldGet$1(this, _YargsInstance_pkgs, "f")[npath])
            return __classPrivateFieldGet$1(this, _YargsInstance_pkgs, "f")[npath];
        let obj = {};
        try {
            let startDir = rootPath || __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").mainFilename;
            if (__classPrivateFieldGet$1(this, _YargsInstance_shim, "f").path.extname(startDir)) {
                startDir = __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").path.dirname(startDir);
            }
            const pkgJsonPath = __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => {
                if (names.includes('package.json')) {
                    return 'package.json';
                }
                else {
                    return undefined;
                }
            });
            assertNotStrictEqual(pkgJsonPath, undefined, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f"));
            obj = JSON.parse(__classPrivateFieldGet$1(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, 'utf8'));
        }
        catch (_noop) { }
        __classPrivateFieldGet$1(this, _YargsInstance_pkgs, "f")[npath] = obj || {};
        return __classPrivateFieldGet$1(this, _YargsInstance_pkgs, "f")[npath];
    }
    [kPopulateParserHintArray](type, keys) {
        keys = [].concat(keys);
        keys.forEach(key => {
            key = this[kSanitizeKey](key);
            __classPrivateFieldGet$1(this, _YargsInstance_options, "f")[type].push(key);
        });
    }
    [kPopulateParserHintSingleValueDictionary](builder, type, key, value) {
        this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => {
            __classPrivateFieldGet$1(this, _YargsInstance_options, "f")[type][key] = value;
        });
    }
    [kPopulateParserHintArrayDictionary](builder, type, key, value) {
        this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => {
            __classPrivateFieldGet$1(this, _YargsInstance_options, "f")[type][key] = (__classPrivateFieldGet$1(this, _YargsInstance_options, "f")[type][key] || []).concat(value);
        });
    }
    [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) {
        if (Array.isArray(key)) {
            key.forEach(k => {
                builder(k, value);
            });
        }
        else if (((key) => typeof key === 'object')(key)) {
            for (const k of objectKeys(key)) {
                builder(k, key[k]);
            }
        }
        else {
            singleKeyHandler(type, this[kSanitizeKey](key), value);
        }
    }
    [kSanitizeKey](key) {
        if (key === '__proto__')
            return '___proto___';
        return key;
    }
    [kSetKey](key, set) {
        this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), 'key', key, set);
        return this;
    }
    [kUnfreeze]() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
        const frozen = __classPrivateFieldGet$1(this, _YargsInstance_frozens, "f").pop();
        assertNotStrictEqual(frozen, undefined, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f"));
        let configObjects;
        (_a = this, _b = this, _c = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, {
            options: ({ set value(_o) { __classPrivateFieldSet$1(_a, _YargsInstance_options, _o, "f"); } }).value,
            configObjects,
            exitProcess: ({ set value(_o) { __classPrivateFieldSet$1(_b, _YargsInstance_exitProcess, _o, "f"); } }).value,
            groups: ({ set value(_o) { __classPrivateFieldSet$1(_c, _YargsInstance_groups, _o, "f"); } }).value,
            output: ({ set value(_o) { __classPrivateFieldSet$1(_d, _YargsInstance_output, _o, "f"); } }).value,
            exitError: ({ set value(_o) { __classPrivateFieldSet$1(_e, _YargsInstance_exitError, _o, "f"); } }).value,
            hasOutput: ({ set value(_o) { __classPrivateFieldSet$1(_f, _YargsInstance_hasOutput, _o, "f"); } }).value,
            parsed: this.parsed,
            strict: ({ set value(_o) { __classPrivateFieldSet$1(_g, _YargsInstance_strict, _o, "f"); } }).value,
            strictCommands: ({ set value(_o) { __classPrivateFieldSet$1(_h, _YargsInstance_strictCommands, _o, "f"); } }).value,
            strictOptions: ({ set value(_o) { __classPrivateFieldSet$1(_j, _YargsInstance_strictOptions, _o, "f"); } }).value,
            completionCommand: ({ set value(_o) { __classPrivateFieldSet$1(_k, _YargsInstance_completionCommand, _o, "f"); } }).value,
            parseFn: ({ set value(_o) { __classPrivateFieldSet$1(_l, _YargsInstance_parseFn, _o, "f"); } }).value,
            parseContext: ({ set value(_o) { __classPrivateFieldSet$1(_m, _YargsInstance_parseContext, _o, "f"); } }).value,
        } = frozen);
        __classPrivateFieldGet$1(this, _YargsInstance_options, "f").configObjects = configObjects;
        __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").unfreeze();
        __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").unfreeze();
        __classPrivateFieldGet$1(this, _YargsInstance_command, "f").unfreeze();
        __classPrivateFieldGet$1(this, _YargsInstance_globalMiddleware, "f").unfreeze();
    }
    [kValidateAsync](validation, argv) {
        return maybeAsyncResult(argv, result => {
            validation(result);
            return result;
        });
    }
    getInternalMethods() {
        return {
            getCommandInstance: this[kGetCommandInstance].bind(this),
            getContext: this[kGetContext].bind(this),
            getHasOutput: this[kGetHasOutput].bind(this),
            getLoggerInstance: this[kGetLoggerInstance].bind(this),
            getParseContext: this[kGetParseContext].bind(this),
            getParserConfiguration: this[kGetParserConfiguration].bind(this),
            getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
            getUsageInstance: this[kGetUsageInstance].bind(this),
            getValidationInstance: this[kGetValidationInstance].bind(this),
            hasParseCallback: this[kHasParseCallback].bind(this),
            isGlobalContext: this[kIsGlobalContext].bind(this),
            postProcess: this[kPostProcess].bind(this),
            reset: this[kReset].bind(this),
            runValidation: this[kRunValidation].bind(this),
            runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this),
            setHasOutput: this[kSetHasOutput].bind(this),
        };
    }
    [kGetCommandInstance]() {
        return __classPrivateFieldGet$1(this, _YargsInstance_command, "f");
    }
    [kGetContext]() {
        return __classPrivateFieldGet$1(this, _YargsInstance_context, "f");
    }
    [kGetHasOutput]() {
        return __classPrivateFieldGet$1(this, _YargsInstance_hasOutput, "f");
    }
    [kGetLoggerInstance]() {
        return __classPrivateFieldGet$1(this, _YargsInstance_logger, "f");
    }
    [kGetParseContext]() {
        return __classPrivateFieldGet$1(this, _YargsInstance_parseContext, "f") || {};
    }
    [kGetUsageInstance]() {
        return __classPrivateFieldGet$1(this, _YargsInstance_usage, "f");
    }
    [kGetValidationInstance]() {
        return __classPrivateFieldGet$1(this, _YargsInstance_validation, "f");
    }
    [kHasParseCallback]() {
        return !!__classPrivateFieldGet$1(this, _YargsInstance_parseFn, "f");
    }
    [kIsGlobalContext]() {
        return __classPrivateFieldGet$1(this, _YargsInstance_isGlobalContext, "f");
    }
    [kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) {
        if (calledFromCommand)
            return argv;
        if (isPromise$1(argv))
            return argv;
        if (!populateDoubleDash) {
            argv = this[kCopyDoubleDash](argv);
        }
        const parsePositionalNumbers = this[kGetParserConfiguration]()['parse-positional-numbers'] ||
            this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined;
        if (parsePositionalNumbers) {
            argv = this[kParsePositionalNumbers](argv);
        }
        if (runGlobalMiddleware) {
            argv = applyMiddleware(argv, this, __classPrivateFieldGet$1(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
        }
        return argv;
    }
    [kReset](aliases = {}) {
        __classPrivateFieldSet$1(this, _YargsInstance_options, __classPrivateFieldGet$1(this, _YargsInstance_options, "f") || {}, "f");
        const tmpOptions = {};
        tmpOptions.local = __classPrivateFieldGet$1(this, _YargsInstance_options, "f").local || [];
        tmpOptions.configObjects = __classPrivateFieldGet$1(this, _YargsInstance_options, "f").configObjects || [];
        const localLookup = {};
        tmpOptions.local.forEach(l => {
            localLookup[l] = true;
            (aliases[l] || []).forEach(a => {
                localLookup[a] = true;
            });
        });
        Object.assign(__classPrivateFieldGet$1(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet$1(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => {
            const keys = __classPrivateFieldGet$1(this, _YargsInstance_groups, "f")[groupName].filter(key => !(key in localLookup));
            if (keys.length > 0) {
                acc[groupName] = keys;
            }
            return acc;
        }, {}));
        __classPrivateFieldSet$1(this, _YargsInstance_groups, {}, "f");
        const arrayOptions = [
            'array',
            'boolean',
            'string',
            'skipValidation',
            'count',
            'normalize',
            'number',
            'hiddenOptions',
        ];
        const objectOptions = [
            'narg',
            'key',
            'alias',
            'default',
            'defaultDescription',
            'config',
            'choices',
            'demandedOptions',
            'demandedCommands',
            'deprecatedOptions',
        ];
        arrayOptions.forEach(k => {
            tmpOptions[k] = (__classPrivateFieldGet$1(this, _YargsInstance_options, "f")[k] || []).filter((k) => !localLookup[k]);
        });
        objectOptions.forEach((k) => {
            tmpOptions[k] = objFilter(__classPrivateFieldGet$1(this, _YargsInstance_options, "f")[k], k => !localLookup[k]);
        });
        tmpOptions.envPrefix = __classPrivateFieldGet$1(this, _YargsInstance_options, "f").envPrefix;
        __classPrivateFieldSet$1(this, _YargsInstance_options, tmpOptions, "f");
        __classPrivateFieldSet$1(this, _YargsInstance_usage, __classPrivateFieldGet$1(this, _YargsInstance_usage, "f")
            ? __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").reset(localLookup)
            : usage(this, __classPrivateFieldGet$1(this, _YargsInstance_shim, "f")), "f");
        __classPrivateFieldSet$1(this, _YargsInstance_validation, __classPrivateFieldGet$1(this, _YargsInstance_validation, "f")
            ? __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").reset(localLookup)
            : validation$3(this, __classPrivateFieldGet$1(this, _YargsInstance_usage, "f"), __classPrivateFieldGet$1(this, _YargsInstance_shim, "f")), "f");
        __classPrivateFieldSet$1(this, _YargsInstance_command, __classPrivateFieldGet$1(this, _YargsInstance_command, "f")
            ? __classPrivateFieldGet$1(this, _YargsInstance_command, "f").reset()
            : command(__classPrivateFieldGet$1(this, _YargsInstance_usage, "f"), __classPrivateFieldGet$1(this, _YargsInstance_validation, "f"), __classPrivateFieldGet$1(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet$1(this, _YargsInstance_shim, "f")), "f");
        if (!__classPrivateFieldGet$1(this, _YargsInstance_completion, "f"))
            __classPrivateFieldSet$1(this, _YargsInstance_completion, completion(this, __classPrivateFieldGet$1(this, _YargsInstance_usage, "f"), __classPrivateFieldGet$1(this, _YargsInstance_command, "f"), __classPrivateFieldGet$1(this, _YargsInstance_shim, "f")), "f");
        __classPrivateFieldGet$1(this, _YargsInstance_globalMiddleware, "f").reset();
        __classPrivateFieldSet$1(this, _YargsInstance_completionCommand, null, "f");
        __classPrivateFieldSet$1(this, _YargsInstance_output, '', "f");
        __classPrivateFieldSet$1(this, _YargsInstance_exitError, null, "f");
        __classPrivateFieldSet$1(this, _YargsInstance_hasOutput, false, "f");
        this.parsed = false;
        return this;
    }
    [kRebase](base, dir) {
        return __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").path.relative(base, dir);
    }
    [kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) {
        var _a, _b, _c, _d;
        let skipValidation = !!calledFromCommand || helpOnly;
        args = args || __classPrivateFieldGet$1(this, _YargsInstance_processArgs, "f");
        __classPrivateFieldGet$1(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").y18n.__;
        __classPrivateFieldGet$1(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration]();
        const populateDoubleDash = !!__classPrivateFieldGet$1(this, _YargsInstance_options, "f").configuration['populate--'];
        const config = Object.assign({}, __classPrivateFieldGet$1(this, _YargsInstance_options, "f").configuration, {
            'populate--': true,
        });
        const parsed = __classPrivateFieldGet$1(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet$1(this, _YargsInstance_options, "f"), {
            configuration: { 'parse-positional-numbers': false, ...config },
        }));
        const argv = Object.assign(parsed.argv, __classPrivateFieldGet$1(this, _YargsInstance_parseContext, "f"));
        let argvPromise = undefined;
        const aliases = parsed.aliases;
        let helpOptSet = false;
        let versionOptSet = false;
        Object.keys(argv).forEach(key => {
            if (key === __classPrivateFieldGet$1(this, _YargsInstance_helpOpt, "f") && argv[key]) {
                helpOptSet = true;
            }
            else if (key === __classPrivateFieldGet$1(this, _YargsInstance_versionOpt, "f") && argv[key]) {
                versionOptSet = true;
            }
        });
        argv.$0 = this.$0;
        this.parsed = parsed;
        if (commandIndex === 0) {
            __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").clearCachedHelpMessage();
        }
        try {
            this[kGuessLocale]();
            if (shortCircuit) {
                return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false);
            }
            if (__classPrivateFieldGet$1(this, _YargsInstance_helpOpt, "f")) {
                const helpCmds = [__classPrivateFieldGet$1(this, _YargsInstance_helpOpt, "f")]
                    .concat(aliases[__classPrivateFieldGet$1(this, _YargsInstance_helpOpt, "f")] || [])
                    .filter(k => k.length > 1);
                if (helpCmds.includes('' + argv._[argv._.length - 1])) {
                    argv._.pop();
                    helpOptSet = true;
                }
            }
            __classPrivateFieldSet$1(this, _YargsInstance_isGlobalContext, false, "f");
            const handlerKeys = __classPrivateFieldGet$1(this, _YargsInstance_command, "f").getCommands();
            const requestCompletions = ((_a = __classPrivateFieldGet$1(this, _YargsInstance_completion, "f")) === null || _a === void 0 ? void 0 : _a.completionKey)
                ? [
                    (_b = __classPrivateFieldGet$1(this, _YargsInstance_completion, "f")) === null || _b === void 0 ? void 0 : _b.completionKey,
                    ...((_d = this.getAliases()[(_c = __classPrivateFieldGet$1(this, _YargsInstance_completion, "f")) === null || _c === void 0 ? void 0 : _c.completionKey]) !== null && _d !== void 0 ? _d : []),
                ].some((key) => Object.prototype.hasOwnProperty.call(argv, key))
                : false;
            const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
            if (argv._.length) {
                if (handlerKeys.length) {
                    let firstUnknownCommand;
                    for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) {
                        cmd = String(argv._[i]);
                        if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet$1(this, _YargsInstance_completionCommand, "f")) {
                            const innerArgv = __classPrivateFieldGet$1(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly);
                            return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
                        }
                        else if (!firstUnknownCommand &&
                            cmd !== __classPrivateFieldGet$1(this, _YargsInstance_completionCommand, "f")) {
                            firstUnknownCommand = cmd;
                            break;
                        }
                    }
                    if (!__classPrivateFieldGet$1(this, _YargsInstance_command, "f").hasDefaultCommand() &&
                        __classPrivateFieldGet$1(this, _YargsInstance_recommendCommands, "f") &&
                        firstUnknownCommand &&
                        !skipRecommendation) {
                        __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys);
                    }
                }
                if (__classPrivateFieldGet$1(this, _YargsInstance_completionCommand, "f") &&
                    argv._.includes(__classPrivateFieldGet$1(this, _YargsInstance_completionCommand, "f")) &&
                    !requestCompletions) {
                    if (__classPrivateFieldGet$1(this, _YargsInstance_exitProcess, "f"))
                        setBlocking(true);
                    this.showCompletionScript();
                    this.exit(0);
                }
            }
            if (__classPrivateFieldGet$1(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) {
                const innerArgv = __classPrivateFieldGet$1(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly);
                return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
            }
            if (requestCompletions) {
                if (__classPrivateFieldGet$1(this, _YargsInstance_exitProcess, "f"))
                    setBlocking(true);
                args = [].concat(args);
                const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet$1(this, _YargsInstance_completion, "f").completionKey}`) + 1);
                __classPrivateFieldGet$1(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => {
                    if (err)
                        throw new YError(err.message);
                    (completions || []).forEach(completion => {
                        __classPrivateFieldGet$1(this, _YargsInstance_logger, "f").log(completion);
                    });
                    this.exit(0);
                });
                return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false);
            }
            if (!__classPrivateFieldGet$1(this, _YargsInstance_hasOutput, "f")) {
                if (helpOptSet) {
                    if (__classPrivateFieldGet$1(this, _YargsInstance_exitProcess, "f"))
                        setBlocking(true);
                    skipValidation = true;
                    this.showHelp(message => {
                        __classPrivateFieldGet$1(this, _YargsInstance_logger, "f").log(message);
                        this.exit(0);
                    });
                }
                else if (versionOptSet) {
                    if (__classPrivateFieldGet$1(this, _YargsInstance_exitProcess, "f"))
                        setBlocking(true);
                    skipValidation = true;
                    __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").showVersion('log');
                    this.exit(0);
                }
            }
            if (!skipValidation && __classPrivateFieldGet$1(this, _YargsInstance_options, "f").skipValidation.length > 0) {
                skipValidation = Object.keys(argv).some(key => __classPrivateFieldGet$1(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true);
            }
            if (!skipValidation) {
                if (parsed.error)
                    throw new YError(parsed.error.message);
                if (!requestCompletions) {
                    const validation = this[kRunValidation](aliases, {}, parsed.error);
                    if (!calledFromCommand) {
                        argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet$1(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true);
                    }
                    argvPromise = this[kValidateAsync](validation, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv);
                    if (isPromise$1(argvPromise) && !calledFromCommand) {
                        argvPromise = argvPromise.then(() => {
                            return applyMiddleware(argv, this, __classPrivateFieldGet$1(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
                        });
                    }
                }
            }
        }
        catch (err) {
            if (err instanceof YError)
                __classPrivateFieldGet$1(this, _YargsInstance_usage, "f").fail(err.message, err);
            else
                throw err;
        }
        return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true);
    }
    [kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) {
        const demandedOptions = { ...this.getDemandedOptions() };
        return (argv) => {
            if (parseErrors)
                throw new YError(parseErrors.message);
            __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").nonOptionCount(argv);
            __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions);
            let failedStrictCommands = false;
            if (__classPrivateFieldGet$1(this, _YargsInstance_strictCommands, "f")) {
                failedStrictCommands = __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").unknownCommands(argv);
            }
            if (__classPrivateFieldGet$1(this, _YargsInstance_strict, "f") && !failedStrictCommands) {
                __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand);
            }
            else if (__classPrivateFieldGet$1(this, _YargsInstance_strictOptions, "f")) {
                __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false);
            }
            __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").limitedChoices(argv);
            __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").implications(argv);
            __classPrivateFieldGet$1(this, _YargsInstance_validation, "f").conflicting(argv);
        };
    }
    [kSetHasOutput]() {
        __classPrivateFieldSet$1(this, _YargsInstance_hasOutput, true, "f");
    }
    [kTrackManuallySetKeys](keys) {
        if (typeof keys === 'string') {
            __classPrivateFieldGet$1(this, _YargsInstance_options, "f").key[keys] = true;
        }
        else {
            for (const k of keys) {
                __classPrivateFieldGet$1(this, _YargsInstance_options, "f").key[k] = true;
            }
        }
    }
}
function isYargsInstance(y) {
    return !!y && typeof y.getInternalMethods === 'function';
}

const Yargs = YargsFactory(shim$1);

var src = {exports: {}};

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

var ms;
var hasRequiredMs;

function requireMs () {
	if (hasRequiredMs) return ms;
	hasRequiredMs = 1;
	var s = 1000;
	var m = s * 60;
	var h = m * 60;
	var d = h * 24;
	var w = d * 7;
	var y = d * 365.25;
	ms = function (val, options) {
	  options = options || {};
	  var type = typeof val;
	  if (type === 'string' && val.length > 0) {
	    return parse(val);
	  } else if (type === 'number' && isFinite(val)) {
	    return options.long ? fmtLong(val) : fmtShort(val);
	  }
	  throw new Error(
	    'val is not a non-empty string or a valid number. val=' +
	      JSON.stringify(val)
	  );
	};
	function parse(str) {
	  str = String(str);
	  if (str.length > 100) {
	    return;
	  }
	  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
	    str
	  );
	  if (!match) {
	    return;
	  }
	  var n = parseFloat(match[1]);
	  var type = (match[2] || 'ms').toLowerCase();
	  switch (type) {
	    case 'years':
	    case 'year':
	    case 'yrs':
	    case 'yr':
	    case 'y':
	      return n * y;
	    case 'weeks':
	    case 'week':
	    case 'w':
	      return n * w;
	    case 'days':
	    case 'day':
	    case 'd':
	      return n * d;
	    case 'hours':
	    case 'hour':
	    case 'hrs':
	    case 'hr':
	    case 'h':
	      return n * h;
	    case 'minutes':
	    case 'minute':
	    case 'mins':
	    case 'min':
	    case 'm':
	      return n * m;
	    case 'seconds':
	    case 'second':
	    case 'secs':
	    case 'sec':
	    case 's':
	      return n * s;
	    case 'milliseconds':
	    case 'millisecond':
	    case 'msecs':
	    case 'msec':
	    case 'ms':
	      return n;
	    default:
	      return undefined;
	  }
	}
	function fmtShort(ms) {
	  var msAbs = Math.abs(ms);
	  if (msAbs >= d) {
	    return Math.round(ms / d) + 'd';
	  }
	  if (msAbs >= h) {
	    return Math.round(ms / h) + 'h';
	  }
	  if (msAbs >= m) {
	    return Math.round(ms / m) + 'm';
	  }
	  if (msAbs >= s) {
	    return Math.round(ms / s) + 's';
	  }
	  return ms + 'ms';
	}
	function fmtLong(ms) {
	  var msAbs = Math.abs(ms);
	  if (msAbs >= d) {
	    return plural(ms, msAbs, d, 'day');
	  }
	  if (msAbs >= h) {
	    return plural(ms, msAbs, h, 'hour');
	  }
	  if (msAbs >= m) {
	    return plural(ms, msAbs, m, 'minute');
	  }
	  if (msAbs >= s) {
	    return plural(ms, msAbs, s, 'second');
	  }
	  return ms + ' ms';
	}
	function plural(ms, msAbs, n, name) {
	  var isPlural = msAbs >= n * 1.5;
	  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
	}
	return ms;
}

var common$3;
var hasRequiredCommon$2;

function requireCommon$2 () {
	if (hasRequiredCommon$2) return common$3;
	hasRequiredCommon$2 = 1;
	function setup(env) {
		createDebug.debug = createDebug;
		createDebug.default = createDebug;
		createDebug.coerce = coerce;
		createDebug.disable = disable;
		createDebug.enable = enable;
		createDebug.enabled = enabled;
		createDebug.humanize = requireMs();
		createDebug.destroy = destroy;
		Object.keys(env).forEach(key => {
			createDebug[key] = env[key];
		});
		createDebug.names = [];
		createDebug.skips = [];
		createDebug.formatters = {};
		function selectColor(namespace) {
			let hash = 0;
			for (let i = 0; i < namespace.length; i++) {
				hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
				hash |= 0;
			}
			return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
		}
		createDebug.selectColor = selectColor;
		function createDebug(namespace) {
			let prevTime;
			let enableOverride = null;
			let namespacesCache;
			let enabledCache;
			function debug(...args) {
				if (!debug.enabled) {
					return;
				}
				const self = debug;
				const curr = Number(new Date());
				const ms = curr - (prevTime || curr);
				self.diff = ms;
				self.prev = prevTime;
				self.curr = curr;
				prevTime = curr;
				args[0] = createDebug.coerce(args[0]);
				if (typeof args[0] !== 'string') {
					args.unshift('%O');
				}
				let index = 0;
				args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
					if (match === '%%') {
						return '%';
					}
					index++;
					const formatter = createDebug.formatters[format];
					if (typeof formatter === 'function') {
						const val = args[index];
						match = formatter.call(self, val);
						args.splice(index, 1);
						index--;
					}
					return match;
				});
				createDebug.formatArgs.call(self, args);
				const logFn = self.log || createDebug.log;
				logFn.apply(self, args);
			}
			debug.namespace = namespace;
			debug.useColors = createDebug.useColors();
			debug.color = createDebug.selectColor(namespace);
			debug.extend = extend;
			debug.destroy = createDebug.destroy;
			Object.defineProperty(debug, 'enabled', {
				enumerable: true,
				configurable: false,
				get: () => {
					if (enableOverride !== null) {
						return enableOverride;
					}
					if (namespacesCache !== createDebug.namespaces) {
						namespacesCache = createDebug.namespaces;
						enabledCache = createDebug.enabled(namespace);
					}
					return enabledCache;
				},
				set: v => {
					enableOverride = v;
				}
			});
			if (typeof createDebug.init === 'function') {
				createDebug.init(debug);
			}
			return debug;
		}
		function extend(namespace, delimiter) {
			const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
			newDebug.log = this.log;
			return newDebug;
		}
		function enable(namespaces) {
			createDebug.save(namespaces);
			createDebug.namespaces = namespaces;
			createDebug.names = [];
			createDebug.skips = [];
			const split = (typeof namespaces === 'string' ? namespaces : '')
				.trim()
				.replace(/\s+/g, ',')
				.split(',')
				.filter(Boolean);
			for (const ns of split) {
				if (ns[0] === '-') {
					createDebug.skips.push(ns.slice(1));
				} else {
					createDebug.names.push(ns);
				}
			}
		}
		function matchesTemplate(search, template) {
			let searchIndex = 0;
			let templateIndex = 0;
			let starIndex = -1;
			let matchIndex = 0;
			while (searchIndex < search.length) {
				if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
					if (template[templateIndex] === '*') {
						starIndex = templateIndex;
						matchIndex = searchIndex;
						templateIndex++;
					} else {
						searchIndex++;
						templateIndex++;
					}
				} else if (starIndex !== -1) {
					templateIndex = starIndex + 1;
					matchIndex++;
					searchIndex = matchIndex;
				} else {
					return false;
				}
			}
			while (templateIndex < template.length && template[templateIndex] === '*') {
				templateIndex++;
			}
			return templateIndex === template.length;
		}
		function disable() {
			const namespaces = [
				...createDebug.names,
				...createDebug.skips.map(namespace => '-' + namespace)
			].join(',');
			createDebug.enable('');
			return namespaces;
		}
		function enabled(name) {
			for (const skip of createDebug.skips) {
				if (matchesTemplate(name, skip)) {
					return false;
				}
			}
			for (const ns of createDebug.names) {
				if (matchesTemplate(name, ns)) {
					return true;
				}
			}
			return false;
		}
		function coerce(val) {
			if (val instanceof Error) {
				return val.stack || val.message;
			}
			return val;
		}
		function destroy() {
			console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
		}
		createDebug.enable(createDebug.load());
		return createDebug;
	}
	common$3 = setup;
	return common$3;
}

var hasRequiredBrowser;

function requireBrowser () {
	if (hasRequiredBrowser) return browser$1.exports;
	hasRequiredBrowser = 1;
	(function (module, exports$1) {
		exports$1.formatArgs = formatArgs;
		exports$1.save = save;
		exports$1.load = load;
		exports$1.useColors = useColors;
		exports$1.storage = localstorage();
		exports$1.destroy = (() => {
			let warned = false;
			return () => {
				if (!warned) {
					warned = true;
					console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
				}
			};
		})();
		exports$1.colors = [
			'#0000CC',
			'#0000FF',
			'#0033CC',
			'#0033FF',
			'#0066CC',
			'#0066FF',
			'#0099CC',
			'#0099FF',
			'#00CC00',
			'#00CC33',
			'#00CC66',
			'#00CC99',
			'#00CCCC',
			'#00CCFF',
			'#3300CC',
			'#3300FF',
			'#3333CC',
			'#3333FF',
			'#3366CC',
			'#3366FF',
			'#3399CC',
			'#3399FF',
			'#33CC00',
			'#33CC33',
			'#33CC66',
			'#33CC99',
			'#33CCCC',
			'#33CCFF',
			'#6600CC',
			'#6600FF',
			'#6633CC',
			'#6633FF',
			'#66CC00',
			'#66CC33',
			'#9900CC',
			'#9900FF',
			'#9933CC',
			'#9933FF',
			'#99CC00',
			'#99CC33',
			'#CC0000',
			'#CC0033',
			'#CC0066',
			'#CC0099',
			'#CC00CC',
			'#CC00FF',
			'#CC3300',
			'#CC3333',
			'#CC3366',
			'#CC3399',
			'#CC33CC',
			'#CC33FF',
			'#CC6600',
			'#CC6633',
			'#CC9900',
			'#CC9933',
			'#CCCC00',
			'#CCCC33',
			'#FF0000',
			'#FF0033',
			'#FF0066',
			'#FF0099',
			'#FF00CC',
			'#FF00FF',
			'#FF3300',
			'#FF3333',
			'#FF3366',
			'#FF3399',
			'#FF33CC',
			'#FF33FF',
			'#FF6600',
			'#FF6633',
			'#FF9900',
			'#FF9933',
			'#FFCC00',
			'#FFCC33'
		];
		function useColors() {
			if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
				return true;
			}
			if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
				return false;
			}
			let m;
			return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
				(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
				(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
				(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
		}
		function formatArgs(args) {
			args[0] = (this.useColors ? '%c' : '') +
				this.namespace +
				(this.useColors ? ' %c' : ' ') +
				args[0] +
				(this.useColors ? '%c ' : ' ') +
				'+' + module.exports.humanize(this.diff);
			if (!this.useColors) {
				return;
			}
			const c = 'color: ' + this.color;
			args.splice(1, 0, c, 'color: inherit');
			let index = 0;
			let lastC = 0;
			args[0].replace(/%[a-zA-Z%]/g, match => {
				if (match === '%%') {
					return;
				}
				index++;
				if (match === '%c') {
					lastC = index;
				}
			});
			args.splice(lastC, 0, c);
		}
		exports$1.log = console.debug || console.log || (() => {});
		function save(namespaces) {
			try {
				if (namespaces) {
					exports$1.storage.setItem('debug', namespaces);
				} else {
					exports$1.storage.removeItem('debug');
				}
			} catch (error) {
			}
		}
		function load() {
			let r;
			try {
				r = exports$1.storage.getItem('debug') || exports$1.storage.getItem('DEBUG') ;
			} catch (error) {
			}
			if (!r && typeof process !== 'undefined' && 'env' in process) {
				r = process.env.DEBUG;
			}
			return r;
		}
		function localstorage() {
			try {
				return localStorage;
			} catch (error) {
			}
		}
		module.exports = requireCommon$2()(exports$1);
		const {formatters} = module.exports;
		formatters.j = function (v) {
			try {
				return JSON.stringify(v);
			} catch (error) {
				return '[UnexpectedJSONParseError]: ' + error.message;
			}
		}; 
	} (browser$1, browser$1.exports));
	return browser$1.exports;
}

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

var hasFlag;
var hasRequiredHasFlag;

function requireHasFlag () {
	if (hasRequiredHasFlag) return hasFlag;
	hasRequiredHasFlag = 1;
	hasFlag = (flag, argv = process.argv) => {
		const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
		const position = argv.indexOf(prefix + flag);
		const terminatorPosition = argv.indexOf('--');
		return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
	};
	return hasFlag;
}

var supportsColor_1;
var hasRequiredSupportsColor;

function requireSupportsColor () {
	if (hasRequiredSupportsColor) return supportsColor_1;
	hasRequiredSupportsColor = 1;
	const os = require$$0$1;
	const tty = require$$1;
	const hasFlag = requireHasFlag();
	const {env} = process;
	let forceColor;
	if (hasFlag('no-color') ||
		hasFlag('no-colors') ||
		hasFlag('color=false') ||
		hasFlag('color=never')) {
		forceColor = 0;
	} else if (hasFlag('color') ||
		hasFlag('colors') ||
		hasFlag('color=true') ||
		hasFlag('color=always')) {
		forceColor = 1;
	}
	if ('FORCE_COLOR' in env) {
		if (env.FORCE_COLOR === 'true') {
			forceColor = 1;
		} else if (env.FORCE_COLOR === 'false') {
			forceColor = 0;
		} else {
			forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
		}
	}
	function translateLevel(level) {
		if (level === 0) {
			return false;
		}
		return {
			level,
			hasBasic: true,
			has256: level >= 2,
			has16m: level >= 3
		};
	}
	function supportsColor(haveStream, streamIsTTY) {
		if (forceColor === 0) {
			return 0;
		}
		if (hasFlag('color=16m') ||
			hasFlag('color=full') ||
			hasFlag('color=truecolor')) {
			return 3;
		}
		if (hasFlag('color=256')) {
			return 2;
		}
		if (haveStream && !streamIsTTY && forceColor === undefined) {
			return 0;
		}
		const min = forceColor || 0;
		if (env.TERM === 'dumb') {
			return min;
		}
		if (process.platform === 'win32') {
			const osRelease = os.release().split('.');
			if (
				Number(osRelease[0]) >= 10 &&
				Number(osRelease[2]) >= 10586
			) {
				return Number(osRelease[2]) >= 14931 ? 3 : 2;
			}
			return 1;
		}
		if ('CI' in env) {
			if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
				return 1;
			}
			return min;
		}
		if ('TEAMCITY_VERSION' in env) {
			return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
		}
		if (env.COLORTERM === 'truecolor') {
			return 3;
		}
		if ('TERM_PROGRAM' in env) {
			const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
			switch (env.TERM_PROGRAM) {
				case 'iTerm.app':
					return version >= 3 ? 3 : 2;
				case 'Apple_Terminal':
					return 2;
			}
		}
		if (/-256(color)?$/i.test(env.TERM)) {
			return 2;
		}
		if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
			return 1;
		}
		if ('COLORTERM' in env) {
			return 1;
		}
		return min;
	}
	function getSupportLevel(stream) {
		const level = supportsColor(stream, stream && stream.isTTY);
		return translateLevel(level);
	}
	supportsColor_1 = {
		supportsColor: getSupportLevel,
		stdout: translateLevel(supportsColor(true, tty.isatty(1))),
		stderr: translateLevel(supportsColor(true, tty.isatty(2)))
	};
	return supportsColor_1;
}

var hasRequiredNode;

function requireNode () {
	if (hasRequiredNode) return node$1.exports;
	hasRequiredNode = 1;
	(function (module, exports$1) {
		const tty = require$$1;
		const util = require$$0$2;
		exports$1.init = init;
		exports$1.log = log;
		exports$1.formatArgs = formatArgs;
		exports$1.save = save;
		exports$1.load = load;
		exports$1.useColors = useColors;
		exports$1.destroy = util.deprecate(
			() => {},
			'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
		);
		exports$1.colors = [6, 2, 3, 4, 5, 1];
		try {
			const supportsColor = requireSupportsColor();
			if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
				exports$1.colors = [
					20,
					21,
					26,
					27,
					32,
					33,
					38,
					39,
					40,
					41,
					42,
					43,
					44,
					45,
					56,
					57,
					62,
					63,
					68,
					69,
					74,
					75,
					76,
					77,
					78,
					79,
					80,
					81,
					92,
					93,
					98,
					99,
					112,
					113,
					128,
					129,
					134,
					135,
					148,
					149,
					160,
					161,
					162,
					163,
					164,
					165,
					166,
					167,
					168,
					169,
					170,
					171,
					172,
					173,
					178,
					179,
					184,
					185,
					196,
					197,
					198,
					199,
					200,
					201,
					202,
					203,
					204,
					205,
					206,
					207,
					208,
					209,
					214,
					215,
					220,
					221
				];
			}
		} catch (error) {
		}
		exports$1.inspectOpts = Object.keys(process.env).filter(key => {
			return /^debug_/i.test(key);
		}).reduce((obj, key) => {
			const prop = key
				.substring(6)
				.toLowerCase()
				.replace(/_([a-z])/g, (_, k) => {
					return k.toUpperCase();
				});
			let val = process.env[key];
			if (/^(yes|on|true|enabled)$/i.test(val)) {
				val = true;
			} else if (/^(no|off|false|disabled)$/i.test(val)) {
				val = false;
			} else if (val === 'null') {
				val = null;
			} else {
				val = Number(val);
			}
			obj[prop] = val;
			return obj;
		}, {});
		function useColors() {
			return 'colors' in exports$1.inspectOpts ?
				Boolean(exports$1.inspectOpts.colors) :
				tty.isatty(process.stderr.fd);
		}
		function formatArgs(args) {
			const {namespace: name, useColors} = this;
			if (useColors) {
				const c = this.color;
				const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
				const prefix = `  ${colorCode};1m${name} \u001B[0m`;
				args[0] = prefix + args[0].split('\n').join('\n' + prefix);
				args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
			} else {
				args[0] = getDate() + name + ' ' + args[0];
			}
		}
		function getDate() {
			if (exports$1.inspectOpts.hideDate) {
				return '';
			}
			return new Date().toISOString() + ' ';
		}
		function log(...args) {
			return process.stderr.write(util.formatWithOptions(exports$1.inspectOpts, ...args) + '\n');
		}
		function save(namespaces) {
			if (namespaces) {
				process.env.DEBUG = namespaces;
			} else {
				delete process.env.DEBUG;
			}
		}
		function load() {
			return process.env.DEBUG;
		}
		function init(debug) {
			debug.inspectOpts = {};
			const keys = Object.keys(exports$1.inspectOpts);
			for (let i = 0; i < keys.length; i++) {
				debug.inspectOpts[keys[i]] = exports$1.inspectOpts[keys[i]];
			}
		}
		module.exports = requireCommon$2()(exports$1);
		const {formatters} = module.exports;
		formatters.o = function (v) {
			this.inspectOpts.colors = this.useColors;
			return util.inspect(v, this.inspectOpts)
				.split('\n')
				.map(str => str.trim())
				.join(' ');
		};
		formatters.O = function (v) {
			this.inspectOpts.colors = this.useColors;
			return util.inspect(v, this.inspectOpts);
		}; 
	} (node$1, node$1.exports));
	return node$1.exports;
}

var hasRequiredSrc;

function requireSrc () {
	if (hasRequiredSrc) return src.exports;
	hasRequiredSrc = 1;
	if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
		src.exports = requireBrowser();
	} else {
		src.exports = requireNode();
	}
	return src.exports;
}

var srcExports = requireSrc();
var debug$2 = /*@__PURE__*/getDefaultExportFromCjs(srcExports);

var index = /*#__PURE__*/_mergeNamespaces({
	__proto__: null,
	default: debug$2
}, [srcExports]);

var util$5;
(function (util) {
    util.assertEqual = (_) => { };
    function assertIs(_arg) { }
    util.assertIs = assertIs;
    function assertNever(_x) {
        throw new Error();
    }
    util.assertNever = assertNever;
    util.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
            obj[item] = item;
        }
        return obj;
    };
    util.getValidEnumValues = (obj) => {
        const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
        const filtered = {};
        for (const k of validKeys) {
            filtered[k] = obj[k];
        }
        return util.objectValues(filtered);
    };
    util.objectValues = (obj) => {
        return util.objectKeys(obj).map(function (e) {
            return obj[e];
        });
    };
    util.objectKeys = typeof Object.keys === "function"
        ? (obj) => Object.keys(obj)
        : (object) => {
            const keys = [];
            for (const key in object) {
                if (Object.prototype.hasOwnProperty.call(object, key)) {
                    keys.push(key);
                }
            }
            return keys;
        };
    util.find = (arr, checker) => {
        for (const item of arr) {
            if (checker(item))
                return item;
        }
        return undefined;
    };
    util.isInteger = typeof Number.isInteger === "function"
        ? (val) => Number.isInteger(val)
        : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
    function joinValues(array, separator = " | ") {
        return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
    }
    util.joinValues = joinValues;
    util.jsonStringifyReplacer = (_, value) => {
        if (typeof value === "bigint") {
            return value.toString();
        }
        return value;
    };
})(util$5 || (util$5 = {}));
var objectUtil;
(function (objectUtil) {
    objectUtil.mergeShapes = (first, second) => {
        return {
            ...first,
            ...second,
        };
    };
})(objectUtil || (objectUtil = {}));
const ZodParsedType = util$5.arrayToEnum([
    "string",
    "nan",
    "number",
    "integer",
    "float",
    "boolean",
    "date",
    "bigint",
    "symbol",
    "function",
    "undefined",
    "null",
    "array",
    "object",
    "unknown",
    "promise",
    "void",
    "never",
    "map",
    "set",
]);
const getParsedType = (data) => {
    const t = typeof data;
    switch (t) {
        case "undefined":
            return ZodParsedType.undefined;
        case "string":
            return ZodParsedType.string;
        case "number":
            return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
        case "boolean":
            return ZodParsedType.boolean;
        case "function":
            return ZodParsedType.function;
        case "bigint":
            return ZodParsedType.bigint;
        case "symbol":
            return ZodParsedType.symbol;
        case "object":
            if (Array.isArray(data)) {
                return ZodParsedType.array;
            }
            if (data === null) {
                return ZodParsedType.null;
            }
            if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
                return ZodParsedType.promise;
            }
            if (typeof Map !== "undefined" && data instanceof Map) {
                return ZodParsedType.map;
            }
            if (typeof Set !== "undefined" && data instanceof Set) {
                return ZodParsedType.set;
            }
            if (typeof Date !== "undefined" && data instanceof Date) {
                return ZodParsedType.date;
            }
            return ZodParsedType.object;
        default:
            return ZodParsedType.unknown;
    }
};

const ZodIssueCode = util$5.arrayToEnum([
    "invalid_type",
    "invalid_literal",
    "custom",
    "invalid_union",
    "invalid_union_discriminator",
    "invalid_enum_value",
    "unrecognized_keys",
    "invalid_arguments",
    "invalid_return_type",
    "invalid_date",
    "invalid_string",
    "too_small",
    "too_big",
    "invalid_intersection_types",
    "not_multiple_of",
    "not_finite",
]);
const quotelessJson = (obj) => {
    const json = JSON.stringify(obj, null, 2);
    return json.replace(/"([^"]+)":/g, "$1:");
};
class ZodError extends Error {
    get errors() {
        return this.issues;
    }
    constructor(issues) {
        super();
        this.issues = [];
        this.addIssue = (sub) => {
            this.issues = [...this.issues, sub];
        };
        this.addIssues = (subs = []) => {
            this.issues = [...this.issues, ...subs];
        };
        const actualProto = new.target.prototype;
        if (Object.setPrototypeOf) {
            Object.setPrototypeOf(this, actualProto);
        }
        else {
            this.__proto__ = actualProto;
        }
        this.name = "ZodError";
        this.issues = issues;
    }
    format(_mapper) {
        const mapper = _mapper ||
            function (issue) {
                return issue.message;
            };
        const fieldErrors = { _errors: [] };
        const processError = (error) => {
            for (const issue of error.issues) {
                if (issue.code === "invalid_union") {
                    issue.unionErrors.map(processError);
                }
                else if (issue.code === "invalid_return_type") {
                    processError(issue.returnTypeError);
                }
                else if (issue.code === "invalid_arguments") {
                    processError(issue.argumentsError);
                }
                else if (issue.path.length === 0) {
                    fieldErrors._errors.push(mapper(issue));
                }
                else {
                    let curr = fieldErrors;
                    let i = 0;
                    while (i < issue.path.length) {
                        const el = issue.path[i];
                        const terminal = i === issue.path.length - 1;
                        if (!terminal) {
                            curr[el] = curr[el] || { _errors: [] };
                        }
                        else {
                            curr[el] = curr[el] || { _errors: [] };
                            curr[el]._errors.push(mapper(issue));
                        }
                        curr = curr[el];
                        i++;
                    }
                }
            }
        };
        processError(this);
        return fieldErrors;
    }
    static assert(value) {
        if (!(value instanceof ZodError)) {
            throw new Error(`Not a ZodError: ${value}`);
        }
    }
    toString() {
        return this.message;
    }
    get message() {
        return JSON.stringify(this.issues, util$5.jsonStringifyReplacer, 2);
    }
    get isEmpty() {
        return this.issues.length === 0;
    }
    flatten(mapper = (issue) => issue.message) {
        const fieldErrors = {};
        const formErrors = [];
        for (const sub of this.issues) {
            if (sub.path.length > 0) {
                const firstEl = sub.path[0];
                fieldErrors[firstEl] = fieldErrors[firstEl] || [];
                fieldErrors[firstEl].push(mapper(sub));
            }
            else {
                formErrors.push(mapper(sub));
            }
        }
        return { formErrors, fieldErrors };
    }
    get formErrors() {
        return this.flatten();
    }
}
ZodError.create = (issues) => {
    const error = new ZodError(issues);
    return error;
};

const errorMap = (issue, _ctx) => {
    let message;
    switch (issue.code) {
        case ZodIssueCode.invalid_type:
            if (issue.received === ZodParsedType.undefined) {
                message = "Required";
            }
            else {
                message = `Expected ${issue.expected}, received ${issue.received}`;
            }
            break;
        case ZodIssueCode.invalid_literal:
            message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util$5.jsonStringifyReplacer)}`;
            break;
        case ZodIssueCode.unrecognized_keys:
            message = `Unrecognized key(s) in object: ${util$5.joinValues(issue.keys, ", ")}`;
            break;
        case ZodIssueCode.invalid_union:
            message = `Invalid input`;
            break;
        case ZodIssueCode.invalid_union_discriminator:
            message = `Invalid discriminator value. Expected ${util$5.joinValues(issue.options)}`;
            break;
        case ZodIssueCode.invalid_enum_value:
            message = `Invalid enum value. Expected ${util$5.joinValues(issue.options)}, received '${issue.received}'`;
            break;
        case ZodIssueCode.invalid_arguments:
            message = `Invalid function arguments`;
            break;
        case ZodIssueCode.invalid_return_type:
            message = `Invalid function return type`;
            break;
        case ZodIssueCode.invalid_date:
            message = `Invalid date`;
            break;
        case ZodIssueCode.invalid_string:
            if (typeof issue.validation === "object") {
                if ("includes" in issue.validation) {
                    message = `Invalid input: must include "${issue.validation.includes}"`;
                    if (typeof issue.validation.position === "number") {
                        message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
                    }
                }
                else if ("startsWith" in issue.validation) {
                    message = `Invalid input: must start with "${issue.validation.startsWith}"`;
                }
                else if ("endsWith" in issue.validation) {
                    message = `Invalid input: must end with "${issue.validation.endsWith}"`;
                }
                else {
                    util$5.assertNever(issue.validation);
                }
            }
            else if (issue.validation !== "regex") {
                message = `Invalid ${issue.validation}`;
            }
            else {
                message = "Invalid";
            }
            break;
        case ZodIssueCode.too_small:
            if (issue.type === "array")
                message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
            else if (issue.type === "string")
                message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
            else if (issue.type === "number")
                message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
            else if (issue.type === "bigint")
                message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
            else if (issue.type === "date")
                message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
            else
                message = "Invalid input";
            break;
        case ZodIssueCode.too_big:
            if (issue.type === "array")
                message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
            else if (issue.type === "string")
                message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
            else if (issue.type === "number")
                message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
            else if (issue.type === "bigint")
                message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
            else if (issue.type === "date")
                message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
            else
                message = "Invalid input";
            break;
        case ZodIssueCode.custom:
            message = `Invalid input`;
            break;
        case ZodIssueCode.invalid_intersection_types:
            message = `Intersection results could not be merged`;
            break;
        case ZodIssueCode.not_multiple_of:
            message = `Number must be a multiple of ${issue.multipleOf}`;
            break;
        case ZodIssueCode.not_finite:
            message = "Number must be finite";
            break;
        default:
            message = _ctx.defaultError;
            util$5.assertNever(issue);
    }
    return { message };
};

let overrideErrorMap = errorMap;
function setErrorMap(map) {
    overrideErrorMap = map;
}
function getErrorMap() {
    return overrideErrorMap;
}

const makeIssue = (params) => {
    const { data, path, errorMaps, issueData } = params;
    const fullPath = [...path, ...(issueData.path || [])];
    const fullIssue = {
        ...issueData,
        path: fullPath,
    };
    if (issueData.message !== undefined) {
        return {
            ...issueData,
            path: fullPath,
            message: issueData.message,
        };
    }
    let errorMessage = "";
    const maps = errorMaps
        .filter((m) => !!m)
        .slice()
        .reverse();
    for (const map of maps) {
        errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
    }
    return {
        ...issueData,
        path: fullPath,
        message: errorMessage,
    };
};
const EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
    const overrideMap = getErrorMap();
    const issue = makeIssue({
        issueData: issueData,
        data: ctx.data,
        path: ctx.path,
        errorMaps: [
            ctx.common.contextualErrorMap,
            ctx.schemaErrorMap,
            overrideMap,
            overrideMap === errorMap ? undefined : errorMap,
        ].filter((x) => !!x),
    });
    ctx.common.issues.push(issue);
}
class ParseStatus {
    constructor() {
        this.value = "valid";
    }
    dirty() {
        if (this.value === "valid")
            this.value = "dirty";
    }
    abort() {
        if (this.value !== "aborted")
            this.value = "aborted";
    }
    static mergeArray(status, results) {
        const arrayValue = [];
        for (const s of results) {
            if (s.status === "aborted")
                return INVALID;
            if (s.status === "dirty")
                status.dirty();
            arrayValue.push(s.value);
        }
        return { status: status.value, value: arrayValue };
    }
    static async mergeObjectAsync(status, pairs) {
        const syncPairs = [];
        for (const pair of pairs) {
            const key = await pair.key;
            const value = await pair.value;
            syncPairs.push({
                key,
                value,
            });
        }
        return ParseStatus.mergeObjectSync(status, syncPairs);
    }
    static mergeObjectSync(status, pairs) {
        const finalObject = {};
        for (const pair of pairs) {
            const { key, value } = pair;
            if (key.status === "aborted")
                return INVALID;
            if (value.status === "aborted")
                return INVALID;
            if (key.status === "dirty")
                status.dirty();
            if (value.status === "dirty")
                status.dirty();
            if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
                finalObject[key.value] = value.value;
            }
        }
        return { status: status.value, value: finalObject };
    }
}
const INVALID = Object.freeze({
    status: "aborted",
});
const DIRTY = (value) => ({ status: "dirty", value });
const OK = (value) => ({ status: "valid", value });
const isAborted = (x) => x.status === "aborted";
const isDirty = (x) => x.status === "dirty";
const isValid$1 = (x) => x.status === "valid";
const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;

var errorUtil;
(function (errorUtil) {
    errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
    errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));

class ParseInputLazyPath {
    constructor(parent, value, path, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path;
        this._key = key;
    }
    get path() {
        if (!this._cachedPath.length) {
            if (Array.isArray(this._key)) {
                this._cachedPath.push(...this._path, ...this._key);
            }
            else {
                this._cachedPath.push(...this._path, this._key);
            }
        }
        return this._cachedPath;
    }
}
const handleResult = (ctx, result) => {
    if (isValid$1(result)) {
        return { success: true, data: result.value };
    }
    else {
        if (!ctx.common.issues.length) {
            throw new Error("Validation failed but no issues detected.");
        }
        return {
            success: false,
            get error() {
                if (this._error)
                    return this._error;
                const error = new ZodError(ctx.common.issues);
                this._error = error;
                return this._error;
            },
        };
    }
};
function processCreateParams(params) {
    if (!params)
        return {};
    const { errorMap, invalid_type_error, required_error, description } = params;
    if (errorMap && (invalid_type_error || required_error)) {
        throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
    }
    if (errorMap)
        return { errorMap: errorMap, description };
    const customMap = (iss, ctx) => {
        const { message } = params;
        if (iss.code === "invalid_enum_value") {
            return { message: message ?? ctx.defaultError };
        }
        if (typeof ctx.data === "undefined") {
            return { message: message ?? required_error ?? ctx.defaultError };
        }
        if (iss.code !== "invalid_type")
            return { message: ctx.defaultError };
        return { message: message ?? invalid_type_error ?? ctx.defaultError };
    };
    return { errorMap: customMap, description };
}
let ZodType$1 = class ZodType {
    get description() {
        return this._def.description;
    }
    _getType(input) {
        return getParsedType(input.data);
    }
    _getOrReturnCtx(input, ctx) {
        return (ctx || {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent,
        });
    }
    _processInputParams(input) {
        return {
            status: new ParseStatus(),
            ctx: {
                common: input.parent.common,
                data: input.data,
                parsedType: getParsedType(input.data),
                schemaErrorMap: this._def.errorMap,
                path: input.path,
                parent: input.parent,
            },
        };
    }
    _parseSync(input) {
        const result = this._parse(input);
        if (isAsync(result)) {
            throw new Error("Synchronous parse encountered promise.");
        }
        return result;
    }
    _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
    }
    parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
            return result.data;
        throw result.error;
    }
    safeParse(data, params) {
        const ctx = {
            common: {
                issues: [],
                async: params?.async ?? false,
                contextualErrorMap: params?.errorMap,
            },
            path: params?.path || [],
            schemaErrorMap: this._def.errorMap,
            parent: null,
            data,
            parsedType: getParsedType(data),
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult(ctx, result);
    }
    "~validate"(data) {
        const ctx = {
            common: {
                issues: [],
                async: !!this["~standard"].async,
            },
            path: [],
            schemaErrorMap: this._def.errorMap,
            parent: null,
            data,
            parsedType: getParsedType(data),
        };
        if (!this["~standard"].async) {
            try {
                const result = this._parseSync({ data, path: [], parent: ctx });
                return isValid$1(result)
                    ? {
                        value: result.value,
                    }
                    : {
                        issues: ctx.common.issues,
                    };
            }
            catch (err) {
                if (err?.message?.toLowerCase()?.includes("encountered")) {
                    this["~standard"].async = true;
                }
                ctx.common = {
                    issues: [],
                    async: true,
                };
            }
        }
        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid$1(result)
            ? {
                value: result.value,
            }
            : {
                issues: ctx.common.issues,
            });
    }
    async parseAsync(data, params) {
        const result = await this.safeParseAsync(data, params);
        if (result.success)
            return result.data;
        throw result.error;
    }
    async safeParseAsync(data, params) {
        const ctx = {
            common: {
                issues: [],
                contextualErrorMap: params?.errorMap,
                async: true,
            },
            path: params?.path || [],
            schemaErrorMap: this._def.errorMap,
            parent: null,
            data,
            parsedType: getParsedType(data),
        };
        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
        const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
        return handleResult(ctx, result);
    }
    refine(check, message) {
        const getIssueProperties = (val) => {
            if (typeof message === "string" || typeof message === "undefined") {
                return { message };
            }
            else if (typeof message === "function") {
                return message(val);
            }
            else {
                return message;
            }
        };
        return this._refinement((val, ctx) => {
            const result = check(val);
            const setError = () => ctx.addIssue({
                code: ZodIssueCode.custom,
                ...getIssueProperties(val),
            });
            if (typeof Promise !== "undefined" && result instanceof Promise) {
                return result.then((data) => {
                    if (!data) {
                        setError();
                        return false;
                    }
                    else {
                        return true;
                    }
                });
            }
            if (!result) {
                setError();
                return false;
            }
            else {
                return true;
            }
        });
    }
    refinement(check, refinementData) {
        return this._refinement((val, ctx) => {
            if (!check(val)) {
                ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
                return false;
            }
            else {
                return true;
            }
        });
    }
    _refinement(refinement) {
        return new ZodEffects({
            schema: this,
            typeName: ZodFirstPartyTypeKind.ZodEffects,
            effect: { type: "refinement", refinement },
        });
    }
    superRefine(refinement) {
        return this._refinement(refinement);
    }
    constructor(def) {
        this.spa = this.safeParseAsync;
        this._def = def;
        this.parse = this.parse.bind(this);
        this.safeParse = this.safeParse.bind(this);
        this.parseAsync = this.parseAsync.bind(this);
        this.safeParseAsync = this.safeParseAsync.bind(this);
        this.spa = this.spa.bind(this);
        this.refine = this.refine.bind(this);
        this.refinement = this.refinement.bind(this);
        this.superRefine = this.superRefine.bind(this);
        this.optional = this.optional.bind(this);
        this.nullable = this.nullable.bind(this);
        this.nullish = this.nullish.bind(this);
        this.array = this.array.bind(this);
        this.promise = this.promise.bind(this);
        this.or = this.or.bind(this);
        this.and = this.and.bind(this);
        this.transform = this.transform.bind(this);
        this.brand = this.brand.bind(this);
        this.default = this.default.bind(this);
        this.catch = this.catch.bind(this);
        this.describe = this.describe.bind(this);
        this.pipe = this.pipe.bind(this);
        this.readonly = this.readonly.bind(this);
        this.isNullable = this.isNullable.bind(this);
        this.isOptional = this.isOptional.bind(this);
        this["~standard"] = {
            version: 1,
            vendor: "zod",
            validate: (data) => this["~validate"](data),
        };
    }
    optional() {
        return ZodOptional$1.create(this, this._def);
    }
    nullable() {
        return ZodNullable$1.create(this, this._def);
    }
    nullish() {
        return this.nullable().optional();
    }
    array() {
        return ZodArray$1.create(this);
    }
    promise() {
        return ZodPromise.create(this, this._def);
    }
    or(option) {
        return ZodUnion$1.create([this, option], this._def);
    }
    and(incoming) {
        return ZodIntersection$1.create(this, incoming, this._def);
    }
    transform(transform) {
        return new ZodEffects({
            ...processCreateParams(this._def),
            schema: this,
            typeName: ZodFirstPartyTypeKind.ZodEffects,
            effect: { type: "transform", transform },
        });
    }
    default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault$1({
            ...processCreateParams(this._def),
            innerType: this,
            defaultValue: defaultValueFunc,
            typeName: ZodFirstPartyTypeKind.ZodDefault,
        });
    }
    brand() {
        return new ZodBranded({
            typeName: ZodFirstPartyTypeKind.ZodBranded,
            type: this,
            ...processCreateParams(this._def),
        });
    }
    catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch$1({
            ...processCreateParams(this._def),
            innerType: this,
            catchValue: catchValueFunc,
            typeName: ZodFirstPartyTypeKind.ZodCatch,
        });
    }
    describe(description) {
        const This = this.constructor;
        return new This({
            ...this._def,
            description,
        });
    }
    pipe(target) {
        return ZodPipeline.create(this, target);
    }
    readonly() {
        return ZodReadonly$1.create(this);
    }
    isOptional() {
        return this.safeParse(undefined).success;
    }
    isNullable() {
        return this.safeParse(null).success;
    }
};
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[0-9a-z]+$/;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex$1;
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
const dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
    let secondsRegexSource = `[0-5]\\d`;
    if (args.precision) {
        secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
    }
    else if (args.precision == null) {
        secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
    }
    const secondsQuantifier = args.precision ? "+" : "?";
    return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
    return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
    let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
    const opts = [];
    opts.push(args.local ? `Z?` : `Z`);
    if (args.offset)
        opts.push(`([+-]\\d{2}:?\\d{2})`);
    regex = `${regex}(${opts.join("|")})`;
    return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
    if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
        return true;
    }
    if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
        return true;
    }
    return false;
}
function isValidJWT$1(jwt, alg) {
    if (!jwtRegex.test(jwt))
        return false;
    try {
        const [header] = jwt.split(".");
        if (!header)
            return false;
        const base64 = header
            .replace(/-/g, "+")
            .replace(/_/g, "/")
            .padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
        const decoded = JSON.parse(atob(base64));
        if (typeof decoded !== "object" || decoded === null)
            return false;
        if ("typ" in decoded && decoded?.typ !== "JWT")
            return false;
        if (!decoded.alg)
            return false;
        if (alg && decoded.alg !== alg)
            return false;
        return true;
    }
    catch {
        return false;
    }
}
function isValidCidr(ip, version) {
    if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
        return true;
    }
    if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
        return true;
    }
    return false;
}
let ZodString$1 = class ZodString extends ZodType$1 {
    _parse(input) {
        if (this._def.coerce) {
            input.data = String(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.string) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.string,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const status = new ParseStatus();
        let ctx = undefined;
        for (const check of this._def.checks) {
            if (check.kind === "min") {
                if (input.data.length < check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        minimum: check.value,
                        type: "string",
                        inclusive: true,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                if (input.data.length > check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        maximum: check.value,
                        type: "string",
                        inclusive: true,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "length") {
                const tooBig = input.data.length > check.value;
                const tooSmall = input.data.length < check.value;
                if (tooBig || tooSmall) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    if (tooBig) {
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_big,
                            maximum: check.value,
                            type: "string",
                            inclusive: true,
                            exact: true,
                            message: check.message,
                        });
                    }
                    else if (tooSmall) {
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_small,
                            minimum: check.value,
                            type: "string",
                            inclusive: true,
                            exact: true,
                            message: check.message,
                        });
                    }
                    status.dirty();
                }
            }
            else if (check.kind === "email") {
                if (!emailRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "email",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "emoji") {
                if (!emojiRegex$1) {
                    emojiRegex$1 = new RegExp(_emojiRegex, "u");
                }
                if (!emojiRegex$1.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "emoji",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "uuid") {
                if (!uuidRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "uuid",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "nanoid") {
                if (!nanoidRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "nanoid",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "cuid") {
                if (!cuidRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "cuid",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "cuid2") {
                if (!cuid2Regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "cuid2",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "ulid") {
                if (!ulidRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "ulid",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "url") {
                try {
                    new URL(input.data);
                }
                catch {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "url",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "regex") {
                check.regex.lastIndex = 0;
                const testResult = check.regex.test(input.data);
                if (!testResult) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "regex",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "trim") {
                input.data = input.data.trim();
            }
            else if (check.kind === "includes") {
                if (!input.data.includes(check.value, check.position)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: { includes: check.value, position: check.position },
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "toLowerCase") {
                input.data = input.data.toLowerCase();
            }
            else if (check.kind === "toUpperCase") {
                input.data = input.data.toUpperCase();
            }
            else if (check.kind === "startsWith") {
                if (!input.data.startsWith(check.value)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: { startsWith: check.value },
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "endsWith") {
                if (!input.data.endsWith(check.value)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: { endsWith: check.value },
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "datetime") {
                const regex = datetimeRegex(check);
                if (!regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: "datetime",
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "date") {
                const regex = dateRegex;
                if (!regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: "date",
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "time") {
                const regex = timeRegex(check);
                if (!regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_string,
                        validation: "time",
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "duration") {
                if (!durationRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "duration",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "ip") {
                if (!isValidIP(input.data, check.version)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "ip",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "jwt") {
                if (!isValidJWT$1(input.data, check.alg)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "jwt",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "cidr") {
                if (!isValidCidr(input.data, check.version)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "cidr",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "base64") {
                if (!base64Regex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "base64",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "base64url") {
                if (!base64urlRegex.test(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        validation: "base64url",
                        code: ZodIssueCode.invalid_string,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else {
                util$5.assertNever(check);
            }
        }
        return { status: status.value, value: input.data };
    }
    _regex(regex, validation, message) {
        return this.refinement((data) => regex.test(data), {
            validation,
            code: ZodIssueCode.invalid_string,
            ...errorUtil.errToObj(message),
        });
    }
    _addCheck(check) {
        return new ZodString({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
    }
    url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
    }
    emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
    }
    uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
    }
    nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
    }
    cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
    }
    cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
    }
    ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
    }
    base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
    }
    base64url(message) {
        return this._addCheck({
            kind: "base64url",
            ...errorUtil.errToObj(message),
        });
    }
    jwt(options) {
        return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
    }
    ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
    }
    cidr(options) {
        return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
    }
    datetime(options) {
        if (typeof options === "string") {
            return this._addCheck({
                kind: "datetime",
                precision: null,
                offset: false,
                local: false,
                message: options,
            });
        }
        return this._addCheck({
            kind: "datetime",
            precision: typeof options?.precision === "undefined" ? null : options?.precision,
            offset: options?.offset ?? false,
            local: options?.local ?? false,
            ...errorUtil.errToObj(options?.message),
        });
    }
    date(message) {
        return this._addCheck({ kind: "date", message });
    }
    time(options) {
        if (typeof options === "string") {
            return this._addCheck({
                kind: "time",
                precision: null,
                message: options,
            });
        }
        return this._addCheck({
            kind: "time",
            precision: typeof options?.precision === "undefined" ? null : options?.precision,
            ...errorUtil.errToObj(options?.message),
        });
    }
    duration(message) {
        return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
    }
    regex(regex, message) {
        return this._addCheck({
            kind: "regex",
            regex: regex,
            ...errorUtil.errToObj(message),
        });
    }
    includes(value, options) {
        return this._addCheck({
            kind: "includes",
            value: value,
            position: options?.position,
            ...errorUtil.errToObj(options?.message),
        });
    }
    startsWith(value, message) {
        return this._addCheck({
            kind: "startsWith",
            value: value,
            ...errorUtil.errToObj(message),
        });
    }
    endsWith(value, message) {
        return this._addCheck({
            kind: "endsWith",
            value: value,
            ...errorUtil.errToObj(message),
        });
    }
    min(minLength, message) {
        return this._addCheck({
            kind: "min",
            value: minLength,
            ...errorUtil.errToObj(message),
        });
    }
    max(maxLength, message) {
        return this._addCheck({
            kind: "max",
            value: maxLength,
            ...errorUtil.errToObj(message),
        });
    }
    length(len, message) {
        return this._addCheck({
            kind: "length",
            value: len,
            ...errorUtil.errToObj(message),
        });
    }
    nonempty(message) {
        return this.min(1, errorUtil.errToObj(message));
    }
    trim() {
        return new ZodString({
            ...this._def,
            checks: [...this._def.checks, { kind: "trim" }],
        });
    }
    toLowerCase() {
        return new ZodString({
            ...this._def,
            checks: [...this._def.checks, { kind: "toLowerCase" }],
        });
    }
    toUpperCase() {
        return new ZodString({
            ...this._def,
            checks: [...this._def.checks, { kind: "toUpperCase" }],
        });
    }
    get isDatetime() {
        return !!this._def.checks.find((ch) => ch.kind === "datetime");
    }
    get isDate() {
        return !!this._def.checks.find((ch) => ch.kind === "date");
    }
    get isTime() {
        return !!this._def.checks.find((ch) => ch.kind === "time");
    }
    get isDuration() {
        return !!this._def.checks.find((ch) => ch.kind === "duration");
    }
    get isEmail() {
        return !!this._def.checks.find((ch) => ch.kind === "email");
    }
    get isURL() {
        return !!this._def.checks.find((ch) => ch.kind === "url");
    }
    get isEmoji() {
        return !!this._def.checks.find((ch) => ch.kind === "emoji");
    }
    get isUUID() {
        return !!this._def.checks.find((ch) => ch.kind === "uuid");
    }
    get isNANOID() {
        return !!this._def.checks.find((ch) => ch.kind === "nanoid");
    }
    get isCUID() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid");
    }
    get isCUID2() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid2");
    }
    get isULID() {
        return !!this._def.checks.find((ch) => ch.kind === "ulid");
    }
    get isIP() {
        return !!this._def.checks.find((ch) => ch.kind === "ip");
    }
    get isCIDR() {
        return !!this._def.checks.find((ch) => ch.kind === "cidr");
    }
    get isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
    }
    get isBase64url() {
        return !!this._def.checks.find((ch) => ch.kind === "base64url");
    }
    get minLength() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min;
    }
    get maxLength() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max;
    }
};
ZodString$1.create = (params) => {
    return new ZodString$1({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params),
    });
};
function floatSafeRemainder$1(val, step) {
    const valDecCount = (val.toString().split(".")[1] || "").length;
    const stepDecCount = (step.toString().split(".")[1] || "").length;
    const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
    const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
    const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
    return (valInt % stepInt) / 10 ** decCount;
}
let ZodNumber$1 = class ZodNumber extends ZodType$1 {
    constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
        this.step = this.multipleOf;
    }
    _parse(input) {
        if (this._def.coerce) {
            input.data = Number(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.number) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.number,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        let ctx = undefined;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
            if (check.kind === "int") {
                if (!util$5.isInteger(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_type,
                        expected: "integer",
                        received: "float",
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "min") {
                const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
                if (tooSmall) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        minimum: check.value,
                        type: "number",
                        inclusive: check.inclusive,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
                if (tooBig) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        maximum: check.value,
                        type: "number",
                        inclusive: check.inclusive,
                        exact: false,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "multipleOf") {
                if (floatSafeRemainder$1(input.data, check.value) !== 0) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.not_multiple_of,
                        multipleOf: check.value,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "finite") {
                if (!Number.isFinite(input.data)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.not_finite,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else {
                util$5.assertNever(check);
            }
        }
        return { status: status.value, value: input.data };
    }
    gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
    }
    gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
    }
    lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
    }
    lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
    }
    setLimit(kind, value, inclusive, message) {
        return new ZodNumber({
            ...this._def,
            checks: [
                ...this._def.checks,
                {
                    kind,
                    value,
                    inclusive,
                    message: errorUtil.toString(message),
                },
            ],
        });
    }
    _addCheck(check) {
        return new ZodNumber({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    int(message) {
        return this._addCheck({
            kind: "int",
            message: errorUtil.toString(message),
        });
    }
    positive(message) {
        return this._addCheck({
            kind: "min",
            value: 0,
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    negative(message) {
        return this._addCheck({
            kind: "max",
            value: 0,
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    nonpositive(message) {
        return this._addCheck({
            kind: "max",
            value: 0,
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    nonnegative(message) {
        return this._addCheck({
            kind: "min",
            value: 0,
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    multipleOf(value, message) {
        return this._addCheck({
            kind: "multipleOf",
            value: value,
            message: errorUtil.toString(message),
        });
    }
    finite(message) {
        return this._addCheck({
            kind: "finite",
            message: errorUtil.toString(message),
        });
    }
    safe(message) {
        return this._addCheck({
            kind: "min",
            inclusive: true,
            value: Number.MIN_SAFE_INTEGER,
            message: errorUtil.toString(message),
        })._addCheck({
            kind: "max",
            inclusive: true,
            value: Number.MAX_SAFE_INTEGER,
            message: errorUtil.toString(message),
        });
    }
    get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min;
    }
    get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max;
    }
    get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util$5.isInteger(ch.value)));
    }
    get isFinite() {
        let max = null;
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
                return true;
            }
            else if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
            else if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return Number.isFinite(min) && Number.isFinite(max);
    }
};
ZodNumber$1.create = (params) => {
    return new ZodNumber$1({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: params?.coerce || false,
        ...processCreateParams(params),
    });
};
let ZodBigInt$1 = class ZodBigInt extends ZodType$1 {
    constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
    }
    _parse(input) {
        if (this._def.coerce) {
            try {
                input.data = BigInt(input.data);
            }
            catch {
                return this._getInvalidInput(input);
            }
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
            return this._getInvalidInput(input);
        }
        let ctx = undefined;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
            if (check.kind === "min") {
                const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
                if (tooSmall) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        type: "bigint",
                        minimum: check.value,
                        inclusive: check.inclusive,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
                if (tooBig) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        type: "bigint",
                        maximum: check.value,
                        inclusive: check.inclusive,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "multipleOf") {
                if (input.data % check.value !== BigInt(0)) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.not_multiple_of,
                        multipleOf: check.value,
                        message: check.message,
                    });
                    status.dirty();
                }
            }
            else {
                util$5.assertNever(check);
            }
        }
        return { status: status.value, value: input.data };
    }
    _getInvalidInput(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.bigint,
            received: ctx.parsedType,
        });
        return INVALID;
    }
    gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
    }
    gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
    }
    lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
    }
    lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
    }
    setLimit(kind, value, inclusive, message) {
        return new ZodBigInt({
            ...this._def,
            checks: [
                ...this._def.checks,
                {
                    kind,
                    value,
                    inclusive,
                    message: errorUtil.toString(message),
                },
            ],
        });
    }
    _addCheck(check) {
        return new ZodBigInt({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    positive(message) {
        return this._addCheck({
            kind: "min",
            value: BigInt(0),
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    negative(message) {
        return this._addCheck({
            kind: "max",
            value: BigInt(0),
            inclusive: false,
            message: errorUtil.toString(message),
        });
    }
    nonpositive(message) {
        return this._addCheck({
            kind: "max",
            value: BigInt(0),
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    nonnegative(message) {
        return this._addCheck({
            kind: "min",
            value: BigInt(0),
            inclusive: true,
            message: errorUtil.toString(message),
        });
    }
    multipleOf(value, message) {
        return this._addCheck({
            kind: "multipleOf",
            value,
            message: errorUtil.toString(message),
        });
    }
    get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min;
    }
    get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max;
    }
};
ZodBigInt$1.create = (params) => {
    return new ZodBigInt$1({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params),
    });
};
let ZodBoolean$1 = class ZodBoolean extends ZodType$1 {
    _parse(input) {
        if (this._def.coerce) {
            input.data = Boolean(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.boolean) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.boolean,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
};
ZodBoolean$1.create = (params) => {
    return new ZodBoolean$1({
        typeName: ZodFirstPartyTypeKind.ZodBoolean,
        coerce: params?.coerce || false,
        ...processCreateParams(params),
    });
};
class ZodDate extends ZodType$1 {
    _parse(input) {
        if (this._def.coerce) {
            input.data = new Date(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.date) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.date,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        if (Number.isNaN(input.data.getTime())) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_date,
            });
            return INVALID;
        }
        const status = new ParseStatus();
        let ctx = undefined;
        for (const check of this._def.checks) {
            if (check.kind === "min") {
                if (input.data.getTime() < check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        message: check.message,
                        inclusive: true,
                        exact: false,
                        minimum: check.value,
                        type: "date",
                    });
                    status.dirty();
                }
            }
            else if (check.kind === "max") {
                if (input.data.getTime() > check.value) {
                    ctx = this._getOrReturnCtx(input, ctx);
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        message: check.message,
                        inclusive: true,
                        exact: false,
                        maximum: check.value,
                        type: "date",
                    });
                    status.dirty();
                }
            }
            else {
                util$5.assertNever(check);
            }
        }
        return {
            status: status.value,
            value: new Date(input.data.getTime()),
        };
    }
    _addCheck(check) {
        return new ZodDate({
            ...this._def,
            checks: [...this._def.checks, check],
        });
    }
    min(minDate, message) {
        return this._addCheck({
            kind: "min",
            value: minDate.getTime(),
            message: errorUtil.toString(message),
        });
    }
    max(maxDate, message) {
        return this._addCheck({
            kind: "max",
            value: maxDate.getTime(),
            message: errorUtil.toString(message),
        });
    }
    get minDate() {
        let min = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "min") {
                if (min === null || ch.value > min)
                    min = ch.value;
            }
        }
        return min != null ? new Date(min) : null;
    }
    get maxDate() {
        let max = null;
        for (const ch of this._def.checks) {
            if (ch.kind === "max") {
                if (max === null || ch.value < max)
                    max = ch.value;
            }
        }
        return max != null ? new Date(max) : null;
    }
}
ZodDate.create = (params) => {
    return new ZodDate({
        checks: [],
        coerce: params?.coerce || false,
        typeName: ZodFirstPartyTypeKind.ZodDate,
        ...processCreateParams(params),
    });
};
class ZodSymbol extends ZodType$1 {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.symbol) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.symbol,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodSymbol.create = (params) => {
    return new ZodSymbol({
        typeName: ZodFirstPartyTypeKind.ZodSymbol,
        ...processCreateParams(params),
    });
};
class ZodUndefined extends ZodType$1 {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.undefined,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodUndefined.create = (params) => {
    return new ZodUndefined({
        typeName: ZodFirstPartyTypeKind.ZodUndefined,
        ...processCreateParams(params),
    });
};
let ZodNull$1 = class ZodNull extends ZodType$1 {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.null) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.null,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
};
ZodNull$1.create = (params) => {
    return new ZodNull$1({
        typeName: ZodFirstPartyTypeKind.ZodNull,
        ...processCreateParams(params),
    });
};
class ZodAny extends ZodType$1 {
    constructor() {
        super(...arguments);
        this._any = true;
    }
    _parse(input) {
        return OK(input.data);
    }
}
ZodAny.create = (params) => {
    return new ZodAny({
        typeName: ZodFirstPartyTypeKind.ZodAny,
        ...processCreateParams(params),
    });
};
let ZodUnknown$1 = class ZodUnknown extends ZodType$1 {
    constructor() {
        super(...arguments);
        this._unknown = true;
    }
    _parse(input) {
        return OK(input.data);
    }
};
ZodUnknown$1.create = (params) => {
    return new ZodUnknown$1({
        typeName: ZodFirstPartyTypeKind.ZodUnknown,
        ...processCreateParams(params),
    });
};
let ZodNever$1 = class ZodNever extends ZodType$1 {
    _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.never,
            received: ctx.parsedType,
        });
        return INVALID;
    }
};
ZodNever$1.create = (params) => {
    return new ZodNever$1({
        typeName: ZodFirstPartyTypeKind.ZodNever,
        ...processCreateParams(params),
    });
};
class ZodVoid extends ZodType$1 {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.void,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return OK(input.data);
    }
}
ZodVoid.create = (params) => {
    return new ZodVoid({
        typeName: ZodFirstPartyTypeKind.ZodVoid,
        ...processCreateParams(params),
    });
};
let ZodArray$1 = class ZodArray extends ZodType$1 {
    _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def = this._def;
        if (ctx.parsedType !== ZodParsedType.array) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.array,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        if (def.exactLength !== null) {
            const tooBig = ctx.data.length > def.exactLength.value;
            const tooSmall = ctx.data.length < def.exactLength.value;
            if (tooBig || tooSmall) {
                addIssueToContext(ctx, {
                    code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
                    minimum: (tooSmall ? def.exactLength.value : undefined),
                    maximum: (tooBig ? def.exactLength.value : undefined),
                    type: "array",
                    inclusive: true,
                    exact: true,
                    message: def.exactLength.message,
                });
                status.dirty();
            }
        }
        if (def.minLength !== null) {
            if (ctx.data.length < def.minLength.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_small,
                    minimum: def.minLength.value,
                    type: "array",
                    inclusive: true,
                    exact: false,
                    message: def.minLength.message,
                });
                status.dirty();
            }
        }
        if (def.maxLength !== null) {
            if (ctx.data.length > def.maxLength.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_big,
                    maximum: def.maxLength.value,
                    type: "array",
                    inclusive: true,
                    exact: false,
                    message: def.maxLength.message,
                });
                status.dirty();
            }
        }
        if (ctx.common.async) {
            return Promise.all([...ctx.data].map((item, i) => {
                return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
            })).then((result) => {
                return ParseStatus.mergeArray(status, result);
            });
        }
        const result = [...ctx.data].map((item, i) => {
            return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
        });
        return ParseStatus.mergeArray(status, result);
    }
    get element() {
        return this._def.type;
    }
    min(minLength, message) {
        return new ZodArray({
            ...this._def,
            minLength: { value: minLength, message: errorUtil.toString(message) },
        });
    }
    max(maxLength, message) {
        return new ZodArray({
            ...this._def,
            maxLength: { value: maxLength, message: errorUtil.toString(message) },
        });
    }
    length(len, message) {
        return new ZodArray({
            ...this._def,
            exactLength: { value: len, message: errorUtil.toString(message) },
        });
    }
    nonempty(message) {
        return this.min(1, message);
    }
};
ZodArray$1.create = (schema, params) => {
    return new ZodArray$1({
        type: schema,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind.ZodArray,
        ...processCreateParams(params),
    });
};
function deepPartialify(schema) {
    if (schema instanceof ZodObject$1) {
        const newShape = {};
        for (const key in schema.shape) {
            const fieldSchema = schema.shape[key];
            newShape[key] = ZodOptional$1.create(deepPartialify(fieldSchema));
        }
        return new ZodObject$1({
            ...schema._def,
            shape: () => newShape,
        });
    }
    else if (schema instanceof ZodArray$1) {
        return new ZodArray$1({
            ...schema._def,
            type: deepPartialify(schema.element),
        });
    }
    else if (schema instanceof ZodOptional$1) {
        return ZodOptional$1.create(deepPartialify(schema.unwrap()));
    }
    else if (schema instanceof ZodNullable$1) {
        return ZodNullable$1.create(deepPartialify(schema.unwrap()));
    }
    else if (schema instanceof ZodTuple) {
        return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
    }
    else {
        return schema;
    }
}
let ZodObject$1 = class ZodObject extends ZodType$1 {
    constructor() {
        super(...arguments);
        this._cached = null;
        this.nonstrict = this.passthrough;
        this.augment = this.extend;
    }
    _getCached() {
        if (this._cached !== null)
            return this._cached;
        const shape = this._def.shape();
        const keys = util$5.objectKeys(shape);
        this._cached = { shape, keys };
        return this._cached;
    }
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.object) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.object,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever$1 && this._def.unknownKeys === "strip")) {
            for (const key in ctx.data) {
                if (!shapeKeys.includes(key)) {
                    extraKeys.push(key);
                }
            }
        }
        const pairs = [];
        for (const key of shapeKeys) {
            const keyValidator = shape[key];
            const value = ctx.data[key];
            pairs.push({
                key: { status: "valid", value: key },
                value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
                alwaysSet: key in ctx.data,
            });
        }
        if (this._def.catchall instanceof ZodNever$1) {
            const unknownKeys = this._def.unknownKeys;
            if (unknownKeys === "passthrough") {
                for (const key of extraKeys) {
                    pairs.push({
                        key: { status: "valid", value: key },
                        value: { status: "valid", value: ctx.data[key] },
                    });
                }
            }
            else if (unknownKeys === "strict") {
                if (extraKeys.length > 0) {
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.unrecognized_keys,
                        keys: extraKeys,
                    });
                    status.dirty();
                }
            }
            else if (unknownKeys === "strip") ;
            else {
                throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
            }
        }
        else {
            const catchall = this._def.catchall;
            for (const key of extraKeys) {
                const value = ctx.data[key];
                pairs.push({
                    key: { status: "valid", value: key },
                    value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)
                    ),
                    alwaysSet: key in ctx.data,
                });
            }
        }
        if (ctx.common.async) {
            return Promise.resolve()
                .then(async () => {
                const syncPairs = [];
                for (const pair of pairs) {
                    const key = await pair.key;
                    const value = await pair.value;
                    syncPairs.push({
                        key,
                        value,
                        alwaysSet: pair.alwaysSet,
                    });
                }
                return syncPairs;
            })
                .then((syncPairs) => {
                return ParseStatus.mergeObjectSync(status, syncPairs);
            });
        }
        else {
            return ParseStatus.mergeObjectSync(status, pairs);
        }
    }
    get shape() {
        return this._def.shape();
    }
    strict(message) {
        errorUtil.errToObj;
        return new ZodObject({
            ...this._def,
            unknownKeys: "strict",
            ...(message !== undefined
                ? {
                    errorMap: (issue, ctx) => {
                        const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
                        if (issue.code === "unrecognized_keys")
                            return {
                                message: errorUtil.errToObj(message).message ?? defaultError,
                            };
                        return {
                            message: defaultError,
                        };
                    },
                }
                : {}),
        });
    }
    strip() {
        return new ZodObject({
            ...this._def,
            unknownKeys: "strip",
        });
    }
    passthrough() {
        return new ZodObject({
            ...this._def,
            unknownKeys: "passthrough",
        });
    }
    extend(augmentation) {
        return new ZodObject({
            ...this._def,
            shape: () => ({
                ...this._def.shape(),
                ...augmentation,
            }),
        });
    }
    merge(merging) {
        const merged = new ZodObject({
            unknownKeys: merging._def.unknownKeys,
            catchall: merging._def.catchall,
            shape: () => ({
                ...this._def.shape(),
                ...merging._def.shape(),
            }),
            typeName: ZodFirstPartyTypeKind.ZodObject,
        });
        return merged;
    }
    setKey(key, schema) {
        return this.augment({ [key]: schema });
    }
    catchall(index) {
        return new ZodObject({
            ...this._def,
            catchall: index,
        });
    }
    pick(mask) {
        const shape = {};
        for (const key of util$5.objectKeys(mask)) {
            if (mask[key] && this.shape[key]) {
                shape[key] = this.shape[key];
            }
        }
        return new ZodObject({
            ...this._def,
            shape: () => shape,
        });
    }
    omit(mask) {
        const shape = {};
        for (const key of util$5.objectKeys(this.shape)) {
            if (!mask[key]) {
                shape[key] = this.shape[key];
            }
        }
        return new ZodObject({
            ...this._def,
            shape: () => shape,
        });
    }
    deepPartial() {
        return deepPartialify(this);
    }
    partial(mask) {
        const newShape = {};
        for (const key of util$5.objectKeys(this.shape)) {
            const fieldSchema = this.shape[key];
            if (mask && !mask[key]) {
                newShape[key] = fieldSchema;
            }
            else {
                newShape[key] = fieldSchema.optional();
            }
        }
        return new ZodObject({
            ...this._def,
            shape: () => newShape,
        });
    }
    required(mask) {
        const newShape = {};
        for (const key of util$5.objectKeys(this.shape)) {
            if (mask && !mask[key]) {
                newShape[key] = this.shape[key];
            }
            else {
                const fieldSchema = this.shape[key];
                let newField = fieldSchema;
                while (newField instanceof ZodOptional$1) {
                    newField = newField._def.innerType;
                }
                newShape[key] = newField;
            }
        }
        return new ZodObject({
            ...this._def,
            shape: () => newShape,
        });
    }
    keyof() {
        return createZodEnum(util$5.objectKeys(this.shape));
    }
};
ZodObject$1.create = (shape, params) => {
    return new ZodObject$1({
        shape: () => shape,
        unknownKeys: "strip",
        catchall: ZodNever$1.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params),
    });
};
ZodObject$1.strictCreate = (shape, params) => {
    return new ZodObject$1({
        shape: () => shape,
        unknownKeys: "strict",
        catchall: ZodNever$1.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params),
    });
};
ZodObject$1.lazycreate = (shape, params) => {
    return new ZodObject$1({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever$1.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params),
    });
};
let ZodUnion$1 = class ZodUnion extends ZodType$1 {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        const options = this._def.options;
        function handleResults(results) {
            for (const result of results) {
                if (result.result.status === "valid") {
                    return result.result;
                }
            }
            for (const result of results) {
                if (result.result.status === "dirty") {
                    ctx.common.issues.push(...result.ctx.common.issues);
                    return result.result;
                }
            }
            const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_union,
                unionErrors,
            });
            return INVALID;
        }
        if (ctx.common.async) {
            return Promise.all(options.map(async (option) => {
                const childCtx = {
                    ...ctx,
                    common: {
                        ...ctx.common,
                        issues: [],
                    },
                    parent: null,
                };
                return {
                    result: await option._parseAsync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: childCtx,
                    }),
                    ctx: childCtx,
                };
            })).then(handleResults);
        }
        else {
            let dirty = undefined;
            const issues = [];
            for (const option of options) {
                const childCtx = {
                    ...ctx,
                    common: {
                        ...ctx.common,
                        issues: [],
                    },
                    parent: null,
                };
                const result = option._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: childCtx,
                });
                if (result.status === "valid") {
                    return result;
                }
                else if (result.status === "dirty" && !dirty) {
                    dirty = { result, ctx: childCtx };
                }
                if (childCtx.common.issues.length) {
                    issues.push(childCtx.common.issues);
                }
            }
            if (dirty) {
                ctx.common.issues.push(...dirty.ctx.common.issues);
                return dirty.result;
            }
            const unionErrors = issues.map((issues) => new ZodError(issues));
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_union,
                unionErrors,
            });
            return INVALID;
        }
    }
    get options() {
        return this._def.options;
    }
};
ZodUnion$1.create = (types, params) => {
    return new ZodUnion$1({
        options: types,
        typeName: ZodFirstPartyTypeKind.ZodUnion,
        ...processCreateParams(params),
    });
};
const getDiscriminator = (type) => {
    if (type instanceof ZodLazy) {
        return getDiscriminator(type.schema);
    }
    else if (type instanceof ZodEffects) {
        return getDiscriminator(type.innerType());
    }
    else if (type instanceof ZodLiteral$1) {
        return [type.value];
    }
    else if (type instanceof ZodEnum$1) {
        return type.options;
    }
    else if (type instanceof ZodNativeEnum) {
        return util$5.objectValues(type.enum);
    }
    else if (type instanceof ZodDefault$1) {
        return getDiscriminator(type._def.innerType);
    }
    else if (type instanceof ZodUndefined) {
        return [undefined];
    }
    else if (type instanceof ZodNull$1) {
        return [null];
    }
    else if (type instanceof ZodOptional$1) {
        return [undefined, ...getDiscriminator(type.unwrap())];
    }
    else if (type instanceof ZodNullable$1) {
        return [null, ...getDiscriminator(type.unwrap())];
    }
    else if (type instanceof ZodBranded) {
        return getDiscriminator(type.unwrap());
    }
    else if (type instanceof ZodReadonly$1) {
        return getDiscriminator(type.unwrap());
    }
    else if (type instanceof ZodCatch$1) {
        return getDiscriminator(type._def.innerType);
    }
    else {
        return [];
    }
};
let ZodDiscriminatedUnion$1 = class ZodDiscriminatedUnion extends ZodType$1 {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.object,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option = this.optionsMap.get(discriminatorValue);
        if (!option) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_union_discriminator,
                options: Array.from(this.optionsMap.keys()),
                path: [discriminator],
            });
            return INVALID;
        }
        if (ctx.common.async) {
            return option._parseAsync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            });
        }
        else {
            return option._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            });
        }
    }
    get discriminator() {
        return this._def.discriminator;
    }
    get options() {
        return this._def.options;
    }
    get optionsMap() {
        return this._def.optionsMap;
    }
    static create(discriminator, options, params) {
        const optionsMap = new Map();
        for (const type of options) {
            const discriminatorValues = getDiscriminator(type.shape[discriminator]);
            if (!discriminatorValues.length) {
                throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
            }
            for (const value of discriminatorValues) {
                if (optionsMap.has(value)) {
                    throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
                }
                optionsMap.set(value, type);
            }
        }
        return new ZodDiscriminatedUnion({
            typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
            discriminator,
            options,
            optionsMap,
            ...processCreateParams(params),
        });
    }
};
function mergeValues$1(a, b) {
    const aType = getParsedType(a);
    const bType = getParsedType(b);
    if (a === b) {
        return { valid: true, data: a };
    }
    else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
        const bKeys = util$5.objectKeys(b);
        const sharedKeys = util$5.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
        const newObj = { ...a, ...b };
        for (const key of sharedKeys) {
            const sharedValue = mergeValues$1(a[key], b[key]);
            if (!sharedValue.valid) {
                return { valid: false };
            }
            newObj[key] = sharedValue.data;
        }
        return { valid: true, data: newObj };
    }
    else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
        if (a.length !== b.length) {
            return { valid: false };
        }
        const newArray = [];
        for (let index = 0; index < a.length; index++) {
            const itemA = a[index];
            const itemB = b[index];
            const sharedValue = mergeValues$1(itemA, itemB);
            if (!sharedValue.valid) {
                return { valid: false };
            }
            newArray.push(sharedValue.data);
        }
        return { valid: true, data: newArray };
    }
    else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
        return { valid: true, data: a };
    }
    else {
        return { valid: false };
    }
}
let ZodIntersection$1 = class ZodIntersection extends ZodType$1 {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = (parsedLeft, parsedRight) => {
            if (isAborted(parsedLeft) || isAborted(parsedRight)) {
                return INVALID;
            }
            const merged = mergeValues$1(parsedLeft.value, parsedRight.value);
            if (!merged.valid) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_intersection_types,
                });
                return INVALID;
            }
            if (isDirty(parsedLeft) || isDirty(parsedRight)) {
                status.dirty();
            }
            return { status: status.value, value: merged.data };
        };
        if (ctx.common.async) {
            return Promise.all([
                this._def.left._parseAsync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                }),
                this._def.right._parseAsync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                }),
            ]).then(([left, right]) => handleParsed(left, right));
        }
        else {
            return handleParsed(this._def.left._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            }), this._def.right._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            }));
        }
    }
};
ZodIntersection$1.create = (left, right, params) => {
    return new ZodIntersection$1({
        left: left,
        right: right,
        typeName: ZodFirstPartyTypeKind.ZodIntersection,
        ...processCreateParams(params),
    });
};
class ZodTuple extends ZodType$1 {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.array) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.array,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: this._def.items.length,
                inclusive: true,
                exact: false,
                type: "array",
            });
            return INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: this._def.items.length,
                inclusive: true,
                exact: false,
                type: "array",
            });
            status.dirty();
        }
        const items = [...ctx.data]
            .map((item, itemIndex) => {
            const schema = this._def.items[itemIndex] || this._def.rest;
            if (!schema)
                return null;
            return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        })
            .filter((x) => !!x);
        if (ctx.common.async) {
            return Promise.all(items).then((results) => {
                return ParseStatus.mergeArray(status, results);
            });
        }
        else {
            return ParseStatus.mergeArray(status, items);
        }
    }
    get items() {
        return this._def.items;
    }
    rest(rest) {
        return new ZodTuple({
            ...this._def,
            rest,
        });
    }
}
ZodTuple.create = (schemas, params) => {
    if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
    }
    return new ZodTuple({
        items: schemas,
        typeName: ZodFirstPartyTypeKind.ZodTuple,
        rest: null,
        ...processCreateParams(params),
    });
};
let ZodRecord$1 = class ZodRecord extends ZodType$1 {
    get keySchema() {
        return this._def.keyType;
    }
    get valueSchema() {
        return this._def.valueType;
    }
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.object,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const pairs = [];
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        for (const key in ctx.data) {
            pairs.push({
                key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
                value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
                alwaysSet: key in ctx.data,
            });
        }
        if (ctx.common.async) {
            return ParseStatus.mergeObjectAsync(status, pairs);
        }
        else {
            return ParseStatus.mergeObjectSync(status, pairs);
        }
    }
    get element() {
        return this._def.valueType;
    }
    static create(first, second, third) {
        if (second instanceof ZodType$1) {
            return new ZodRecord({
                keyType: first,
                valueType: second,
                typeName: ZodFirstPartyTypeKind.ZodRecord,
                ...processCreateParams(third),
            });
        }
        return new ZodRecord({
            keyType: ZodString$1.create(),
            valueType: first,
            typeName: ZodFirstPartyTypeKind.ZodRecord,
            ...processCreateParams(second),
        });
    }
};
class ZodMap extends ZodType$1 {
    get keySchema() {
        return this._def.keyType;
    }
    get valueSchema() {
        return this._def.valueType;
    }
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.map) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.map,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        const pairs = [...ctx.data.entries()].map(([key, value], index) => {
            return {
                key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
                value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
            };
        });
        if (ctx.common.async) {
            const finalMap = new Map();
            return Promise.resolve().then(async () => {
                for (const pair of pairs) {
                    const key = await pair.key;
                    const value = await pair.value;
                    if (key.status === "aborted" || value.status === "aborted") {
                        return INVALID;
                    }
                    if (key.status === "dirty" || value.status === "dirty") {
                        status.dirty();
                    }
                    finalMap.set(key.value, value.value);
                }
                return { status: status.value, value: finalMap };
            });
        }
        else {
            const finalMap = new Map();
            for (const pair of pairs) {
                const key = pair.key;
                const value = pair.value;
                if (key.status === "aborted" || value.status === "aborted") {
                    return INVALID;
                }
                if (key.status === "dirty" || value.status === "dirty") {
                    status.dirty();
                }
                finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
        }
    }
}
ZodMap.create = (keyType, valueType, params) => {
    return new ZodMap({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind.ZodMap,
        ...processCreateParams(params),
    });
};
class ZodSet extends ZodType$1 {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.set) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.set,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const def = this._def;
        if (def.minSize !== null) {
            if (ctx.data.size < def.minSize.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_small,
                    minimum: def.minSize.value,
                    type: "set",
                    inclusive: true,
                    exact: false,
                    message: def.minSize.message,
                });
                status.dirty();
            }
        }
        if (def.maxSize !== null) {
            if (ctx.data.size > def.maxSize.value) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_big,
                    maximum: def.maxSize.value,
                    type: "set",
                    inclusive: true,
                    exact: false,
                    message: def.maxSize.message,
                });
                status.dirty();
            }
        }
        const valueType = this._def.valueType;
        function finalizeSet(elements) {
            const parsedSet = new Set();
            for (const element of elements) {
                if (element.status === "aborted")
                    return INVALID;
                if (element.status === "dirty")
                    status.dirty();
                parsedSet.add(element.value);
            }
            return { status: status.value, value: parsedSet };
        }
        const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
        if (ctx.common.async) {
            return Promise.all(elements).then((elements) => finalizeSet(elements));
        }
        else {
            return finalizeSet(elements);
        }
    }
    min(minSize, message) {
        return new ZodSet({
            ...this._def,
            minSize: { value: minSize, message: errorUtil.toString(message) },
        });
    }
    max(maxSize, message) {
        return new ZodSet({
            ...this._def,
            maxSize: { value: maxSize, message: errorUtil.toString(message) },
        });
    }
    size(size, message) {
        return this.min(size, message).max(size, message);
    }
    nonempty(message) {
        return this.min(1, message);
    }
}
ZodSet.create = (valueType, params) => {
    return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params),
    });
};
class ZodFunction extends ZodType$1 {
    constructor() {
        super(...arguments);
        this.validate = this.implement;
    }
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.function) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.function,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        function makeArgsIssue(args, error) {
            return makeIssue({
                data: args,
                path: ctx.path,
                errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap].filter((x) => !!x),
                issueData: {
                    code: ZodIssueCode.invalid_arguments,
                    argumentsError: error,
                },
            });
        }
        function makeReturnsIssue(returns, error) {
            return makeIssue({
                data: returns,
                path: ctx.path,
                errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap].filter((x) => !!x),
                issueData: {
                    code: ZodIssueCode.invalid_return_type,
                    returnTypeError: error,
                },
            });
        }
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
            const me = this;
            return OK(async function (...args) {
                const error = new ZodError([]);
                const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
                    error.addIssue(makeArgsIssue(args, e));
                    throw error;
                });
                const result = await Reflect.apply(fn, this, parsedArgs);
                const parsedReturns = await me._def.returns._def.type
                    .parseAsync(result, params)
                    .catch((e) => {
                    error.addIssue(makeReturnsIssue(result, e));
                    throw error;
                });
                return parsedReturns;
            });
        }
        else {
            const me = this;
            return OK(function (...args) {
                const parsedArgs = me._def.args.safeParse(args, params);
                if (!parsedArgs.success) {
                    throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
                }
                const result = Reflect.apply(fn, this, parsedArgs.data);
                const parsedReturns = me._def.returns.safeParse(result, params);
                if (!parsedReturns.success) {
                    throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
                }
                return parsedReturns.data;
            });
        }
    }
    parameters() {
        return this._def.args;
    }
    returnType() {
        return this._def.returns;
    }
    args(...items) {
        return new ZodFunction({
            ...this._def,
            args: ZodTuple.create(items).rest(ZodUnknown$1.create()),
        });
    }
    returns(returnType) {
        return new ZodFunction({
            ...this._def,
            returns: returnType,
        });
    }
    implement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
    }
    strictImplement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
    }
    static create(args, returns, params) {
        return new ZodFunction({
            args: (args ? args : ZodTuple.create([]).rest(ZodUnknown$1.create())),
            returns: returns || ZodUnknown$1.create(),
            typeName: ZodFirstPartyTypeKind.ZodFunction,
            ...processCreateParams(params),
        });
    }
}
class ZodLazy extends ZodType$1 {
    get schema() {
        return this._def.getter();
    }
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        const lazySchema = this._def.getter();
        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
    }
}
ZodLazy.create = (getter, params) => {
    return new ZodLazy({
        getter: getter,
        typeName: ZodFirstPartyTypeKind.ZodLazy,
        ...processCreateParams(params),
    });
};
let ZodLiteral$1 = class ZodLiteral extends ZodType$1 {
    _parse(input) {
        if (input.data !== this._def.value) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                received: ctx.data,
                code: ZodIssueCode.invalid_literal,
                expected: this._def.value,
            });
            return INVALID;
        }
        return { status: "valid", value: input.data };
    }
    get value() {
        return this._def.value;
    }
};
ZodLiteral$1.create = (value, params) => {
    return new ZodLiteral$1({
        value: value,
        typeName: ZodFirstPartyTypeKind.ZodLiteral,
        ...processCreateParams(params),
    });
};
function createZodEnum(values, params) {
    return new ZodEnum$1({
        values,
        typeName: ZodFirstPartyTypeKind.ZodEnum,
        ...processCreateParams(params),
    });
}
let ZodEnum$1 = class ZodEnum extends ZodType$1 {
    _parse(input) {
        if (typeof input.data !== "string") {
            const ctx = this._getOrReturnCtx(input);
            const expectedValues = this._def.values;
            addIssueToContext(ctx, {
                expected: util$5.joinValues(expectedValues),
                received: ctx.parsedType,
                code: ZodIssueCode.invalid_type,
            });
            return INVALID;
        }
        if (!this._cache) {
            this._cache = new Set(this._def.values);
        }
        if (!this._cache.has(input.data)) {
            const ctx = this._getOrReturnCtx(input);
            const expectedValues = this._def.values;
            addIssueToContext(ctx, {
                received: ctx.data,
                code: ZodIssueCode.invalid_enum_value,
                options: expectedValues,
            });
            return INVALID;
        }
        return OK(input.data);
    }
    get options() {
        return this._def.values;
    }
    get enum() {
        const enumValues = {};
        for (const val of this._def.values) {
            enumValues[val] = val;
        }
        return enumValues;
    }
    get Values() {
        const enumValues = {};
        for (const val of this._def.values) {
            enumValues[val] = val;
        }
        return enumValues;
    }
    get Enum() {
        const enumValues = {};
        for (const val of this._def.values) {
            enumValues[val] = val;
        }
        return enumValues;
    }
    extract(values, newDef = this._def) {
        return ZodEnum.create(values, {
            ...this._def,
            ...newDef,
        });
    }
    exclude(values, newDef = this._def) {
        return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
            ...this._def,
            ...newDef,
        });
    }
};
ZodEnum$1.create = createZodEnum;
class ZodNativeEnum extends ZodType$1 {
    _parse(input) {
        const nativeEnumValues = util$5.getValidEnumValues(this._def.values);
        const ctx = this._getOrReturnCtx(input);
        if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
            const expectedValues = util$5.objectValues(nativeEnumValues);
            addIssueToContext(ctx, {
                expected: util$5.joinValues(expectedValues),
                received: ctx.parsedType,
                code: ZodIssueCode.invalid_type,
            });
            return INVALID;
        }
        if (!this._cache) {
            this._cache = new Set(util$5.getValidEnumValues(this._def.values));
        }
        if (!this._cache.has(input.data)) {
            const expectedValues = util$5.objectValues(nativeEnumValues);
            addIssueToContext(ctx, {
                received: ctx.data,
                code: ZodIssueCode.invalid_enum_value,
                options: expectedValues,
            });
            return INVALID;
        }
        return OK(input.data);
    }
    get enum() {
        return this._def.values;
    }
}
ZodNativeEnum.create = (values, params) => {
    return new ZodNativeEnum({
        values: values,
        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
        ...processCreateParams(params),
    });
};
class ZodPromise extends ZodType$1 {
    unwrap() {
        return this._def.type;
    }
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.promise,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
        return OK(promisified.then((data) => {
            return this._def.type.parseAsync(data, {
                path: ctx.path,
                errorMap: ctx.common.contextualErrorMap,
            });
        }));
    }
}
ZodPromise.create = (schema, params) => {
    return new ZodPromise({
        type: schema,
        typeName: ZodFirstPartyTypeKind.ZodPromise,
        ...processCreateParams(params),
    });
};
class ZodEffects extends ZodType$1 {
    innerType() {
        return this._def.schema;
    }
    sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
            ? this._def.schema.sourceType()
            : this._def.schema;
    }
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const effect = this._def.effect || null;
        const checkCtx = {
            addIssue: (arg) => {
                addIssueToContext(ctx, arg);
                if (arg.fatal) {
                    status.abort();
                }
                else {
                    status.dirty();
                }
            },
            get path() {
                return ctx.path;
            },
        };
        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
        if (effect.type === "preprocess") {
            const processed = effect.transform(ctx.data, checkCtx);
            if (ctx.common.async) {
                return Promise.resolve(processed).then(async (processed) => {
                    if (status.value === "aborted")
                        return INVALID;
                    const result = await this._def.schema._parseAsync({
                        data: processed,
                        path: ctx.path,
                        parent: ctx,
                    });
                    if (result.status === "aborted")
                        return INVALID;
                    if (result.status === "dirty")
                        return DIRTY(result.value);
                    if (status.value === "dirty")
                        return DIRTY(result.value);
                    return result;
                });
            }
            else {
                if (status.value === "aborted")
                    return INVALID;
                const result = this._def.schema._parseSync({
                    data: processed,
                    path: ctx.path,
                    parent: ctx,
                });
                if (result.status === "aborted")
                    return INVALID;
                if (result.status === "dirty")
                    return DIRTY(result.value);
                if (status.value === "dirty")
                    return DIRTY(result.value);
                return result;
            }
        }
        if (effect.type === "refinement") {
            const executeRefinement = (acc) => {
                const result = effect.refinement(acc, checkCtx);
                if (ctx.common.async) {
                    return Promise.resolve(result);
                }
                if (result instanceof Promise) {
                    throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
                }
                return acc;
            };
            if (ctx.common.async === false) {
                const inner = this._def.schema._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                });
                if (inner.status === "aborted")
                    return INVALID;
                if (inner.status === "dirty")
                    status.dirty();
                executeRefinement(inner.value);
                return { status: status.value, value: inner.value };
            }
            else {
                return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
                    if (inner.status === "aborted")
                        return INVALID;
                    if (inner.status === "dirty")
                        status.dirty();
                    return executeRefinement(inner.value).then(() => {
                        return { status: status.value, value: inner.value };
                    });
                });
            }
        }
        if (effect.type === "transform") {
            if (ctx.common.async === false) {
                const base = this._def.schema._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                });
                if (!isValid$1(base))
                    return INVALID;
                const result = effect.transform(base.value, checkCtx);
                if (result instanceof Promise) {
                    throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
                }
                return { status: status.value, value: result };
            }
            else {
                return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
                    if (!isValid$1(base))
                        return INVALID;
                    return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
                        status: status.value,
                        value: result,
                    }));
                });
            }
        }
        util$5.assertNever(effect);
    }
}
ZodEffects.create = (schema, effect, params) => {
    return new ZodEffects({
        schema,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params),
    });
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
    return new ZodEffects({
        schema,
        effect: { type: "preprocess", transform: preprocess },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params),
    });
};
let ZodOptional$1 = class ZodOptional extends ZodType$1 {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.undefined) {
            return OK(undefined);
        }
        return this._def.innerType._parse(input);
    }
    unwrap() {
        return this._def.innerType;
    }
};
ZodOptional$1.create = (type, params) => {
    return new ZodOptional$1({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodOptional,
        ...processCreateParams(params),
    });
};
let ZodNullable$1 = class ZodNullable extends ZodType$1 {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.null) {
            return OK(null);
        }
        return this._def.innerType._parse(input);
    }
    unwrap() {
        return this._def.innerType;
    }
};
ZodNullable$1.create = (type, params) => {
    return new ZodNullable$1({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodNullable,
        ...processCreateParams(params),
    });
};
let ZodDefault$1 = class ZodDefault extends ZodType$1 {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data = ctx.data;
        if (ctx.parsedType === ZodParsedType.undefined) {
            data = this._def.defaultValue();
        }
        return this._def.innerType._parse({
            data,
            path: ctx.path,
            parent: ctx,
        });
    }
    removeDefault() {
        return this._def.innerType;
    }
};
ZodDefault$1.create = (type, params) => {
    return new ZodDefault$1({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodDefault,
        defaultValue: typeof params.default === "function" ? params.default : () => params.default,
        ...processCreateParams(params),
    });
};
let ZodCatch$1 = class ZodCatch extends ZodType$1 {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        const newCtx = {
            ...ctx,
            common: {
                ...ctx.common,
                issues: [],
            },
        };
        const result = this._def.innerType._parse({
            data: newCtx.data,
            path: newCtx.path,
            parent: {
                ...newCtx,
            },
        });
        if (isAsync(result)) {
            return result.then((result) => {
                return {
                    status: "valid",
                    value: result.status === "valid"
                        ? result.value
                        : this._def.catchValue({
                            get error() {
                                return new ZodError(newCtx.common.issues);
                            },
                            input: newCtx.data,
                        }),
                };
            });
        }
        else {
            return {
                status: "valid",
                value: result.status === "valid"
                    ? result.value
                    : this._def.catchValue({
                        get error() {
                            return new ZodError(newCtx.common.issues);
                        },
                        input: newCtx.data,
                    }),
            };
        }
    }
    removeCatch() {
        return this._def.innerType;
    }
};
ZodCatch$1.create = (type, params) => {
    return new ZodCatch$1({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams(params),
    });
};
class ZodNaN extends ZodType$1 {
    _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.nan) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.nan,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        return { status: "valid", value: input.data };
    }
}
ZodNaN.create = (params) => {
    return new ZodNaN({
        typeName: ZodFirstPartyTypeKind.ZodNaN,
        ...processCreateParams(params),
    });
};
const BRAND = Symbol("zod_brand");
class ZodBranded extends ZodType$1 {
    _parse(input) {
        const { ctx } = this._processInputParams(input);
        const data = ctx.data;
        return this._def.type._parse({
            data,
            path: ctx.path,
            parent: ctx,
        });
    }
    unwrap() {
        return this._def.type;
    }
}
class ZodPipeline extends ZodType$1 {
    _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.common.async) {
            const handleAsync = async () => {
                const inResult = await this._def.in._parseAsync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                });
                if (inResult.status === "aborted")
                    return INVALID;
                if (inResult.status === "dirty") {
                    status.dirty();
                    return DIRTY(inResult.value);
                }
                else {
                    return this._def.out._parseAsync({
                        data: inResult.value,
                        path: ctx.path,
                        parent: ctx,
                    });
                }
            };
            return handleAsync();
        }
        else {
            const inResult = this._def.in._parseSync({
                data: ctx.data,
                path: ctx.path,
                parent: ctx,
            });
            if (inResult.status === "aborted")
                return INVALID;
            if (inResult.status === "dirty") {
                status.dirty();
                return {
                    status: "dirty",
                    value: inResult.value,
                };
            }
            else {
                return this._def.out._parseSync({
                    data: inResult.value,
                    path: ctx.path,
                    parent: ctx,
                });
            }
        }
    }
    static create(a, b) {
        return new ZodPipeline({
            in: a,
            out: b,
            typeName: ZodFirstPartyTypeKind.ZodPipeline,
        });
    }
}
let ZodReadonly$1 = class ZodReadonly extends ZodType$1 {
    _parse(input) {
        const result = this._def.innerType._parse(input);
        const freeze = (data) => {
            if (isValid$1(data)) {
                data.value = Object.freeze(data.value);
            }
            return data;
        };
        return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
    }
    unwrap() {
        return this._def.innerType;
    }
};
ZodReadonly$1.create = (type, params) => {
    return new ZodReadonly$1({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodReadonly,
        ...processCreateParams(params),
    });
};
function cleanParams(params, data) {
    const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
    const p2 = typeof p === "string" ? { message: p } : p;
    return p2;
}
function custom$1(check, _params = {},
fatal) {
    if (check)
        return ZodAny.create().superRefine((data, ctx) => {
            const r = check(data);
            if (r instanceof Promise) {
                return r.then((r) => {
                    if (!r) {
                        const params = cleanParams(_params, data);
                        const _fatal = params.fatal ?? fatal ?? true;
                        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
                    }
                });
            }
            if (!r) {
                const params = cleanParams(_params, data);
                const _fatal = params.fatal ?? fatal ?? true;
                ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
            }
            return;
        });
    return ZodAny.create();
}
const late = {
    object: ZodObject$1.lazycreate,
};
var ZodFirstPartyTypeKind;
(function (ZodFirstPartyTypeKind) {
    ZodFirstPartyTypeKind["ZodString"] = "ZodString";
    ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
    ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
    ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
    ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
    ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
    ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
    ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
    ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
    ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
    ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
    ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
    ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
    ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
    ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
    ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
    ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
    ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
    ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
    ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
    ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
    ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
    ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
    ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
    ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
    ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
    ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
    ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
    ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
    ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
    ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
    ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
    ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
    ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
    ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
    ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
const instanceOfType = (
cls, params = {
    message: `Input not instance of ${cls.name}`,
}) => custom$1((data) => data instanceof cls, params);
const stringType = ZodString$1.create;
const numberType = ZodNumber$1.create;
const nanType = ZodNaN.create;
const bigIntType = ZodBigInt$1.create;
const booleanType = ZodBoolean$1.create;
const dateType = ZodDate.create;
const symbolType = ZodSymbol.create;
const undefinedType = ZodUndefined.create;
const nullType = ZodNull$1.create;
const anyType = ZodAny.create;
const unknownType = ZodUnknown$1.create;
const neverType = ZodNever$1.create;
const voidType = ZodVoid.create;
const arrayType = ZodArray$1.create;
const objectType = ZodObject$1.create;
const strictObjectType = ZodObject$1.strictCreate;
const unionType = ZodUnion$1.create;
const discriminatedUnionType = ZodDiscriminatedUnion$1.create;
const intersectionType = ZodIntersection$1.create;
const tupleType = ZodTuple.create;
const recordType = ZodRecord$1.create;
const mapType = ZodMap.create;
const setType = ZodSet.create;
const functionType = ZodFunction.create;
const lazyType = ZodLazy.create;
const literalType = ZodLiteral$1.create;
const enumType = ZodEnum$1.create;
const nativeEnumType = ZodNativeEnum.create;
const promiseType = ZodPromise.create;
const effectsType = ZodEffects.create;
const optionalType = ZodOptional$1.create;
const nullableType = ZodNullable$1.create;
const preprocessType = ZodEffects.createWithPreprocess;
const pipelineType = ZodPipeline.create;
const ostring = () => stringType().optional();
const onumber = () => numberType().optional();
const oboolean = () => booleanType().optional();
const coerce = {
    string: ((arg) => ZodString$1.create({ ...arg, coerce: true })),
    number: ((arg) => ZodNumber$1.create({ ...arg, coerce: true })),
    boolean: ((arg) => ZodBoolean$1.create({
        ...arg,
        coerce: true,
    })),
    bigint: ((arg) => ZodBigInt$1.create({ ...arg, coerce: true })),
    date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
};
const NEVER$1 = INVALID;

var z = /*#__PURE__*/Object.freeze({
	__proto__: null,
	BRAND: BRAND,
	DIRTY: DIRTY,
	EMPTY_PATH: EMPTY_PATH,
	INVALID: INVALID,
	NEVER: NEVER$1,
	OK: OK,
	ParseStatus: ParseStatus,
	Schema: ZodType$1,
	ZodAny: ZodAny,
	ZodArray: ZodArray$1,
	ZodBigInt: ZodBigInt$1,
	ZodBoolean: ZodBoolean$1,
	ZodBranded: ZodBranded,
	ZodCatch: ZodCatch$1,
	ZodDate: ZodDate,
	ZodDefault: ZodDefault$1,
	ZodDiscriminatedUnion: ZodDiscriminatedUnion$1,
	ZodEffects: ZodEffects,
	ZodEnum: ZodEnum$1,
	ZodError: ZodError,
	get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },
	ZodFunction: ZodFunction,
	ZodIntersection: ZodIntersection$1,
	ZodIssueCode: ZodIssueCode,
	ZodLazy: ZodLazy,
	ZodLiteral: ZodLiteral$1,
	ZodMap: ZodMap,
	ZodNaN: ZodNaN,
	ZodNativeEnum: ZodNativeEnum,
	ZodNever: ZodNever$1,
	ZodNull: ZodNull$1,
	ZodNullable: ZodNullable$1,
	ZodNumber: ZodNumber$1,
	ZodObject: ZodObject$1,
	ZodOptional: ZodOptional$1,
	ZodParsedType: ZodParsedType,
	ZodPipeline: ZodPipeline,
	ZodPromise: ZodPromise,
	ZodReadonly: ZodReadonly$1,
	ZodRecord: ZodRecord$1,
	ZodSchema: ZodType$1,
	ZodSet: ZodSet,
	ZodString: ZodString$1,
	ZodSymbol: ZodSymbol,
	ZodTransformer: ZodEffects,
	ZodTuple: ZodTuple,
	ZodType: ZodType$1,
	ZodUndefined: ZodUndefined,
	ZodUnion: ZodUnion$1,
	ZodUnknown: ZodUnknown$1,
	ZodVoid: ZodVoid,
	addIssueToContext: addIssueToContext,
	any: anyType,
	array: arrayType,
	bigint: bigIntType,
	boolean: booleanType,
	coerce: coerce,
	custom: custom$1,
	date: dateType,
	datetimeRegex: datetimeRegex,
	defaultErrorMap: errorMap,
	discriminatedUnion: discriminatedUnionType,
	effect: effectsType,
	enum: enumType,
	function: functionType,
	getErrorMap: getErrorMap,
	getParsedType: getParsedType,
	instanceof: instanceOfType,
	intersection: intersectionType,
	isAborted: isAborted,
	isAsync: isAsync,
	isDirty: isDirty,
	isValid: isValid$1,
	late: late,
	lazy: lazyType,
	literal: literalType,
	makeIssue: makeIssue,
	map: mapType,
	nan: nanType,
	nativeEnum: nativeEnumType,
	never: neverType,
	null: nullType,
	nullable: nullableType,
	number: numberType,
	object: objectType,
	get objectUtil () { return objectUtil; },
	oboolean: oboolean,
	onumber: onumber,
	optional: optionalType,
	ostring: ostring,
	pipeline: pipelineType,
	preprocess: preprocessType,
	promise: promiseType,
	quotelessJson: quotelessJson,
	record: recordType,
	set: setType,
	setErrorMap: setErrorMap,
	strictObject: strictObjectType,
	string: stringType,
	symbol: symbolType,
	transformer: effectsType,
	tuple: tupleType,
	undefined: undefinedType,
	union: unionType,
	unknown: unknownType,
	get util () { return util$5; },
	void: voidType
});

function $constructor(name, initializer, params) {
    function init(inst, def) {
        var _a;
        Object.defineProperty(inst, "_zod", {
            value: inst._zod ?? {},
            enumerable: false,
        });
        (_a = inst._zod).traits ?? (_a.traits = new Set());
        inst._zod.traits.add(name);
        initializer(inst, def);
        for (const k in _.prototype) {
            if (!(k in inst))
                Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
        }
        inst._zod.constr = _;
        inst._zod.def = def;
    }
    const Parent = params?.Parent ?? Object;
    class Definition extends Parent {
    }
    Object.defineProperty(Definition, "name", { value: name });
    function _(def) {
        var _a;
        const inst = params?.Parent ? new Definition() : this;
        init(inst, def);
        (_a = inst._zod).deferred ?? (_a.deferred = []);
        for (const fn of inst._zod.deferred) {
            fn();
        }
        return inst;
    }
    Object.defineProperty(_, "init", { value: init });
    Object.defineProperty(_, Symbol.hasInstance, {
        value: (inst) => {
            if (params?.Parent && inst instanceof params.Parent)
                return true;
            return inst?._zod?.traits?.has(name);
        },
    });
    Object.defineProperty(_, "name", { value: name });
    return _;
}
class $ZodAsyncError extends Error {
    constructor() {
        super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
    }
}
const globalConfig = {};
function config$3(newConfig) {
    return globalConfig;
}

function getEnumValues(entries) {
    const numericValues = Object.values(entries).filter((v) => typeof v === "number");
    const values = Object.entries(entries)
        .filter(([k, _]) => numericValues.indexOf(+k) === -1)
        .map(([_, v]) => v);
    return values;
}
function jsonStringifyReplacer(_, value) {
    if (typeof value === "bigint")
        return value.toString();
    return value;
}
function cached(getter) {
    return {
        get value() {
            {
                const value = getter();
                Object.defineProperty(this, "value", { value });
                return value;
            }
        },
    };
}
function nullish(input) {
    return input === null || input === undefined;
}
function cleanRegex(source) {
    const start = source.startsWith("^") ? 1 : 0;
    const end = source.endsWith("$") ? source.length - 1 : source.length;
    return source.slice(start, end);
}
function floatSafeRemainder(val, step) {
    const valDecCount = (val.toString().split(".")[1] || "").length;
    const stepDecCount = (step.toString().split(".")[1] || "").length;
    const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
    const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
    const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
    return (valInt % stepInt) / 10 ** decCount;
}
function defineLazy(object, key, getter) {
    Object.defineProperty(object, key, {
        get() {
            {
                const value = getter();
                object[key] = value;
                return value;
            }
        },
        set(v) {
            Object.defineProperty(object, key, {
                value: v,
            });
        },
        configurable: true,
    });
}
function assignProp(target, prop, value) {
    Object.defineProperty(target, prop, {
        value,
        writable: true,
        enumerable: true,
        configurable: true,
    });
}
function esc(str) {
    return JSON.stringify(str);
}
const captureStackTrace = Error.captureStackTrace
    ? Error.captureStackTrace
    : (..._args) => { };
function isObject(data) {
    return typeof data === "object" && data !== null && !Array.isArray(data);
}
const allowsEval = cached(() => {
    if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
        return false;
    }
    try {
        const F = Function;
        new F("");
        return true;
    }
    catch (_) {
        return false;
    }
});
function isPlainObject$1(o) {
    if (isObject(o) === false)
        return false;
    const ctor = o.constructor;
    if (ctor === undefined)
        return true;
    const prot = ctor.prototype;
    if (isObject(prot) === false)
        return false;
    if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
        return false;
    }
    return true;
}
const propertyKeyTypes = new Set(["string", "number", "symbol"]);
const primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
function escapeRegex(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone(inst, def, params) {
    const cl = new inst._zod.constr(def ?? inst._zod.def);
    if (!def || params?.parent)
        cl._zod.parent = inst;
    return cl;
}
function normalizeParams(_params) {
    const params = _params;
    if (!params)
        return {};
    if (typeof params === "string")
        return { error: () => params };
    if (params?.message !== undefined) {
        if (params?.error !== undefined)
            throw new Error("Cannot specify both `message` and `error` params");
        params.error = params.message;
    }
    delete params.message;
    if (typeof params.error === "string")
        return { ...params, error: () => params.error };
    return params;
}
function optionalKeys(shape) {
    return Object.keys(shape).filter((k) => {
        return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
    });
}
const NUMBER_FORMAT_RANGES = {
    safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
    int32: [-2147483648, 2147483647],
    uint32: [0, 4294967295],
    float32: [-34028234663852886e22, 3.4028234663852886e38],
    float64: [-Number.MAX_VALUE, Number.MAX_VALUE],
};
const BIGINT_FORMAT_RANGES = {
    int64: [ BigInt("-9223372036854775808"),  BigInt("9223372036854775807")],
    uint64: [ BigInt(0),  BigInt("18446744073709551615")],
};
function pick(schema, mask) {
    const newShape = {};
    const currDef = schema._zod.def;
    for (const key in mask) {
        if (!(key in currDef.shape)) {
            throw new Error(`Unrecognized key: "${key}"`);
        }
        if (!mask[key])
            continue;
        newShape[key] = currDef.shape[key];
    }
    return clone(schema, {
        ...schema._zod.def,
        shape: newShape,
        checks: [],
    });
}
function omit(schema, mask) {
    const newShape = { ...schema._zod.def.shape };
    const currDef = schema._zod.def;
    for (const key in mask) {
        if (!(key in currDef.shape)) {
            throw new Error(`Unrecognized key: "${key}"`);
        }
        if (!mask[key])
            continue;
        delete newShape[key];
    }
    return clone(schema, {
        ...schema._zod.def,
        shape: newShape,
        checks: [],
    });
}
function extend(schema, shape) {
    if (!isPlainObject$1(shape)) {
        throw new Error("Invalid input to extend: expected a plain object");
    }
    const def = {
        ...schema._zod.def,
        get shape() {
            const _shape = { ...schema._zod.def.shape, ...shape };
            assignProp(this, "shape", _shape);
            return _shape;
        },
        checks: [],
    };
    return clone(schema, def);
}
function merge$1(a, b) {
    return clone(a, {
        ...a._zod.def,
        get shape() {
            const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
            assignProp(this, "shape", _shape);
            return _shape;
        },
        catchall: b._zod.def.catchall,
        checks: [],
    });
}
function partial(Class, schema, mask) {
    const oldShape = schema._zod.def.shape;
    const shape = { ...oldShape };
    if (mask) {
        for (const key in mask) {
            if (!(key in oldShape)) {
                throw new Error(`Unrecognized key: "${key}"`);
            }
            if (!mask[key])
                continue;
            shape[key] = Class
                ? new Class({
                    type: "optional",
                    innerType: oldShape[key],
                })
                : oldShape[key];
        }
    }
    else {
        for (const key in oldShape) {
            shape[key] = Class
                ? new Class({
                    type: "optional",
                    innerType: oldShape[key],
                })
                : oldShape[key];
        }
    }
    return clone(schema, {
        ...schema._zod.def,
        shape,
        checks: [],
    });
}
function required$4(Class, schema, mask) {
    const oldShape = schema._zod.def.shape;
    const shape = { ...oldShape };
    if (mask) {
        for (const key in mask) {
            if (!(key in shape)) {
                throw new Error(`Unrecognized key: "${key}"`);
            }
            if (!mask[key])
                continue;
            shape[key] = new Class({
                type: "nonoptional",
                innerType: oldShape[key],
            });
        }
    }
    else {
        for (const key in oldShape) {
            shape[key] = new Class({
                type: "nonoptional",
                innerType: oldShape[key],
            });
        }
    }
    return clone(schema, {
        ...schema._zod.def,
        shape,
        checks: [],
    });
}
function aborted(x, startIndex = 0) {
    for (let i = startIndex; i < x.issues.length; i++) {
        if (x.issues[i]?.continue !== true)
            return true;
    }
    return false;
}
function prefixIssues(path, issues) {
    return issues.map((iss) => {
        var _a;
        (_a = iss).path ?? (_a.path = []);
        iss.path.unshift(path);
        return iss;
    });
}
function unwrapMessage(message) {
    return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config) {
    const full = { ...iss, path: iss.path ?? [] };
    if (!iss.message) {
        const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
            unwrapMessage(ctx?.error?.(iss)) ??
            unwrapMessage(config.customError?.(iss)) ??
            unwrapMessage(config.localeError?.(iss)) ??
            "Invalid input";
        full.message = message;
    }
    delete full.inst;
    delete full.continue;
    if (!ctx?.reportInput) {
        delete full.input;
    }
    return full;
}
function getSizableOrigin(input) {
    if (input instanceof Set)
        return "set";
    if (input instanceof Map)
        return "map";
    if (input instanceof File)
        return "file";
    return "unknown";
}
function getLengthableOrigin(input) {
    if (Array.isArray(input))
        return "array";
    if (typeof input === "string")
        return "string";
    return "unknown";
}
function issue(...args) {
    const [iss, input, inst] = args;
    if (typeof iss === "string") {
        return {
            message: iss,
            code: "custom",
            input,
            inst,
        };
    }
    return { ...iss };
}

const initializer$1 = (inst, def) => {
    inst.name = "$ZodError";
    Object.defineProperty(inst, "_zod", {
        value: inst._zod,
        enumerable: false,
    });
    Object.defineProperty(inst, "issues", {
        value: def,
        enumerable: false,
    });
    Object.defineProperty(inst, "message", {
        get() {
            return JSON.stringify(def, jsonStringifyReplacer, 2);
        },
        enumerable: true,
    });
    Object.defineProperty(inst, "toString", {
        value: () => inst.message,
        enumerable: false,
    });
};
const $ZodError = $constructor("$ZodError", initializer$1);
const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
function flattenError(error, mapper = (issue) => issue.message) {
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of error.issues) {
        if (sub.path.length > 0) {
            fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
            fieldErrors[sub.path[0]].push(mapper(sub));
        }
        else {
            formErrors.push(mapper(sub));
        }
    }
    return { formErrors, fieldErrors };
}
function formatError(error, _mapper) {
    const mapper = _mapper ||
        function (issue) {
            return issue.message;
        };
    const fieldErrors = { _errors: [] };
    const processError = (error) => {
        for (const issue of error.issues) {
            if (issue.code === "invalid_union" && issue.errors.length) {
                issue.errors.map((issues) => processError({ issues }));
            }
            else if (issue.code === "invalid_key") {
                processError({ issues: issue.issues });
            }
            else if (issue.code === "invalid_element") {
                processError({ issues: issue.issues });
            }
            else if (issue.path.length === 0) {
                fieldErrors._errors.push(mapper(issue));
            }
            else {
                let curr = fieldErrors;
                let i = 0;
                while (i < issue.path.length) {
                    const el = issue.path[i];
                    const terminal = i === issue.path.length - 1;
                    if (!terminal) {
                        curr[el] = curr[el] || { _errors: [] };
                    }
                    else {
                        curr[el] = curr[el] || { _errors: [] };
                        curr[el]._errors.push(mapper(issue));
                    }
                    curr = curr[el];
                    i++;
                }
            }
        }
    };
    processError(error);
    return fieldErrors;
}

const _parse = (_Err) => (schema, value, _ctx, _params) => {
    const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
    const result = schema._zod.run({ value, issues: [] }, ctx);
    if (result instanceof Promise) {
        throw new $ZodAsyncError();
    }
    if (result.issues.length) {
        const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$3())));
        captureStackTrace(e, _params?.callee);
        throw e;
    }
    return result.value;
};
const parse$4 =  _parse($ZodRealError);
const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
    const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
    let result = schema._zod.run({ value, issues: [] }, ctx);
    if (result instanceof Promise)
        result = await result;
    if (result.issues.length) {
        const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$3())));
        captureStackTrace(e, params?.callee);
        throw e;
    }
    return result.value;
};
const parseAsync$1 =  _parseAsync($ZodRealError);
const _safeParse = (_Err) => (schema, value, _ctx) => {
    const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
    const result = schema._zod.run({ value, issues: [] }, ctx);
    if (result instanceof Promise) {
        throw new $ZodAsyncError();
    }
    return result.issues.length
        ? {
            success: false,
            error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$3()))),
        }
        : { success: true, data: result.value };
};
const safeParse$2 =  _safeParse($ZodRealError);
const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
    const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
    let result = schema._zod.run({ value, issues: [] }, ctx);
    if (result instanceof Promise)
        result = await result;
    return result.issues.length
        ? {
            success: false,
            error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config$3()))),
        }
        : { success: true, data: result.value };
};
const safeParseAsync$2 =  _safeParseAsync($ZodRealError);

const cuid = /^[cC][^\s-]{8,}$/;
const cuid2 = /^[0-9a-z]+$/;
const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
const xid = /^[0-9a-vA-V]{20}$/;
const ksuid = /^[A-Za-z0-9]{27}$/;
const nanoid = /^[a-zA-Z0-9_-]{21}$/;
const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
const uuid = (version) => {
    if (!version)
        return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
    return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji() {
    return new RegExp(_emoji$1, "u");
}
const ipv4$1 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv6$1 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
const base64$1 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
const base64url = /^[A-Za-z0-9_-]*$/;
const hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
const e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
const date$1 =  new RegExp(`^${dateSource}$`);
function timeSource(args) {
    const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
    const regex = typeof args.precision === "number"
        ? args.precision === -1
            ? `${hhmm}`
            : args.precision === 0
                ? `${hhmm}:[0-5]\\d`
                : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`
        : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
    return regex;
}
function time$1(args) {
    return new RegExp(`^${timeSource(args)}$`);
}
function datetime$1(args) {
    const time = timeSource({ precision: args.precision });
    const opts = ["Z"];
    if (args.local)
        opts.push("");
    if (args.offset)
        opts.push(`([+-]\\d{2}:\\d{2})`);
    const timeRegex = `${time}(?:${opts.join("|")})`;
    return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
const string$1 = (params) => {
    const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
    return new RegExp(`^${regex}$`);
};
const bigint = /^\d+n?$/;
const integer = /^\d+$/;
const number$1 = /^-?\d+(?:\.\d+)?/i;
const boolean$1 = /true|false/i;
const _null$2 = /null/i;
const _undefined = /undefined/i;
const lowercase = /^[^A-Z]*$/;
const uppercase = /^[^a-z]*$/;

const $ZodCheck =  $constructor("$ZodCheck", (inst, def) => {
    var _a;
    inst._zod ?? (inst._zod = {});
    inst._zod.def = def;
    (_a = inst._zod).onattach ?? (_a.onattach = []);
});
const numericOriginMap = {
    number: "number",
    bigint: "bigint",
    object: "date",
};
const $ZodCheckLessThan =  $constructor("$ZodCheckLessThan", (inst, def) => {
    $ZodCheck.init(inst, def);
    const origin = numericOriginMap[typeof def.value];
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
        if (def.value < curr) {
            if (def.inclusive)
                bag.maximum = def.value;
            else
                bag.exclusiveMaximum = def.value;
        }
    });
    inst._zod.check = (payload) => {
        if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
            return;
        }
        payload.issues.push({
            origin,
            code: "too_big",
            maximum: def.value,
            input: payload.value,
            inclusive: def.inclusive,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckGreaterThan =  $constructor("$ZodCheckGreaterThan", (inst, def) => {
    $ZodCheck.init(inst, def);
    const origin = numericOriginMap[typeof def.value];
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
        if (def.value > curr) {
            if (def.inclusive)
                bag.minimum = def.value;
            else
                bag.exclusiveMinimum = def.value;
        }
    });
    inst._zod.check = (payload) => {
        if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
            return;
        }
        payload.issues.push({
            origin,
            code: "too_small",
            minimum: def.value,
            input: payload.value,
            inclusive: def.inclusive,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckMultipleOf =
 $constructor("$ZodCheckMultipleOf", (inst, def) => {
    $ZodCheck.init(inst, def);
    inst._zod.onattach.push((inst) => {
        var _a;
        (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
    });
    inst._zod.check = (payload) => {
        if (typeof payload.value !== typeof def.value)
            throw new Error("Cannot mix number and bigint in multiple_of check.");
        const isMultiple = typeof payload.value === "bigint"
            ? payload.value % def.value === BigInt(0)
            : floatSafeRemainder(payload.value, def.value) === 0;
        if (isMultiple)
            return;
        payload.issues.push({
            origin: typeof payload.value,
            code: "not_multiple_of",
            divisor: def.value,
            input: payload.value,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckNumberFormat =  $constructor("$ZodCheckNumberFormat", (inst, def) => {
    $ZodCheck.init(inst, def);
    def.format = def.format || "float64";
    const isInt = def.format?.includes("int");
    const origin = isInt ? "int" : "number";
    const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        bag.format = def.format;
        bag.minimum = minimum;
        bag.maximum = maximum;
        if (isInt)
            bag.pattern = integer;
    });
    inst._zod.check = (payload) => {
        const input = payload.value;
        if (isInt) {
            if (!Number.isInteger(input)) {
                payload.issues.push({
                    expected: origin,
                    format: def.format,
                    code: "invalid_type",
                    input,
                    inst,
                });
                return;
            }
            if (!Number.isSafeInteger(input)) {
                if (input > 0) {
                    payload.issues.push({
                        input,
                        code: "too_big",
                        maximum: Number.MAX_SAFE_INTEGER,
                        note: "Integers must be within the safe integer range.",
                        inst,
                        origin,
                        continue: !def.abort,
                    });
                }
                else {
                    payload.issues.push({
                        input,
                        code: "too_small",
                        minimum: Number.MIN_SAFE_INTEGER,
                        note: "Integers must be within the safe integer range.",
                        inst,
                        origin,
                        continue: !def.abort,
                    });
                }
                return;
            }
        }
        if (input < minimum) {
            payload.issues.push({
                origin: "number",
                input,
                code: "too_small",
                minimum,
                inclusive: true,
                inst,
                continue: !def.abort,
            });
        }
        if (input > maximum) {
            payload.issues.push({
                origin: "number",
                input,
                code: "too_big",
                maximum,
                inst,
            });
        }
    };
});
const $ZodCheckBigIntFormat =  $constructor("$ZodCheckBigIntFormat", (inst, def) => {
    $ZodCheck.init(inst, def);
    const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format];
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        bag.format = def.format;
        bag.minimum = minimum;
        bag.maximum = maximum;
    });
    inst._zod.check = (payload) => {
        const input = payload.value;
        if (input < minimum) {
            payload.issues.push({
                origin: "bigint",
                input,
                code: "too_small",
                minimum: minimum,
                inclusive: true,
                inst,
                continue: !def.abort,
            });
        }
        if (input > maximum) {
            payload.issues.push({
                origin: "bigint",
                input,
                code: "too_big",
                maximum,
                inst,
            });
        }
    };
});
const $ZodCheckMaxSize =  $constructor("$ZodCheckMaxSize", (inst, def) => {
    var _a;
    $ZodCheck.init(inst, def);
    (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.size !== undefined;
    });
    inst._zod.onattach.push((inst) => {
        const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);
        if (def.maximum < curr)
            inst._zod.bag.maximum = def.maximum;
    });
    inst._zod.check = (payload) => {
        const input = payload.value;
        const size = input.size;
        if (size <= def.maximum)
            return;
        payload.issues.push({
            origin: getSizableOrigin(input),
            code: "too_big",
            maximum: def.maximum,
            input,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckMinSize =  $constructor("$ZodCheckMinSize", (inst, def) => {
    var _a;
    $ZodCheck.init(inst, def);
    (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.size !== undefined;
    });
    inst._zod.onattach.push((inst) => {
        const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);
        if (def.minimum > curr)
            inst._zod.bag.minimum = def.minimum;
    });
    inst._zod.check = (payload) => {
        const input = payload.value;
        const size = input.size;
        if (size >= def.minimum)
            return;
        payload.issues.push({
            origin: getSizableOrigin(input),
            code: "too_small",
            minimum: def.minimum,
            input,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckSizeEquals =  $constructor("$ZodCheckSizeEquals", (inst, def) => {
    var _a;
    $ZodCheck.init(inst, def);
    (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.size !== undefined;
    });
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        bag.minimum = def.size;
        bag.maximum = def.size;
        bag.size = def.size;
    });
    inst._zod.check = (payload) => {
        const input = payload.value;
        const size = input.size;
        if (size === def.size)
            return;
        const tooBig = size > def.size;
        payload.issues.push({
            origin: getSizableOrigin(input),
            ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }),
            inclusive: true,
            exact: true,
            input: payload.value,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckMaxLength =  $constructor("$ZodCheckMaxLength", (inst, def) => {
    var _a;
    $ZodCheck.init(inst, def);
    (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.length !== undefined;
    });
    inst._zod.onattach.push((inst) => {
        const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);
        if (def.maximum < curr)
            inst._zod.bag.maximum = def.maximum;
    });
    inst._zod.check = (payload) => {
        const input = payload.value;
        const length = input.length;
        if (length <= def.maximum)
            return;
        const origin = getLengthableOrigin(input);
        payload.issues.push({
            origin,
            code: "too_big",
            maximum: def.maximum,
            inclusive: true,
            input,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckMinLength =  $constructor("$ZodCheckMinLength", (inst, def) => {
    var _a;
    $ZodCheck.init(inst, def);
    (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.length !== undefined;
    });
    inst._zod.onattach.push((inst) => {
        const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);
        if (def.minimum > curr)
            inst._zod.bag.minimum = def.minimum;
    });
    inst._zod.check = (payload) => {
        const input = payload.value;
        const length = input.length;
        if (length >= def.minimum)
            return;
        const origin = getLengthableOrigin(input);
        payload.issues.push({
            origin,
            code: "too_small",
            minimum: def.minimum,
            inclusive: true,
            input,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckLengthEquals =  $constructor("$ZodCheckLengthEquals", (inst, def) => {
    var _a;
    $ZodCheck.init(inst, def);
    (_a = inst._zod.def).when ?? (_a.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.length !== undefined;
    });
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        bag.minimum = def.length;
        bag.maximum = def.length;
        bag.length = def.length;
    });
    inst._zod.check = (payload) => {
        const input = payload.value;
        const length = input.length;
        if (length === def.length)
            return;
        const origin = getLengthableOrigin(input);
        const tooBig = length > def.length;
        payload.issues.push({
            origin,
            ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }),
            inclusive: true,
            exact: true,
            input: payload.value,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckStringFormat =  $constructor("$ZodCheckStringFormat", (inst, def) => {
    var _a, _b;
    $ZodCheck.init(inst, def);
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        bag.format = def.format;
        if (def.pattern) {
            bag.patterns ?? (bag.patterns = new Set());
            bag.patterns.add(def.pattern);
        }
    });
    if (def.pattern)
        (_a = inst._zod).check ?? (_a.check = (payload) => {
            def.pattern.lastIndex = 0;
            if (def.pattern.test(payload.value))
                return;
            payload.issues.push({
                origin: "string",
                code: "invalid_format",
                format: def.format,
                input: payload.value,
                ...(def.pattern ? { pattern: def.pattern.toString() } : {}),
                inst,
                continue: !def.abort,
            });
        });
    else
        (_b = inst._zod).check ?? (_b.check = () => { });
});
const $ZodCheckRegex =  $constructor("$ZodCheckRegex", (inst, def) => {
    $ZodCheckStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
        def.pattern.lastIndex = 0;
        if (def.pattern.test(payload.value))
            return;
        payload.issues.push({
            origin: "string",
            code: "invalid_format",
            format: "regex",
            input: payload.value,
            pattern: def.pattern.toString(),
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckLowerCase =  $constructor("$ZodCheckLowerCase", (inst, def) => {
    def.pattern ?? (def.pattern = lowercase);
    $ZodCheckStringFormat.init(inst, def);
});
const $ZodCheckUpperCase =  $constructor("$ZodCheckUpperCase", (inst, def) => {
    def.pattern ?? (def.pattern = uppercase);
    $ZodCheckStringFormat.init(inst, def);
});
const $ZodCheckIncludes =  $constructor("$ZodCheckIncludes", (inst, def) => {
    $ZodCheck.init(inst, def);
    const escapedRegex = escapeRegex(def.includes);
    const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
    def.pattern = pattern;
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        bag.patterns ?? (bag.patterns = new Set());
        bag.patterns.add(pattern);
    });
    inst._zod.check = (payload) => {
        if (payload.value.includes(def.includes, def.position))
            return;
        payload.issues.push({
            origin: "string",
            code: "invalid_format",
            format: "includes",
            includes: def.includes,
            input: payload.value,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckStartsWith =  $constructor("$ZodCheckStartsWith", (inst, def) => {
    $ZodCheck.init(inst, def);
    const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
    def.pattern ?? (def.pattern = pattern);
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        bag.patterns ?? (bag.patterns = new Set());
        bag.patterns.add(pattern);
    });
    inst._zod.check = (payload) => {
        if (payload.value.startsWith(def.prefix))
            return;
        payload.issues.push({
            origin: "string",
            code: "invalid_format",
            format: "starts_with",
            prefix: def.prefix,
            input: payload.value,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCheckEndsWith =  $constructor("$ZodCheckEndsWith", (inst, def) => {
    $ZodCheck.init(inst, def);
    const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
    def.pattern ?? (def.pattern = pattern);
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        bag.patterns ?? (bag.patterns = new Set());
        bag.patterns.add(pattern);
    });
    inst._zod.check = (payload) => {
        if (payload.value.endsWith(def.suffix))
            return;
        payload.issues.push({
            origin: "string",
            code: "invalid_format",
            format: "ends_with",
            suffix: def.suffix,
            input: payload.value,
            inst,
            continue: !def.abort,
        });
    };
});
function handleCheckPropertyResult(result, payload, property) {
    if (result.issues.length) {
        payload.issues.push(...prefixIssues(property, result.issues));
    }
}
$constructor("$ZodCheckProperty", (inst, def) => {
    $ZodCheck.init(inst, def);
    inst._zod.check = (payload) => {
        const result = def.schema._zod.run({
            value: payload.value[def.property],
            issues: [],
        }, {});
        if (result instanceof Promise) {
            return result.then((result) => handleCheckPropertyResult(result, payload, def.property));
        }
        handleCheckPropertyResult(result, payload, def.property);
        return;
    };
});
const $ZodCheckMimeType =  $constructor("$ZodCheckMimeType", (inst, def) => {
    $ZodCheck.init(inst, def);
    const mimeSet = new Set(def.mime);
    inst._zod.onattach.push((inst) => {
        inst._zod.bag.mime = def.mime;
    });
    inst._zod.check = (payload) => {
        if (mimeSet.has(payload.value.type))
            return;
        payload.issues.push({
            code: "invalid_value",
            values: def.mime,
            input: payload.value.type,
            inst,
        });
    };
});
const $ZodCheckOverwrite =  $constructor("$ZodCheckOverwrite", (inst, def) => {
    $ZodCheck.init(inst, def);
    inst._zod.check = (payload) => {
        payload.value = def.tx(payload.value);
    };
});

class Doc {
    constructor(args = []) {
        this.content = [];
        this.indent = 0;
        if (this)
            this.args = args;
    }
    indented(fn) {
        this.indent += 1;
        fn(this);
        this.indent -= 1;
    }
    write(arg) {
        if (typeof arg === "function") {
            arg(this, { execution: "sync" });
            arg(this, { execution: "async" });
            return;
        }
        const content = arg;
        const lines = content.split("\n").filter((x) => x);
        const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
        const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
        for (const line of dedented) {
            this.content.push(line);
        }
    }
    compile() {
        const F = Function;
        const args = this?.args;
        const content = this?.content ?? [``];
        const lines = [...content.map((x) => `  ${x}`)];
        return new F(...args, lines.join("\n"));
    }
}

const version$1 = {
    major: 4,
    minor: 0,
    patch: 0,
};

const $ZodType =  $constructor("$ZodType", (inst, def) => {
    var _a;
    inst ?? (inst = {});
    inst._zod.def = def;
    inst._zod.bag = inst._zod.bag || {};
    inst._zod.version = version$1;
    const checks = [...(inst._zod.def.checks ?? [])];
    if (inst._zod.traits.has("$ZodCheck")) {
        checks.unshift(inst);
    }
    for (const ch of checks) {
        for (const fn of ch._zod.onattach) {
            fn(inst);
        }
    }
    if (checks.length === 0) {
        (_a = inst._zod).deferred ?? (_a.deferred = []);
        inst._zod.deferred?.push(() => {
            inst._zod.run = inst._zod.parse;
        });
    }
    else {
        const runChecks = (payload, checks, ctx) => {
            let isAborted = aborted(payload);
            let asyncResult;
            for (const ch of checks) {
                if (ch._zod.def.when) {
                    const shouldRun = ch._zod.def.when(payload);
                    if (!shouldRun)
                        continue;
                }
                else if (isAborted) {
                    continue;
                }
                const currLen = payload.issues.length;
                const _ = ch._zod.check(payload);
                if (_ instanceof Promise && ctx?.async === false) {
                    throw new $ZodAsyncError();
                }
                if (asyncResult || _ instanceof Promise) {
                    asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
                        await _;
                        const nextLen = payload.issues.length;
                        if (nextLen === currLen)
                            return;
                        if (!isAborted)
                            isAborted = aborted(payload, currLen);
                    });
                }
                else {
                    const nextLen = payload.issues.length;
                    if (nextLen === currLen)
                        continue;
                    if (!isAborted)
                        isAborted = aborted(payload, currLen);
                }
            }
            if (asyncResult) {
                return asyncResult.then(() => {
                    return payload;
                });
            }
            return payload;
        };
        inst._zod.run = (payload, ctx) => {
            const result = inst._zod.parse(payload, ctx);
            if (result instanceof Promise) {
                if (ctx.async === false)
                    throw new $ZodAsyncError();
                return result.then((result) => runChecks(result, checks, ctx));
            }
            return runChecks(result, checks, ctx);
        };
    }
    inst["~standard"] = {
        validate: (value) => {
            try {
                const r = safeParse$2(inst, value);
                return r.success ? { value: r.data } : { issues: r.error?.issues };
            }
            catch (_) {
                return safeParseAsync$2(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));
            }
        },
        vendor: "zod",
        version: 1,
    };
});
const $ZodString =  $constructor("$ZodString", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string$1(inst._zod.bag);
    inst._zod.parse = (payload, _) => {
        if (def.coerce)
            try {
                payload.value = String(payload.value);
            }
            catch (_) { }
        if (typeof payload.value === "string")
            return payload;
        payload.issues.push({
            expected: "string",
            code: "invalid_type",
            input: payload.value,
            inst,
        });
        return payload;
    };
});
const $ZodStringFormat =  $constructor("$ZodStringFormat", (inst, def) => {
    $ZodCheckStringFormat.init(inst, def);
    $ZodString.init(inst, def);
});
const $ZodGUID =  $constructor("$ZodGUID", (inst, def) => {
    def.pattern ?? (def.pattern = guid);
    $ZodStringFormat.init(inst, def);
});
const $ZodUUID =  $constructor("$ZodUUID", (inst, def) => {
    if (def.version) {
        const versionMap = {
            v1: 1,
            v2: 2,
            v3: 3,
            v4: 4,
            v5: 5,
            v6: 6,
            v7: 7,
            v8: 8,
        };
        const v = versionMap[def.version];
        if (v === undefined)
            throw new Error(`Invalid UUID version: "${def.version}"`);
        def.pattern ?? (def.pattern = uuid(v));
    }
    else
        def.pattern ?? (def.pattern = uuid());
    $ZodStringFormat.init(inst, def);
});
const $ZodEmail =  $constructor("$ZodEmail", (inst, def) => {
    def.pattern ?? (def.pattern = email);
    $ZodStringFormat.init(inst, def);
});
const $ZodURL =  $constructor("$ZodURL", (inst, def) => {
    $ZodStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
        try {
            const orig = payload.value;
            const url = new URL(orig);
            const href = url.href;
            if (def.hostname) {
                def.hostname.lastIndex = 0;
                if (!def.hostname.test(url.hostname)) {
                    payload.issues.push({
                        code: "invalid_format",
                        format: "url",
                        note: "Invalid hostname",
                        pattern: hostname.source,
                        input: payload.value,
                        inst,
                        continue: !def.abort,
                    });
                }
            }
            if (def.protocol) {
                def.protocol.lastIndex = 0;
                if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
                    payload.issues.push({
                        code: "invalid_format",
                        format: "url",
                        note: "Invalid protocol",
                        pattern: def.protocol.source,
                        input: payload.value,
                        inst,
                        continue: !def.abort,
                    });
                }
            }
            if (!orig.endsWith("/") && href.endsWith("/")) {
                payload.value = href.slice(0, -1);
            }
            else {
                payload.value = href;
            }
            return;
        }
        catch (_) {
            payload.issues.push({
                code: "invalid_format",
                format: "url",
                input: payload.value,
                inst,
                continue: !def.abort,
            });
        }
    };
});
const $ZodEmoji =  $constructor("$ZodEmoji", (inst, def) => {
    def.pattern ?? (def.pattern = emoji());
    $ZodStringFormat.init(inst, def);
});
const $ZodNanoID =  $constructor("$ZodNanoID", (inst, def) => {
    def.pattern ?? (def.pattern = nanoid);
    $ZodStringFormat.init(inst, def);
});
const $ZodCUID =  $constructor("$ZodCUID", (inst, def) => {
    def.pattern ?? (def.pattern = cuid);
    $ZodStringFormat.init(inst, def);
});
const $ZodCUID2 =  $constructor("$ZodCUID2", (inst, def) => {
    def.pattern ?? (def.pattern = cuid2);
    $ZodStringFormat.init(inst, def);
});
const $ZodULID =  $constructor("$ZodULID", (inst, def) => {
    def.pattern ?? (def.pattern = ulid);
    $ZodStringFormat.init(inst, def);
});
const $ZodXID =  $constructor("$ZodXID", (inst, def) => {
    def.pattern ?? (def.pattern = xid);
    $ZodStringFormat.init(inst, def);
});
const $ZodKSUID =  $constructor("$ZodKSUID", (inst, def) => {
    def.pattern ?? (def.pattern = ksuid);
    $ZodStringFormat.init(inst, def);
});
const $ZodISODateTime =  $constructor("$ZodISODateTime", (inst, def) => {
    def.pattern ?? (def.pattern = datetime$1(def));
    $ZodStringFormat.init(inst, def);
});
const $ZodISODate =  $constructor("$ZodISODate", (inst, def) => {
    def.pattern ?? (def.pattern = date$1);
    $ZodStringFormat.init(inst, def);
});
const $ZodISOTime =  $constructor("$ZodISOTime", (inst, def) => {
    def.pattern ?? (def.pattern = time$1(def));
    $ZodStringFormat.init(inst, def);
});
const $ZodISODuration =  $constructor("$ZodISODuration", (inst, def) => {
    def.pattern ?? (def.pattern = duration$1);
    $ZodStringFormat.init(inst, def);
});
const $ZodIPv4 =  $constructor("$ZodIPv4", (inst, def) => {
    def.pattern ?? (def.pattern = ipv4$1);
    $ZodStringFormat.init(inst, def);
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        bag.format = `ipv4`;
    });
});
const $ZodIPv6 =  $constructor("$ZodIPv6", (inst, def) => {
    def.pattern ?? (def.pattern = ipv6$1);
    $ZodStringFormat.init(inst, def);
    inst._zod.onattach.push((inst) => {
        const bag = inst._zod.bag;
        bag.format = `ipv6`;
    });
    inst._zod.check = (payload) => {
        try {
            new URL(`http://[${payload.value}]`);
        }
        catch {
            payload.issues.push({
                code: "invalid_format",
                format: "ipv6",
                input: payload.value,
                inst,
                continue: !def.abort,
            });
        }
    };
});
const $ZodCIDRv4 =  $constructor("$ZodCIDRv4", (inst, def) => {
    def.pattern ?? (def.pattern = cidrv4);
    $ZodStringFormat.init(inst, def);
});
const $ZodCIDRv6 =  $constructor("$ZodCIDRv6", (inst, def) => {
    def.pattern ?? (def.pattern = cidrv6);
    $ZodStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
        const [address, prefix] = payload.value.split("/");
        try {
            if (!prefix)
                throw new Error();
            const prefixNum = Number(prefix);
            if (`${prefixNum}` !== prefix)
                throw new Error();
            if (prefixNum < 0 || prefixNum > 128)
                throw new Error();
            new URL(`http://[${address}]`);
        }
        catch {
            payload.issues.push({
                code: "invalid_format",
                format: "cidrv6",
                input: payload.value,
                inst,
                continue: !def.abort,
            });
        }
    };
});
function isValidBase64(data) {
    if (data === "")
        return true;
    if (data.length % 4 !== 0)
        return false;
    try {
        atob(data);
        return true;
    }
    catch {
        return false;
    }
}
const $ZodBase64 =  $constructor("$ZodBase64", (inst, def) => {
    def.pattern ?? (def.pattern = base64$1);
    $ZodStringFormat.init(inst, def);
    inst._zod.onattach.push((inst) => {
        inst._zod.bag.contentEncoding = "base64";
    });
    inst._zod.check = (payload) => {
        if (isValidBase64(payload.value))
            return;
        payload.issues.push({
            code: "invalid_format",
            format: "base64",
            input: payload.value,
            inst,
            continue: !def.abort,
        });
    };
});
function isValidBase64URL(data) {
    if (!base64url.test(data))
        return false;
    const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/"));
    const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
    return isValidBase64(padded);
}
const $ZodBase64URL =  $constructor("$ZodBase64URL", (inst, def) => {
    def.pattern ?? (def.pattern = base64url);
    $ZodStringFormat.init(inst, def);
    inst._zod.onattach.push((inst) => {
        inst._zod.bag.contentEncoding = "base64url";
    });
    inst._zod.check = (payload) => {
        if (isValidBase64URL(payload.value))
            return;
        payload.issues.push({
            code: "invalid_format",
            format: "base64url",
            input: payload.value,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodE164 =  $constructor("$ZodE164", (inst, def) => {
    def.pattern ?? (def.pattern = e164);
    $ZodStringFormat.init(inst, def);
});
function isValidJWT(token, algorithm = null) {
    try {
        const tokensParts = token.split(".");
        if (tokensParts.length !== 3)
            return false;
        const [header] = tokensParts;
        if (!header)
            return false;
        const parsedHeader = JSON.parse(atob(header));
        if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
            return false;
        if (!parsedHeader.alg)
            return false;
        if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
            return false;
        return true;
    }
    catch {
        return false;
    }
}
const $ZodJWT =  $constructor("$ZodJWT", (inst, def) => {
    $ZodStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
        if (isValidJWT(payload.value, def.alg))
            return;
        payload.issues.push({
            code: "invalid_format",
            format: "jwt",
            input: payload.value,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodCustomStringFormat =  $constructor("$ZodCustomStringFormat", (inst, def) => {
    $ZodStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
        if (def.fn(payload.value))
            return;
        payload.issues.push({
            code: "invalid_format",
            format: def.format,
            input: payload.value,
            inst,
            continue: !def.abort,
        });
    };
});
const $ZodNumber =  $constructor("$ZodNumber", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
    inst._zod.parse = (payload, _ctx) => {
        if (def.coerce)
            try {
                payload.value = Number(payload.value);
            }
            catch (_) { }
        const input = payload.value;
        if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
            return payload;
        }
        const received = typeof input === "number"
            ? Number.isNaN(input)
                ? "NaN"
                : !Number.isFinite(input)
                    ? "Infinity"
                    : undefined
            : undefined;
        payload.issues.push({
            expected: "number",
            code: "invalid_type",
            input,
            inst,
            ...(received ? { received } : {}),
        });
        return payload;
    };
});
const $ZodNumberFormat =  $constructor("$ZodNumber", (inst, def) => {
    $ZodCheckNumberFormat.init(inst, def);
    $ZodNumber.init(inst, def);
});
const $ZodBoolean =  $constructor("$ZodBoolean", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = boolean$1;
    inst._zod.parse = (payload, _ctx) => {
        if (def.coerce)
            try {
                payload.value = Boolean(payload.value);
            }
            catch (_) { }
        const input = payload.value;
        if (typeof input === "boolean")
            return payload;
        payload.issues.push({
            expected: "boolean",
            code: "invalid_type",
            input,
            inst,
        });
        return payload;
    };
});
const $ZodBigInt =  $constructor("$ZodBigInt", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = bigint;
    inst._zod.parse = (payload, _ctx) => {
        if (def.coerce)
            try {
                payload.value = BigInt(payload.value);
            }
            catch (_) { }
        if (typeof payload.value === "bigint")
            return payload;
        payload.issues.push({
            expected: "bigint",
            code: "invalid_type",
            input: payload.value,
            inst,
        });
        return payload;
    };
});
const $ZodBigIntFormat =  $constructor("$ZodBigInt", (inst, def) => {
    $ZodCheckBigIntFormat.init(inst, def);
    $ZodBigInt.init(inst, def);
});
const $ZodSymbol =  $constructor("$ZodSymbol", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (typeof input === "symbol")
            return payload;
        payload.issues.push({
            expected: "symbol",
            code: "invalid_type",
            input,
            inst,
        });
        return payload;
    };
});
const $ZodUndefined =  $constructor("$ZodUndefined", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = _undefined;
    inst._zod.values = new Set([undefined]);
    inst._zod.optin = "optional";
    inst._zod.optout = "optional";
    inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (typeof input === "undefined")
            return payload;
        payload.issues.push({
            expected: "undefined",
            code: "invalid_type",
            input,
            inst,
        });
        return payload;
    };
});
const $ZodNull =  $constructor("$ZodNull", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = _null$2;
    inst._zod.values = new Set([null]);
    inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (input === null)
            return payload;
        payload.issues.push({
            expected: "null",
            code: "invalid_type",
            input,
            inst,
        });
        return payload;
    };
});
const $ZodAny =  $constructor("$ZodAny", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload) => payload;
});
const $ZodUnknown =  $constructor("$ZodUnknown", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload) => payload;
});
const $ZodNever =  $constructor("$ZodNever", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
        payload.issues.push({
            expected: "never",
            code: "invalid_type",
            input: payload.value,
            inst,
        });
        return payload;
    };
});
const $ZodVoid =  $constructor("$ZodVoid", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (typeof input === "undefined")
            return payload;
        payload.issues.push({
            expected: "void",
            code: "invalid_type",
            input,
            inst,
        });
        return payload;
    };
});
const $ZodDate =  $constructor("$ZodDate", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
        if (def.coerce) {
            try {
                payload.value = new Date(payload.value);
            }
            catch (_err) { }
        }
        const input = payload.value;
        const isDate = input instanceof Date;
        const isValidDate = isDate && !Number.isNaN(input.getTime());
        if (isValidDate)
            return payload;
        payload.issues.push({
            expected: "date",
            code: "invalid_type",
            input,
            ...(isDate ? { received: "Invalid Date" } : {}),
            inst,
        });
        return payload;
    };
});
function handleArrayResult(result, final, index) {
    if (result.issues.length) {
        final.issues.push(...prefixIssues(index, result.issues));
    }
    final.value[index] = result.value;
}
const $ZodArray =  $constructor("$ZodArray", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!Array.isArray(input)) {
            payload.issues.push({
                expected: "array",
                code: "invalid_type",
                input,
                inst,
            });
            return payload;
        }
        payload.value = Array(input.length);
        const proms = [];
        for (let i = 0; i < input.length; i++) {
            const item = input[i];
            const result = def.element._zod.run({
                value: item,
                issues: [],
            }, ctx);
            if (result instanceof Promise) {
                proms.push(result.then((result) => handleArrayResult(result, payload, i)));
            }
            else {
                handleArrayResult(result, payload, i);
            }
        }
        if (proms.length) {
            return Promise.all(proms).then(() => payload);
        }
        return payload;
    };
});
function handleObjectResult(result, final, key) {
    if (result.issues.length) {
        final.issues.push(...prefixIssues(key, result.issues));
    }
    final.value[key] = result.value;
}
function handleOptionalObjectResult(result, final, key, input) {
    if (result.issues.length) {
        if (input[key] === undefined) {
            if (key in input) {
                final.value[key] = undefined;
            }
            else {
                final.value[key] = result.value;
            }
        }
        else {
            final.issues.push(...prefixIssues(key, result.issues));
        }
    }
    else if (result.value === undefined) {
        if (key in input)
            final.value[key] = undefined;
    }
    else {
        final.value[key] = result.value;
    }
}
const $ZodObject =  $constructor("$ZodObject", (inst, def) => {
    $ZodType.init(inst, def);
    const _normalized = cached(() => {
        const keys = Object.keys(def.shape);
        for (const k of keys) {
            if (!(def.shape[k] instanceof $ZodType)) {
                throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
            }
        }
        const okeys = optionalKeys(def.shape);
        return {
            shape: def.shape,
            keys,
            keySet: new Set(keys),
            numKeys: keys.length,
            optionalKeys: new Set(okeys),
        };
    });
    defineLazy(inst._zod, "propValues", () => {
        const shape = def.shape;
        const propValues = {};
        for (const key in shape) {
            const field = shape[key]._zod;
            if (field.values) {
                propValues[key] ?? (propValues[key] = new Set());
                for (const v of field.values)
                    propValues[key].add(v);
            }
        }
        return propValues;
    });
    const generateFastpass = (shape) => {
        const doc = new Doc(["shape", "payload", "ctx"]);
        const normalized = _normalized.value;
        const parseStr = (key) => {
            const k = esc(key);
            return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
        };
        doc.write(`const input = payload.value;`);
        const ids = Object.create(null);
        let counter = 0;
        for (const key of normalized.keys) {
            ids[key] = `key_${counter++}`;
        }
        doc.write(`const newResult = {}`);
        for (const key of normalized.keys) {
            if (normalized.optionalKeys.has(key)) {
                const id = ids[key];
                doc.write(`const ${id} = ${parseStr(key)};`);
                const k = esc(key);
                doc.write(`
        if (${id}.issues.length) {
          if (input[${k}] === undefined) {
            if (${k} in input) {
              newResult[${k}] = undefined;
            }
          } else {
            payload.issues = payload.issues.concat(
              ${id}.issues.map((iss) => ({
                ...iss,
                path: iss.path ? [${k}, ...iss.path] : [${k}],
              }))
            );
          }
        } else if (${id}.value === undefined) {
          if (${k} in input) newResult[${k}] = undefined;
        } else {
          newResult[${k}] = ${id}.value;
        }
        `);
            }
            else {
                const id = ids[key];
                doc.write(`const ${id} = ${parseStr(key)};`);
                doc.write(`
          if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
          })));`);
                doc.write(`newResult[${esc(key)}] = ${id}.value`);
            }
        }
        doc.write(`payload.value = newResult;`);
        doc.write(`return payload;`);
        const fn = doc.compile();
        return (payload, ctx) => fn(shape, payload, ctx);
    };
    let fastpass;
    const isObject$1 = isObject;
    const jit = !globalConfig.jitless;
    const allowsEval$1 = allowsEval;
    const fastEnabled = jit && allowsEval$1.value;
    const catchall = def.catchall;
    let value;
    inst._zod.parse = (payload, ctx) => {
        value ?? (value = _normalized.value);
        const input = payload.value;
        if (!isObject$1(input)) {
            payload.issues.push({
                expected: "object",
                code: "invalid_type",
                input,
                inst,
            });
            return payload;
        }
        const proms = [];
        if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
            if (!fastpass)
                fastpass = generateFastpass(def.shape);
            payload = fastpass(payload, ctx);
        }
        else {
            payload.value = {};
            const shape = value.shape;
            for (const key of value.keys) {
                const el = shape[key];
                const r = el._zod.run({ value: input[key], issues: [] }, ctx);
                const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
                if (r instanceof Promise) {
                    proms.push(r.then((r) => isOptional ? handleOptionalObjectResult(r, payload, key, input) : handleObjectResult(r, payload, key)));
                }
                else if (isOptional) {
                    handleOptionalObjectResult(r, payload, key, input);
                }
                else {
                    handleObjectResult(r, payload, key);
                }
            }
        }
        if (!catchall) {
            return proms.length ? Promise.all(proms).then(() => payload) : payload;
        }
        const unrecognized = [];
        const keySet = value.keySet;
        const _catchall = catchall._zod;
        const t = _catchall.def.type;
        for (const key of Object.keys(input)) {
            if (keySet.has(key))
                continue;
            if (t === "never") {
                unrecognized.push(key);
                continue;
            }
            const r = _catchall.run({ value: input[key], issues: [] }, ctx);
            if (r instanceof Promise) {
                proms.push(r.then((r) => handleObjectResult(r, payload, key)));
            }
            else {
                handleObjectResult(r, payload, key);
            }
        }
        if (unrecognized.length) {
            payload.issues.push({
                code: "unrecognized_keys",
                keys: unrecognized,
                input,
                inst,
            });
        }
        if (!proms.length)
            return payload;
        return Promise.all(proms).then(() => {
            return payload;
        });
    };
});
function handleUnionResults(results, final, inst, ctx) {
    for (const result of results) {
        if (result.issues.length === 0) {
            final.value = result.value;
            return final;
        }
    }
    final.issues.push({
        code: "invalid_union",
        input: final.value,
        inst,
        errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config$3()))),
    });
    return final;
}
const $ZodUnion =  $constructor("$ZodUnion", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
    defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
    defineLazy(inst._zod, "values", () => {
        if (def.options.every((o) => o._zod.values)) {
            return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
        }
        return undefined;
    });
    defineLazy(inst._zod, "pattern", () => {
        if (def.options.every((o) => o._zod.pattern)) {
            const patterns = def.options.map((o) => o._zod.pattern);
            return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
        }
        return undefined;
    });
    inst._zod.parse = (payload, ctx) => {
        let async = false;
        const results = [];
        for (const option of def.options) {
            const result = option._zod.run({
                value: payload.value,
                issues: [],
            }, ctx);
            if (result instanceof Promise) {
                results.push(result);
                async = true;
            }
            else {
                if (result.issues.length === 0)
                    return result;
                results.push(result);
            }
        }
        if (!async)
            return handleUnionResults(results, payload, inst, ctx);
        return Promise.all(results).then((results) => {
            return handleUnionResults(results, payload, inst, ctx);
        });
    };
});
const $ZodDiscriminatedUnion =
$constructor("$ZodDiscriminatedUnion", (inst, def) => {
    $ZodUnion.init(inst, def);
    const _super = inst._zod.parse;
    defineLazy(inst._zod, "propValues", () => {
        const propValues = {};
        for (const option of def.options) {
            const pv = option._zod.propValues;
            if (!pv || Object.keys(pv).length === 0)
                throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
            for (const [k, v] of Object.entries(pv)) {
                if (!propValues[k])
                    propValues[k] = new Set();
                for (const val of v) {
                    propValues[k].add(val);
                }
            }
        }
        return propValues;
    });
    const disc = cached(() => {
        const opts = def.options;
        const map = new Map();
        for (const o of opts) {
            const values = o._zod.propValues[def.discriminator];
            if (!values || values.size === 0)
                throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
            for (const v of values) {
                if (map.has(v)) {
                    throw new Error(`Duplicate discriminator value "${String(v)}"`);
                }
                map.set(v, o);
            }
        }
        return map;
    });
    inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!isObject(input)) {
            payload.issues.push({
                code: "invalid_type",
                expected: "object",
                input,
                inst,
            });
            return payload;
        }
        const opt = disc.value.get(input?.[def.discriminator]);
        if (opt) {
            return opt._zod.run(payload, ctx);
        }
        if (def.unionFallback) {
            return _super(payload, ctx);
        }
        payload.issues.push({
            code: "invalid_union",
            errors: [],
            note: "No matching discriminator",
            input,
            path: [def.discriminator],
            inst,
        });
        return payload;
    };
});
const $ZodIntersection =  $constructor("$ZodIntersection", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        const left = def.left._zod.run({ value: input, issues: [] }, ctx);
        const right = def.right._zod.run({ value: input, issues: [] }, ctx);
        const async = left instanceof Promise || right instanceof Promise;
        if (async) {
            return Promise.all([left, right]).then(([left, right]) => {
                return handleIntersectionResults(payload, left, right);
            });
        }
        return handleIntersectionResults(payload, left, right);
    };
});
function mergeValues(a, b) {
    if (a === b) {
        return { valid: true, data: a };
    }
    if (a instanceof Date && b instanceof Date && +a === +b) {
        return { valid: true, data: a };
    }
    if (isPlainObject$1(a) && isPlainObject$1(b)) {
        const bKeys = Object.keys(b);
        const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
        const newObj = { ...a, ...b };
        for (const key of sharedKeys) {
            const sharedValue = mergeValues(a[key], b[key]);
            if (!sharedValue.valid) {
                return {
                    valid: false,
                    mergeErrorPath: [key, ...sharedValue.mergeErrorPath],
                };
            }
            newObj[key] = sharedValue.data;
        }
        return { valid: true, data: newObj };
    }
    if (Array.isArray(a) && Array.isArray(b)) {
        if (a.length !== b.length) {
            return { valid: false, mergeErrorPath: [] };
        }
        const newArray = [];
        for (let index = 0; index < a.length; index++) {
            const itemA = a[index];
            const itemB = b[index];
            const sharedValue = mergeValues(itemA, itemB);
            if (!sharedValue.valid) {
                return {
                    valid: false,
                    mergeErrorPath: [index, ...sharedValue.mergeErrorPath],
                };
            }
            newArray.push(sharedValue.data);
        }
        return { valid: true, data: newArray };
    }
    return { valid: false, mergeErrorPath: [] };
}
function handleIntersectionResults(result, left, right) {
    if (left.issues.length) {
        result.issues.push(...left.issues);
    }
    if (right.issues.length) {
        result.issues.push(...right.issues);
    }
    if (aborted(result))
        return result;
    const merged = mergeValues(left.value, right.value);
    if (!merged.valid) {
        throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
    }
    result.value = merged.data;
    return result;
}
const $ZodTuple =  $constructor("$ZodTuple", (inst, def) => {
    $ZodType.init(inst, def);
    const items = def.items;
    const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional");
    inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!Array.isArray(input)) {
            payload.issues.push({
                input,
                inst,
                expected: "tuple",
                code: "invalid_type",
            });
            return payload;
        }
        payload.value = [];
        const proms = [];
        if (!def.rest) {
            const tooBig = input.length > items.length;
            const tooSmall = input.length < optStart - 1;
            if (tooBig || tooSmall) {
                payload.issues.push({
                    input,
                    inst,
                    origin: "array",
                    ...(tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }),
                });
                return payload;
            }
        }
        let i = -1;
        for (const item of items) {
            i++;
            if (i >= input.length)
                if (i >= optStart)
                    continue;
            const result = item._zod.run({
                value: input[i],
                issues: [],
            }, ctx);
            if (result instanceof Promise) {
                proms.push(result.then((result) => handleTupleResult(result, payload, i)));
            }
            else {
                handleTupleResult(result, payload, i);
            }
        }
        if (def.rest) {
            const rest = input.slice(items.length);
            for (const el of rest) {
                i++;
                const result = def.rest._zod.run({
                    value: el,
                    issues: [],
                }, ctx);
                if (result instanceof Promise) {
                    proms.push(result.then((result) => handleTupleResult(result, payload, i)));
                }
                else {
                    handleTupleResult(result, payload, i);
                }
            }
        }
        if (proms.length)
            return Promise.all(proms).then(() => payload);
        return payload;
    };
});
function handleTupleResult(result, final, index) {
    if (result.issues.length) {
        final.issues.push(...prefixIssues(index, result.issues));
    }
    final.value[index] = result.value;
}
const $ZodRecord =  $constructor("$ZodRecord", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!isPlainObject$1(input)) {
            payload.issues.push({
                expected: "record",
                code: "invalid_type",
                input,
                inst,
            });
            return payload;
        }
        const proms = [];
        if (def.keyType._zod.values) {
            const values = def.keyType._zod.values;
            payload.value = {};
            for (const key of values) {
                if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
                    const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
                    if (result instanceof Promise) {
                        proms.push(result.then((result) => {
                            if (result.issues.length) {
                                payload.issues.push(...prefixIssues(key, result.issues));
                            }
                            payload.value[key] = result.value;
                        }));
                    }
                    else {
                        if (result.issues.length) {
                            payload.issues.push(...prefixIssues(key, result.issues));
                        }
                        payload.value[key] = result.value;
                    }
                }
            }
            let unrecognized;
            for (const key in input) {
                if (!values.has(key)) {
                    unrecognized = unrecognized ?? [];
                    unrecognized.push(key);
                }
            }
            if (unrecognized && unrecognized.length > 0) {
                payload.issues.push({
                    code: "unrecognized_keys",
                    input,
                    inst,
                    keys: unrecognized,
                });
            }
        }
        else {
            payload.value = {};
            for (const key of Reflect.ownKeys(input)) {
                if (key === "__proto__")
                    continue;
                const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
                if (keyResult instanceof Promise) {
                    throw new Error("Async schemas not supported in object keys currently");
                }
                if (keyResult.issues.length) {
                    payload.issues.push({
                        origin: "record",
                        code: "invalid_key",
                        issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config$3())),
                        input: key,
                        path: [key],
                        inst,
                    });
                    payload.value[keyResult.value] = keyResult.value;
                    continue;
                }
                const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
                if (result instanceof Promise) {
                    proms.push(result.then((result) => {
                        if (result.issues.length) {
                            payload.issues.push(...prefixIssues(key, result.issues));
                        }
                        payload.value[keyResult.value] = result.value;
                    }));
                }
                else {
                    if (result.issues.length) {
                        payload.issues.push(...prefixIssues(key, result.issues));
                    }
                    payload.value[keyResult.value] = result.value;
                }
            }
        }
        if (proms.length) {
            return Promise.all(proms).then(() => payload);
        }
        return payload;
    };
});
const $ZodMap =  $constructor("$ZodMap", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!(input instanceof Map)) {
            payload.issues.push({
                expected: "map",
                code: "invalid_type",
                input,
                inst,
            });
            return payload;
        }
        const proms = [];
        payload.value = new Map();
        for (const [key, value] of input) {
            const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
            const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);
            if (keyResult instanceof Promise || valueResult instanceof Promise) {
                proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {
                    handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
                }));
            }
            else {
                handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
            }
        }
        if (proms.length)
            return Promise.all(proms).then(() => payload);
        return payload;
    };
});
function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
    if (keyResult.issues.length) {
        if (propertyKeyTypes.has(typeof key)) {
            final.issues.push(...prefixIssues(key, keyResult.issues));
        }
        else {
            final.issues.push({
                origin: "map",
                code: "invalid_key",
                input,
                inst,
                issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config$3())),
            });
        }
    }
    if (valueResult.issues.length) {
        if (propertyKeyTypes.has(typeof key)) {
            final.issues.push(...prefixIssues(key, valueResult.issues));
        }
        else {
            final.issues.push({
                origin: "map",
                code: "invalid_element",
                input,
                inst,
                key: key,
                issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config$3())),
            });
        }
    }
    final.value.set(keyResult.value, valueResult.value);
}
const $ZodSet =  $constructor("$ZodSet", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!(input instanceof Set)) {
            payload.issues.push({
                input,
                inst,
                expected: "set",
                code: "invalid_type",
            });
            return payload;
        }
        const proms = [];
        payload.value = new Set();
        for (const item of input) {
            const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
            if (result instanceof Promise) {
                proms.push(result.then((result) => handleSetResult(result, payload)));
            }
            else
                handleSetResult(result, payload);
        }
        if (proms.length)
            return Promise.all(proms).then(() => payload);
        return payload;
    };
});
function handleSetResult(result, final) {
    if (result.issues.length) {
        final.issues.push(...result.issues);
    }
    final.value.add(result.value);
}
const $ZodEnum =  $constructor("$ZodEnum", (inst, def) => {
    $ZodType.init(inst, def);
    const values = getEnumValues(def.entries);
    inst._zod.values = new Set(values);
    inst._zod.pattern = new RegExp(`^(${values
        .filter((k) => propertyKeyTypes.has(typeof k))
        .map((o) => (typeof o === "string" ? escapeRegex(o) : o.toString()))
        .join("|")})$`);
    inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (inst._zod.values.has(input)) {
            return payload;
        }
        payload.issues.push({
            code: "invalid_value",
            values,
            input,
            inst,
        });
        return payload;
    };
});
const $ZodLiteral =  $constructor("$ZodLiteral", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.values = new Set(def.values);
    inst._zod.pattern = new RegExp(`^(${def.values
        .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)))
        .join("|")})$`);
    inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (inst._zod.values.has(input)) {
            return payload;
        }
        payload.issues.push({
            code: "invalid_value",
            values: def.values,
            input,
            inst,
        });
        return payload;
    };
});
const $ZodFile =  $constructor("$ZodFile", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (input instanceof File)
            return payload;
        payload.issues.push({
            expected: "file",
            code: "invalid_type",
            input,
            inst,
        });
        return payload;
    };
});
const $ZodTransform =  $constructor("$ZodTransform", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
        const _out = def.transform(payload.value, payload);
        if (_ctx.async) {
            const output = _out instanceof Promise ? _out : Promise.resolve(_out);
            return output.then((output) => {
                payload.value = output;
                return payload;
            });
        }
        if (_out instanceof Promise) {
            throw new $ZodAsyncError();
        }
        payload.value = _out;
        return payload;
    };
});
const $ZodOptional =  $constructor("$ZodOptional", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.optin = "optional";
    inst._zod.optout = "optional";
    defineLazy(inst._zod, "values", () => {
        return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
    });
    defineLazy(inst._zod, "pattern", () => {
        const pattern = def.innerType._zod.pattern;
        return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
    });
    inst._zod.parse = (payload, ctx) => {
        if (def.innerType._zod.optin === "optional") {
            return def.innerType._zod.run(payload, ctx);
        }
        if (payload.value === undefined) {
            return payload;
        }
        return def.innerType._zod.run(payload, ctx);
    };
});
const $ZodNullable =  $constructor("$ZodNullable", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
    defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
    defineLazy(inst._zod, "pattern", () => {
        const pattern = def.innerType._zod.pattern;
        return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined;
    });
    defineLazy(inst._zod, "values", () => {
        return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
    });
    inst._zod.parse = (payload, ctx) => {
        if (payload.value === null)
            return payload;
        return def.innerType._zod.run(payload, ctx);
    };
});
const $ZodDefault =  $constructor("$ZodDefault", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.optin = "optional";
    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
    inst._zod.parse = (payload, ctx) => {
        if (payload.value === undefined) {
            payload.value = def.defaultValue;
            return payload;
        }
        const result = def.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
            return result.then((result) => handleDefaultResult(result, def));
        }
        return handleDefaultResult(result, def);
    };
});
function handleDefaultResult(payload, def) {
    if (payload.value === undefined) {
        payload.value = def.defaultValue;
    }
    return payload;
}
const $ZodPrefault =  $constructor("$ZodPrefault", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.optin = "optional";
    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
    inst._zod.parse = (payload, ctx) => {
        if (payload.value === undefined) {
            payload.value = def.defaultValue;
        }
        return def.innerType._zod.run(payload, ctx);
    };
});
const $ZodNonOptional =  $constructor("$ZodNonOptional", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "values", () => {
        const v = def.innerType._zod.values;
        return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;
    });
    inst._zod.parse = (payload, ctx) => {
        const result = def.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
            return result.then((result) => handleNonOptionalResult(result, inst));
        }
        return handleNonOptionalResult(result, inst);
    };
});
function handleNonOptionalResult(payload, inst) {
    if (!payload.issues.length && payload.value === undefined) {
        payload.issues.push({
            code: "invalid_type",
            expected: "nonoptional",
            input: payload.value,
            inst,
        });
    }
    return payload;
}
const $ZodSuccess =  $constructor("$ZodSuccess", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
        const result = def.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
            return result.then((result) => {
                payload.value = result.issues.length === 0;
                return payload;
            });
        }
        payload.value = result.issues.length === 0;
        return payload;
    };
});
const $ZodCatch =  $constructor("$ZodCatch", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.optin = "optional";
    defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
    inst._zod.parse = (payload, ctx) => {
        const result = def.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
            return result.then((result) => {
                payload.value = result.value;
                if (result.issues.length) {
                    payload.value = def.catchValue({
                        ...payload,
                        error: {
                            issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config$3())),
                        },
                        input: payload.value,
                    });
                    payload.issues = [];
                }
                return payload;
            });
        }
        payload.value = result.value;
        if (result.issues.length) {
            payload.value = def.catchValue({
                ...payload,
                error: {
                    issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config$3())),
                },
                input: payload.value,
            });
            payload.issues = [];
        }
        return payload;
    };
});
const $ZodNaN =  $constructor("$ZodNaN", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
        if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
            payload.issues.push({
                input: payload.value,
                inst,
                expected: "nan",
                code: "invalid_type",
            });
            return payload;
        }
        return payload;
    };
});
const $ZodPipe =  $constructor("$ZodPipe", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "values", () => def.in._zod.values);
    defineLazy(inst._zod, "optin", () => def.in._zod.optin);
    defineLazy(inst._zod, "optout", () => def.out._zod.optout);
    inst._zod.parse = (payload, ctx) => {
        const left = def.in._zod.run(payload, ctx);
        if (left instanceof Promise) {
            return left.then((left) => handlePipeResult(left, def, ctx));
        }
        return handlePipeResult(left, def, ctx);
    };
});
function handlePipeResult(left, def, ctx) {
    if (aborted(left)) {
        return left;
    }
    return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);
}
const $ZodReadonly =  $constructor("$ZodReadonly", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
    defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
    defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
    inst._zod.parse = (payload, ctx) => {
        const result = def.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
            return result.then(handleReadonlyResult);
        }
        return handleReadonlyResult(result);
    };
});
function handleReadonlyResult(payload) {
    payload.value = Object.freeze(payload.value);
    return payload;
}
const $ZodTemplateLiteral =  $constructor("$ZodTemplateLiteral", (inst, def) => {
    $ZodType.init(inst, def);
    const regexParts = [];
    for (const part of def.parts) {
        if (part instanceof $ZodType) {
            if (!part._zod.pattern) {
                throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
            }
            const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
            if (!source)
                throw new Error(`Invalid template literal part: ${part._zod.traits}`);
            const start = source.startsWith("^") ? 1 : 0;
            const end = source.endsWith("$") ? source.length - 1 : source.length;
            regexParts.push(source.slice(start, end));
        }
        else if (part === null || primitiveTypes.has(typeof part)) {
            regexParts.push(escapeRegex(`${part}`));
        }
        else {
            throw new Error(`Invalid template literal part: ${part}`);
        }
    }
    inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
    inst._zod.parse = (payload, _ctx) => {
        if (typeof payload.value !== "string") {
            payload.issues.push({
                input: payload.value,
                inst,
                expected: "template_literal",
                code: "invalid_type",
            });
            return payload;
        }
        inst._zod.pattern.lastIndex = 0;
        if (!inst._zod.pattern.test(payload.value)) {
            payload.issues.push({
                input: payload.value,
                inst,
                code: "invalid_format",
                format: "template_literal",
                pattern: inst._zod.pattern.source,
            });
            return payload;
        }
        return payload;
    };
});
const $ZodPromise =  $constructor("$ZodPromise", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
        return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
    };
});
const $ZodLazy =  $constructor("$ZodLazy", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "innerType", () => def.getter());
    defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern);
    defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues);
    defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin);
    defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout);
    inst._zod.parse = (payload, ctx) => {
        const inner = inst._zod.innerType;
        return inner._zod.run(payload, ctx);
    };
});
const $ZodCustom =  $constructor("$ZodCustom", (inst, def) => {
    $ZodCheck.init(inst, def);
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _) => {
        return payload;
    };
    inst._zod.check = (payload) => {
        const input = payload.value;
        const r = def.fn(input);
        if (r instanceof Promise) {
            return r.then((r) => handleRefineResult(r, payload, input, inst));
        }
        handleRefineResult(r, payload, input, inst);
        return;
    };
});
function handleRefineResult(result, payload, input, inst) {
    if (!result) {
        const _iss = {
            code: "custom",
            input,
            inst,
            path: [...(inst._zod.def.path ?? [])],
            continue: !inst._zod.def.abort,
        };
        if (inst._zod.def.params)
            _iss.params = inst._zod.def.params;
        payload.issues.push(issue(_iss));
    }
}

class $ZodRegistry {
    constructor() {
        this._map = new Map();
        this._idmap = new Map();
    }
    add(schema, ..._meta) {
        const meta = _meta[0];
        this._map.set(schema, meta);
        if (meta && typeof meta === "object" && "id" in meta) {
            if (this._idmap.has(meta.id)) {
                throw new Error(`ID ${meta.id} already exists in the registry`);
            }
            this._idmap.set(meta.id, schema);
        }
        return this;
    }
    clear() {
        this._map = new Map();
        this._idmap = new Map();
        return this;
    }
    remove(schema) {
        const meta = this._map.get(schema);
        if (meta && typeof meta === "object" && "id" in meta) {
            this._idmap.delete(meta.id);
        }
        this._map.delete(schema);
        return this;
    }
    get(schema) {
        const p = schema._zod.parent;
        if (p) {
            const pm = { ...(this.get(p) ?? {}) };
            delete pm.id;
            return { ...pm, ...this._map.get(schema) };
        }
        return this._map.get(schema);
    }
    has(schema) {
        return this._map.has(schema);
    }
}
function registry() {
    return new $ZodRegistry();
}
const globalRegistry =  registry();

function _string(Class, params) {
    return new Class({
        type: "string",
        ...normalizeParams(params),
    });
}
function _email(Class, params) {
    return new Class({
        type: "string",
        format: "email",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _guid(Class, params) {
    return new Class({
        type: "string",
        format: "guid",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _uuid(Class, params) {
    return new Class({
        type: "string",
        format: "uuid",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _uuidv4(Class, params) {
    return new Class({
        type: "string",
        format: "uuid",
        check: "string_format",
        abort: false,
        version: "v4",
        ...normalizeParams(params),
    });
}
function _uuidv6(Class, params) {
    return new Class({
        type: "string",
        format: "uuid",
        check: "string_format",
        abort: false,
        version: "v6",
        ...normalizeParams(params),
    });
}
function _uuidv7(Class, params) {
    return new Class({
        type: "string",
        format: "uuid",
        check: "string_format",
        abort: false,
        version: "v7",
        ...normalizeParams(params),
    });
}
function _url(Class, params) {
    return new Class({
        type: "string",
        format: "url",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _emoji(Class, params) {
    return new Class({
        type: "string",
        format: "emoji",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _nanoid(Class, params) {
    return new Class({
        type: "string",
        format: "nanoid",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _cuid(Class, params) {
    return new Class({
        type: "string",
        format: "cuid",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _cuid2(Class, params) {
    return new Class({
        type: "string",
        format: "cuid2",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _ulid(Class, params) {
    return new Class({
        type: "string",
        format: "ulid",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _xid(Class, params) {
    return new Class({
        type: "string",
        format: "xid",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _ksuid(Class, params) {
    return new Class({
        type: "string",
        format: "ksuid",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _ipv4(Class, params) {
    return new Class({
        type: "string",
        format: "ipv4",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _ipv6(Class, params) {
    return new Class({
        type: "string",
        format: "ipv6",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _cidrv4(Class, params) {
    return new Class({
        type: "string",
        format: "cidrv4",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _cidrv6(Class, params) {
    return new Class({
        type: "string",
        format: "cidrv6",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _base64(Class, params) {
    return new Class({
        type: "string",
        format: "base64",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _base64url(Class, params) {
    return new Class({
        type: "string",
        format: "base64url",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _e164(Class, params) {
    return new Class({
        type: "string",
        format: "e164",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _jwt(Class, params) {
    return new Class({
        type: "string",
        format: "jwt",
        check: "string_format",
        abort: false,
        ...normalizeParams(params),
    });
}
function _isoDateTime(Class, params) {
    return new Class({
        type: "string",
        format: "datetime",
        check: "string_format",
        offset: false,
        local: false,
        precision: null,
        ...normalizeParams(params),
    });
}
function _isoDate(Class, params) {
    return new Class({
        type: "string",
        format: "date",
        check: "string_format",
        ...normalizeParams(params),
    });
}
function _isoTime(Class, params) {
    return new Class({
        type: "string",
        format: "time",
        check: "string_format",
        precision: null,
        ...normalizeParams(params),
    });
}
function _isoDuration(Class, params) {
    return new Class({
        type: "string",
        format: "duration",
        check: "string_format",
        ...normalizeParams(params),
    });
}
function _number(Class, params) {
    return new Class({
        type: "number",
        checks: [],
        ...normalizeParams(params),
    });
}
function _int(Class, params) {
    return new Class({
        type: "number",
        check: "number_format",
        abort: false,
        format: "safeint",
        ...normalizeParams(params),
    });
}
function _boolean(Class, params) {
    return new Class({
        type: "boolean",
        ...normalizeParams(params),
    });
}
function _null$1(Class, params) {
    return new Class({
        type: "null",
        ...normalizeParams(params),
    });
}
function _unknown(Class) {
    return new Class({
        type: "unknown",
    });
}
function _never(Class, params) {
    return new Class({
        type: "never",
        ...normalizeParams(params),
    });
}
function _lt(value, params) {
    return new $ZodCheckLessThan({
        check: "less_than",
        ...normalizeParams(params),
        value,
        inclusive: false,
    });
}
function _lte(value, params) {
    return new $ZodCheckLessThan({
        check: "less_than",
        ...normalizeParams(params),
        value,
        inclusive: true,
    });
}
function _gt(value, params) {
    return new $ZodCheckGreaterThan({
        check: "greater_than",
        ...normalizeParams(params),
        value,
        inclusive: false,
    });
}
function _gte(value, params) {
    return new $ZodCheckGreaterThan({
        check: "greater_than",
        ...normalizeParams(params),
        value,
        inclusive: true,
    });
}
function _multipleOf(value, params) {
    return new $ZodCheckMultipleOf({
        check: "multiple_of",
        ...normalizeParams(params),
        value,
    });
}
function _maxSize(maximum, params) {
    return new $ZodCheckMaxSize({
        check: "max_size",
        ...normalizeParams(params),
        maximum,
    });
}
function _minSize(minimum, params) {
    return new $ZodCheckMinSize({
        check: "min_size",
        ...normalizeParams(params),
        minimum,
    });
}
function _size(size, params) {
    return new $ZodCheckSizeEquals({
        check: "size_equals",
        ...normalizeParams(params),
        size,
    });
}
function _maxLength(maximum, params) {
    const ch = new $ZodCheckMaxLength({
        check: "max_length",
        ...normalizeParams(params),
        maximum,
    });
    return ch;
}
function _minLength(minimum, params) {
    return new $ZodCheckMinLength({
        check: "min_length",
        ...normalizeParams(params),
        minimum,
    });
}
function _length(length, params) {
    return new $ZodCheckLengthEquals({
        check: "length_equals",
        ...normalizeParams(params),
        length,
    });
}
function _regex(pattern, params) {
    return new $ZodCheckRegex({
        check: "string_format",
        format: "regex",
        ...normalizeParams(params),
        pattern,
    });
}
function _lowercase(params) {
    return new $ZodCheckLowerCase({
        check: "string_format",
        format: "lowercase",
        ...normalizeParams(params),
    });
}
function _uppercase(params) {
    return new $ZodCheckUpperCase({
        check: "string_format",
        format: "uppercase",
        ...normalizeParams(params),
    });
}
function _includes(includes, params) {
    return new $ZodCheckIncludes({
        check: "string_format",
        format: "includes",
        ...normalizeParams(params),
        includes,
    });
}
function _startsWith(prefix, params) {
    return new $ZodCheckStartsWith({
        check: "string_format",
        format: "starts_with",
        ...normalizeParams(params),
        prefix,
    });
}
function _endsWith(suffix, params) {
    return new $ZodCheckEndsWith({
        check: "string_format",
        format: "ends_with",
        ...normalizeParams(params),
        suffix,
    });
}
function _mime(types, params) {
    return new $ZodCheckMimeType({
        check: "mime_type",
        mime: types,
        ...normalizeParams(params),
    });
}
function _overwrite(tx) {
    return new $ZodCheckOverwrite({
        check: "overwrite",
        tx,
    });
}
function _normalize(form) {
    return _overwrite((input) => input.normalize(form));
}
function _trim() {
    return _overwrite((input) => input.trim());
}
function _toLowerCase() {
    return _overwrite((input) => input.toLowerCase());
}
function _toUpperCase() {
    return _overwrite((input) => input.toUpperCase());
}
function _array(Class, element, params) {
    return new Class({
        type: "array",
        element,
        ...normalizeParams(params),
    });
}
function _custom(Class, fn, _params) {
    const norm = normalizeParams(_params);
    norm.abort ?? (norm.abort = true);
    const schema = new Class({
        type: "custom",
        check: "custom",
        fn: fn,
        ...norm,
    });
    return schema;
}
function _refine(Class, fn, _params) {
    const schema = new Class({
        type: "custom",
        check: "custom",
        fn: fn,
        ...normalizeParams(_params),
    });
    return schema;
}

class JSONSchemaGenerator {
    constructor(params) {
        this.counter = 0;
        this.metadataRegistry = params?.metadata ?? globalRegistry;
        this.target = params?.target ?? "draft-2020-12";
        this.unrepresentable = params?.unrepresentable ?? "throw";
        this.override = params?.override ?? (() => { });
        this.io = params?.io ?? "output";
        this.seen = new Map();
    }
    process(schema, _params = { path: [], schemaPath: [] }) {
        var _a;
        const def = schema._zod.def;
        const formatMap = {
            guid: "uuid",
            url: "uri",
            datetime: "date-time",
            json_string: "json-string",
            regex: "",
        };
        const seen = this.seen.get(schema);
        if (seen) {
            seen.count++;
            const isCycle = _params.schemaPath.includes(schema);
            if (isCycle) {
                seen.cycle = _params.path;
            }
            return seen.schema;
        }
        const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
        this.seen.set(schema, result);
        const overrideSchema = schema._zod.toJSONSchema?.();
        if (overrideSchema) {
            result.schema = overrideSchema;
        }
        else {
            const params = {
                ..._params,
                schemaPath: [..._params.schemaPath, schema],
                path: _params.path,
            };
            const parent = schema._zod.parent;
            if (parent) {
                result.ref = parent;
                this.process(parent, params);
                this.seen.get(parent).isParent = true;
            }
            else {
                const _json = result.schema;
                switch (def.type) {
                    case "string": {
                        const json = _json;
                        json.type = "string";
                        const { minimum, maximum, format, patterns, contentEncoding } = schema._zod
                            .bag;
                        if (typeof minimum === "number")
                            json.minLength = minimum;
                        if (typeof maximum === "number")
                            json.maxLength = maximum;
                        if (format) {
                            json.format = formatMap[format] ?? format;
                            if (json.format === "")
                                delete json.format;
                        }
                        if (contentEncoding)
                            json.contentEncoding = contentEncoding;
                        if (patterns && patterns.size > 0) {
                            const regexes = [...patterns];
                            if (regexes.length === 1)
                                json.pattern = regexes[0].source;
                            else if (regexes.length > 1) {
                                result.schema.allOf = [
                                    ...regexes.map((regex) => ({
                                        ...(this.target === "draft-7" ? { type: "string" } : {}),
                                        pattern: regex.source,
                                    })),
                                ];
                            }
                        }
                        break;
                    }
                    case "number": {
                        const json = _json;
                        const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
                        if (typeof format === "string" && format.includes("int"))
                            json.type = "integer";
                        else
                            json.type = "number";
                        if (typeof exclusiveMinimum === "number")
                            json.exclusiveMinimum = exclusiveMinimum;
                        if (typeof minimum === "number") {
                            json.minimum = minimum;
                            if (typeof exclusiveMinimum === "number") {
                                if (exclusiveMinimum >= minimum)
                                    delete json.minimum;
                                else
                                    delete json.exclusiveMinimum;
                            }
                        }
                        if (typeof exclusiveMaximum === "number")
                            json.exclusiveMaximum = exclusiveMaximum;
                        if (typeof maximum === "number") {
                            json.maximum = maximum;
                            if (typeof exclusiveMaximum === "number") {
                                if (exclusiveMaximum <= maximum)
                                    delete json.maximum;
                                else
                                    delete json.exclusiveMaximum;
                            }
                        }
                        if (typeof multipleOf === "number")
                            json.multipleOf = multipleOf;
                        break;
                    }
                    case "boolean": {
                        const json = _json;
                        json.type = "boolean";
                        break;
                    }
                    case "bigint": {
                        if (this.unrepresentable === "throw") {
                            throw new Error("BigInt cannot be represented in JSON Schema");
                        }
                        break;
                    }
                    case "symbol": {
                        if (this.unrepresentable === "throw") {
                            throw new Error("Symbols cannot be represented in JSON Schema");
                        }
                        break;
                    }
                    case "null": {
                        _json.type = "null";
                        break;
                    }
                    case "any": {
                        break;
                    }
                    case "unknown": {
                        break;
                    }
                    case "undefined": {
                        if (this.unrepresentable === "throw") {
                            throw new Error("Undefined cannot be represented in JSON Schema");
                        }
                        break;
                    }
                    case "void": {
                        if (this.unrepresentable === "throw") {
                            throw new Error("Void cannot be represented in JSON Schema");
                        }
                        break;
                    }
                    case "never": {
                        _json.not = {};
                        break;
                    }
                    case "date": {
                        if (this.unrepresentable === "throw") {
                            throw new Error("Date cannot be represented in JSON Schema");
                        }
                        break;
                    }
                    case "array": {
                        const json = _json;
                        const { minimum, maximum } = schema._zod.bag;
                        if (typeof minimum === "number")
                            json.minItems = minimum;
                        if (typeof maximum === "number")
                            json.maxItems = maximum;
                        json.type = "array";
                        json.items = this.process(def.element, { ...params, path: [...params.path, "items"] });
                        break;
                    }
                    case "object": {
                        const json = _json;
                        json.type = "object";
                        json.properties = {};
                        const shape = def.shape;
                        for (const key in shape) {
                            json.properties[key] = this.process(shape[key], {
                                ...params,
                                path: [...params.path, "properties", key],
                            });
                        }
                        const allKeys = new Set(Object.keys(shape));
                        const requiredKeys = new Set([...allKeys].filter((key) => {
                            const v = def.shape[key]._zod;
                            if (this.io === "input") {
                                return v.optin === undefined;
                            }
                            else {
                                return v.optout === undefined;
                            }
                        }));
                        if (requiredKeys.size > 0) {
                            json.required = Array.from(requiredKeys);
                        }
                        if (def.catchall?._zod.def.type === "never") {
                            json.additionalProperties = false;
                        }
                        else if (!def.catchall) {
                            if (this.io === "output")
                                json.additionalProperties = false;
                        }
                        else if (def.catchall) {
                            json.additionalProperties = this.process(def.catchall, {
                                ...params,
                                path: [...params.path, "additionalProperties"],
                            });
                        }
                        break;
                    }
                    case "union": {
                        const json = _json;
                        json.anyOf = def.options.map((x, i) => this.process(x, {
                            ...params,
                            path: [...params.path, "anyOf", i],
                        }));
                        break;
                    }
                    case "intersection": {
                        const json = _json;
                        const a = this.process(def.left, {
                            ...params,
                            path: [...params.path, "allOf", 0],
                        });
                        const b = this.process(def.right, {
                            ...params,
                            path: [...params.path, "allOf", 1],
                        });
                        const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
                        const allOf = [
                            ...(isSimpleIntersection(a) ? a.allOf : [a]),
                            ...(isSimpleIntersection(b) ? b.allOf : [b]),
                        ];
                        json.allOf = allOf;
                        break;
                    }
                    case "tuple": {
                        const json = _json;
                        json.type = "array";
                        const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] }));
                        if (this.target === "draft-2020-12") {
                            json.prefixItems = prefixItems;
                        }
                        else {
                            json.items = prefixItems;
                        }
                        if (def.rest) {
                            const rest = this.process(def.rest, {
                                ...params,
                                path: [...params.path, "items"],
                            });
                            if (this.target === "draft-2020-12") {
                                json.items = rest;
                            }
                            else {
                                json.additionalItems = rest;
                            }
                        }
                        if (def.rest) {
                            json.items = this.process(def.rest, {
                                ...params,
                                path: [...params.path, "items"],
                            });
                        }
                        const { minimum, maximum } = schema._zod.bag;
                        if (typeof minimum === "number")
                            json.minItems = minimum;
                        if (typeof maximum === "number")
                            json.maxItems = maximum;
                        break;
                    }
                    case "record": {
                        const json = _json;
                        json.type = "object";
                        json.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] });
                        json.additionalProperties = this.process(def.valueType, {
                            ...params,
                            path: [...params.path, "additionalProperties"],
                        });
                        break;
                    }
                    case "map": {
                        if (this.unrepresentable === "throw") {
                            throw new Error("Map cannot be represented in JSON Schema");
                        }
                        break;
                    }
                    case "set": {
                        if (this.unrepresentable === "throw") {
                            throw new Error("Set cannot be represented in JSON Schema");
                        }
                        break;
                    }
                    case "enum": {
                        const json = _json;
                        const values = getEnumValues(def.entries);
                        if (values.every((v) => typeof v === "number"))
                            json.type = "number";
                        if (values.every((v) => typeof v === "string"))
                            json.type = "string";
                        json.enum = values;
                        break;
                    }
                    case "literal": {
                        const json = _json;
                        const vals = [];
                        for (const val of def.values) {
                            if (val === undefined) {
                                if (this.unrepresentable === "throw") {
                                    throw new Error("Literal `undefined` cannot be represented in JSON Schema");
                                }
                            }
                            else if (typeof val === "bigint") {
                                if (this.unrepresentable === "throw") {
                                    throw new Error("BigInt literals cannot be represented in JSON Schema");
                                }
                                else {
                                    vals.push(Number(val));
                                }
                            }
                            else {
                                vals.push(val);
                            }
                        }
                        if (vals.length === 0) ;
                        else if (vals.length === 1) {
                            const val = vals[0];
                            json.type = val === null ? "null" : typeof val;
                            json.const = val;
                        }
                        else {
                            if (vals.every((v) => typeof v === "number"))
                                json.type = "number";
                            if (vals.every((v) => typeof v === "string"))
                                json.type = "string";
                            if (vals.every((v) => typeof v === "boolean"))
                                json.type = "string";
                            if (vals.every((v) => v === null))
                                json.type = "null";
                            json.enum = vals;
                        }
                        break;
                    }
                    case "file": {
                        const json = _json;
                        const file = {
                            type: "string",
                            format: "binary",
                            contentEncoding: "binary",
                        };
                        const { minimum, maximum, mime } = schema._zod.bag;
                        if (minimum !== undefined)
                            file.minLength = minimum;
                        if (maximum !== undefined)
                            file.maxLength = maximum;
                        if (mime) {
                            if (mime.length === 1) {
                                file.contentMediaType = mime[0];
                                Object.assign(json, file);
                            }
                            else {
                                json.anyOf = mime.map((m) => {
                                    const mFile = { ...file, contentMediaType: m };
                                    return mFile;
                                });
                            }
                        }
                        else {
                            Object.assign(json, file);
                        }
                        break;
                    }
                    case "transform": {
                        if (this.unrepresentable === "throw") {
                            throw new Error("Transforms cannot be represented in JSON Schema");
                        }
                        break;
                    }
                    case "nullable": {
                        const inner = this.process(def.innerType, params);
                        _json.anyOf = [inner, { type: "null" }];
                        break;
                    }
                    case "nonoptional": {
                        this.process(def.innerType, params);
                        result.ref = def.innerType;
                        break;
                    }
                    case "success": {
                        const json = _json;
                        json.type = "boolean";
                        break;
                    }
                    case "default": {
                        this.process(def.innerType, params);
                        result.ref = def.innerType;
                        _json.default = JSON.parse(JSON.stringify(def.defaultValue));
                        break;
                    }
                    case "prefault": {
                        this.process(def.innerType, params);
                        result.ref = def.innerType;
                        if (this.io === "input")
                            _json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
                        break;
                    }
                    case "catch": {
                        this.process(def.innerType, params);
                        result.ref = def.innerType;
                        let catchValue;
                        try {
                            catchValue = def.catchValue(undefined);
                        }
                        catch {
                            throw new Error("Dynamic catch values are not supported in JSON Schema");
                        }
                        _json.default = catchValue;
                        break;
                    }
                    case "nan": {
                        if (this.unrepresentable === "throw") {
                            throw new Error("NaN cannot be represented in JSON Schema");
                        }
                        break;
                    }
                    case "template_literal": {
                        const json = _json;
                        const pattern = schema._zod.pattern;
                        if (!pattern)
                            throw new Error("Pattern not found in template literal");
                        json.type = "string";
                        json.pattern = pattern.source;
                        break;
                    }
                    case "pipe": {
                        const innerType = this.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out;
                        this.process(innerType, params);
                        result.ref = innerType;
                        break;
                    }
                    case "readonly": {
                        this.process(def.innerType, params);
                        result.ref = def.innerType;
                        _json.readOnly = true;
                        break;
                    }
                    case "promise": {
                        this.process(def.innerType, params);
                        result.ref = def.innerType;
                        break;
                    }
                    case "optional": {
                        this.process(def.innerType, params);
                        result.ref = def.innerType;
                        break;
                    }
                    case "lazy": {
                        const innerType = schema._zod.innerType;
                        this.process(innerType, params);
                        result.ref = innerType;
                        break;
                    }
                    case "custom": {
                        if (this.unrepresentable === "throw") {
                            throw new Error("Custom types cannot be represented in JSON Schema");
                        }
                        break;
                    }
                }
            }
        }
        const meta = this.metadataRegistry.get(schema);
        if (meta)
            Object.assign(result.schema, meta);
        if (this.io === "input" && isTransforming(schema)) {
            delete result.schema.examples;
            delete result.schema.default;
        }
        if (this.io === "input" && result.schema._prefault)
            (_a = result.schema).default ?? (_a.default = result.schema._prefault);
        delete result.schema._prefault;
        const _result = this.seen.get(schema);
        return _result.schema;
    }
    emit(schema, _params) {
        const params = {
            cycles: _params?.cycles ?? "ref",
            reused: _params?.reused ?? "inline",
            external: _params?.external ?? undefined,
        };
        const root = this.seen.get(schema);
        if (!root)
            throw new Error("Unprocessed schema. This is a bug in Zod.");
        const makeURI = (entry) => {
            const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions";
            if (params.external) {
                const externalId = params.external.registry.get(entry[0])?.id;
                const uriGenerator = params.external.uri ?? ((id) => id);
                if (externalId) {
                    return { ref: uriGenerator(externalId) };
                }
                const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;
                entry[1].defId = id;
                return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
            }
            if (entry[1] === root) {
                return { ref: "#" };
            }
            const uriPrefix = `#`;
            const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
            const defId = entry[1].schema.id ?? `__schema${this.counter++}`;
            return { defId, ref: defUriPrefix + defId };
        };
        const extractToDef = (entry) => {
            if (entry[1].schema.$ref) {
                return;
            }
            const seen = entry[1];
            const { ref, defId } = makeURI(entry);
            seen.def = { ...seen.schema };
            if (defId)
                seen.defId = defId;
            const schema = seen.schema;
            for (const key in schema) {
                delete schema[key];
            }
            schema.$ref = ref;
        };
        if (params.cycles === "throw") {
            for (const entry of this.seen.entries()) {
                const seen = entry[1];
                if (seen.cycle) {
                    throw new Error("Cycle detected: " +
                        `#/${seen.cycle?.join("/")}/<root>` +
                        '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.');
                }
            }
        }
        for (const entry of this.seen.entries()) {
            const seen = entry[1];
            if (schema === entry[0]) {
                extractToDef(entry);
                continue;
            }
            if (params.external) {
                const ext = params.external.registry.get(entry[0])?.id;
                if (schema !== entry[0] && ext) {
                    extractToDef(entry);
                    continue;
                }
            }
            const id = this.metadataRegistry.get(entry[0])?.id;
            if (id) {
                extractToDef(entry);
                continue;
            }
            if (seen.cycle) {
                extractToDef(entry);
                continue;
            }
            if (seen.count > 1) {
                if (params.reused === "ref") {
                    extractToDef(entry);
                    continue;
                }
            }
        }
        const flattenRef = (zodSchema, params) => {
            const seen = this.seen.get(zodSchema);
            const schema = seen.def ?? seen.schema;
            const _cached = { ...schema };
            if (seen.ref === null) {
                return;
            }
            const ref = seen.ref;
            seen.ref = null;
            if (ref) {
                flattenRef(ref, params);
                const refSchema = this.seen.get(ref).schema;
                if (refSchema.$ref && params.target === "draft-7") {
                    schema.allOf = schema.allOf ?? [];
                    schema.allOf.push(refSchema);
                }
                else {
                    Object.assign(schema, refSchema);
                    Object.assign(schema, _cached);
                }
            }
            if (!seen.isParent)
                this.override({
                    zodSchema: zodSchema,
                    jsonSchema: schema,
                    path: seen.path ?? [],
                });
        };
        for (const entry of [...this.seen.entries()].reverse()) {
            flattenRef(entry[0], { target: this.target });
        }
        const result = {};
        if (this.target === "draft-2020-12") {
            result.$schema = "https://json-schema.org/draft/2020-12/schema";
        }
        else if (this.target === "draft-7") {
            result.$schema = "http://json-schema.org/draft-07/schema#";
        }
        else {
            console.warn(`Invalid target: ${this.target}`);
        }
        if (params.external?.uri) {
            const id = params.external.registry.get(schema)?.id;
            if (!id)
                throw new Error("Schema is missing an `id` property");
            result.$id = params.external.uri(id);
        }
        Object.assign(result, root.def);
        const defs = params.external?.defs ?? {};
        for (const entry of this.seen.entries()) {
            const seen = entry[1];
            if (seen.def && seen.defId) {
                defs[seen.defId] = seen.def;
            }
        }
        if (params.external) ;
        else {
            if (Object.keys(defs).length > 0) {
                if (this.target === "draft-2020-12") {
                    result.$defs = defs;
                }
                else {
                    result.definitions = defs;
                }
            }
        }
        try {
            return JSON.parse(JSON.stringify(result));
        }
        catch (_err) {
            throw new Error("Error converting schema to JSON.");
        }
    }
}
function toJSONSchema(input, _params) {
    if (input instanceof $ZodRegistry) {
        const gen = new JSONSchemaGenerator(_params);
        const defs = {};
        for (const entry of input._idmap.entries()) {
            const [_, schema] = entry;
            gen.process(schema);
        }
        const schemas = {};
        const external = {
            registry: input,
            uri: _params?.uri,
            defs,
        };
        for (const entry of input._idmap.entries()) {
            const [key, schema] = entry;
            schemas[key] = gen.emit(schema, {
                ..._params,
                external,
            });
        }
        if (Object.keys(defs).length > 0) {
            const defsSegment = gen.target === "draft-2020-12" ? "$defs" : "definitions";
            schemas.__shared = {
                [defsSegment]: defs,
            };
        }
        return { schemas };
    }
    const gen = new JSONSchemaGenerator(_params);
    gen.process(input);
    return gen.emit(input, _params);
}
function isTransforming(_schema, _ctx) {
    const ctx = _ctx ?? { seen: new Set() };
    if (ctx.seen.has(_schema))
        return false;
    ctx.seen.add(_schema);
    const schema = _schema;
    const def = schema._zod.def;
    switch (def.type) {
        case "string":
        case "number":
        case "bigint":
        case "boolean":
        case "date":
        case "symbol":
        case "undefined":
        case "null":
        case "any":
        case "unknown":
        case "never":
        case "void":
        case "literal":
        case "enum":
        case "nan":
        case "file":
        case "template_literal":
            return false;
        case "array": {
            return isTransforming(def.element, ctx);
        }
        case "object": {
            for (const key in def.shape) {
                if (isTransforming(def.shape[key], ctx))
                    return true;
            }
            return false;
        }
        case "union": {
            for (const option of def.options) {
                if (isTransforming(option, ctx))
                    return true;
            }
            return false;
        }
        case "intersection": {
            return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
        }
        case "tuple": {
            for (const item of def.items) {
                if (isTransforming(item, ctx))
                    return true;
            }
            if (def.rest && isTransforming(def.rest, ctx))
                return true;
            return false;
        }
        case "record": {
            return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
        }
        case "map": {
            return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
        }
        case "set": {
            return isTransforming(def.valueType, ctx);
        }
        case "promise":
        case "optional":
        case "nonoptional":
        case "nullable":
        case "readonly":
            return isTransforming(def.innerType, ctx);
        case "lazy":
            return isTransforming(def.getter(), ctx);
        case "default": {
            return isTransforming(def.innerType, ctx);
        }
        case "prefault": {
            return isTransforming(def.innerType, ctx);
        }
        case "custom": {
            return false;
        }
        case "transform": {
            return true;
        }
        case "pipe": {
            return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
        }
        case "success": {
            return false;
        }
        case "catch": {
            return false;
        }
    }
    throw new Error(`Unknown schema type: ${def.type}`);
}

const ZodMiniType =  $constructor("ZodMiniType", (inst, def) => {
    if (!inst._zod)
        throw new Error("Uninitialized schema in ZodMiniType.");
    $ZodType.init(inst, def);
    inst.def = def;
    inst.parse = (data, params) => parse$4(inst, data, params, { callee: inst.parse });
    inst.safeParse = (data, params) => safeParse$2(inst, data, params);
    inst.parseAsync = async (data, params) => parseAsync$1(inst, data, params, { callee: inst.parseAsync });
    inst.safeParseAsync = async (data, params) => safeParseAsync$2(inst, data, params);
    inst.check = (...checks) => {
        return inst.clone({
            ...def,
            checks: [
                ...(def.checks ?? []),
                ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
            ],
        }
        );
    };
    inst.clone = (_def, params) => clone(inst, _def, params);
    inst.brand = () => inst;
    inst.register = ((reg, meta) => {
        reg.add(inst, meta);
        return inst;
    });
});
const ZodMiniString =  $constructor("ZodMiniString", (inst, def) => {
    $ZodString.init(inst, def);
    ZodMiniType.init(inst, def);
});
const ZodMiniStringFormat =  $constructor("ZodMiniStringFormat", (inst, def) => {
    $ZodStringFormat.init(inst, def);
    ZodMiniString.init(inst, def);
});
$constructor("ZodMiniEmail", (inst, def) => {
    $ZodEmail.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniGUID", (inst, def) => {
    $ZodGUID.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniUUID", (inst, def) => {
    $ZodUUID.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniURL", (inst, def) => {
    $ZodURL.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniEmoji", (inst, def) => {
    $ZodEmoji.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniNanoID", (inst, def) => {
    $ZodNanoID.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniCUID", (inst, def) => {
    $ZodCUID.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniCUID2", (inst, def) => {
    $ZodCUID2.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniULID", (inst, def) => {
    $ZodULID.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniXID", (inst, def) => {
    $ZodXID.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniKSUID", (inst, def) => {
    $ZodKSUID.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniIPv4", (inst, def) => {
    $ZodIPv4.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniIPv6", (inst, def) => {
    $ZodIPv6.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniCIDRv4", (inst, def) => {
    $ZodCIDRv4.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniCIDRv6", (inst, def) => {
    $ZodCIDRv6.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniBase64", (inst, def) => {
    $ZodBase64.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniBase64URL", (inst, def) => {
    $ZodBase64URL.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniE164", (inst, def) => {
    $ZodE164.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniJWT", (inst, def) => {
    $ZodJWT.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
$constructor("ZodMiniCustomStringFormat", (inst, def) => {
    $ZodCustomStringFormat.init(inst, def);
    ZodMiniStringFormat.init(inst, def);
});
const ZodMiniNumber =  $constructor("ZodMiniNumber", (inst, def) => {
    $ZodNumber.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniNumberFormat", (inst, def) => {
    $ZodNumberFormat.init(inst, def);
    ZodMiniNumber.init(inst, def);
});
$constructor("ZodMiniBoolean", (inst, def) => {
    $ZodBoolean.init(inst, def);
    ZodMiniType.init(inst, def);
});
const ZodMiniBigInt =  $constructor("ZodMiniBigInt", (inst, def) => {
    $ZodBigInt.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniBigIntFormat", (inst, def) => {
    $ZodBigIntFormat.init(inst, def);
    ZodMiniBigInt.init(inst, def);
});
$constructor("ZodMiniSymbol", (inst, def) => {
    $ZodSymbol.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniUndefined", (inst, def) => {
    $ZodUndefined.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniNull", (inst, def) => {
    $ZodNull.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniAny", (inst, def) => {
    $ZodAny.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniUnknown", (inst, def) => {
    $ZodUnknown.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniNever", (inst, def) => {
    $ZodNever.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniVoid", (inst, def) => {
    $ZodVoid.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniDate", (inst, def) => {
    $ZodDate.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniArray", (inst, def) => {
    $ZodArray.init(inst, def);
    ZodMiniType.init(inst, def);
});
const ZodMiniObject =  $constructor("ZodMiniObject", (inst, def) => {
    $ZodObject.init(inst, def);
    ZodMiniType.init(inst, def);
    defineLazy(inst, "shape", () => def.shape);
});
function object$1(shape, params) {
    const def = {
        type: "object",
        get shape() {
            assignProp(this, "shape", { ...shape });
            return this.shape;
        },
        ...normalizeParams(params),
    };
    return new ZodMiniObject(def);
}
$constructor("ZodMiniUnion", (inst, def) => {
    $ZodUnion.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniDiscriminatedUnion", (inst, def) => {
    $ZodDiscriminatedUnion.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniIntersection", (inst, def) => {
    $ZodIntersection.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniTuple", (inst, def) => {
    $ZodTuple.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniRecord", (inst, def) => {
    $ZodRecord.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniMap", (inst, def) => {
    $ZodMap.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniSet", (inst, def) => {
    $ZodSet.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniEnum", (inst, def) => {
    $ZodEnum.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniLiteral", (inst, def) => {
    $ZodLiteral.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniFile", (inst, def) => {
    $ZodFile.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniTransform", (inst, def) => {
    $ZodTransform.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniOptional", (inst, def) => {
    $ZodOptional.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniNullable", (inst, def) => {
    $ZodNullable.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniDefault", (inst, def) => {
    $ZodDefault.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniPrefault", (inst, def) => {
    $ZodPrefault.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniNonOptional", (inst, def) => {
    $ZodNonOptional.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniSuccess", (inst, def) => {
    $ZodSuccess.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniCatch", (inst, def) => {
    $ZodCatch.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniNaN", (inst, def) => {
    $ZodNaN.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniPipe", (inst, def) => {
    $ZodPipe.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniReadonly", (inst, def) => {
    $ZodReadonly.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniTemplateLiteral", (inst, def) => {
    $ZodTemplateLiteral.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniLazy", (inst, def) => {
    $ZodLazy.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniPromise", (inst, def) => {
    $ZodPromise.init(inst, def);
    ZodMiniType.init(inst, def);
});
$constructor("ZodMiniCustom", (inst, def) => {
    $ZodCustom.init(inst, def);
    ZodMiniType.init(inst, def);
});

function isZ4Schema(s) {
    const schema = s;
    return !!schema._zod;
}
function objectFromShape(shape) {
    const values = Object.values(shape);
    if (values.length === 0)
        return object$1({});
    const allV4 = values.every(isZ4Schema);
    const allV3 = values.every(s => !isZ4Schema(s));
    if (allV4)
        return object$1(shape);
    if (allV3)
        return objectType(shape);
    throw new Error('Mixed Zod versions detected in object shape.');
}
function safeParse$1(schema, data) {
    if (isZ4Schema(schema)) {
        const result = safeParse$2(schema, data);
        return result;
    }
    const v3Schema = schema;
    const result = v3Schema.safeParse(data);
    return result;
}
async function safeParseAsync$1(schema, data) {
    if (isZ4Schema(schema)) {
        const result = await safeParseAsync$2(schema, data);
        return result;
    }
    const v3Schema = schema;
    const result = await v3Schema.safeParseAsync(data);
    return result;
}
function getObjectShape(schema) {
    if (!schema)
        return undefined;
    let rawShape;
    if (isZ4Schema(schema)) {
        const v4Schema = schema;
        rawShape = v4Schema._zod?.def?.shape;
    }
    else {
        const v3Schema = schema;
        rawShape = v3Schema.shape;
    }
    if (!rawShape)
        return undefined;
    if (typeof rawShape === 'function') {
        try {
            return rawShape();
        }
        catch {
            return undefined;
        }
    }
    return rawShape;
}
function normalizeObjectSchema(schema) {
    if (!schema)
        return undefined;
    if (typeof schema === 'object') {
        const asV3 = schema;
        const asV4 = schema;
        if (!asV3._def && !asV4._zod) {
            const values = Object.values(schema);
            if (values.length > 0 &&
                values.every(v => typeof v === 'object' &&
                    v !== null &&
                    (v._def !== undefined ||
                        v._zod !== undefined ||
                        typeof v.parse === 'function'))) {
                return objectFromShape(schema);
            }
        }
    }
    if (isZ4Schema(schema)) {
        const v4Schema = schema;
        const def = v4Schema._zod?.def;
        if (def && (def.type === 'object' || def.shape !== undefined)) {
            return schema;
        }
    }
    else {
        const v3Schema = schema;
        if (v3Schema.shape !== undefined) {
            return schema;
        }
    }
    return undefined;
}
function getParseErrorMessage(error) {
    if (error && typeof error === 'object') {
        if ('message' in error && typeof error.message === 'string') {
            return error.message;
        }
        if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) {
            const firstIssue = error.issues[0];
            if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) {
                return String(firstIssue.message);
            }
        }
        try {
            return JSON.stringify(error);
        }
        catch {
            return String(error);
        }
    }
    return String(error);
}
function getSchemaDescription(schema) {
    return schema.description;
}
function isSchemaOptional(schema) {
    if (isZ4Schema(schema)) {
        const v4Schema = schema;
        return v4Schema._zod?.def?.type === 'optional';
    }
    const v3Schema = schema;
    if (typeof schema.isOptional === 'function') {
        return schema.isOptional();
    }
    return v3Schema._def?.typeName === 'ZodOptional';
}
function getLiteralValue(schema) {
    if (isZ4Schema(schema)) {
        const v4Schema = schema;
        const def = v4Schema._zod?.def;
        if (def) {
            if (def.value !== undefined)
                return def.value;
            if (Array.isArray(def.values) && def.values.length > 0) {
                return def.values[0];
            }
        }
    }
    const v3Schema = schema;
    const def = v3Schema._def;
    if (def) {
        if (def.value !== undefined)
            return def.value;
        if (Array.isArray(def.values) && def.values.length > 0) {
            return def.values[0];
        }
    }
    const directValue = schema.value;
    if (directValue !== undefined)
        return directValue;
    return undefined;
}

const ZodISODateTime =  $constructor("ZodISODateTime", (inst, def) => {
    $ZodISODateTime.init(inst, def);
    ZodStringFormat.init(inst, def);
});
function datetime(params) {
    return _isoDateTime(ZodISODateTime, params);
}
const ZodISODate =  $constructor("ZodISODate", (inst, def) => {
    $ZodISODate.init(inst, def);
    ZodStringFormat.init(inst, def);
});
function date(params) {
    return _isoDate(ZodISODate, params);
}
const ZodISOTime =  $constructor("ZodISOTime", (inst, def) => {
    $ZodISOTime.init(inst, def);
    ZodStringFormat.init(inst, def);
});
function time(params) {
    return _isoTime(ZodISOTime, params);
}
const ZodISODuration =  $constructor("ZodISODuration", (inst, def) => {
    $ZodISODuration.init(inst, def);
    ZodStringFormat.init(inst, def);
});
function duration(params) {
    return _isoDuration(ZodISODuration, params);
}

const initializer = (inst, issues) => {
    $ZodError.init(inst, issues);
    inst.name = "ZodError";
    Object.defineProperties(inst, {
        format: {
            value: (mapper) => formatError(inst, mapper),
        },
        flatten: {
            value: (mapper) => flattenError(inst, mapper),
        },
        addIssue: {
            value: (issue) => inst.issues.push(issue),
        },
        addIssues: {
            value: (issues) => inst.issues.push(...issues),
        },
        isEmpty: {
            get() {
                return inst.issues.length === 0;
            },
        },
    });
};
$constructor("ZodError", initializer);
const ZodRealError = $constructor("ZodError", initializer, {
    Parent: Error,
});

const parse$3 =  _parse(ZodRealError);
const parseAsync =  _parseAsync(ZodRealError);
const safeParse =  _safeParse(ZodRealError);
const safeParseAsync =  _safeParseAsync(ZodRealError);

const ZodType =  $constructor("ZodType", (inst, def) => {
    $ZodType.init(inst, def);
    inst.def = def;
    Object.defineProperty(inst, "_def", { value: def });
    inst.check = (...checks) => {
        return inst.clone({
            ...def,
            checks: [
                ...(def.checks ?? []),
                ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
            ],
        }
        );
    };
    inst.clone = (def, params) => clone(inst, def, params);
    inst.brand = () => inst;
    inst.register = ((reg, meta) => {
        reg.add(inst, meta);
        return inst;
    });
    inst.parse = (data, params) => parse$3(inst, data, params, { callee: inst.parse });
    inst.safeParse = (data, params) => safeParse(inst, data, params);
    inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
    inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
    inst.spa = inst.safeParseAsync;
    inst.refine = (check, params) => inst.check(refine(check, params));
    inst.superRefine = (refinement) => inst.check(superRefine(refinement));
    inst.overwrite = (fn) => inst.check(_overwrite(fn));
    inst.optional = () => optional(inst);
    inst.nullable = () => nullable(inst);
    inst.nullish = () => optional(nullable(inst));
    inst.nonoptional = (params) => nonoptional(inst, params);
    inst.array = () => array(inst);
    inst.or = (arg) => union([inst, arg]);
    inst.and = (arg) => intersection(inst, arg);
    inst.transform = (tx) => pipe$1(inst, transform(tx));
    inst.default = (def) => _default(inst, def);
    inst.prefault = (def) => prefault(inst, def);
    inst.catch = (params) => _catch(inst, params);
    inst.pipe = (target) => pipe$1(inst, target);
    inst.readonly = () => readonly(inst);
    inst.describe = (description) => {
        const cl = inst.clone();
        globalRegistry.add(cl, { description });
        return cl;
    };
    Object.defineProperty(inst, "description", {
        get() {
            return globalRegistry.get(inst)?.description;
        },
        configurable: true,
    });
    inst.meta = (...args) => {
        if (args.length === 0) {
            return globalRegistry.get(inst);
        }
        const cl = inst.clone();
        globalRegistry.add(cl, args[0]);
        return cl;
    };
    inst.isOptional = () => inst.safeParse(undefined).success;
    inst.isNullable = () => inst.safeParse(null).success;
    return inst;
});
const _ZodString =  $constructor("_ZodString", (inst, def) => {
    $ZodString.init(inst, def);
    ZodType.init(inst, def);
    const bag = inst._zod.bag;
    inst.format = bag.format ?? null;
    inst.minLength = bag.minimum ?? null;
    inst.maxLength = bag.maximum ?? null;
    inst.regex = (...args) => inst.check(_regex(...args));
    inst.includes = (...args) => inst.check(_includes(...args));
    inst.startsWith = (...args) => inst.check(_startsWith(...args));
    inst.endsWith = (...args) => inst.check(_endsWith(...args));
    inst.min = (...args) => inst.check(_minLength(...args));
    inst.max = (...args) => inst.check(_maxLength(...args));
    inst.length = (...args) => inst.check(_length(...args));
    inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
    inst.lowercase = (params) => inst.check(_lowercase(params));
    inst.uppercase = (params) => inst.check(_uppercase(params));
    inst.trim = () => inst.check(_trim());
    inst.normalize = (...args) => inst.check(_normalize(...args));
    inst.toLowerCase = () => inst.check(_toLowerCase());
    inst.toUpperCase = () => inst.check(_toUpperCase());
});
const ZodString =  $constructor("ZodString", (inst, def) => {
    $ZodString.init(inst, def);
    _ZodString.init(inst, def);
    inst.email = (params) => inst.check(_email(ZodEmail, params));
    inst.url = (params) => inst.check(_url(ZodURL, params));
    inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
    inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
    inst.guid = (params) => inst.check(_guid(ZodGUID, params));
    inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
    inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
    inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
    inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
    inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
    inst.guid = (params) => inst.check(_guid(ZodGUID, params));
    inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
    inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
    inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
    inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
    inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
    inst.xid = (params) => inst.check(_xid(ZodXID, params));
    inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
    inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
    inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
    inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
    inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
    inst.e164 = (params) => inst.check(_e164(ZodE164, params));
    inst.datetime = (params) => inst.check(datetime(params));
    inst.date = (params) => inst.check(date(params));
    inst.time = (params) => inst.check(time(params));
    inst.duration = (params) => inst.check(duration(params));
});
function string(params) {
    return _string(ZodString, params);
}
const ZodStringFormat =  $constructor("ZodStringFormat", (inst, def) => {
    $ZodStringFormat.init(inst, def);
    _ZodString.init(inst, def);
});
const ZodEmail =  $constructor("ZodEmail", (inst, def) => {
    $ZodEmail.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodGUID =  $constructor("ZodGUID", (inst, def) => {
    $ZodGUID.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodUUID =  $constructor("ZodUUID", (inst, def) => {
    $ZodUUID.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodURL =  $constructor("ZodURL", (inst, def) => {
    $ZodURL.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodEmoji =  $constructor("ZodEmoji", (inst, def) => {
    $ZodEmoji.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodNanoID =  $constructor("ZodNanoID", (inst, def) => {
    $ZodNanoID.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodCUID =  $constructor("ZodCUID", (inst, def) => {
    $ZodCUID.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodCUID2 =  $constructor("ZodCUID2", (inst, def) => {
    $ZodCUID2.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodULID =  $constructor("ZodULID", (inst, def) => {
    $ZodULID.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodXID =  $constructor("ZodXID", (inst, def) => {
    $ZodXID.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodKSUID =  $constructor("ZodKSUID", (inst, def) => {
    $ZodKSUID.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodIPv4 =  $constructor("ZodIPv4", (inst, def) => {
    $ZodIPv4.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodIPv6 =  $constructor("ZodIPv6", (inst, def) => {
    $ZodIPv6.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodCIDRv4 =  $constructor("ZodCIDRv4", (inst, def) => {
    $ZodCIDRv4.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodCIDRv6 =  $constructor("ZodCIDRv6", (inst, def) => {
    $ZodCIDRv6.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodBase64 =  $constructor("ZodBase64", (inst, def) => {
    $ZodBase64.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodBase64URL =  $constructor("ZodBase64URL", (inst, def) => {
    $ZodBase64URL.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodE164 =  $constructor("ZodE164", (inst, def) => {
    $ZodE164.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodJWT =  $constructor("ZodJWT", (inst, def) => {
    $ZodJWT.init(inst, def);
    ZodStringFormat.init(inst, def);
});
$constructor("ZodCustomStringFormat", (inst, def) => {
    $ZodCustomStringFormat.init(inst, def);
    ZodStringFormat.init(inst, def);
});
const ZodNumber =  $constructor("ZodNumber", (inst, def) => {
    $ZodNumber.init(inst, def);
    ZodType.init(inst, def);
    inst.gt = (value, params) => inst.check(_gt(value, params));
    inst.gte = (value, params) => inst.check(_gte(value, params));
    inst.min = (value, params) => inst.check(_gte(value, params));
    inst.lt = (value, params) => inst.check(_lt(value, params));
    inst.lte = (value, params) => inst.check(_lte(value, params));
    inst.max = (value, params) => inst.check(_lte(value, params));
    inst.int = (params) => inst.check(int(params));
    inst.safe = (params) => inst.check(int(params));
    inst.positive = (params) => inst.check(_gt(0, params));
    inst.nonnegative = (params) => inst.check(_gte(0, params));
    inst.negative = (params) => inst.check(_lt(0, params));
    inst.nonpositive = (params) => inst.check(_lte(0, params));
    inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
    inst.step = (value, params) => inst.check(_multipleOf(value, params));
    inst.finite = () => inst;
    const bag = inst._zod.bag;
    inst.minValue =
        Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
    inst.maxValue =
        Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
    inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
    inst.isFinite = true;
    inst.format = bag.format ?? null;
});
function number(params) {
    return _number(ZodNumber, params);
}
const ZodNumberFormat =  $constructor("ZodNumberFormat", (inst, def) => {
    $ZodNumberFormat.init(inst, def);
    ZodNumber.init(inst, def);
});
function int(params) {
    return _int(ZodNumberFormat, params);
}
const ZodBoolean =  $constructor("ZodBoolean", (inst, def) => {
    $ZodBoolean.init(inst, def);
    ZodType.init(inst, def);
});
function boolean(params) {
    return _boolean(ZodBoolean, params);
}
const ZodBigInt =  $constructor("ZodBigInt", (inst, def) => {
    $ZodBigInt.init(inst, def);
    ZodType.init(inst, def);
    inst.gte = (value, params) => inst.check(_gte(value, params));
    inst.min = (value, params) => inst.check(_gte(value, params));
    inst.gt = (value, params) => inst.check(_gt(value, params));
    inst.gte = (value, params) => inst.check(_gte(value, params));
    inst.min = (value, params) => inst.check(_gte(value, params));
    inst.lt = (value, params) => inst.check(_lt(value, params));
    inst.lte = (value, params) => inst.check(_lte(value, params));
    inst.max = (value, params) => inst.check(_lte(value, params));
    inst.positive = (params) => inst.check(_gt(BigInt(0), params));
    inst.negative = (params) => inst.check(_lt(BigInt(0), params));
    inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params));
    inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params));
    inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
    const bag = inst._zod.bag;
    inst.minValue = bag.minimum ?? null;
    inst.maxValue = bag.maximum ?? null;
    inst.format = bag.format ?? null;
});
$constructor("ZodBigIntFormat", (inst, def) => {
    $ZodBigIntFormat.init(inst, def);
    ZodBigInt.init(inst, def);
});
$constructor("ZodSymbol", (inst, def) => {
    $ZodSymbol.init(inst, def);
    ZodType.init(inst, def);
});
$constructor("ZodUndefined", (inst, def) => {
    $ZodUndefined.init(inst, def);
    ZodType.init(inst, def);
});
const ZodNull =  $constructor("ZodNull", (inst, def) => {
    $ZodNull.init(inst, def);
    ZodType.init(inst, def);
});
function _null(params) {
    return _null$1(ZodNull, params);
}
$constructor("ZodAny", (inst, def) => {
    $ZodAny.init(inst, def);
    ZodType.init(inst, def);
});
const ZodUnknown =  $constructor("ZodUnknown", (inst, def) => {
    $ZodUnknown.init(inst, def);
    ZodType.init(inst, def);
});
function unknown() {
    return _unknown(ZodUnknown);
}
const ZodNever =  $constructor("ZodNever", (inst, def) => {
    $ZodNever.init(inst, def);
    ZodType.init(inst, def);
});
function never(params) {
    return _never(ZodNever, params);
}
$constructor("ZodVoid", (inst, def) => {
    $ZodVoid.init(inst, def);
    ZodType.init(inst, def);
});
$constructor("ZodDate", (inst, def) => {
    $ZodDate.init(inst, def);
    ZodType.init(inst, def);
    inst.min = (value, params) => inst.check(_gte(value, params));
    inst.max = (value, params) => inst.check(_lte(value, params));
    const c = inst._zod.bag;
    inst.minDate = c.minimum ? new Date(c.minimum) : null;
    inst.maxDate = c.maximum ? new Date(c.maximum) : null;
});
const ZodArray =  $constructor("ZodArray", (inst, def) => {
    $ZodArray.init(inst, def);
    ZodType.init(inst, def);
    inst.element = def.element;
    inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
    inst.nonempty = (params) => inst.check(_minLength(1, params));
    inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
    inst.length = (len, params) => inst.check(_length(len, params));
    inst.unwrap = () => inst.element;
});
function array(element, params) {
    return _array(ZodArray, element, params);
}
const ZodObject =  $constructor("ZodObject", (inst, def) => {
    $ZodObject.init(inst, def);
    ZodType.init(inst, def);
    defineLazy(inst, "shape", () => def.shape);
    inst.keyof = () => _enum$2(Object.keys(inst._zod.def.shape));
    inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });
    inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
    inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
    inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
    inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });
    inst.extend = (incoming) => {
        return extend(inst, incoming);
    };
    inst.merge = (other) => merge$1(inst, other);
    inst.pick = (mask) => pick(inst, mask);
    inst.omit = (mask) => omit(inst, mask);
    inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
    inst.required = (...args) => required$4(ZodNonOptional, inst, args[0]);
});
function object(shape, params) {
    const def = {
        type: "object",
        get shape() {
            assignProp(this, "shape", { ...shape });
            return this.shape;
        },
        ...normalizeParams(params),
    };
    return new ZodObject(def);
}
function looseObject(shape, params) {
    return new ZodObject({
        type: "object",
        get shape() {
            assignProp(this, "shape", { ...shape });
            return this.shape;
        },
        catchall: unknown(),
        ...normalizeParams(params),
    });
}
const ZodUnion =  $constructor("ZodUnion", (inst, def) => {
    $ZodUnion.init(inst, def);
    ZodType.init(inst, def);
    inst.options = def.options;
});
function union(options, params) {
    return new ZodUnion({
        type: "union",
        options: options,
        ...normalizeParams(params),
    });
}
const ZodDiscriminatedUnion =  $constructor("ZodDiscriminatedUnion", (inst, def) => {
    ZodUnion.init(inst, def);
    $ZodDiscriminatedUnion.init(inst, def);
});
function discriminatedUnion(discriminator, options, params) {
    return new ZodDiscriminatedUnion({
        type: "union",
        options,
        discriminator,
        ...normalizeParams(params),
    });
}
const ZodIntersection =  $constructor("ZodIntersection", (inst, def) => {
    $ZodIntersection.init(inst, def);
    ZodType.init(inst, def);
});
function intersection(left, right) {
    return new ZodIntersection({
        type: "intersection",
        left: left,
        right: right,
    });
}
$constructor("ZodTuple", (inst, def) => {
    $ZodTuple.init(inst, def);
    ZodType.init(inst, def);
    inst.rest = (rest) => inst.clone({
        ...inst._zod.def,
        rest: rest,
    });
});
const ZodRecord =  $constructor("ZodRecord", (inst, def) => {
    $ZodRecord.init(inst, def);
    ZodType.init(inst, def);
    inst.keyType = def.keyType;
    inst.valueType = def.valueType;
});
function record(keyType, valueType, params) {
    return new ZodRecord({
        type: "record",
        keyType,
        valueType: valueType,
        ...normalizeParams(params),
    });
}
$constructor("ZodMap", (inst, def) => {
    $ZodMap.init(inst, def);
    ZodType.init(inst, def);
    inst.keyType = def.keyType;
    inst.valueType = def.valueType;
});
$constructor("ZodSet", (inst, def) => {
    $ZodSet.init(inst, def);
    ZodType.init(inst, def);
    inst.min = (...args) => inst.check(_minSize(...args));
    inst.nonempty = (params) => inst.check(_minSize(1, params));
    inst.max = (...args) => inst.check(_maxSize(...args));
    inst.size = (...args) => inst.check(_size(...args));
});
const ZodEnum =  $constructor("ZodEnum", (inst, def) => {
    $ZodEnum.init(inst, def);
    ZodType.init(inst, def);
    inst.enum = def.entries;
    inst.options = Object.values(def.entries);
    const keys = new Set(Object.keys(def.entries));
    inst.extract = (values, params) => {
        const newEntries = {};
        for (const value of values) {
            if (keys.has(value)) {
                newEntries[value] = def.entries[value];
            }
            else
                throw new Error(`Key ${value} not found in enum`);
        }
        return new ZodEnum({
            ...def,
            checks: [],
            ...normalizeParams(params),
            entries: newEntries,
        });
    };
    inst.exclude = (values, params) => {
        const newEntries = { ...def.entries };
        for (const value of values) {
            if (keys.has(value)) {
                delete newEntries[value];
            }
            else
                throw new Error(`Key ${value} not found in enum`);
        }
        return new ZodEnum({
            ...def,
            checks: [],
            ...normalizeParams(params),
            entries: newEntries,
        });
    };
});
function _enum$2(values, params) {
    const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
    return new ZodEnum({
        type: "enum",
        entries,
        ...normalizeParams(params),
    });
}
const ZodLiteral =  $constructor("ZodLiteral", (inst, def) => {
    $ZodLiteral.init(inst, def);
    ZodType.init(inst, def);
    inst.values = new Set(def.values);
    Object.defineProperty(inst, "value", {
        get() {
            if (def.values.length > 1) {
                throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
            }
            return def.values[0];
        },
    });
});
function literal(value, params) {
    return new ZodLiteral({
        type: "literal",
        values: Array.isArray(value) ? value : [value],
        ...normalizeParams(params),
    });
}
$constructor("ZodFile", (inst, def) => {
    $ZodFile.init(inst, def);
    ZodType.init(inst, def);
    inst.min = (size, params) => inst.check(_minSize(size, params));
    inst.max = (size, params) => inst.check(_maxSize(size, params));
    inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params));
});
const ZodTransform =  $constructor("ZodTransform", (inst, def) => {
    $ZodTransform.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
        payload.addIssue = (issue$1) => {
            if (typeof issue$1 === "string") {
                payload.issues.push(issue(issue$1, payload.value, def));
            }
            else {
                const _issue = issue$1;
                if (_issue.fatal)
                    _issue.continue = false;
                _issue.code ?? (_issue.code = "custom");
                _issue.input ?? (_issue.input = payload.value);
                _issue.inst ?? (_issue.inst = inst);
                _issue.continue ?? (_issue.continue = true);
                payload.issues.push(issue(_issue));
            }
        };
        const output = def.transform(payload.value, payload);
        if (output instanceof Promise) {
            return output.then((output) => {
                payload.value = output;
                return payload;
            });
        }
        payload.value = output;
        return payload;
    };
});
function transform(fn) {
    return new ZodTransform({
        type: "transform",
        transform: fn,
    });
}
const ZodOptional =  $constructor("ZodOptional", (inst, def) => {
    $ZodOptional.init(inst, def);
    ZodType.init(inst, def);
    inst.unwrap = () => inst._zod.def.innerType;
});
function optional(innerType) {
    return new ZodOptional({
        type: "optional",
        innerType: innerType,
    });
}
const ZodNullable =  $constructor("ZodNullable", (inst, def) => {
    $ZodNullable.init(inst, def);
    ZodType.init(inst, def);
    inst.unwrap = () => inst._zod.def.innerType;
});
function nullable(innerType) {
    return new ZodNullable({
        type: "nullable",
        innerType: innerType,
    });
}
const ZodDefault =  $constructor("ZodDefault", (inst, def) => {
    $ZodDefault.init(inst, def);
    ZodType.init(inst, def);
    inst.unwrap = () => inst._zod.def.innerType;
    inst.removeDefault = inst.unwrap;
});
function _default(innerType, defaultValue) {
    return new ZodDefault({
        type: "default",
        innerType: innerType,
        get defaultValue() {
            return typeof defaultValue === "function" ? defaultValue() : defaultValue;
        },
    });
}
const ZodPrefault =  $constructor("ZodPrefault", (inst, def) => {
    $ZodPrefault.init(inst, def);
    ZodType.init(inst, def);
    inst.unwrap = () => inst._zod.def.innerType;
});
function prefault(innerType, defaultValue) {
    return new ZodPrefault({
        type: "prefault",
        innerType: innerType,
        get defaultValue() {
            return typeof defaultValue === "function" ? defaultValue() : defaultValue;
        },
    });
}
const ZodNonOptional =  $constructor("ZodNonOptional", (inst, def) => {
    $ZodNonOptional.init(inst, def);
    ZodType.init(inst, def);
    inst.unwrap = () => inst._zod.def.innerType;
});
function nonoptional(innerType, params) {
    return new ZodNonOptional({
        type: "nonoptional",
        innerType: innerType,
        ...normalizeParams(params),
    });
}
$constructor("ZodSuccess", (inst, def) => {
    $ZodSuccess.init(inst, def);
    ZodType.init(inst, def);
    inst.unwrap = () => inst._zod.def.innerType;
});
const ZodCatch =  $constructor("ZodCatch", (inst, def) => {
    $ZodCatch.init(inst, def);
    ZodType.init(inst, def);
    inst.unwrap = () => inst._zod.def.innerType;
    inst.removeCatch = inst.unwrap;
});
function _catch(innerType, catchValue) {
    return new ZodCatch({
        type: "catch",
        innerType: innerType,
        catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue),
    });
}
$constructor("ZodNaN", (inst, def) => {
    $ZodNaN.init(inst, def);
    ZodType.init(inst, def);
});
const ZodPipe =  $constructor("ZodPipe", (inst, def) => {
    $ZodPipe.init(inst, def);
    ZodType.init(inst, def);
    inst.in = def.in;
    inst.out = def.out;
});
function pipe$1(in_, out) {
    return new ZodPipe({
        type: "pipe",
        in: in_,
        out: out,
    });
}
const ZodReadonly =  $constructor("ZodReadonly", (inst, def) => {
    $ZodReadonly.init(inst, def);
    ZodType.init(inst, def);
});
function readonly(innerType) {
    return new ZodReadonly({
        type: "readonly",
        innerType: innerType,
    });
}
$constructor("ZodTemplateLiteral", (inst, def) => {
    $ZodTemplateLiteral.init(inst, def);
    ZodType.init(inst, def);
});
$constructor("ZodLazy", (inst, def) => {
    $ZodLazy.init(inst, def);
    ZodType.init(inst, def);
    inst.unwrap = () => inst._zod.def.getter();
});
$constructor("ZodPromise", (inst, def) => {
    $ZodPromise.init(inst, def);
    ZodType.init(inst, def);
    inst.unwrap = () => inst._zod.def.innerType;
});
const ZodCustom =  $constructor("ZodCustom", (inst, def) => {
    $ZodCustom.init(inst, def);
    ZodType.init(inst, def);
});
function check(fn) {
    const ch = new $ZodCheck({
        check: "custom",
    });
    ch._zod.check = fn;
    return ch;
}
function custom(fn, _params) {
    return _custom(ZodCustom, fn ?? (() => true), _params);
}
function refine(fn, _params = {}) {
    return _refine(ZodCustom, fn, _params);
}
function superRefine(fn) {
    const ch = check((payload) => {
        payload.addIssue = (issue$1) => {
            if (typeof issue$1 === "string") {
                payload.issues.push(issue(issue$1, payload.value, ch._zod.def));
            }
            else {
                const _issue = issue$1;
                if (_issue.fatal)
                    _issue.continue = false;
                _issue.code ?? (_issue.code = "custom");
                _issue.input ?? (_issue.input = payload.value);
                _issue.inst ?? (_issue.inst = ch);
                _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
                payload.issues.push(issue(_issue));
            }
        };
        return fn(payload.value, payload);
    });
    return ch;
}
function preprocess(fn, schema) {
    return pipe$1(transform(fn), schema);
}

const LATEST_PROTOCOL_VERSION = '2025-11-25';
const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];
const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';
const JSONRPC_VERSION = '2.0';
const AssertObjectSchema = custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function'));
const ProgressTokenSchema = union([string(), number().int()]);
const CursorSchema = string();
looseObject({
    ttl: union([number(), _null()]).optional(),
    pollInterval: number().optional()
});
const TaskMetadataSchema = object({
    ttl: number().optional()
});
const RelatedTaskMetadataSchema = object({
    taskId: string()
});
const RequestMetaSchema = looseObject({
    progressToken: ProgressTokenSchema.optional(),
    [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
});
const BaseRequestParamsSchema = object({
    _meta: RequestMetaSchema.optional()
});
const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
    task: TaskMetadataSchema.optional()
});
const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
const RequestSchema = object({
    method: string(),
    params: BaseRequestParamsSchema.loose().optional()
});
const NotificationsParamsSchema = object({
    _meta: RequestMetaSchema.optional()
});
const NotificationSchema = object({
    method: string(),
    params: NotificationsParamsSchema.loose().optional()
});
const ResultSchema = looseObject({
    _meta: RequestMetaSchema.optional()
});
const RequestIdSchema = union([string(), number().int()]);
const JSONRPCRequestSchema = object({
    jsonrpc: literal(JSONRPC_VERSION),
    id: RequestIdSchema,
    ...RequestSchema.shape
})
    .strict();
const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
const JSONRPCNotificationSchema = object({
    jsonrpc: literal(JSONRPC_VERSION),
    ...NotificationSchema.shape
})
    .strict();
const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
const JSONRPCResultResponseSchema = object({
    jsonrpc: literal(JSONRPC_VERSION),
    id: RequestIdSchema,
    result: ResultSchema
})
    .strict();
const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
var ErrorCode$1;
(function (ErrorCode) {
    ErrorCode[ErrorCode["ConnectionClosed"] = -32e3] = "ConnectionClosed";
    ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout";
    ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError";
    ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest";
    ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound";
    ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams";
    ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError";
    ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
})(ErrorCode$1 || (ErrorCode$1 = {}));
const JSONRPCErrorResponseSchema = object({
    jsonrpc: literal(JSONRPC_VERSION),
    id: RequestIdSchema.optional(),
    error: object({
        code: number().int(),
        message: string(),
        data: unknown().optional()
    })
})
    .strict();
const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
const JSONRPCMessageSchema = union([
    JSONRPCRequestSchema,
    JSONRPCNotificationSchema,
    JSONRPCResultResponseSchema,
    JSONRPCErrorResponseSchema
]);
union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
const EmptyResultSchema = ResultSchema.strict();
const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
    requestId: RequestIdSchema.optional(),
    reason: string().optional()
});
const CancelledNotificationSchema = NotificationSchema.extend({
    method: literal('notifications/cancelled'),
    params: CancelledNotificationParamsSchema
});
const IconSchema = object({
    src: string(),
    mimeType: string().optional(),
    sizes: array(string()).optional(),
    theme: _enum$2(['light', 'dark']).optional()
});
const IconsSchema = object({
    icons: array(IconSchema).optional()
});
const BaseMetadataSchema = object({
    name: string(),
    title: string().optional()
});
const ImplementationSchema = BaseMetadataSchema.extend({
    ...BaseMetadataSchema.shape,
    ...IconsSchema.shape,
    version: string(),
    websiteUrl: string().optional(),
    description: string().optional()
});
const FormElicitationCapabilitySchema = intersection(object({
    applyDefaults: boolean().optional()
}), record(string(), unknown()));
const ElicitationCapabilitySchema = preprocess(value => {
    if (value && typeof value === 'object' && !Array.isArray(value)) {
        if (Object.keys(value).length === 0) {
            return { form: {} };
        }
    }
    return value;
}, intersection(object({
    form: FormElicitationCapabilitySchema.optional(),
    url: AssertObjectSchema.optional()
}), record(string(), unknown()).optional()));
const ClientTasksCapabilitySchema = looseObject({
    list: AssertObjectSchema.optional(),
    cancel: AssertObjectSchema.optional(),
    requests: looseObject({
        sampling: looseObject({
            createMessage: AssertObjectSchema.optional()
        })
            .optional(),
        elicitation: looseObject({
            create: AssertObjectSchema.optional()
        })
            .optional()
    })
        .optional()
});
const ServerTasksCapabilitySchema = looseObject({
    list: AssertObjectSchema.optional(),
    cancel: AssertObjectSchema.optional(),
    requests: looseObject({
        tools: looseObject({
            call: AssertObjectSchema.optional()
        })
            .optional()
    })
        .optional()
});
const ClientCapabilitiesSchema = object({
    experimental: record(string(), AssertObjectSchema).optional(),
    sampling: object({
        context: AssertObjectSchema.optional(),
        tools: AssertObjectSchema.optional()
    })
        .optional(),
    elicitation: ElicitationCapabilitySchema.optional(),
    roots: object({
        listChanged: boolean().optional()
    })
        .optional(),
    tasks: ClientTasksCapabilitySchema.optional()
});
const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
    protocolVersion: string(),
    capabilities: ClientCapabilitiesSchema,
    clientInfo: ImplementationSchema
});
const InitializeRequestSchema = RequestSchema.extend({
    method: literal('initialize'),
    params: InitializeRequestParamsSchema
});
const ServerCapabilitiesSchema = object({
    experimental: record(string(), AssertObjectSchema).optional(),
    logging: AssertObjectSchema.optional(),
    completions: AssertObjectSchema.optional(),
    prompts: object({
        listChanged: boolean().optional()
    })
        .optional(),
    resources: object({
        subscribe: boolean().optional(),
        listChanged: boolean().optional()
    })
        .optional(),
    tools: object({
        listChanged: boolean().optional()
    })
        .optional(),
    tasks: ServerTasksCapabilitySchema.optional()
});
const InitializeResultSchema = ResultSchema.extend({
    protocolVersion: string(),
    capabilities: ServerCapabilitiesSchema,
    serverInfo: ImplementationSchema,
    instructions: string().optional()
});
const InitializedNotificationSchema = NotificationSchema.extend({
    method: literal('notifications/initialized'),
    params: NotificationsParamsSchema.optional()
});
const PingRequestSchema = RequestSchema.extend({
    method: literal('ping'),
    params: BaseRequestParamsSchema.optional()
});
const ProgressSchema = object({
    progress: number(),
    total: optional(number()),
    message: optional(string())
});
const ProgressNotificationParamsSchema = object({
    ...NotificationsParamsSchema.shape,
    ...ProgressSchema.shape,
    progressToken: ProgressTokenSchema
});
const ProgressNotificationSchema = NotificationSchema.extend({
    method: literal('notifications/progress'),
    params: ProgressNotificationParamsSchema
});
const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
    cursor: CursorSchema.optional()
});
const PaginatedRequestSchema = RequestSchema.extend({
    params: PaginatedRequestParamsSchema.optional()
});
const PaginatedResultSchema = ResultSchema.extend({
    nextCursor: CursorSchema.optional()
});
const TaskStatusSchema = _enum$2(['working', 'input_required', 'completed', 'failed', 'cancelled']);
const TaskSchema = object({
    taskId: string(),
    status: TaskStatusSchema,
    ttl: union([number(), _null()]),
    createdAt: string(),
    lastUpdatedAt: string(),
    pollInterval: optional(number()),
    statusMessage: optional(string())
});
const CreateTaskResultSchema = ResultSchema.extend({
    task: TaskSchema
});
const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
const TaskStatusNotificationSchema = NotificationSchema.extend({
    method: literal('notifications/tasks/status'),
    params: TaskStatusNotificationParamsSchema
});
const GetTaskRequestSchema = RequestSchema.extend({
    method: literal('tasks/get'),
    params: BaseRequestParamsSchema.extend({
        taskId: string()
    })
});
const GetTaskResultSchema = ResultSchema.merge(TaskSchema);
const GetTaskPayloadRequestSchema = RequestSchema.extend({
    method: literal('tasks/result'),
    params: BaseRequestParamsSchema.extend({
        taskId: string()
    })
});
ResultSchema.loose();
const ListTasksRequestSchema = PaginatedRequestSchema.extend({
    method: literal('tasks/list')
});
const ListTasksResultSchema = PaginatedResultSchema.extend({
    tasks: array(TaskSchema)
});
const CancelTaskRequestSchema = RequestSchema.extend({
    method: literal('tasks/cancel'),
    params: BaseRequestParamsSchema.extend({
        taskId: string()
    })
});
const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
const ResourceContentsSchema = object({
    uri: string(),
    mimeType: optional(string()),
    _meta: record(string(), unknown()).optional()
});
const TextResourceContentsSchema = ResourceContentsSchema.extend({
    text: string()
});
const Base64Schema = string().refine(val => {
    try {
        atob(val);
        return true;
    }
    catch {
        return false;
    }
}, { message: 'Invalid Base64 string' });
const BlobResourceContentsSchema = ResourceContentsSchema.extend({
    blob: Base64Schema
});
const RoleSchema = _enum$2(['user', 'assistant']);
const AnnotationsSchema = object({
    audience: array(RoleSchema).optional(),
    priority: number().min(0).max(1).optional(),
    lastModified: datetime({ offset: true }).optional()
});
const ResourceSchema = object({
    ...BaseMetadataSchema.shape,
    ...IconsSchema.shape,
    uri: string(),
    description: optional(string()),
    mimeType: optional(string()),
    annotations: AnnotationsSchema.optional(),
    _meta: optional(looseObject({}))
});
const ResourceTemplateSchema = object({
    ...BaseMetadataSchema.shape,
    ...IconsSchema.shape,
    uriTemplate: string(),
    description: optional(string()),
    mimeType: optional(string()),
    annotations: AnnotationsSchema.optional(),
    _meta: optional(looseObject({}))
});
const ListResourcesRequestSchema = PaginatedRequestSchema.extend({
    method: literal('resources/list')
});
const ListResourcesResultSchema = PaginatedResultSchema.extend({
    resources: array(ResourceSchema)
});
const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
    method: literal('resources/templates/list')
});
const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
    resourceTemplates: array(ResourceTemplateSchema)
});
const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
    uri: string()
});
const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
const ReadResourceRequestSchema = RequestSchema.extend({
    method: literal('resources/read'),
    params: ReadResourceRequestParamsSchema
});
const ReadResourceResultSchema = ResultSchema.extend({
    contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
});
const ResourceListChangedNotificationSchema = NotificationSchema.extend({
    method: literal('notifications/resources/list_changed'),
    params: NotificationsParamsSchema.optional()
});
const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
const SubscribeRequestSchema = RequestSchema.extend({
    method: literal('resources/subscribe'),
    params: SubscribeRequestParamsSchema
});
const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
const UnsubscribeRequestSchema = RequestSchema.extend({
    method: literal('resources/unsubscribe'),
    params: UnsubscribeRequestParamsSchema
});
const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
    uri: string()
});
const ResourceUpdatedNotificationSchema = NotificationSchema.extend({
    method: literal('notifications/resources/updated'),
    params: ResourceUpdatedNotificationParamsSchema
});
const PromptArgumentSchema = object({
    name: string(),
    description: optional(string()),
    required: optional(boolean())
});
const PromptSchema = object({
    ...BaseMetadataSchema.shape,
    ...IconsSchema.shape,
    description: optional(string()),
    arguments: optional(array(PromptArgumentSchema)),
    _meta: optional(looseObject({}))
});
const ListPromptsRequestSchema = PaginatedRequestSchema.extend({
    method: literal('prompts/list')
});
const ListPromptsResultSchema = PaginatedResultSchema.extend({
    prompts: array(PromptSchema)
});
const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
    name: string(),
    arguments: record(string(), string()).optional()
});
const GetPromptRequestSchema = RequestSchema.extend({
    method: literal('prompts/get'),
    params: GetPromptRequestParamsSchema
});
const TextContentSchema = object({
    type: literal('text'),
    text: string(),
    annotations: AnnotationsSchema.optional(),
    _meta: record(string(), unknown()).optional()
});
const ImageContentSchema = object({
    type: literal('image'),
    data: Base64Schema,
    mimeType: string(),
    annotations: AnnotationsSchema.optional(),
    _meta: record(string(), unknown()).optional()
});
const AudioContentSchema = object({
    type: literal('audio'),
    data: Base64Schema,
    mimeType: string(),
    annotations: AnnotationsSchema.optional(),
    _meta: record(string(), unknown()).optional()
});
const ToolUseContentSchema = object({
    type: literal('tool_use'),
    name: string(),
    id: string(),
    input: record(string(), unknown()),
    _meta: record(string(), unknown()).optional()
});
const EmbeddedResourceSchema = object({
    type: literal('resource'),
    resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
    annotations: AnnotationsSchema.optional(),
    _meta: record(string(), unknown()).optional()
});
const ResourceLinkSchema = ResourceSchema.extend({
    type: literal('resource_link')
});
const ContentBlockSchema = union([
    TextContentSchema,
    ImageContentSchema,
    AudioContentSchema,
    ResourceLinkSchema,
    EmbeddedResourceSchema
]);
const PromptMessageSchema = object({
    role: RoleSchema,
    content: ContentBlockSchema
});
const GetPromptResultSchema = ResultSchema.extend({
    description: string().optional(),
    messages: array(PromptMessageSchema)
});
const PromptListChangedNotificationSchema = NotificationSchema.extend({
    method: literal('notifications/prompts/list_changed'),
    params: NotificationsParamsSchema.optional()
});
const ToolAnnotationsSchema = object({
    title: string().optional(),
    readOnlyHint: boolean().optional(),
    destructiveHint: boolean().optional(),
    idempotentHint: boolean().optional(),
    openWorldHint: boolean().optional()
});
const ToolExecutionSchema = object({
    taskSupport: _enum$2(['required', 'optional', 'forbidden']).optional()
});
const ToolSchema = object({
    ...BaseMetadataSchema.shape,
    ...IconsSchema.shape,
    description: string().optional(),
    inputSchema: object({
        type: literal('object'),
        properties: record(string(), AssertObjectSchema).optional(),
        required: array(string()).optional()
    })
        .catchall(unknown()),
    outputSchema: object({
        type: literal('object'),
        properties: record(string(), AssertObjectSchema).optional(),
        required: array(string()).optional()
    })
        .catchall(unknown())
        .optional(),
    annotations: ToolAnnotationsSchema.optional(),
    execution: ToolExecutionSchema.optional(),
    _meta: record(string(), unknown()).optional()
});
const ListToolsRequestSchema = PaginatedRequestSchema.extend({
    method: literal('tools/list')
});
const ListToolsResultSchema = PaginatedResultSchema.extend({
    tools: array(ToolSchema)
});
const CallToolResultSchema = ResultSchema.extend({
    content: array(ContentBlockSchema).default([]),
    structuredContent: record(string(), unknown()).optional(),
    isError: boolean().optional()
});
CallToolResultSchema.or(ResultSchema.extend({
    toolResult: unknown()
}));
const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
    name: string(),
    arguments: record(string(), unknown()).optional()
});
const CallToolRequestSchema = RequestSchema.extend({
    method: literal('tools/call'),
    params: CallToolRequestParamsSchema
});
const ToolListChangedNotificationSchema = NotificationSchema.extend({
    method: literal('notifications/tools/list_changed'),
    params: NotificationsParamsSchema.optional()
});
const ListChangedOptionsBaseSchema = object({
    autoRefresh: boolean().default(true),
    debounceMs: number().int().nonnegative().default(300)
});
const LoggingLevelSchema = _enum$2(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);
const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
    level: LoggingLevelSchema
});
const SetLevelRequestSchema = RequestSchema.extend({
    method: literal('logging/setLevel'),
    params: SetLevelRequestParamsSchema
});
const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
    level: LoggingLevelSchema,
    logger: string().optional(),
    data: unknown()
});
const LoggingMessageNotificationSchema = NotificationSchema.extend({
    method: literal('notifications/message'),
    params: LoggingMessageNotificationParamsSchema
});
const ModelHintSchema = object({
    name: string().optional()
});
const ModelPreferencesSchema = object({
    hints: array(ModelHintSchema).optional(),
    costPriority: number().min(0).max(1).optional(),
    speedPriority: number().min(0).max(1).optional(),
    intelligencePriority: number().min(0).max(1).optional()
});
const ToolChoiceSchema = object({
    mode: _enum$2(['auto', 'required', 'none']).optional()
});
const ToolResultContentSchema = object({
    type: literal('tool_result'),
    toolUseId: string().describe('The unique identifier for the corresponding tool call.'),
    content: array(ContentBlockSchema).default([]),
    structuredContent: object({}).loose().optional(),
    isError: boolean().optional(),
    _meta: record(string(), unknown()).optional()
});
const SamplingContentSchema = discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);
const SamplingMessageContentBlockSchema = discriminatedUnion('type', [
    TextContentSchema,
    ImageContentSchema,
    AudioContentSchema,
    ToolUseContentSchema,
    ToolResultContentSchema
]);
const SamplingMessageSchema = object({
    role: RoleSchema,
    content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
    _meta: record(string(), unknown()).optional()
});
const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
    messages: array(SamplingMessageSchema),
    modelPreferences: ModelPreferencesSchema.optional(),
    systemPrompt: string().optional(),
    includeContext: _enum$2(['none', 'thisServer', 'allServers']).optional(),
    temperature: number().optional(),
    maxTokens: number().int(),
    stopSequences: array(string()).optional(),
    metadata: AssertObjectSchema.optional(),
    tools: array(ToolSchema).optional(),
    toolChoice: ToolChoiceSchema.optional()
});
const CreateMessageRequestSchema = RequestSchema.extend({
    method: literal('sampling/createMessage'),
    params: CreateMessageRequestParamsSchema
});
const CreateMessageResultSchema = ResultSchema.extend({
    model: string(),
    stopReason: optional(_enum$2(['endTurn', 'stopSequence', 'maxTokens']).or(string())),
    role: RoleSchema,
    content: SamplingContentSchema
});
const CreateMessageResultWithToolsSchema = ResultSchema.extend({
    model: string(),
    stopReason: optional(_enum$2(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(string())),
    role: RoleSchema,
    content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
});
const BooleanSchemaSchema = object({
    type: literal('boolean'),
    title: string().optional(),
    description: string().optional(),
    default: boolean().optional()
});
const StringSchemaSchema = object({
    type: literal('string'),
    title: string().optional(),
    description: string().optional(),
    minLength: number().optional(),
    maxLength: number().optional(),
    format: _enum$2(['email', 'uri', 'date', 'date-time']).optional(),
    default: string().optional()
});
const NumberSchemaSchema = object({
    type: _enum$2(['number', 'integer']),
    title: string().optional(),
    description: string().optional(),
    minimum: number().optional(),
    maximum: number().optional(),
    default: number().optional()
});
const UntitledSingleSelectEnumSchemaSchema = object({
    type: literal('string'),
    title: string().optional(),
    description: string().optional(),
    enum: array(string()),
    default: string().optional()
});
const TitledSingleSelectEnumSchemaSchema = object({
    type: literal('string'),
    title: string().optional(),
    description: string().optional(),
    oneOf: array(object({
        const: string(),
        title: string()
    })),
    default: string().optional()
});
const LegacyTitledEnumSchemaSchema = object({
    type: literal('string'),
    title: string().optional(),
    description: string().optional(),
    enum: array(string()),
    enumNames: array(string()).optional(),
    default: string().optional()
});
const SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
const UntitledMultiSelectEnumSchemaSchema = object({
    type: literal('array'),
    title: string().optional(),
    description: string().optional(),
    minItems: number().optional(),
    maxItems: number().optional(),
    items: object({
        type: literal('string'),
        enum: array(string())
    }),
    default: array(string()).optional()
});
const TitledMultiSelectEnumSchemaSchema = object({
    type: literal('array'),
    title: string().optional(),
    description: string().optional(),
    minItems: number().optional(),
    maxItems: number().optional(),
    items: object({
        anyOf: array(object({
            const: string(),
            title: string()
        }))
    }),
    default: array(string()).optional()
});
const MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
const EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
const PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
    mode: literal('form').optional(),
    message: string(),
    requestedSchema: object({
        type: literal('object'),
        properties: record(string(), PrimitiveSchemaDefinitionSchema),
        required: array(string()).optional()
    })
});
const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
    mode: literal('url'),
    message: string(),
    elicitationId: string(),
    url: string().url()
});
const ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
const ElicitRequestSchema = RequestSchema.extend({
    method: literal('elicitation/create'),
    params: ElicitRequestParamsSchema
});
const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
    elicitationId: string()
});
const ElicitationCompleteNotificationSchema = NotificationSchema.extend({
    method: literal('notifications/elicitation/complete'),
    params: ElicitationCompleteNotificationParamsSchema
});
const ElicitResultSchema = ResultSchema.extend({
    action: _enum$2(['accept', 'decline', 'cancel']),
    content: preprocess(val => (val === null ? undefined : val), record(string(), union([string(), number(), boolean(), array(string())])).optional())
});
const ResourceTemplateReferenceSchema = object({
    type: literal('ref/resource'),
    uri: string()
});
const PromptReferenceSchema = object({
    type: literal('ref/prompt'),
    name: string()
});
const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
    ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
    argument: object({
        name: string(),
        value: string()
    }),
    context: object({
        arguments: record(string(), string()).optional()
    })
        .optional()
});
const CompleteRequestSchema = RequestSchema.extend({
    method: literal('completion/complete'),
    params: CompleteRequestParamsSchema
});
function assertCompleteRequestPrompt(request) {
    if (request.params.ref.type !== 'ref/prompt') {
        throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);
    }
}
function assertCompleteRequestResourceTemplate(request) {
    if (request.params.ref.type !== 'ref/resource') {
        throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);
    }
}
const CompleteResultSchema = ResultSchema.extend({
    completion: looseObject({
        values: array(string()).max(100),
        total: optional(number().int()),
        hasMore: optional(boolean())
    })
});
const RootSchema = object({
    uri: string().startsWith('file://'),
    name: string().optional(),
    _meta: record(string(), unknown()).optional()
});
const ListRootsRequestSchema = RequestSchema.extend({
    method: literal('roots/list'),
    params: BaseRequestParamsSchema.optional()
});
const ListRootsResultSchema = ResultSchema.extend({
    roots: array(RootSchema)
});
const RootsListChangedNotificationSchema = NotificationSchema.extend({
    method: literal('notifications/roots/list_changed'),
    params: NotificationsParamsSchema.optional()
});
union([
    PingRequestSchema,
    InitializeRequestSchema,
    CompleteRequestSchema,
    SetLevelRequestSchema,
    GetPromptRequestSchema,
    ListPromptsRequestSchema,
    ListResourcesRequestSchema,
    ListResourceTemplatesRequestSchema,
    ReadResourceRequestSchema,
    SubscribeRequestSchema,
    UnsubscribeRequestSchema,
    CallToolRequestSchema,
    ListToolsRequestSchema,
    GetTaskRequestSchema,
    GetTaskPayloadRequestSchema,
    ListTasksRequestSchema,
    CancelTaskRequestSchema
]);
union([
    CancelledNotificationSchema,
    ProgressNotificationSchema,
    InitializedNotificationSchema,
    RootsListChangedNotificationSchema,
    TaskStatusNotificationSchema
]);
union([
    EmptyResultSchema,
    CreateMessageResultSchema,
    CreateMessageResultWithToolsSchema,
    ElicitResultSchema,
    ListRootsResultSchema,
    GetTaskResultSchema,
    ListTasksResultSchema,
    CreateTaskResultSchema
]);
union([
    PingRequestSchema,
    CreateMessageRequestSchema,
    ElicitRequestSchema,
    ListRootsRequestSchema,
    GetTaskRequestSchema,
    GetTaskPayloadRequestSchema,
    ListTasksRequestSchema,
    CancelTaskRequestSchema
]);
union([
    CancelledNotificationSchema,
    ProgressNotificationSchema,
    LoggingMessageNotificationSchema,
    ResourceUpdatedNotificationSchema,
    ResourceListChangedNotificationSchema,
    ToolListChangedNotificationSchema,
    PromptListChangedNotificationSchema,
    TaskStatusNotificationSchema,
    ElicitationCompleteNotificationSchema
]);
union([
    EmptyResultSchema,
    InitializeResultSchema,
    CompleteResultSchema,
    GetPromptResultSchema,
    ListPromptsResultSchema,
    ListResourcesResultSchema,
    ListResourceTemplatesResultSchema,
    ReadResourceResultSchema,
    CallToolResultSchema,
    ListToolsResultSchema,
    GetTaskResultSchema,
    ListTasksResultSchema,
    CreateTaskResultSchema
]);
class McpError extends Error {
    constructor(code, message, data) {
        super(`MCP error ${code}: ${message}`);
        this.code = code;
        this.data = data;
        this.name = 'McpError';
    }
    static fromError(code, message, data) {
        if (code === ErrorCode$1.UrlElicitationRequired && data) {
            const errorData = data;
            if (errorData.elicitations) {
                return new UrlElicitationRequiredError(errorData.elicitations, message);
            }
        }
        return new McpError(code, message, data);
    }
}
class UrlElicitationRequiredError extends McpError {
    constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {
        super(ErrorCode$1.UrlElicitationRequired, message, {
            elicitations: elicitations
        });
    }
    get elicitations() {
        return this.data?.elicitations ?? [];
    }
}

function isTerminal(status) {
    return status === 'completed' || status === 'failed' || status === 'cancelled';
}

const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
const defaultOptions = {
    name: undefined,
    $refStrategy: "root",
    basePath: ["#"],
    effectStrategy: "input",
    pipeStrategy: "all",
    dateStrategy: "format:date-time",
    mapStrategy: "entries",
    removeAdditionalStrategy: "passthrough",
    allowedAdditionalProperties: true,
    rejectedAdditionalProperties: false,
    definitionPath: "definitions",
    target: "jsonSchema7",
    strictUnions: false,
    definitions: {},
    errorMessages: false,
    markdownDescription: false,
    patternStrategy: "escape",
    applyRegexFlags: false,
    emailStrategy: "format:email",
    base64Strategy: "contentEncoding:base64",
    nameStrategy: "ref",
    openAiAnyTypeName: "OpenAiAnyType"
};
const getDefaultOptions = (options) => (typeof options === "string"
    ? {
        ...defaultOptions,
        name: options,
    }
    : {
        ...defaultOptions,
        ...options,
    });

const getRefs = (options) => {
    const _options = getDefaultOptions(options);
    const currentPath = _options.name !== undefined
        ? [..._options.basePath, _options.definitionPath, _options.name]
        : _options.basePath;
    return {
        ..._options,
        flags: { hasReferencedOpenAiAnyType: false },
        currentPath: currentPath,
        propertyPath: undefined,
        seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
            def._def,
            {
                def: def._def,
                path: [..._options.basePath, _options.definitionPath, name],
                jsonSchema: undefined,
            },
        ])),
    };
};

function addErrorMessage(res, key, errorMessage, refs) {
    if (!refs?.errorMessages)
        return;
    if (errorMessage) {
        res.errorMessage = {
            ...res.errorMessage,
            [key]: errorMessage,
        };
    }
}
function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
    res[key] = value;
    addErrorMessage(res, key, errorMessage, refs);
}

const getRelativePath = (pathA, pathB) => {
    let i = 0;
    for (; i < pathA.length && i < pathB.length; i++) {
        if (pathA[i] !== pathB[i])
            break;
    }
    return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
};

function parseAnyDef(refs) {
    if (refs.target !== "openAi") {
        return {};
    }
    const anyDefinitionPath = [
        ...refs.basePath,
        refs.definitionPath,
        refs.openAiAnyTypeName,
    ];
    refs.flags.hasReferencedOpenAiAnyType = true;
    return {
        $ref: refs.$refStrategy === "relative"
            ? getRelativePath(anyDefinitionPath, refs.currentPath)
            : anyDefinitionPath.join("/"),
    };
}

function parseArrayDef(def, refs) {
    const res = {
        type: "array",
    };
    if (def.type?._def &&
        def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
        res.items = parseDef(def.type._def, {
            ...refs,
            currentPath: [...refs.currentPath, "items"],
        });
    }
    if (def.minLength) {
        setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
    }
    if (def.maxLength) {
        setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
    }
    if (def.exactLength) {
        setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
        setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
    }
    return res;
}

function parseBigintDef(def, refs) {
    const res = {
        type: "integer",
        format: "int64",
    };
    if (!def.checks)
        return res;
    for (const check of def.checks) {
        switch (check.kind) {
            case "min":
                if (refs.target === "jsonSchema7") {
                    if (check.inclusive) {
                        setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
                    }
                    else {
                        setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
                    }
                }
                else {
                    if (!check.inclusive) {
                        res.exclusiveMinimum = true;
                    }
                    setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
                }
                break;
            case "max":
                if (refs.target === "jsonSchema7") {
                    if (check.inclusive) {
                        setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
                    }
                    else {
                        setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
                    }
                }
                else {
                    if (!check.inclusive) {
                        res.exclusiveMaximum = true;
                    }
                    setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
                }
                break;
            case "multipleOf":
                setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
                break;
        }
    }
    return res;
}

function parseBooleanDef() {
    return {
        type: "boolean",
    };
}

function parseBrandedDef(_def, refs) {
    return parseDef(_def.type._def, refs);
}

const parseCatchDef = (def, refs) => {
    return parseDef(def.innerType._def, refs);
};

function parseDateDef(def, refs, overrideDateStrategy) {
    const strategy = overrideDateStrategy ?? refs.dateStrategy;
    if (Array.isArray(strategy)) {
        return {
            anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),
        };
    }
    switch (strategy) {
        case "string":
        case "format:date-time":
            return {
                type: "string",
                format: "date-time",
            };
        case "format:date":
            return {
                type: "string",
                format: "date",
            };
        case "integer":
            return integerDateParser(def, refs);
    }
}
const integerDateParser = (def, refs) => {
    const res = {
        type: "integer",
        format: "unix-time",
    };
    if (refs.target === "openApi3") {
        return res;
    }
    for (const check of def.checks) {
        switch (check.kind) {
            case "min":
                setResponseValueAndErrors(res, "minimum", check.value,
                check.message, refs);
                break;
            case "max":
                setResponseValueAndErrors(res, "maximum", check.value,
                check.message, refs);
                break;
        }
    }
    return res;
};

function parseDefaultDef(_def, refs) {
    return {
        ...parseDef(_def.innerType._def, refs),
        default: _def.defaultValue(),
    };
}

function parseEffectsDef(_def, refs) {
    return refs.effectStrategy === "input"
        ? parseDef(_def.schema._def, refs)
        : parseAnyDef(refs);
}

function parseEnumDef(def) {
    return {
        type: "string",
        enum: Array.from(def.values),
    };
}

const isJsonSchema7AllOfType = (type) => {
    if ("type" in type && type.type === "string")
        return false;
    return "allOf" in type;
};
function parseIntersectionDef(def, refs) {
    const allOf = [
        parseDef(def.left._def, {
            ...refs,
            currentPath: [...refs.currentPath, "allOf", "0"],
        }),
        parseDef(def.right._def, {
            ...refs,
            currentPath: [...refs.currentPath, "allOf", "1"],
        }),
    ].filter((x) => !!x);
    let unevaluatedProperties = refs.target === "jsonSchema2019-09"
        ? { unevaluatedProperties: false }
        : undefined;
    const mergedAllOf = [];
    allOf.forEach((schema) => {
        if (isJsonSchema7AllOfType(schema)) {
            mergedAllOf.push(...schema.allOf);
            if (schema.unevaluatedProperties === undefined) {
                unevaluatedProperties = undefined;
            }
        }
        else {
            let nestedSchema = schema;
            if ("additionalProperties" in schema &&
                schema.additionalProperties === false) {
                const { additionalProperties, ...rest } = schema;
                nestedSchema = rest;
            }
            else {
                unevaluatedProperties = undefined;
            }
            mergedAllOf.push(nestedSchema);
        }
    });
    return mergedAllOf.length
        ? {
            allOf: mergedAllOf,
            ...unevaluatedProperties,
        }
        : undefined;
}

function parseLiteralDef(def, refs) {
    const parsedType = typeof def.value;
    if (parsedType !== "bigint" &&
        parsedType !== "number" &&
        parsedType !== "boolean" &&
        parsedType !== "string") {
        return {
            type: Array.isArray(def.value) ? "array" : "object",
        };
    }
    if (refs.target === "openApi3") {
        return {
            type: parsedType === "bigint" ? "integer" : parsedType,
            enum: [def.value],
        };
    }
    return {
        type: parsedType === "bigint" ? "integer" : parsedType,
        const: def.value,
    };
}

let emojiRegex = undefined;
const zodPatterns = {
    cuid: /^[cC][^\s-]{8,}$/,
    cuid2: /^[0-9a-z]+$/,
    ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
    email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
    emoji: () => {
        if (emojiRegex === undefined) {
            emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
        }
        return emojiRegex;
    },
    uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
    ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
    ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
    ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
    ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
    base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
    base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
    nanoid: /^[a-zA-Z0-9_-]{21}$/,
    jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,
};
function parseStringDef(def, refs) {
    const res = {
        type: "string",
    };
    if (def.checks) {
        for (const check of def.checks) {
            switch (check.kind) {
                case "min":
                    setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number"
                        ? Math.max(res.minLength, check.value)
                        : check.value, check.message, refs);
                    break;
                case "max":
                    setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number"
                        ? Math.min(res.maxLength, check.value)
                        : check.value, check.message, refs);
                    break;
                case "email":
                    switch (refs.emailStrategy) {
                        case "format:email":
                            addFormat(res, "email", check.message, refs);
                            break;
                        case "format:idn-email":
                            addFormat(res, "idn-email", check.message, refs);
                            break;
                        case "pattern:zod":
                            addPattern(res, zodPatterns.email, check.message, refs);
                            break;
                    }
                    break;
                case "url":
                    addFormat(res, "uri", check.message, refs);
                    break;
                case "uuid":
                    addFormat(res, "uuid", check.message, refs);
                    break;
                case "regex":
                    addPattern(res, check.regex, check.message, refs);
                    break;
                case "cuid":
                    addPattern(res, zodPatterns.cuid, check.message, refs);
                    break;
                case "cuid2":
                    addPattern(res, zodPatterns.cuid2, check.message, refs);
                    break;
                case "startsWith":
                    addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
                    break;
                case "endsWith":
                    addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
                    break;
                case "datetime":
                    addFormat(res, "date-time", check.message, refs);
                    break;
                case "date":
                    addFormat(res, "date", check.message, refs);
                    break;
                case "time":
                    addFormat(res, "time", check.message, refs);
                    break;
                case "duration":
                    addFormat(res, "duration", check.message, refs);
                    break;
                case "length":
                    setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number"
                        ? Math.max(res.minLength, check.value)
                        : check.value, check.message, refs);
                    setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number"
                        ? Math.min(res.maxLength, check.value)
                        : check.value, check.message, refs);
                    break;
                case "includes": {
                    addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
                    break;
                }
                case "ip": {
                    if (check.version !== "v6") {
                        addFormat(res, "ipv4", check.message, refs);
                    }
                    if (check.version !== "v4") {
                        addFormat(res, "ipv6", check.message, refs);
                    }
                    break;
                }
                case "base64url":
                    addPattern(res, zodPatterns.base64url, check.message, refs);
                    break;
                case "jwt":
                    addPattern(res, zodPatterns.jwt, check.message, refs);
                    break;
                case "cidr": {
                    if (check.version !== "v6") {
                        addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
                    }
                    if (check.version !== "v4") {
                        addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
                    }
                    break;
                }
                case "emoji":
                    addPattern(res, zodPatterns.emoji(), check.message, refs);
                    break;
                case "ulid": {
                    addPattern(res, zodPatterns.ulid, check.message, refs);
                    break;
                }
                case "base64": {
                    switch (refs.base64Strategy) {
                        case "format:binary": {
                            addFormat(res, "binary", check.message, refs);
                            break;
                        }
                        case "contentEncoding:base64": {
                            setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
                            break;
                        }
                        case "pattern:zod": {
                            addPattern(res, zodPatterns.base64, check.message, refs);
                            break;
                        }
                    }
                    break;
                }
                case "nanoid": {
                    addPattern(res, zodPatterns.nanoid, check.message, refs);
                }
            }
        }
    }
    return res;
}
function escapeLiteralCheckValue(literal, refs) {
    return refs.patternStrategy === "escape"
        ? escapeNonAlphaNumeric(literal)
        : literal;
}
const ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function escapeNonAlphaNumeric(source) {
    let result = "";
    for (let i = 0; i < source.length; i++) {
        if (!ALPHA_NUMERIC.has(source[i])) {
            result += "\\";
        }
        result += source[i];
    }
    return result;
}
function addFormat(schema, value, message, refs) {
    if (schema.format || schema.anyOf?.some((x) => x.format)) {
        if (!schema.anyOf) {
            schema.anyOf = [];
        }
        if (schema.format) {
            schema.anyOf.push({
                format: schema.format,
                ...(schema.errorMessage &&
                    refs.errorMessages && {
                    errorMessage: { format: schema.errorMessage.format },
                }),
            });
            delete schema.format;
            if (schema.errorMessage) {
                delete schema.errorMessage.format;
                if (Object.keys(schema.errorMessage).length === 0) {
                    delete schema.errorMessage;
                }
            }
        }
        schema.anyOf.push({
            format: value,
            ...(message &&
                refs.errorMessages && { errorMessage: { format: message } }),
        });
    }
    else {
        setResponseValueAndErrors(schema, "format", value, message, refs);
    }
}
function addPattern(schema, regex, message, refs) {
    if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
        if (!schema.allOf) {
            schema.allOf = [];
        }
        if (schema.pattern) {
            schema.allOf.push({
                pattern: schema.pattern,
                ...(schema.errorMessage &&
                    refs.errorMessages && {
                    errorMessage: { pattern: schema.errorMessage.pattern },
                }),
            });
            delete schema.pattern;
            if (schema.errorMessage) {
                delete schema.errorMessage.pattern;
                if (Object.keys(schema.errorMessage).length === 0) {
                    delete schema.errorMessage;
                }
            }
        }
        schema.allOf.push({
            pattern: stringifyRegExpWithFlags(regex, refs),
            ...(message &&
                refs.errorMessages && { errorMessage: { pattern: message } }),
        });
    }
    else {
        setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
    }
}
function stringifyRegExpWithFlags(regex, refs) {
    if (!refs.applyRegexFlags || !regex.flags) {
        return regex.source;
    }
    const flags = {
        i: regex.flags.includes("i"),
        m: regex.flags.includes("m"),
        s: regex.flags.includes("s"),
    };
    const source = flags.i ? regex.source.toLowerCase() : regex.source;
    let pattern = "";
    let isEscaped = false;
    let inCharGroup = false;
    let inCharRange = false;
    for (let i = 0; i < source.length; i++) {
        if (isEscaped) {
            pattern += source[i];
            isEscaped = false;
            continue;
        }
        if (flags.i) {
            if (inCharGroup) {
                if (source[i].match(/[a-z]/)) {
                    if (inCharRange) {
                        pattern += source[i];
                        pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
                        inCharRange = false;
                    }
                    else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
                        pattern += source[i];
                        inCharRange = true;
                    }
                    else {
                        pattern += `${source[i]}${source[i].toUpperCase()}`;
                    }
                    continue;
                }
            }
            else if (source[i].match(/[a-z]/)) {
                pattern += `[${source[i]}${source[i].toUpperCase()}]`;
                continue;
            }
        }
        if (flags.m) {
            if (source[i] === "^") {
                pattern += `(^|(?<=[\r\n]))`;
                continue;
            }
            else if (source[i] === "$") {
                pattern += `($|(?=[\r\n]))`;
                continue;
            }
        }
        if (flags.s && source[i] === ".") {
            pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`;
            continue;
        }
        pattern += source[i];
        if (source[i] === "\\") {
            isEscaped = true;
        }
        else if (inCharGroup && source[i] === "]") {
            inCharGroup = false;
        }
        else if (!inCharGroup && source[i] === "[") {
            inCharGroup = true;
        }
    }
    try {
        new RegExp(pattern);
    }
    catch {
        console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
        return regex.source;
    }
    return pattern;
}

function parseRecordDef(def, refs) {
    if (refs.target === "openAi") {
        console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
    }
    if (refs.target === "openApi3" &&
        def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
        return {
            type: "object",
            required: def.keyType._def.values,
            properties: def.keyType._def.values.reduce((acc, key) => ({
                ...acc,
                [key]: parseDef(def.valueType._def, {
                    ...refs,
                    currentPath: [...refs.currentPath, "properties", key],
                }) ?? parseAnyDef(refs),
            }), {}),
            additionalProperties: refs.rejectedAdditionalProperties,
        };
    }
    const schema = {
        type: "object",
        additionalProperties: parseDef(def.valueType._def, {
            ...refs,
            currentPath: [...refs.currentPath, "additionalProperties"],
        }) ?? refs.allowedAdditionalProperties,
    };
    if (refs.target === "openApi3") {
        return schema;
    }
    if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString &&
        def.keyType._def.checks?.length) {
        const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
        return {
            ...schema,
            propertyNames: keyType,
        };
    }
    else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
        return {
            ...schema,
            propertyNames: {
                enum: def.keyType._def.values,
            },
        };
    }
    else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded &&
        def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString &&
        def.keyType._def.type._def.checks?.length) {
        const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
        return {
            ...schema,
            propertyNames: keyType,
        };
    }
    return schema;
}

function parseMapDef(def, refs) {
    if (refs.mapStrategy === "record") {
        return parseRecordDef(def, refs);
    }
    const keys = parseDef(def.keyType._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", "items", "0"],
    }) || parseAnyDef(refs);
    const values = parseDef(def.valueType._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", "items", "1"],
    }) || parseAnyDef(refs);
    return {
        type: "array",
        maxItems: 125,
        items: {
            type: "array",
            items: [keys, values],
            minItems: 2,
            maxItems: 2,
        },
    };
}

function parseNativeEnumDef(def) {
    const object = def.values;
    const actualKeys = Object.keys(def.values).filter((key) => {
        return typeof object[object[key]] !== "number";
    });
    const actualValues = actualKeys.map((key) => object[key]);
    const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
    return {
        type: parsedTypes.length === 1
            ? parsedTypes[0] === "string"
                ? "string"
                : "number"
            : ["string", "number"],
        enum: actualValues,
    };
}

function parseNeverDef(refs) {
    return refs.target === "openAi"
        ? undefined
        : {
            not: parseAnyDef({
                ...refs,
                currentPath: [...refs.currentPath, "not"],
            }),
        };
}

function parseNullDef(refs) {
    return refs.target === "openApi3"
        ? {
            enum: ["null"],
            nullable: true,
        }
        : {
            type: "null",
        };
}

const primitiveMappings = {
    ZodString: "string",
    ZodNumber: "number",
    ZodBigInt: "integer",
    ZodBoolean: "boolean",
    ZodNull: "null",
};
function parseUnionDef(def, refs) {
    if (refs.target === "openApi3")
        return asAnyOf(def, refs);
    const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
    if (options.every((x) => x._def.typeName in primitiveMappings &&
        (!x._def.checks || !x._def.checks.length))) {
        const types = options.reduce((types, x) => {
            const type = primitiveMappings[x._def.typeName];
            return type && !types.includes(type) ? [...types, type] : types;
        }, []);
        return {
            type: types.length > 1 ? types : types[0],
        };
    }
    else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
        const types = options.reduce((acc, x) => {
            const type = typeof x._def.value;
            switch (type) {
                case "string":
                case "number":
                case "boolean":
                    return [...acc, type];
                case "bigint":
                    return [...acc, "integer"];
                case "object":
                    if (x._def.value === null)
                        return [...acc, "null"];
                case "symbol":
                case "undefined":
                case "function":
                default:
                    return acc;
            }
        }, []);
        if (types.length === options.length) {
            const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
            return {
                type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
                enum: options.reduce((acc, x) => {
                    return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
                }, []),
            };
        }
    }
    else if (options.every((x) => x._def.typeName === "ZodEnum")) {
        return {
            type: "string",
            enum: options.reduce((acc, x) => [
                ...acc,
                ...x._def.values.filter((x) => !acc.includes(x)),
            ], []),
        };
    }
    return asAnyOf(def, refs);
}
const asAnyOf = (def, refs) => {
    const anyOf = (def.options instanceof Map
        ? Array.from(def.options.values())
        : def.options)
        .map((x, i) => parseDef(x._def, {
        ...refs,
        currentPath: [...refs.currentPath, "anyOf", `${i}`],
    }))
        .filter((x) => !!x &&
        (!refs.strictUnions ||
            (typeof x === "object" && Object.keys(x).length > 0)));
    return anyOf.length ? { anyOf } : undefined;
};

function parseNullableDef(def, refs) {
    if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) &&
        (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
        if (refs.target === "openApi3") {
            return {
                type: primitiveMappings[def.innerType._def.typeName],
                nullable: true,
            };
        }
        return {
            type: [
                primitiveMappings[def.innerType._def.typeName],
                "null",
            ],
        };
    }
    if (refs.target === "openApi3") {
        const base = parseDef(def.innerType._def, {
            ...refs,
            currentPath: [...refs.currentPath],
        });
        if (base && "$ref" in base)
            return { allOf: [base], nullable: true };
        return base && { ...base, nullable: true };
    }
    const base = parseDef(def.innerType._def, {
        ...refs,
        currentPath: [...refs.currentPath, "anyOf", "0"],
    });
    return base && { anyOf: [base, { type: "null" }] };
}

function parseNumberDef(def, refs) {
    const res = {
        type: "number",
    };
    if (!def.checks)
        return res;
    for (const check of def.checks) {
        switch (check.kind) {
            case "int":
                res.type = "integer";
                addErrorMessage(res, "type", check.message, refs);
                break;
            case "min":
                if (refs.target === "jsonSchema7") {
                    if (check.inclusive) {
                        setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
                    }
                    else {
                        setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
                    }
                }
                else {
                    if (!check.inclusive) {
                        res.exclusiveMinimum = true;
                    }
                    setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
                }
                break;
            case "max":
                if (refs.target === "jsonSchema7") {
                    if (check.inclusive) {
                        setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
                    }
                    else {
                        setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
                    }
                }
                else {
                    if (!check.inclusive) {
                        res.exclusiveMaximum = true;
                    }
                    setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
                }
                break;
            case "multipleOf":
                setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
                break;
        }
    }
    return res;
}

function parseObjectDef(def, refs) {
    const forceOptionalIntoNullable = refs.target === "openAi";
    const result = {
        type: "object",
        properties: {},
    };
    const required = [];
    const shape = def.shape();
    for (const propName in shape) {
        let propDef = shape[propName];
        if (propDef === undefined || propDef._def === undefined) {
            continue;
        }
        let propOptional = safeIsOptional(propDef);
        if (propOptional && forceOptionalIntoNullable) {
            if (propDef._def.typeName === "ZodOptional") {
                propDef = propDef._def.innerType;
            }
            if (!propDef.isNullable()) {
                propDef = propDef.nullable();
            }
            propOptional = false;
        }
        const parsedDef = parseDef(propDef._def, {
            ...refs,
            currentPath: [...refs.currentPath, "properties", propName],
            propertyPath: [...refs.currentPath, "properties", propName],
        });
        if (parsedDef === undefined) {
            continue;
        }
        result.properties[propName] = parsedDef;
        if (!propOptional) {
            required.push(propName);
        }
    }
    if (required.length) {
        result.required = required;
    }
    const additionalProperties = decideAdditionalProperties(def, refs);
    if (additionalProperties !== undefined) {
        result.additionalProperties = additionalProperties;
    }
    return result;
}
function decideAdditionalProperties(def, refs) {
    if (def.catchall._def.typeName !== "ZodNever") {
        return parseDef(def.catchall._def, {
            ...refs,
            currentPath: [...refs.currentPath, "additionalProperties"],
        });
    }
    switch (def.unknownKeys) {
        case "passthrough":
            return refs.allowedAdditionalProperties;
        case "strict":
            return refs.rejectedAdditionalProperties;
        case "strip":
            return refs.removeAdditionalStrategy === "strict"
                ? refs.allowedAdditionalProperties
                : refs.rejectedAdditionalProperties;
    }
}
function safeIsOptional(schema) {
    try {
        return schema.isOptional();
    }
    catch {
        return true;
    }
}

const parseOptionalDef = (def, refs) => {
    if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
        return parseDef(def.innerType._def, refs);
    }
    const innerSchema = parseDef(def.innerType._def, {
        ...refs,
        currentPath: [...refs.currentPath, "anyOf", "1"],
    });
    return innerSchema
        ? {
            anyOf: [
                {
                    not: parseAnyDef(refs),
                },
                innerSchema,
            ],
        }
        : parseAnyDef(refs);
};

const parsePipelineDef = (def, refs) => {
    if (refs.pipeStrategy === "input") {
        return parseDef(def.in._def, refs);
    }
    else if (refs.pipeStrategy === "output") {
        return parseDef(def.out._def, refs);
    }
    const a = parseDef(def.in._def, {
        ...refs,
        currentPath: [...refs.currentPath, "allOf", "0"],
    });
    const b = parseDef(def.out._def, {
        ...refs,
        currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"],
    });
    return {
        allOf: [a, b].filter((x) => x !== undefined),
    };
};

function parsePromiseDef(def, refs) {
    return parseDef(def.type._def, refs);
}

function parseSetDef(def, refs) {
    const items = parseDef(def.valueType._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items"],
    });
    const schema = {
        type: "array",
        uniqueItems: true,
        items,
    };
    if (def.minSize) {
        setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
    }
    if (def.maxSize) {
        setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
    }
    return schema;
}

function parseTupleDef(def, refs) {
    if (def.rest) {
        return {
            type: "array",
            minItems: def.items.length,
            items: def.items
                .map((x, i) => parseDef(x._def, {
                ...refs,
                currentPath: [...refs.currentPath, "items", `${i}`],
            }))
                .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),
            additionalItems: parseDef(def.rest._def, {
                ...refs,
                currentPath: [...refs.currentPath, "additionalItems"],
            }),
        };
    }
    else {
        return {
            type: "array",
            minItems: def.items.length,
            maxItems: def.items.length,
            items: def.items
                .map((x, i) => parseDef(x._def, {
                ...refs,
                currentPath: [...refs.currentPath, "items", `${i}`],
            }))
                .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),
        };
    }
}

function parseUndefinedDef(refs) {
    return {
        not: parseAnyDef(refs),
    };
}

function parseUnknownDef(refs) {
    return parseAnyDef(refs);
}

const parseReadonlyDef = (def, refs) => {
    return parseDef(def.innerType._def, refs);
};

const selectParser = (def, typeName, refs) => {
    switch (typeName) {
        case ZodFirstPartyTypeKind.ZodString:
            return parseStringDef(def, refs);
        case ZodFirstPartyTypeKind.ZodNumber:
            return parseNumberDef(def, refs);
        case ZodFirstPartyTypeKind.ZodObject:
            return parseObjectDef(def, refs);
        case ZodFirstPartyTypeKind.ZodBigInt:
            return parseBigintDef(def, refs);
        case ZodFirstPartyTypeKind.ZodBoolean:
            return parseBooleanDef();
        case ZodFirstPartyTypeKind.ZodDate:
            return parseDateDef(def, refs);
        case ZodFirstPartyTypeKind.ZodUndefined:
            return parseUndefinedDef(refs);
        case ZodFirstPartyTypeKind.ZodNull:
            return parseNullDef(refs);
        case ZodFirstPartyTypeKind.ZodArray:
            return parseArrayDef(def, refs);
        case ZodFirstPartyTypeKind.ZodUnion:
        case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
            return parseUnionDef(def, refs);
        case ZodFirstPartyTypeKind.ZodIntersection:
            return parseIntersectionDef(def, refs);
        case ZodFirstPartyTypeKind.ZodTuple:
            return parseTupleDef(def, refs);
        case ZodFirstPartyTypeKind.ZodRecord:
            return parseRecordDef(def, refs);
        case ZodFirstPartyTypeKind.ZodLiteral:
            return parseLiteralDef(def, refs);
        case ZodFirstPartyTypeKind.ZodEnum:
            return parseEnumDef(def);
        case ZodFirstPartyTypeKind.ZodNativeEnum:
            return parseNativeEnumDef(def);
        case ZodFirstPartyTypeKind.ZodNullable:
            return parseNullableDef(def, refs);
        case ZodFirstPartyTypeKind.ZodOptional:
            return parseOptionalDef(def, refs);
        case ZodFirstPartyTypeKind.ZodMap:
            return parseMapDef(def, refs);
        case ZodFirstPartyTypeKind.ZodSet:
            return parseSetDef(def, refs);
        case ZodFirstPartyTypeKind.ZodLazy:
            return () => def.getter()._def;
        case ZodFirstPartyTypeKind.ZodPromise:
            return parsePromiseDef(def, refs);
        case ZodFirstPartyTypeKind.ZodNaN:
        case ZodFirstPartyTypeKind.ZodNever:
            return parseNeverDef(refs);
        case ZodFirstPartyTypeKind.ZodEffects:
            return parseEffectsDef(def, refs);
        case ZodFirstPartyTypeKind.ZodAny:
            return parseAnyDef(refs);
        case ZodFirstPartyTypeKind.ZodUnknown:
            return parseUnknownDef(refs);
        case ZodFirstPartyTypeKind.ZodDefault:
            return parseDefaultDef(def, refs);
        case ZodFirstPartyTypeKind.ZodBranded:
            return parseBrandedDef(def, refs);
        case ZodFirstPartyTypeKind.ZodReadonly:
            return parseReadonlyDef(def, refs);
        case ZodFirstPartyTypeKind.ZodCatch:
            return parseCatchDef(def, refs);
        case ZodFirstPartyTypeKind.ZodPipeline:
            return parsePipelineDef(def, refs);
        case ZodFirstPartyTypeKind.ZodFunction:
        case ZodFirstPartyTypeKind.ZodVoid:
        case ZodFirstPartyTypeKind.ZodSymbol:
            return undefined;
        default:
            return ((_) => undefined)();
    }
};

function parseDef(def, refs, forceResolution = false) {
    const seenItem = refs.seen.get(def);
    if (refs.override) {
        const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
        if (overrideResult !== ignoreOverride) {
            return overrideResult;
        }
    }
    if (seenItem && !forceResolution) {
        const seenSchema = get$ref(seenItem, refs);
        if (seenSchema !== undefined) {
            return seenSchema;
        }
    }
    const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
    refs.seen.set(def, newItem);
    const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
    const jsonSchema = typeof jsonSchemaOrGetter === "function"
        ? parseDef(jsonSchemaOrGetter(), refs)
        : jsonSchemaOrGetter;
    if (jsonSchema) {
        addMeta(def, refs, jsonSchema);
    }
    if (refs.postProcess) {
        const postProcessResult = refs.postProcess(jsonSchema, def, refs);
        newItem.jsonSchema = jsonSchema;
        return postProcessResult;
    }
    newItem.jsonSchema = jsonSchema;
    return jsonSchema;
}
const get$ref = (item, refs) => {
    switch (refs.$refStrategy) {
        case "root":
            return { $ref: item.path.join("/") };
        case "relative":
            return { $ref: getRelativePath(refs.currentPath, item.path) };
        case "none":
        case "seen": {
            if (item.path.length < refs.currentPath.length &&
                item.path.every((value, index) => refs.currentPath[index] === value)) {
                console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
                return parseAnyDef(refs);
            }
            return refs.$refStrategy === "seen" ? parseAnyDef(refs) : undefined;
        }
    }
};
const addMeta = (def, refs, jsonSchema) => {
    if (def.description) {
        jsonSchema.description = def.description;
        if (refs.markdownDescription) {
            jsonSchema.markdownDescription = def.description;
        }
    }
    return jsonSchema;
};

const zodToJsonSchema = (schema, options) => {
    const refs = getRefs(options);
    let definitions = typeof options === "object" && options.definitions
        ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({
            ...acc,
            [name]: parseDef(schema._def, {
                ...refs,
                currentPath: [...refs.basePath, refs.definitionPath, name],
            }, true) ?? parseAnyDef(refs),
        }), {})
        : undefined;
    const name = typeof options === "string"
        ? options
        : options?.nameStrategy === "title"
            ? undefined
            : options?.name;
    const main = parseDef(schema._def, name === undefined
        ? refs
        : {
            ...refs,
            currentPath: [...refs.basePath, refs.definitionPath, name],
        }, false) ?? parseAnyDef(refs);
    const title = typeof options === "object" &&
        options.name !== undefined &&
        options.nameStrategy === "title"
        ? options.name
        : undefined;
    if (title !== undefined) {
        main.title = title;
    }
    if (refs.flags.hasReferencedOpenAiAnyType) {
        if (!definitions) {
            definitions = {};
        }
        if (!definitions[refs.openAiAnyTypeName]) {
            definitions[refs.openAiAnyTypeName] = {
                type: ["string", "number", "integer", "boolean", "array", "null"],
                items: {
                    $ref: refs.$refStrategy === "relative"
                        ? "1"
                        : [
                            ...refs.basePath,
                            refs.definitionPath,
                            refs.openAiAnyTypeName,
                        ].join("/"),
                },
            };
        }
    }
    const combined = name === undefined
        ? definitions
            ? {
                ...main,
                [refs.definitionPath]: definitions,
            }
            : main
        : {
            $ref: [
                ...(refs.$refStrategy === "relative" ? [] : refs.basePath),
                refs.definitionPath,
                name,
            ].join("/"),
            [refs.definitionPath]: {
                ...definitions,
                [name]: main,
            },
        };
    if (refs.target === "jsonSchema7") {
        combined.$schema = "http://json-schema.org/draft-07/schema#";
    }
    else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
        combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
    }
    if (refs.target === "openAi" &&
        ("anyOf" in combined ||
            "oneOf" in combined ||
            "allOf" in combined ||
            ("type" in combined && Array.isArray(combined.type)))) {
        console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
    }
    return combined;
};

function mapMiniTarget(t) {
    if (!t)
        return 'draft-7';
    if (t === 'jsonSchema7' || t === 'draft-7')
        return 'draft-7';
    if (t === 'jsonSchema2019-09' || t === 'draft-2020-12')
        return 'draft-2020-12';
    return 'draft-7';
}
function toJsonSchemaCompat(schema, opts) {
    if (isZ4Schema(schema)) {
        return toJSONSchema(schema, {
            target: mapMiniTarget(opts?.target),
            io: opts?.pipeStrategy ?? 'input'
        });
    }
    return zodToJsonSchema(schema, {
        strictUnions: opts?.strictUnions ?? true,
        pipeStrategy: opts?.pipeStrategy ?? 'input'
    });
}
function getMethodLiteral(schema) {
    const shape = getObjectShape(schema);
    const methodSchema = shape?.method;
    if (!methodSchema) {
        throw new Error('Schema is missing a method literal');
    }
    const value = getLiteralValue(methodSchema);
    if (typeof value !== 'string') {
        throw new Error('Schema method literal must be a string');
    }
    return value;
}
function parseWithCompat(schema, data) {
    const result = safeParse$1(schema, data);
    if (!result.success) {
        throw result.error;
    }
    return result.data;
}

const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;
class Protocol {
    constructor(_options) {
        this._options = _options;
        this._requestMessageId = 0;
        this._requestHandlers = new Map();
        this._requestHandlerAbortControllers = new Map();
        this._notificationHandlers = new Map();
        this._responseHandlers = new Map();
        this._progressHandlers = new Map();
        this._timeoutInfo = new Map();
        this._pendingDebouncedNotifications = new Set();
        this._taskProgressTokens = new Map();
        this._requestResolvers = new Map();
        this.setNotificationHandler(CancelledNotificationSchema, notification => {
            this._oncancel(notification);
        });
        this.setNotificationHandler(ProgressNotificationSchema, notification => {
            this._onprogress(notification);
        });
        this.setRequestHandler(PingRequestSchema,
        _request => ({}));
        this._taskStore = _options?.taskStore;
        this._taskMessageQueue = _options?.taskMessageQueue;
        if (this._taskStore) {
            this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {
                const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
                if (!task) {
                    throw new McpError(ErrorCode$1.InvalidParams, 'Failed to retrieve task: Task not found');
                }
                return {
                    ...task
                };
            });
            this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
                const handleTaskResult = async () => {
                    const taskId = request.params.taskId;
                    if (this._taskMessageQueue) {
                        let queuedMessage;
                        while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) {
                            if (queuedMessage.type === 'response' || queuedMessage.type === 'error') {
                                const message = queuedMessage.message;
                                const requestId = message.id;
                                const resolver = this._requestResolvers.get(requestId);
                                if (resolver) {
                                    this._requestResolvers.delete(requestId);
                                    if (queuedMessage.type === 'response') {
                                        resolver(message);
                                    }
                                    else {
                                        const errorMessage = message;
                                        const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
                                        resolver(error);
                                    }
                                }
                                else {
                                    const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error';
                                    this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
                                }
                                continue;
                            }
                            await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
                        }
                    }
                    const task = await this._taskStore.getTask(taskId, extra.sessionId);
                    if (!task) {
                        throw new McpError(ErrorCode$1.InvalidParams, `Task not found: ${taskId}`);
                    }
                    if (!isTerminal(task.status)) {
                        await this._waitForTaskUpdate(taskId, extra.signal);
                        return await handleTaskResult();
                    }
                    if (isTerminal(task.status)) {
                        const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
                        this._clearTaskQueue(taskId);
                        return {
                            ...result,
                            _meta: {
                                ...result._meta,
                                [RELATED_TASK_META_KEY]: {
                                    taskId: taskId
                                }
                            }
                        };
                    }
                    return await handleTaskResult();
                };
                return await handleTaskResult();
            });
            this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {
                try {
                    const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);
                    return {
                        tasks,
                        nextCursor,
                        _meta: {}
                    };
                }
                catch (error) {
                    throw new McpError(ErrorCode$1.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);
                }
            });
            this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {
                try {
                    const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
                    if (!task) {
                        throw new McpError(ErrorCode$1.InvalidParams, `Task not found: ${request.params.taskId}`);
                    }
                    if (isTerminal(task.status)) {
                        throw new McpError(ErrorCode$1.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
                    }
                    await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId);
                    this._clearTaskQueue(request.params.taskId);
                    const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
                    if (!cancelledTask) {
                        throw new McpError(ErrorCode$1.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
                    }
                    return {
                        _meta: {},
                        ...cancelledTask
                    };
                }
                catch (error) {
                    if (error instanceof McpError) {
                        throw error;
                    }
                    throw new McpError(ErrorCode$1.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);
                }
            });
        }
    }
    async _oncancel(notification) {
        if (!notification.params.requestId) {
            return;
        }
        const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
        controller?.abort(notification.params.reason);
    }
    _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
        this._timeoutInfo.set(messageId, {
            timeoutId: setTimeout(onTimeout, timeout),
            startTime: Date.now(),
            timeout,
            maxTotalTimeout,
            resetTimeoutOnProgress,
            onTimeout
        });
    }
    _resetTimeout(messageId) {
        const info = this._timeoutInfo.get(messageId);
        if (!info)
            return false;
        const totalElapsed = Date.now() - info.startTime;
        if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
            this._timeoutInfo.delete(messageId);
            throw McpError.fromError(ErrorCode$1.RequestTimeout, 'Maximum total timeout exceeded', {
                maxTotalTimeout: info.maxTotalTimeout,
                totalElapsed
            });
        }
        clearTimeout(info.timeoutId);
        info.timeoutId = setTimeout(info.onTimeout, info.timeout);
        return true;
    }
    _cleanupTimeout(messageId) {
        const info = this._timeoutInfo.get(messageId);
        if (info) {
            clearTimeout(info.timeoutId);
            this._timeoutInfo.delete(messageId);
        }
    }
    async connect(transport) {
        if (this._transport) {
            throw new Error('Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.');
        }
        this._transport = transport;
        const _onclose = this.transport?.onclose;
        this._transport.onclose = () => {
            _onclose?.();
            this._onclose();
        };
        const _onerror = this.transport?.onerror;
        this._transport.onerror = (error) => {
            _onerror?.(error);
            this._onerror(error);
        };
        const _onmessage = this._transport?.onmessage;
        this._transport.onmessage = (message, extra) => {
            _onmessage?.(message, extra);
            if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
                this._onresponse(message);
            }
            else if (isJSONRPCRequest(message)) {
                this._onrequest(message, extra);
            }
            else if (isJSONRPCNotification(message)) {
                this._onnotification(message);
            }
            else {
                this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
            }
        };
        await this._transport.start();
    }
    _onclose() {
        const responseHandlers = this._responseHandlers;
        this._responseHandlers = new Map();
        this._progressHandlers.clear();
        this._taskProgressTokens.clear();
        this._pendingDebouncedNotifications.clear();
        for (const controller of this._requestHandlerAbortControllers.values()) {
            controller.abort();
        }
        this._requestHandlerAbortControllers.clear();
        const error = McpError.fromError(ErrorCode$1.ConnectionClosed, 'Connection closed');
        this._transport = undefined;
        this.onclose?.();
        for (const handler of responseHandlers.values()) {
            handler(error);
        }
    }
    _onerror(error) {
        this.onerror?.(error);
    }
    _onnotification(notification) {
        const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
        if (handler === undefined) {
            return;
        }
        Promise.resolve()
            .then(() => handler(notification))
            .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
    }
    _onrequest(request, extra) {
        const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
        const capturedTransport = this._transport;
        const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
        if (handler === undefined) {
            const errorResponse = {
                jsonrpc: '2.0',
                id: request.id,
                error: {
                    code: ErrorCode$1.MethodNotFound,
                    message: 'Method not found'
                }
            };
            if (relatedTaskId && this._taskMessageQueue) {
                this._enqueueTaskMessage(relatedTaskId, {
                    type: 'error',
                    message: errorResponse,
                    timestamp: Date.now()
                }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));
            }
            else {
                capturedTransport
                    ?.send(errorResponse)
                    .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));
            }
            return;
        }
        const abortController = new AbortController();
        this._requestHandlerAbortControllers.set(request.id, abortController);
        const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined;
        const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined;
        const fullExtra = {
            signal: abortController.signal,
            sessionId: capturedTransport?.sessionId,
            _meta: request.params?._meta,
            sendNotification: async (notification) => {
                if (abortController.signal.aborted)
                    return;
                const notificationOptions = { relatedRequestId: request.id };
                if (relatedTaskId) {
                    notificationOptions.relatedTask = { taskId: relatedTaskId };
                }
                await this.notification(notification, notificationOptions);
            },
            sendRequest: async (r, resultSchema, options) => {
                if (abortController.signal.aborted) {
                    throw new McpError(ErrorCode$1.ConnectionClosed, 'Request was cancelled');
                }
                const requestOptions = { ...options, relatedRequestId: request.id };
                if (relatedTaskId && !requestOptions.relatedTask) {
                    requestOptions.relatedTask = { taskId: relatedTaskId };
                }
                const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
                if (effectiveTaskId && taskStore) {
                    await taskStore.updateTaskStatus(effectiveTaskId, 'input_required');
                }
                return await this.request(r, resultSchema, requestOptions);
            },
            authInfo: extra?.authInfo,
            requestId: request.id,
            requestInfo: extra?.requestInfo,
            taskId: relatedTaskId,
            taskStore: taskStore,
            taskRequestedTtl: taskCreationParams?.ttl,
            closeSSEStream: extra?.closeSSEStream,
            closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
        };
        Promise.resolve()
            .then(() => {
            if (taskCreationParams) {
                this.assertTaskHandlerCapability(request.method);
            }
        })
            .then(() => handler(request, fullExtra))
            .then(async (result) => {
            if (abortController.signal.aborted) {
                return;
            }
            const response = {
                result,
                jsonrpc: '2.0',
                id: request.id
            };
            if (relatedTaskId && this._taskMessageQueue) {
                await this._enqueueTaskMessage(relatedTaskId, {
                    type: 'response',
                    message: response,
                    timestamp: Date.now()
                }, capturedTransport?.sessionId);
            }
            else {
                await capturedTransport?.send(response);
            }
        }, async (error) => {
            if (abortController.signal.aborted) {
                return;
            }
            const errorResponse = {
                jsonrpc: '2.0',
                id: request.id,
                error: {
                    code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode$1.InternalError,
                    message: error.message ?? 'Internal error',
                    ...(error['data'] !== undefined && { data: error['data'] })
                }
            };
            if (relatedTaskId && this._taskMessageQueue) {
                await this._enqueueTaskMessage(relatedTaskId, {
                    type: 'error',
                    message: errorResponse,
                    timestamp: Date.now()
                }, capturedTransport?.sessionId);
            }
            else {
                await capturedTransport?.send(errorResponse);
            }
        })
            .catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))
            .finally(() => {
            this._requestHandlerAbortControllers.delete(request.id);
        });
    }
    _onprogress(notification) {
        const { progressToken, ...params } = notification.params;
        const messageId = Number(progressToken);
        const handler = this._progressHandlers.get(messageId);
        if (!handler) {
            this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
            return;
        }
        const responseHandler = this._responseHandlers.get(messageId);
        const timeoutInfo = this._timeoutInfo.get(messageId);
        if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {
            try {
                this._resetTimeout(messageId);
            }
            catch (error) {
                this._responseHandlers.delete(messageId);
                this._progressHandlers.delete(messageId);
                this._cleanupTimeout(messageId);
                responseHandler(error);
                return;
            }
        }
        handler(params);
    }
    _onresponse(response) {
        const messageId = Number(response.id);
        const resolver = this._requestResolvers.get(messageId);
        if (resolver) {
            this._requestResolvers.delete(messageId);
            if (isJSONRPCResultResponse(response)) {
                resolver(response);
            }
            else {
                const error = new McpError(response.error.code, response.error.message, response.error.data);
                resolver(error);
            }
            return;
        }
        const handler = this._responseHandlers.get(messageId);
        if (handler === undefined) {
            this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
            return;
        }
        this._responseHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        let isTaskResponse = false;
        if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') {
            const result = response.result;
            if (result.task && typeof result.task === 'object') {
                const task = result.task;
                if (typeof task.taskId === 'string') {
                    isTaskResponse = true;
                    this._taskProgressTokens.set(task.taskId, messageId);
                }
            }
        }
        if (!isTaskResponse) {
            this._progressHandlers.delete(messageId);
        }
        if (isJSONRPCResultResponse(response)) {
            handler(response);
        }
        else {
            const error = McpError.fromError(response.error.code, response.error.message, response.error.data);
            handler(error);
        }
    }
    get transport() {
        return this._transport;
    }
    async close() {
        await this._transport?.close();
    }
    async *requestStream(request, resultSchema, options) {
        const { task } = options ?? {};
        if (!task) {
            try {
                const result = await this.request(request, resultSchema, options);
                yield { type: 'result', result };
            }
            catch (error) {
                yield {
                    type: 'error',
                    error: error instanceof McpError ? error : new McpError(ErrorCode$1.InternalError, String(error))
                };
            }
            return;
        }
        let taskId;
        try {
            const createResult = await this.request(request, CreateTaskResultSchema, options);
            if (createResult.task) {
                taskId = createResult.task.taskId;
                yield { type: 'taskCreated', task: createResult.task };
            }
            else {
                throw new McpError(ErrorCode$1.InternalError, 'Task creation did not return a task');
            }
            while (true) {
                const task = await this.getTask({ taskId }, options);
                yield { type: 'taskStatus', task };
                if (isTerminal(task.status)) {
                    if (task.status === 'completed') {
                        const result = await this.getTaskResult({ taskId }, resultSchema, options);
                        yield { type: 'result', result };
                    }
                    else if (task.status === 'failed') {
                        yield {
                            type: 'error',
                            error: new McpError(ErrorCode$1.InternalError, `Task ${taskId} failed`)
                        };
                    }
                    else if (task.status === 'cancelled') {
                        yield {
                            type: 'error',
                            error: new McpError(ErrorCode$1.InternalError, `Task ${taskId} was cancelled`)
                        };
                    }
                    return;
                }
                if (task.status === 'input_required') {
                    const result = await this.getTaskResult({ taskId }, resultSchema, options);
                    yield { type: 'result', result };
                    return;
                }
                const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000;
                await new Promise(resolve => setTimeout(resolve, pollInterval));
                options?.signal?.throwIfAborted();
            }
        }
        catch (error) {
            yield {
                type: 'error',
                error: error instanceof McpError ? error : new McpError(ErrorCode$1.InternalError, String(error))
            };
        }
    }
    request(request, resultSchema, options) {
        const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
        return new Promise((resolve, reject) => {
            const earlyReject = (error) => {
                reject(error);
            };
            if (!this._transport) {
                earlyReject(new Error('Not connected'));
                return;
            }
            if (this._options?.enforceStrictCapabilities === true) {
                try {
                    this.assertCapabilityForMethod(request.method);
                    if (task) {
                        this.assertTaskCapability(request.method);
                    }
                }
                catch (e) {
                    earlyReject(e);
                    return;
                }
            }
            options?.signal?.throwIfAborted();
            const messageId = this._requestMessageId++;
            const jsonrpcRequest = {
                ...request,
                jsonrpc: '2.0',
                id: messageId
            };
            if (options?.onprogress) {
                this._progressHandlers.set(messageId, options.onprogress);
                jsonrpcRequest.params = {
                    ...request.params,
                    _meta: {
                        ...(request.params?._meta || {}),
                        progressToken: messageId
                    }
                };
            }
            if (task) {
                jsonrpcRequest.params = {
                    ...jsonrpcRequest.params,
                    task: task
                };
            }
            if (relatedTask) {
                jsonrpcRequest.params = {
                    ...jsonrpcRequest.params,
                    _meta: {
                        ...(jsonrpcRequest.params?._meta || {}),
                        [RELATED_TASK_META_KEY]: relatedTask
                    }
                };
            }
            const cancel = (reason) => {
                this._responseHandlers.delete(messageId);
                this._progressHandlers.delete(messageId);
                this._cleanupTimeout(messageId);
                this._transport
                    ?.send({
                    jsonrpc: '2.0',
                    method: 'notifications/cancelled',
                    params: {
                        requestId: messageId,
                        reason: String(reason)
                    }
                }, { relatedRequestId, resumptionToken, onresumptiontoken })
                    .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`)));
                const error = reason instanceof McpError ? reason : new McpError(ErrorCode$1.RequestTimeout, String(reason));
                reject(error);
            };
            this._responseHandlers.set(messageId, response => {
                if (options?.signal?.aborted) {
                    return;
                }
                if (response instanceof Error) {
                    return reject(response);
                }
                try {
                    const parseResult = safeParse$1(resultSchema, response.result);
                    if (!parseResult.success) {
                        reject(parseResult.error);
                    }
                    else {
                        resolve(parseResult.data);
                    }
                }
                catch (error) {
                    reject(error);
                }
            });
            options?.signal?.addEventListener('abort', () => {
                cancel(options?.signal?.reason);
            });
            const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
            const timeoutHandler = () => cancel(McpError.fromError(ErrorCode$1.RequestTimeout, 'Request timed out', { timeout }));
            this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
            const relatedTaskId = relatedTask?.taskId;
            if (relatedTaskId) {
                const responseResolver = (response) => {
                    const handler = this._responseHandlers.get(messageId);
                    if (handler) {
                        handler(response);
                    }
                    else {
                        this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
                    }
                };
                this._requestResolvers.set(messageId, responseResolver);
                this._enqueueTaskMessage(relatedTaskId, {
                    type: 'request',
                    message: jsonrpcRequest,
                    timestamp: Date.now()
                }).catch(error => {
                    this._cleanupTimeout(messageId);
                    reject(error);
                });
            }
            else {
                this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => {
                    this._cleanupTimeout(messageId);
                    reject(error);
                });
            }
        });
    }
    async getTask(params, options) {
        return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options);
    }
    async getTaskResult(params, resultSchema, options) {
        return this.request({ method: 'tasks/result', params }, resultSchema, options);
    }
    async listTasks(params, options) {
        return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options);
    }
    async cancelTask(params, options) {
        return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options);
    }
    async notification(notification, options) {
        if (!this._transport) {
            throw new Error('Not connected');
        }
        this.assertNotificationCapability(notification.method);
        const relatedTaskId = options?.relatedTask?.taskId;
        if (relatedTaskId) {
            const jsonrpcNotification = {
                ...notification,
                jsonrpc: '2.0',
                params: {
                    ...notification.params,
                    _meta: {
                        ...(notification.params?._meta || {}),
                        [RELATED_TASK_META_KEY]: options.relatedTask
                    }
                }
            };
            await this._enqueueTaskMessage(relatedTaskId, {
                type: 'notification',
                message: jsonrpcNotification,
                timestamp: Date.now()
            });
            return;
        }
        const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];
        const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;
        if (canDebounce) {
            if (this._pendingDebouncedNotifications.has(notification.method)) {
                return;
            }
            this._pendingDebouncedNotifications.add(notification.method);
            Promise.resolve().then(() => {
                this._pendingDebouncedNotifications.delete(notification.method);
                if (!this._transport) {
                    return;
                }
                let jsonrpcNotification = {
                    ...notification,
                    jsonrpc: '2.0'
                };
                if (options?.relatedTask) {
                    jsonrpcNotification = {
                        ...jsonrpcNotification,
                        params: {
                            ...jsonrpcNotification.params,
                            _meta: {
                                ...(jsonrpcNotification.params?._meta || {}),
                                [RELATED_TASK_META_KEY]: options.relatedTask
                            }
                        }
                    };
                }
                this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error));
            });
            return;
        }
        let jsonrpcNotification = {
            ...notification,
            jsonrpc: '2.0'
        };
        if (options?.relatedTask) {
            jsonrpcNotification = {
                ...jsonrpcNotification,
                params: {
                    ...jsonrpcNotification.params,
                    _meta: {
                        ...(jsonrpcNotification.params?._meta || {}),
                        [RELATED_TASK_META_KEY]: options.relatedTask
                    }
                }
            };
        }
        await this._transport.send(jsonrpcNotification, options);
    }
    setRequestHandler(requestSchema, handler) {
        const method = getMethodLiteral(requestSchema);
        this.assertRequestHandlerCapability(method);
        this._requestHandlers.set(method, (request, extra) => {
            const parsed = parseWithCompat(requestSchema, request);
            return Promise.resolve(handler(parsed, extra));
        });
    }
    removeRequestHandler(method) {
        this._requestHandlers.delete(method);
    }
    assertCanSetRequestHandler(method) {
        if (this._requestHandlers.has(method)) {
            throw new Error(`A request handler for ${method} already exists, which would be overridden`);
        }
    }
    setNotificationHandler(notificationSchema, handler) {
        const method = getMethodLiteral(notificationSchema);
        this._notificationHandlers.set(method, notification => {
            const parsed = parseWithCompat(notificationSchema, notification);
            return Promise.resolve(handler(parsed));
        });
    }
    removeNotificationHandler(method) {
        this._notificationHandlers.delete(method);
    }
    _cleanupTaskProgressHandler(taskId) {
        const progressToken = this._taskProgressTokens.get(taskId);
        if (progressToken !== undefined) {
            this._progressHandlers.delete(progressToken);
            this._taskProgressTokens.delete(taskId);
        }
    }
    async _enqueueTaskMessage(taskId, message, sessionId) {
        if (!this._taskStore || !this._taskMessageQueue) {
            throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured');
        }
        const maxQueueSize = this._options?.maxTaskQueueSize;
        await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
    }
    async _clearTaskQueue(taskId, sessionId) {
        if (this._taskMessageQueue) {
            const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
            for (const message of messages) {
                if (message.type === 'request' && isJSONRPCRequest(message.message)) {
                    const requestId = message.message.id;
                    const resolver = this._requestResolvers.get(requestId);
                    if (resolver) {
                        resolver(new McpError(ErrorCode$1.InternalError, 'Task cancelled or completed'));
                        this._requestResolvers.delete(requestId);
                    }
                    else {
                        this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
                    }
                }
            }
        }
    }
    async _waitForTaskUpdate(taskId, signal) {
        let interval = this._options?.defaultTaskPollInterval ?? 1000;
        try {
            const task = await this._taskStore?.getTask(taskId);
            if (task?.pollInterval) {
                interval = task.pollInterval;
            }
        }
        catch {
        }
        return new Promise((resolve, reject) => {
            if (signal.aborted) {
                reject(new McpError(ErrorCode$1.InvalidRequest, 'Request cancelled'));
                return;
            }
            const timeoutId = setTimeout(resolve, interval);
            signal.addEventListener('abort', () => {
                clearTimeout(timeoutId);
                reject(new McpError(ErrorCode$1.InvalidRequest, 'Request cancelled'));
            }, { once: true });
        });
    }
    requestTaskStore(request, sessionId) {
        const taskStore = this._taskStore;
        if (!taskStore) {
            throw new Error('No task store configured');
        }
        return {
            createTask: async (taskParams) => {
                if (!request) {
                    throw new Error('No request provided');
                }
                return await taskStore.createTask(taskParams, request.id, {
                    method: request.method,
                    params: request.params
                }, sessionId);
            },
            getTask: async (taskId) => {
                const task = await taskStore.getTask(taskId, sessionId);
                if (!task) {
                    throw new McpError(ErrorCode$1.InvalidParams, 'Failed to retrieve task: Task not found');
                }
                return task;
            },
            storeTaskResult: async (taskId, status, result) => {
                await taskStore.storeTaskResult(taskId, status, result, sessionId);
                const task = await taskStore.getTask(taskId, sessionId);
                if (task) {
                    const notification = TaskStatusNotificationSchema.parse({
                        method: 'notifications/tasks/status',
                        params: task
                    });
                    await this.notification(notification);
                    if (isTerminal(task.status)) {
                        this._cleanupTaskProgressHandler(taskId);
                    }
                }
            },
            getTaskResult: taskId => {
                return taskStore.getTaskResult(taskId, sessionId);
            },
            updateTaskStatus: async (taskId, status, statusMessage) => {
                const task = await taskStore.getTask(taskId, sessionId);
                if (!task) {
                    throw new McpError(ErrorCode$1.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
                }
                if (isTerminal(task.status)) {
                    throw new McpError(ErrorCode$1.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
                }
                await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
                const updatedTask = await taskStore.getTask(taskId, sessionId);
                if (updatedTask) {
                    const notification = TaskStatusNotificationSchema.parse({
                        method: 'notifications/tasks/status',
                        params: updatedTask
                    });
                    await this.notification(notification);
                    if (isTerminal(updatedTask.status)) {
                        this._cleanupTaskProgressHandler(taskId);
                    }
                }
            },
            listTasks: cursor => {
                return taskStore.listTasks(cursor, sessionId);
            }
        };
    }
}
function isPlainObject(value) {
    return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function mergeCapabilities(base, additional) {
    const result = { ...base };
    for (const key in additional) {
        const k = key;
        const addValue = additional[k];
        if (addValue === undefined)
            continue;
        const baseValue = result[k];
        if (isPlainObject(baseValue) && isPlainObject(addValue)) {
            result[k] = { ...baseValue, ...addValue };
        }
        else {
            result[k] = addValue;
        }
    }
    return result;
}

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

var core$5 = {};

var validate$1 = {};

var boolSchema$1 = {};

var errors$2 = {};

var codegen$1 = {};

var code$4 = {};

var hasRequiredCode$4;

function requireCode$4 () {
	if (hasRequiredCode$4) return code$4;
	hasRequiredCode$4 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.regexpCode = exports$1.getEsmExportName = exports$1.getProperty = exports$1.safeStringify = exports$1.stringify = exports$1.strConcat = exports$1.addCodeArg = exports$1.str = exports$1._ = exports$1.nil = exports$1._Code = exports$1.Name = exports$1.IDENTIFIER = exports$1._CodeOrName = void 0;
		class _CodeOrName {
		}
		exports$1._CodeOrName = _CodeOrName;
		exports$1.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
		class Name extends _CodeOrName {
		    constructor(s) {
		        super();
		        if (!exports$1.IDENTIFIER.test(s))
		            throw new Error("CodeGen: name must be a valid identifier");
		        this.str = s;
		    }
		    toString() {
		        return this.str;
		    }
		    emptyStr() {
		        return false;
		    }
		    get names() {
		        return { [this.str]: 1 };
		    }
		}
		exports$1.Name = Name;
		class _Code extends _CodeOrName {
		    constructor(code) {
		        super();
		        this._items = typeof code === "string" ? [code] : code;
		    }
		    toString() {
		        return this.str;
		    }
		    emptyStr() {
		        if (this._items.length > 1)
		            return false;
		        const item = this._items[0];
		        return item === "" || item === '""';
		    }
		    get str() {
		        var _a;
		        return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
		    }
		    get names() {
		        var _a;
		        return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
		            if (c instanceof Name)
		                names[c.str] = (names[c.str] || 0) + 1;
		            return names;
		        }, {})));
		    }
		}
		exports$1._Code = _Code;
		exports$1.nil = new _Code("");
		function _(strs, ...args) {
		    const code = [strs[0]];
		    let i = 0;
		    while (i < args.length) {
		        addCodeArg(code, args[i]);
		        code.push(strs[++i]);
		    }
		    return new _Code(code);
		}
		exports$1._ = _;
		const plus = new _Code("+");
		function str(strs, ...args) {
		    const expr = [safeStringify(strs[0])];
		    let i = 0;
		    while (i < args.length) {
		        expr.push(plus);
		        addCodeArg(expr, args[i]);
		        expr.push(plus, safeStringify(strs[++i]));
		    }
		    optimize(expr);
		    return new _Code(expr);
		}
		exports$1.str = str;
		function addCodeArg(code, arg) {
		    if (arg instanceof _Code)
		        code.push(...arg._items);
		    else if (arg instanceof Name)
		        code.push(arg);
		    else
		        code.push(interpolate(arg));
		}
		exports$1.addCodeArg = addCodeArg;
		function optimize(expr) {
		    let i = 1;
		    while (i < expr.length - 1) {
		        if (expr[i] === plus) {
		            const res = mergeExprItems(expr[i - 1], expr[i + 1]);
		            if (res !== undefined) {
		                expr.splice(i - 1, 3, res);
		                continue;
		            }
		            expr[i++] = "+";
		        }
		        i++;
		    }
		}
		function mergeExprItems(a, b) {
		    if (b === '""')
		        return a;
		    if (a === '""')
		        return b;
		    if (typeof a == "string") {
		        if (b instanceof Name || a[a.length - 1] !== '"')
		            return;
		        if (typeof b != "string")
		            return `${a.slice(0, -1)}${b}"`;
		        if (b[0] === '"')
		            return a.slice(0, -1) + b.slice(1);
		        return;
		    }
		    if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
		        return `"${a}${b.slice(1)}`;
		    return;
		}
		function strConcat(c1, c2) {
		    return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
		}
		exports$1.strConcat = strConcat;
		function interpolate(x) {
		    return typeof x == "number" || typeof x == "boolean" || x === null
		        ? x
		        : safeStringify(Array.isArray(x) ? x.join(",") : x);
		}
		function stringify(x) {
		    return new _Code(safeStringify(x));
		}
		exports$1.stringify = stringify;
		function safeStringify(x) {
		    return JSON.stringify(x)
		        .replace(/\u2028/g, "\\u2028")
		        .replace(/\u2029/g, "\\u2029");
		}
		exports$1.safeStringify = safeStringify;
		function getProperty(key) {
		    return typeof key == "string" && exports$1.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
		}
		exports$1.getProperty = getProperty;
		function getEsmExportName(key) {
		    if (typeof key == "string" && exports$1.IDENTIFIER.test(key)) {
		        return new _Code(`${key}`);
		    }
		    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
		}
		exports$1.getEsmExportName = getEsmExportName;
		function regexpCode(rx) {
		    return new _Code(rx.toString());
		}
		exports$1.regexpCode = regexpCode; 
	} (code$4));
	return code$4;
}

var scope$2 = {};

var hasRequiredScope$2;

function requireScope$2 () {
	if (hasRequiredScope$2) return scope$2;
	hasRequiredScope$2 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.ValueScope = exports$1.ValueScopeName = exports$1.Scope = exports$1.varKinds = exports$1.UsedValueState = void 0;
		const code_1 = requireCode$4();
		class ValueError extends Error {
		    constructor(name) {
		        super(`CodeGen: "code" for ${name} not defined`);
		        this.value = name.value;
		    }
		}
		var UsedValueState;
		(function (UsedValueState) {
		    UsedValueState[UsedValueState["Started"] = 0] = "Started";
		    UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
		})(UsedValueState || (exports$1.UsedValueState = UsedValueState = {}));
		exports$1.varKinds = {
		    const: new code_1.Name("const"),
		    let: new code_1.Name("let"),
		    var: new code_1.Name("var"),
		};
		class Scope {
		    constructor({ prefixes, parent } = {}) {
		        this._names = {};
		        this._prefixes = prefixes;
		        this._parent = parent;
		    }
		    toName(nameOrPrefix) {
		        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
		    }
		    name(prefix) {
		        return new code_1.Name(this._newName(prefix));
		    }
		    _newName(prefix) {
		        const ng = this._names[prefix] || this._nameGroup(prefix);
		        return `${prefix}${ng.index++}`;
		    }
		    _nameGroup(prefix) {
		        var _a, _b;
		        if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {
		            throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
		        }
		        return (this._names[prefix] = { prefix, index: 0 });
		    }
		}
		exports$1.Scope = Scope;
		class ValueScopeName extends code_1.Name {
		    constructor(prefix, nameStr) {
		        super(nameStr);
		        this.prefix = prefix;
		    }
		    setValue(value, { property, itemIndex }) {
		        this.value = value;
		        this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;
		    }
		}
		exports$1.ValueScopeName = ValueScopeName;
		const line = (0, code_1._) `\n`;
		class ValueScope extends Scope {
		    constructor(opts) {
		        super(opts);
		        this._values = {};
		        this._scope = opts.scope;
		        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
		    }
		    get() {
		        return this._scope;
		    }
		    name(prefix) {
		        return new ValueScopeName(prefix, this._newName(prefix));
		    }
		    value(nameOrPrefix, value) {
		        var _a;
		        if (value.ref === undefined)
		            throw new Error("CodeGen: ref must be passed in value");
		        const name = this.toName(nameOrPrefix);
		        const { prefix } = name;
		        const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
		        let vs = this._values[prefix];
		        if (vs) {
		            const _name = vs.get(valueKey);
		            if (_name)
		                return _name;
		        }
		        else {
		            vs = this._values[prefix] = new Map();
		        }
		        vs.set(valueKey, name);
		        const s = this._scope[prefix] || (this._scope[prefix] = []);
		        const itemIndex = s.length;
		        s[itemIndex] = value.ref;
		        name.setValue(value, { property: prefix, itemIndex });
		        return name;
		    }
		    getValue(prefix, keyOrRef) {
		        const vs = this._values[prefix];
		        if (!vs)
		            return;
		        return vs.get(keyOrRef);
		    }
		    scopeRefs(scopeName, values = this._values) {
		        return this._reduceValues(values, (name) => {
		            if (name.scopePath === undefined)
		                throw new Error(`CodeGen: name "${name}" has no value`);
		            return (0, code_1._) `${scopeName}${name.scopePath}`;
		        });
		    }
		    scopeCode(values = this._values, usedValues, getCode) {
		        return this._reduceValues(values, (name) => {
		            if (name.value === undefined)
		                throw new Error(`CodeGen: name "${name}" has no value`);
		            return name.value.code;
		        }, usedValues, getCode);
		    }
		    _reduceValues(values, valueCode, usedValues = {}, getCode) {
		        let code = code_1.nil;
		        for (const prefix in values) {
		            const vs = values[prefix];
		            if (!vs)
		                continue;
		            const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());
		            vs.forEach((name) => {
		                if (nameSet.has(name))
		                    return;
		                nameSet.set(name, UsedValueState.Started);
		                let c = valueCode(name);
		                if (c) {
		                    const def = this.opts.es5 ? exports$1.varKinds.var : exports$1.varKinds.const;
		                    code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;
		                }
		                else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {
		                    code = (0, code_1._) `${code}${c}${this.opts._n}`;
		                }
		                else {
		                    throw new ValueError(name);
		                }
		                nameSet.set(name, UsedValueState.Completed);
		            });
		        }
		        return code;
		    }
		}
		exports$1.ValueScope = ValueScope; 
	} (scope$2));
	return scope$2;
}

var hasRequiredCodegen$1;

function requireCodegen$1 () {
	if (hasRequiredCodegen$1) return codegen$1;
	hasRequiredCodegen$1 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.or = exports$1.and = exports$1.not = exports$1.CodeGen = exports$1.operators = exports$1.varKinds = exports$1.ValueScopeName = exports$1.ValueScope = exports$1.Scope = exports$1.Name = exports$1.regexpCode = exports$1.stringify = exports$1.getProperty = exports$1.nil = exports$1.strConcat = exports$1.str = exports$1._ = void 0;
		const code_1 = requireCode$4();
		const scope_1 = requireScope$2();
		var code_2 = requireCode$4();
		Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return code_2._; } });
		Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return code_2.str; } });
		Object.defineProperty(exports$1, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } });
		Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return code_2.nil; } });
		Object.defineProperty(exports$1, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } });
		Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return code_2.stringify; } });
		Object.defineProperty(exports$1, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } });
		Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return code_2.Name; } });
		var scope_2 = requireScope$2();
		Object.defineProperty(exports$1, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } });
		Object.defineProperty(exports$1, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } });
		Object.defineProperty(exports$1, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });
		Object.defineProperty(exports$1, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } });
		exports$1.operators = {
		    GT: new code_1._Code(">"),
		    GTE: new code_1._Code(">="),
		    LT: new code_1._Code("<"),
		    LTE: new code_1._Code("<="),
		    EQ: new code_1._Code("==="),
		    NEQ: new code_1._Code("!=="),
		    NOT: new code_1._Code("!"),
		    OR: new code_1._Code("||"),
		    AND: new code_1._Code("&&"),
		    ADD: new code_1._Code("+"),
		};
		class Node {
		    optimizeNodes() {
		        return this;
		    }
		    optimizeNames(_names, _constants) {
		        return this;
		    }
		}
		class Def extends Node {
		    constructor(varKind, name, rhs) {
		        super();
		        this.varKind = varKind;
		        this.name = name;
		        this.rhs = rhs;
		    }
		    render({ es5, _n }) {
		        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
		        const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
		        return `${varKind} ${this.name}${rhs};` + _n;
		    }
		    optimizeNames(names, constants) {
		        if (!names[this.name.str])
		            return;
		        if (this.rhs)
		            this.rhs = optimizeExpr(this.rhs, names, constants);
		        return this;
		    }
		    get names() {
		        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
		    }
		}
		class Assign extends Node {
		    constructor(lhs, rhs, sideEffects) {
		        super();
		        this.lhs = lhs;
		        this.rhs = rhs;
		        this.sideEffects = sideEffects;
		    }
		    render({ _n }) {
		        return `${this.lhs} = ${this.rhs};` + _n;
		    }
		    optimizeNames(names, constants) {
		        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
		            return;
		        this.rhs = optimizeExpr(this.rhs, names, constants);
		        return this;
		    }
		    get names() {
		        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
		        return addExprNames(names, this.rhs);
		    }
		}
		class AssignOp extends Assign {
		    constructor(lhs, op, rhs, sideEffects) {
		        super(lhs, rhs, sideEffects);
		        this.op = op;
		    }
		    render({ _n }) {
		        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
		    }
		}
		class Label extends Node {
		    constructor(label) {
		        super();
		        this.label = label;
		        this.names = {};
		    }
		    render({ _n }) {
		        return `${this.label}:` + _n;
		    }
		}
		class Break extends Node {
		    constructor(label) {
		        super();
		        this.label = label;
		        this.names = {};
		    }
		    render({ _n }) {
		        const label = this.label ? ` ${this.label}` : "";
		        return `break${label};` + _n;
		    }
		}
		class Throw extends Node {
		    constructor(error) {
		        super();
		        this.error = error;
		    }
		    render({ _n }) {
		        return `throw ${this.error};` + _n;
		    }
		    get names() {
		        return this.error.names;
		    }
		}
		class AnyCode extends Node {
		    constructor(code) {
		        super();
		        this.code = code;
		    }
		    render({ _n }) {
		        return `${this.code};` + _n;
		    }
		    optimizeNodes() {
		        return `${this.code}` ? this : undefined;
		    }
		    optimizeNames(names, constants) {
		        this.code = optimizeExpr(this.code, names, constants);
		        return this;
		    }
		    get names() {
		        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
		    }
		}
		class ParentNode extends Node {
		    constructor(nodes = []) {
		        super();
		        this.nodes = nodes;
		    }
		    render(opts) {
		        return this.nodes.reduce((code, n) => code + n.render(opts), "");
		    }
		    optimizeNodes() {
		        const { nodes } = this;
		        let i = nodes.length;
		        while (i--) {
		            const n = nodes[i].optimizeNodes();
		            if (Array.isArray(n))
		                nodes.splice(i, 1, ...n);
		            else if (n)
		                nodes[i] = n;
		            else
		                nodes.splice(i, 1);
		        }
		        return nodes.length > 0 ? this : undefined;
		    }
		    optimizeNames(names, constants) {
		        const { nodes } = this;
		        let i = nodes.length;
		        while (i--) {
		            const n = nodes[i];
		            if (n.optimizeNames(names, constants))
		                continue;
		            subtractNames(names, n.names);
		            nodes.splice(i, 1);
		        }
		        return nodes.length > 0 ? this : undefined;
		    }
		    get names() {
		        return this.nodes.reduce((names, n) => addNames(names, n.names), {});
		    }
		}
		class BlockNode extends ParentNode {
		    render(opts) {
		        return "{" + opts._n + super.render(opts) + "}" + opts._n;
		    }
		}
		class Root extends ParentNode {
		}
		class Else extends BlockNode {
		}
		Else.kind = "else";
		class If extends BlockNode {
		    constructor(condition, nodes) {
		        super(nodes);
		        this.condition = condition;
		    }
		    render(opts) {
		        let code = `if(${this.condition})` + super.render(opts);
		        if (this.else)
		            code += "else " + this.else.render(opts);
		        return code;
		    }
		    optimizeNodes() {
		        super.optimizeNodes();
		        const cond = this.condition;
		        if (cond === true)
		            return this.nodes;
		        let e = this.else;
		        if (e) {
		            const ns = e.optimizeNodes();
		            e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
		        }
		        if (e) {
		            if (cond === false)
		                return e instanceof If ? e : e.nodes;
		            if (this.nodes.length)
		                return this;
		            return new If(not(cond), e instanceof If ? [e] : e.nodes);
		        }
		        if (cond === false || !this.nodes.length)
		            return undefined;
		        return this;
		    }
		    optimizeNames(names, constants) {
		        var _a;
		        this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
		        if (!(super.optimizeNames(names, constants) || this.else))
		            return;
		        this.condition = optimizeExpr(this.condition, names, constants);
		        return this;
		    }
		    get names() {
		        const names = super.names;
		        addExprNames(names, this.condition);
		        if (this.else)
		            addNames(names, this.else.names);
		        return names;
		    }
		}
		If.kind = "if";
		class For extends BlockNode {
		}
		For.kind = "for";
		class ForLoop extends For {
		    constructor(iteration) {
		        super();
		        this.iteration = iteration;
		    }
		    render(opts) {
		        return `for(${this.iteration})` + super.render(opts);
		    }
		    optimizeNames(names, constants) {
		        if (!super.optimizeNames(names, constants))
		            return;
		        this.iteration = optimizeExpr(this.iteration, names, constants);
		        return this;
		    }
		    get names() {
		        return addNames(super.names, this.iteration.names);
		    }
		}
		class ForRange extends For {
		    constructor(varKind, name, from, to) {
		        super();
		        this.varKind = varKind;
		        this.name = name;
		        this.from = from;
		        this.to = to;
		    }
		    render(opts) {
		        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
		        const { name, from, to } = this;
		        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
		    }
		    get names() {
		        const names = addExprNames(super.names, this.from);
		        return addExprNames(names, this.to);
		    }
		}
		class ForIter extends For {
		    constructor(loop, varKind, name, iterable) {
		        super();
		        this.loop = loop;
		        this.varKind = varKind;
		        this.name = name;
		        this.iterable = iterable;
		    }
		    render(opts) {
		        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
		    }
		    optimizeNames(names, constants) {
		        if (!super.optimizeNames(names, constants))
		            return;
		        this.iterable = optimizeExpr(this.iterable, names, constants);
		        return this;
		    }
		    get names() {
		        return addNames(super.names, this.iterable.names);
		    }
		}
		class Func extends BlockNode {
		    constructor(name, args, async) {
		        super();
		        this.name = name;
		        this.args = args;
		        this.async = async;
		    }
		    render(opts) {
		        const _async = this.async ? "async " : "";
		        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
		    }
		}
		Func.kind = "func";
		class Return extends ParentNode {
		    render(opts) {
		        return "return " + super.render(opts);
		    }
		}
		Return.kind = "return";
		class Try extends BlockNode {
		    render(opts) {
		        let code = "try" + super.render(opts);
		        if (this.catch)
		            code += this.catch.render(opts);
		        if (this.finally)
		            code += this.finally.render(opts);
		        return code;
		    }
		    optimizeNodes() {
		        var _a, _b;
		        super.optimizeNodes();
		        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
		        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
		        return this;
		    }
		    optimizeNames(names, constants) {
		        var _a, _b;
		        super.optimizeNames(names, constants);
		        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
		        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
		        return this;
		    }
		    get names() {
		        const names = super.names;
		        if (this.catch)
		            addNames(names, this.catch.names);
		        if (this.finally)
		            addNames(names, this.finally.names);
		        return names;
		    }
		}
		class Catch extends BlockNode {
		    constructor(error) {
		        super();
		        this.error = error;
		    }
		    render(opts) {
		        return `catch(${this.error})` + super.render(opts);
		    }
		}
		Catch.kind = "catch";
		class Finally extends BlockNode {
		    render(opts) {
		        return "finally" + super.render(opts);
		    }
		}
		Finally.kind = "finally";
		class CodeGen {
		    constructor(extScope, opts = {}) {
		        this._values = {};
		        this._blockStarts = [];
		        this._constants = {};
		        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
		        this._extScope = extScope;
		        this._scope = new scope_1.Scope({ parent: extScope });
		        this._nodes = [new Root()];
		    }
		    toString() {
		        return this._root.render(this.opts);
		    }
		    name(prefix) {
		        return this._scope.name(prefix);
		    }
		    scopeName(prefix) {
		        return this._extScope.name(prefix);
		    }
		    scopeValue(prefixOrName, value) {
		        const name = this._extScope.value(prefixOrName, value);
		        const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
		        vs.add(name);
		        return name;
		    }
		    getScopeValue(prefix, keyOrRef) {
		        return this._extScope.getValue(prefix, keyOrRef);
		    }
		    scopeRefs(scopeName) {
		        return this._extScope.scopeRefs(scopeName, this._values);
		    }
		    scopeCode() {
		        return this._extScope.scopeCode(this._values);
		    }
		    _def(varKind, nameOrPrefix, rhs, constant) {
		        const name = this._scope.toName(nameOrPrefix);
		        if (rhs !== undefined && constant)
		            this._constants[name.str] = rhs;
		        this._leafNode(new Def(varKind, name, rhs));
		        return name;
		    }
		    const(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
		    }
		    let(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
		    }
		    var(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
		    }
		    assign(lhs, rhs, sideEffects) {
		        return this._leafNode(new Assign(lhs, rhs, sideEffects));
		    }
		    add(lhs, rhs) {
		        return this._leafNode(new AssignOp(lhs, exports$1.operators.ADD, rhs));
		    }
		    code(c) {
		        if (typeof c == "function")
		            c();
		        else if (c !== code_1.nil)
		            this._leafNode(new AnyCode(c));
		        return this;
		    }
		    object(...keyValues) {
		        const code = ["{"];
		        for (const [key, value] of keyValues) {
		            if (code.length > 1)
		                code.push(",");
		            code.push(key);
		            if (key !== value || this.opts.es5) {
		                code.push(":");
		                (0, code_1.addCodeArg)(code, value);
		            }
		        }
		        code.push("}");
		        return new code_1._Code(code);
		    }
		    if(condition, thenBody, elseBody) {
		        this._blockNode(new If(condition));
		        if (thenBody && elseBody) {
		            this.code(thenBody).else().code(elseBody).endIf();
		        }
		        else if (thenBody) {
		            this.code(thenBody).endIf();
		        }
		        else if (elseBody) {
		            throw new Error('CodeGen: "else" body without "then" body');
		        }
		        return this;
		    }
		    elseIf(condition) {
		        return this._elseNode(new If(condition));
		    }
		    else() {
		        return this._elseNode(new Else());
		    }
		    endIf() {
		        return this._endBlockNode(If, Else);
		    }
		    _for(node, forBody) {
		        this._blockNode(node);
		        if (forBody)
		            this.code(forBody).endFor();
		        return this;
		    }
		    for(iteration, forBody) {
		        return this._for(new ForLoop(iteration), forBody);
		    }
		    forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
		        const name = this._scope.toName(nameOrPrefix);
		        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
		    }
		    forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
		        const name = this._scope.toName(nameOrPrefix);
		        if (this.opts.es5) {
		            const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
		            return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => {
		                this.var(name, (0, code_1._) `${arr}[${i}]`);
		                forBody(name);
		            });
		        }
		        return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
		    }
		    forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
		        if (this.opts.ownProperties) {
		            return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);
		        }
		        const name = this._scope.toName(nameOrPrefix);
		        return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
		    }
		    endFor() {
		        return this._endBlockNode(For);
		    }
		    label(label) {
		        return this._leafNode(new Label(label));
		    }
		    break(label) {
		        return this._leafNode(new Break(label));
		    }
		    return(value) {
		        const node = new Return();
		        this._blockNode(node);
		        this.code(value);
		        if (node.nodes.length !== 1)
		            throw new Error('CodeGen: "return" should have one node');
		        return this._endBlockNode(Return);
		    }
		    try(tryBody, catchCode, finallyCode) {
		        if (!catchCode && !finallyCode)
		            throw new Error('CodeGen: "try" without "catch" and "finally"');
		        const node = new Try();
		        this._blockNode(node);
		        this.code(tryBody);
		        if (catchCode) {
		            const error = this.name("e");
		            this._currNode = node.catch = new Catch(error);
		            catchCode(error);
		        }
		        if (finallyCode) {
		            this._currNode = node.finally = new Finally();
		            this.code(finallyCode);
		        }
		        return this._endBlockNode(Catch, Finally);
		    }
		    throw(error) {
		        return this._leafNode(new Throw(error));
		    }
		    block(body, nodeCount) {
		        this._blockStarts.push(this._nodes.length);
		        if (body)
		            this.code(body).endBlock(nodeCount);
		        return this;
		    }
		    endBlock(nodeCount) {
		        const len = this._blockStarts.pop();
		        if (len === undefined)
		            throw new Error("CodeGen: not in self-balancing block");
		        const toClose = this._nodes.length - len;
		        if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
		            throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
		        }
		        this._nodes.length = len;
		        return this;
		    }
		    func(name, args = code_1.nil, async, funcBody) {
		        this._blockNode(new Func(name, args, async));
		        if (funcBody)
		            this.code(funcBody).endFunc();
		        return this;
		    }
		    endFunc() {
		        return this._endBlockNode(Func);
		    }
		    optimize(n = 1) {
		        while (n-- > 0) {
		            this._root.optimizeNodes();
		            this._root.optimizeNames(this._root.names, this._constants);
		        }
		    }
		    _leafNode(node) {
		        this._currNode.nodes.push(node);
		        return this;
		    }
		    _blockNode(node) {
		        this._currNode.nodes.push(node);
		        this._nodes.push(node);
		    }
		    _endBlockNode(N1, N2) {
		        const n = this._currNode;
		        if (n instanceof N1 || (N2 && n instanceof N2)) {
		            this._nodes.pop();
		            return this;
		        }
		        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
		    }
		    _elseNode(node) {
		        const n = this._currNode;
		        if (!(n instanceof If)) {
		            throw new Error('CodeGen: "else" without "if"');
		        }
		        this._currNode = n.else = node;
		        return this;
		    }
		    get _root() {
		        return this._nodes[0];
		    }
		    get _currNode() {
		        const ns = this._nodes;
		        return ns[ns.length - 1];
		    }
		    set _currNode(node) {
		        const ns = this._nodes;
		        ns[ns.length - 1] = node;
		    }
		}
		exports$1.CodeGen = CodeGen;
		function addNames(names, from) {
		    for (const n in from)
		        names[n] = (names[n] || 0) + (from[n] || 0);
		    return names;
		}
		function addExprNames(names, from) {
		    return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
		}
		function optimizeExpr(expr, names, constants) {
		    if (expr instanceof code_1.Name)
		        return replaceName(expr);
		    if (!canOptimize(expr))
		        return expr;
		    return new code_1._Code(expr._items.reduce((items, c) => {
		        if (c instanceof code_1.Name)
		            c = replaceName(c);
		        if (c instanceof code_1._Code)
		            items.push(...c._items);
		        else
		            items.push(c);
		        return items;
		    }, []));
		    function replaceName(n) {
		        const c = constants[n.str];
		        if (c === undefined || names[n.str] !== 1)
		            return n;
		        delete names[n.str];
		        return c;
		    }
		    function canOptimize(e) {
		        return (e instanceof code_1._Code &&
		            e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
		    }
		}
		function subtractNames(names, from) {
		    for (const n in from)
		        names[n] = (names[n] || 0) - (from[n] || 0);
		}
		function not(x) {
		    return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`;
		}
		exports$1.not = not;
		const andCode = mappend(exports$1.operators.AND);
		function and(...args) {
		    return args.reduce(andCode);
		}
		exports$1.and = and;
		const orCode = mappend(exports$1.operators.OR);
		function or(...args) {
		    return args.reduce(orCode);
		}
		exports$1.or = or;
		function mappend(op) {
		    return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);
		}
		function par(x) {
		    return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;
		} 
	} (codegen$1));
	return codegen$1;
}

var util$4 = {};

var hasRequiredUtil$4;

function requireUtil$4 () {
	if (hasRequiredUtil$4) return util$4;
	hasRequiredUtil$4 = 1;
	Object.defineProperty(util$4, "__esModule", { value: true });
	util$4.checkStrictMode = util$4.getErrorPath = util$4.Type = util$4.useFunc = util$4.setEvaluated = util$4.evaluatedPropsToName = util$4.mergeEvaluated = util$4.eachItem = util$4.unescapeJsonPointer = util$4.escapeJsonPointer = util$4.escapeFragment = util$4.unescapeFragment = util$4.schemaRefOrVal = util$4.schemaHasRulesButRef = util$4.schemaHasRules = util$4.checkUnknownRules = util$4.alwaysValidSchema = util$4.toHash = void 0;
	const codegen_1 = requireCodegen$1();
	const code_1 = requireCode$4();
	function toHash(arr) {
	    const hash = {};
	    for (const item of arr)
	        hash[item] = true;
	    return hash;
	}
	util$4.toHash = toHash;
	function alwaysValidSchema(it, schema) {
	    if (typeof schema == "boolean")
	        return schema;
	    if (Object.keys(schema).length === 0)
	        return true;
	    checkUnknownRules(it, schema);
	    return !schemaHasRules(schema, it.self.RULES.all);
	}
	util$4.alwaysValidSchema = alwaysValidSchema;
	function checkUnknownRules(it, schema = it.schema) {
	    const { opts, self } = it;
	    if (!opts.strictSchema)
	        return;
	    if (typeof schema === "boolean")
	        return;
	    const rules = self.RULES.keywords;
	    for (const key in schema) {
	        if (!rules[key])
	            checkStrictMode(it, `unknown keyword: "${key}"`);
	    }
	}
	util$4.checkUnknownRules = checkUnknownRules;
	function schemaHasRules(schema, rules) {
	    if (typeof schema == "boolean")
	        return !schema;
	    for (const key in schema)
	        if (rules[key])
	            return true;
	    return false;
	}
	util$4.schemaHasRules = schemaHasRules;
	function schemaHasRulesButRef(schema, RULES) {
	    if (typeof schema == "boolean")
	        return !schema;
	    for (const key in schema)
	        if (key !== "$ref" && RULES.all[key])
	            return true;
	    return false;
	}
	util$4.schemaHasRulesButRef = schemaHasRulesButRef;
	function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
	    if (!$data) {
	        if (typeof schema == "number" || typeof schema == "boolean")
	            return schema;
	        if (typeof schema == "string")
	            return (0, codegen_1._) `${schema}`;
	    }
	    return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
	}
	util$4.schemaRefOrVal = schemaRefOrVal;
	function unescapeFragment(str) {
	    return unescapeJsonPointer(decodeURIComponent(str));
	}
	util$4.unescapeFragment = unescapeFragment;
	function escapeFragment(str) {
	    return encodeURIComponent(escapeJsonPointer(str));
	}
	util$4.escapeFragment = escapeFragment;
	function escapeJsonPointer(str) {
	    if (typeof str == "number")
	        return `${str}`;
	    return str.replace(/~/g, "~0").replace(/\//g, "~1");
	}
	util$4.escapeJsonPointer = escapeJsonPointer;
	function unescapeJsonPointer(str) {
	    return str.replace(/~1/g, "/").replace(/~0/g, "~");
	}
	util$4.unescapeJsonPointer = unescapeJsonPointer;
	function eachItem(xs, f) {
	    if (Array.isArray(xs)) {
	        for (const x of xs)
	            f(x);
	    }
	    else {
	        f(xs);
	    }
	}
	util$4.eachItem = eachItem;
	function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {
	    return (gen, from, to, toName) => {
	        const res = to === undefined
	            ? from
	            : to instanceof codegen_1.Name
	                ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
	                : from instanceof codegen_1.Name
	                    ? (mergeToName(gen, to, from), from)
	                    : mergeValues(from, to);
	        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
	    };
	}
	util$4.mergeEvaluated = {
	    props: makeMergeEvaluated({
	        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {
	            gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`));
	        }),
	        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {
	            if (from === true) {
	                gen.assign(to, true);
	            }
	            else {
	                gen.assign(to, (0, codegen_1._) `${to} || {}`);
	                setEvaluated(gen, to, from);
	            }
	        }),
	        mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),
	        resultToName: evaluatedPropsToName,
	    }),
	    items: makeMergeEvaluated({
	        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
	        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),
	        mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
	        resultToName: (gen, items) => gen.var("items", items),
	    }),
	};
	function evaluatedPropsToName(gen, ps) {
	    if (ps === true)
	        return gen.var("props", true);
	    const props = gen.var("props", (0, codegen_1._) `{}`);
	    if (ps !== undefined)
	        setEvaluated(gen, props, ps);
	    return props;
	}
	util$4.evaluatedPropsToName = evaluatedPropsToName;
	function setEvaluated(gen, props, ps) {
	    Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));
	}
	util$4.setEvaluated = setEvaluated;
	const snippets = {};
	function useFunc(gen, f) {
	    return gen.scopeValue("func", {
	        ref: f,
	        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),
	    });
	}
	util$4.useFunc = useFunc;
	var Type;
	(function (Type) {
	    Type[Type["Num"] = 0] = "Num";
	    Type[Type["Str"] = 1] = "Str";
	})(Type || (util$4.Type = Type = {}));
	function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
	    if (dataProp instanceof codegen_1.Name) {
	        const isNumber = dataPropType === Type.Num;
	        return jsPropertySyntax
	            ? isNumber
	                ? (0, codegen_1._) `"[" + ${dataProp} + "]"`
	                : (0, codegen_1._) `"['" + ${dataProp} + "']"`
	            : isNumber
	                ? (0, codegen_1._) `"/" + ${dataProp}`
	                : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
	    }
	    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
	}
	util$4.getErrorPath = getErrorPath;
	function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
	    if (!mode)
	        return;
	    msg = `strict mode: ${msg}`;
	    if (mode === true)
	        throw new Error(msg);
	    it.self.logger.warn(msg);
	}
	util$4.checkStrictMode = checkStrictMode;
	return util$4;
}

var names$1 = {};

var hasRequiredNames$1;

function requireNames$1 () {
	if (hasRequiredNames$1) return names$1;
	hasRequiredNames$1 = 1;
	Object.defineProperty(names$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const names = {
	    data: new codegen_1.Name("data"),
	    valCxt: new codegen_1.Name("valCxt"),
	    instancePath: new codegen_1.Name("instancePath"),
	    parentData: new codegen_1.Name("parentData"),
	    parentDataProperty: new codegen_1.Name("parentDataProperty"),
	    rootData: new codegen_1.Name("rootData"),
	    dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
	    vErrors: new codegen_1.Name("vErrors"),
	    errors: new codegen_1.Name("errors"),
	    this: new codegen_1.Name("this"),
	    self: new codegen_1.Name("self"),
	    scope: new codegen_1.Name("scope"),
	    json: new codegen_1.Name("json"),
	    jsonPos: new codegen_1.Name("jsonPos"),
	    jsonLen: new codegen_1.Name("jsonLen"),
	    jsonPart: new codegen_1.Name("jsonPart"),
	};
	names$1.default = names;
	return names$1;
}

var hasRequiredErrors$2;

function requireErrors$2 () {
	if (hasRequiredErrors$2) return errors$2;
	hasRequiredErrors$2 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.extendErrors = exports$1.resetErrorsCount = exports$1.reportExtraError = exports$1.reportError = exports$1.keyword$DataError = exports$1.keywordError = void 0;
		const codegen_1 = requireCodegen$1();
		const util_1 = requireUtil$4();
		const names_1 = requireNames$1();
		exports$1.keywordError = {
		    message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`,
		};
		exports$1.keyword$DataError = {
		    message: ({ keyword, schemaType }) => schemaType
		        ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)`
		        : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`,
		};
		function reportError(cxt, error = exports$1.keywordError, errorPaths, overrideAllErrors) {
		    const { it } = cxt;
		    const { gen, compositeRule, allErrors } = it;
		    const errObj = errorObjectCode(cxt, error, errorPaths);
		    if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {
		        addError(gen, errObj);
		    }
		    else {
		        returnErrors(it, (0, codegen_1._) `[${errObj}]`);
		    }
		}
		exports$1.reportError = reportError;
		function reportExtraError(cxt, error = exports$1.keywordError, errorPaths) {
		    const { it } = cxt;
		    const { gen, compositeRule, allErrors } = it;
		    const errObj = errorObjectCode(cxt, error, errorPaths);
		    addError(gen, errObj);
		    if (!(compositeRule || allErrors)) {
		        returnErrors(it, names_1.default.vErrors);
		    }
		}
		exports$1.reportExtraError = reportExtraError;
		function resetErrorsCount(gen, errsCount) {
		    gen.assign(names_1.default.errors, errsCount);
		    gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
		}
		exports$1.resetErrorsCount = resetErrorsCount;
		function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
		    if (errsCount === undefined)
		        throw new Error("ajv implementation error");
		    const err = gen.name("err");
		    gen.forRange("i", errsCount, names_1.default.errors, (i) => {
		        gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);
		        gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
		        gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);
		        if (it.opts.verbose) {
		            gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);
		            gen.assign((0, codegen_1._) `${err}.data`, data);
		        }
		    });
		}
		exports$1.extendErrors = extendErrors;
		function addError(gen, errObj) {
		    const err = gen.const("err", errObj);
		    gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`);
		    gen.code((0, codegen_1._) `${names_1.default.errors}++`);
		}
		function returnErrors(it, errs) {
		    const { gen, validateName, schemaEnv } = it;
		    if (schemaEnv.$async) {
		        gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);
		    }
		    else {
		        gen.assign((0, codegen_1._) `${validateName}.errors`, errs);
		        gen.return(false);
		    }
		}
		const E = {
		    keyword: new codegen_1.Name("keyword"),
		    schemaPath: new codegen_1.Name("schemaPath"),
		    params: new codegen_1.Name("params"),
		    propertyName: new codegen_1.Name("propertyName"),
		    message: new codegen_1.Name("message"),
		    schema: new codegen_1.Name("schema"),
		    parentSchema: new codegen_1.Name("parentSchema"),
		};
		function errorObjectCode(cxt, error, errorPaths) {
		    const { createErrors } = cxt.it;
		    if (createErrors === false)
		        return (0, codegen_1._) `{}`;
		    return errorObject(cxt, error, errorPaths);
		}
		function errorObject(cxt, error, errorPaths = {}) {
		    const { gen, it } = cxt;
		    const keyValues = [
		        errorInstancePath(it, errorPaths),
		        errorSchemaPath(cxt, errorPaths),
		    ];
		    extraErrorProps(cxt, error, keyValues);
		    return gen.object(...keyValues);
		}
		function errorInstancePath({ errorPath }, { instancePath }) {
		    const instPath = instancePath
		        ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`
		        : errorPath;
		    return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
		}
		function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
		    let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;
		    if (schemaPath) {
		        schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
		    }
		    return [E.schemaPath, schPath];
		}
		function extraErrorProps(cxt, { params, message }, keyValues) {
		    const { keyword, data, schemaValue, it } = cxt;
		    const { opts, propertyName, topSchemaRef, schemaPath } = it;
		    keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]);
		    if (opts.messages) {
		        keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
		    }
		    if (opts.verbose) {
		        keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
		    }
		    if (propertyName)
		        keyValues.push([E.propertyName, propertyName]);
		} 
	} (errors$2));
	return errors$2;
}

var hasRequiredBoolSchema$1;

function requireBoolSchema$1 () {
	if (hasRequiredBoolSchema$1) return boolSchema$1;
	hasRequiredBoolSchema$1 = 1;
	Object.defineProperty(boolSchema$1, "__esModule", { value: true });
	boolSchema$1.boolOrEmptySchema = boolSchema$1.topBoolOrEmptySchema = void 0;
	const errors_1 = requireErrors$2();
	const codegen_1 = requireCodegen$1();
	const names_1 = requireNames$1();
	const boolError = {
	    message: "boolean schema is false",
	};
	function topBoolOrEmptySchema(it) {
	    const { gen, schema, validateName } = it;
	    if (schema === false) {
	        falseSchemaError(it, false);
	    }
	    else if (typeof schema == "object" && schema.$async === true) {
	        gen.return(names_1.default.data);
	    }
	    else {
	        gen.assign((0, codegen_1._) `${validateName}.errors`, null);
	        gen.return(true);
	    }
	}
	boolSchema$1.topBoolOrEmptySchema = topBoolOrEmptySchema;
	function boolOrEmptySchema(it, valid) {
	    const { gen, schema } = it;
	    if (schema === false) {
	        gen.var(valid, false);
	        falseSchemaError(it);
	    }
	    else {
	        gen.var(valid, true);
	    }
	}
	boolSchema$1.boolOrEmptySchema = boolOrEmptySchema;
	function falseSchemaError(it, overrideAllErrors) {
	    const { gen, data } = it;
	    const cxt = {
	        gen,
	        keyword: "false schema",
	        data,
	        schema: false,
	        schemaCode: false,
	        schemaValue: false,
	        params: {},
	        it,
	    };
	    (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);
	}
	return boolSchema$1;
}

var dataType$1 = {};

var rules$1 = {};

var hasRequiredRules$1;

function requireRules$1 () {
	if (hasRequiredRules$1) return rules$1;
	hasRequiredRules$1 = 1;
	Object.defineProperty(rules$1, "__esModule", { value: true });
	rules$1.getRules = rules$1.isJSONType = void 0;
	const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
	const jsonTypes = new Set(_jsonTypes);
	function isJSONType(x) {
	    return typeof x == "string" && jsonTypes.has(x);
	}
	rules$1.isJSONType = isJSONType;
	function getRules() {
	    const groups = {
	        number: { type: "number", rules: [] },
	        string: { type: "string", rules: [] },
	        array: { type: "array", rules: [] },
	        object: { type: "object", rules: [] },
	    };
	    return {
	        types: { ...groups, integer: true, boolean: true, null: true },
	        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
	        post: { rules: [] },
	        all: {},
	        keywords: {},
	    };
	}
	rules$1.getRules = getRules;
	return rules$1;
}

var applicability$1 = {};

var hasRequiredApplicability$1;

function requireApplicability$1 () {
	if (hasRequiredApplicability$1) return applicability$1;
	hasRequiredApplicability$1 = 1;
	Object.defineProperty(applicability$1, "__esModule", { value: true });
	applicability$1.shouldUseRule = applicability$1.shouldUseGroup = applicability$1.schemaHasRulesForType = void 0;
	function schemaHasRulesForType({ schema, self }, type) {
	    const group = self.RULES.types[type];
	    return group && group !== true && shouldUseGroup(schema, group);
	}
	applicability$1.schemaHasRulesForType = schemaHasRulesForType;
	function shouldUseGroup(schema, group) {
	    return group.rules.some((rule) => shouldUseRule(schema, rule));
	}
	applicability$1.shouldUseGroup = shouldUseGroup;
	function shouldUseRule(schema, rule) {
	    var _a;
	    return (schema[rule.keyword] !== undefined ||
	        ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));
	}
	applicability$1.shouldUseRule = shouldUseRule;
	return applicability$1;
}

var hasRequiredDataType$1;

function requireDataType$1 () {
	if (hasRequiredDataType$1) return dataType$1;
	hasRequiredDataType$1 = 1;
	Object.defineProperty(dataType$1, "__esModule", { value: true });
	dataType$1.reportTypeError = dataType$1.checkDataTypes = dataType$1.checkDataType = dataType$1.coerceAndCheckDataType = dataType$1.getJSONTypes = dataType$1.getSchemaTypes = dataType$1.DataType = void 0;
	const rules_1 = requireRules$1();
	const applicability_1 = requireApplicability$1();
	const errors_1 = requireErrors$2();
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	var DataType;
	(function (DataType) {
	    DataType[DataType["Correct"] = 0] = "Correct";
	    DataType[DataType["Wrong"] = 1] = "Wrong";
	})(DataType || (dataType$1.DataType = DataType = {}));
	function getSchemaTypes(schema) {
	    const types = getJSONTypes(schema.type);
	    const hasNull = types.includes("null");
	    if (hasNull) {
	        if (schema.nullable === false)
	            throw new Error("type: null contradicts nullable: false");
	    }
	    else {
	        if (!types.length && schema.nullable !== undefined) {
	            throw new Error('"nullable" cannot be used without "type"');
	        }
	        if (schema.nullable === true)
	            types.push("null");
	    }
	    return types;
	}
	dataType$1.getSchemaTypes = getSchemaTypes;
	function getJSONTypes(ts) {
	    const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
	    if (types.every(rules_1.isJSONType))
	        return types;
	    throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
	}
	dataType$1.getJSONTypes = getJSONTypes;
	function coerceAndCheckDataType(it, types) {
	    const { gen, data, opts } = it;
	    const coerceTo = coerceToTypes(types, opts.coerceTypes);
	    const checkTypes = types.length > 0 &&
	        !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
	    if (checkTypes) {
	        const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
	        gen.if(wrongType, () => {
	            if (coerceTo.length)
	                coerceData(it, types, coerceTo);
	            else
	                reportTypeError(it);
	        });
	    }
	    return checkTypes;
	}
	dataType$1.coerceAndCheckDataType = coerceAndCheckDataType;
	const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]);
	function coerceToTypes(types, coerceTypes) {
	    return coerceTypes
	        ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
	        : [];
	}
	function coerceData(it, types, coerceTo) {
	    const { gen, data, opts } = it;
	    const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`);
	    const coerced = gen.let("coerced", (0, codegen_1._) `undefined`);
	    if (opts.coerceTypes === "array") {
	        gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen
	            .assign(data, (0, codegen_1._) `${data}[0]`)
	            .assign(dataType, (0, codegen_1._) `typeof ${data}`)
	            .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
	    }
	    gen.if((0, codegen_1._) `${coerced} !== undefined`);
	    for (const t of coerceTo) {
	        if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
	            coerceSpecificType(t);
	        }
	    }
	    gen.else();
	    reportTypeError(it);
	    gen.endIf();
	    gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {
	        gen.assign(data, coerced);
	        assignParentData(it, coerced);
	    });
	    function coerceSpecificType(t) {
	        switch (t) {
	            case "string":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`)
	                    .assign(coerced, (0, codegen_1._) `"" + ${data}`)
	                    .elseIf((0, codegen_1._) `${data} === null`)
	                    .assign(coerced, (0, codegen_1._) `""`);
	                return;
	            case "number":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`)
	                    .assign(coerced, (0, codegen_1._) `+${data}`);
	                return;
	            case "integer":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`)
	                    .assign(coerced, (0, codegen_1._) `+${data}`);
	                return;
	            case "boolean":
	                gen
	                    .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`)
	                    .assign(coerced, false)
	                    .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`)
	                    .assign(coerced, true);
	                return;
	            case "null":
	                gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`);
	                gen.assign(coerced, null);
	                return;
	            case "array":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`)
	                    .assign(coerced, (0, codegen_1._) `[${data}]`);
	        }
	    }
	}
	function assignParentData({ gen, parentData, parentDataProperty }, expr) {
	    gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));
	}
	function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
	    const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
	    let cond;
	    switch (dataType) {
	        case "null":
	            return (0, codegen_1._) `${data} ${EQ} null`;
	        case "array":
	            cond = (0, codegen_1._) `Array.isArray(${data})`;
	            break;
	        case "object":
	            cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
	            break;
	        case "integer":
	            cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);
	            break;
	        case "number":
	            cond = numCond();
	            break;
	        default:
	            return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;
	    }
	    return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
	    function numCond(_cond = codegen_1.nil) {
	        return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);
	    }
	}
	dataType$1.checkDataType = checkDataType;
	function checkDataTypes(dataTypes, data, strictNums, correct) {
	    if (dataTypes.length === 1) {
	        return checkDataType(dataTypes[0], data, strictNums, correct);
	    }
	    let cond;
	    const types = (0, util_1.toHash)(dataTypes);
	    if (types.array && types.object) {
	        const notObj = (0, codegen_1._) `typeof ${data} != "object"`;
	        cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;
	        delete types.null;
	        delete types.array;
	        delete types.object;
	    }
	    else {
	        cond = codegen_1.nil;
	    }
	    if (types.number)
	        delete types.integer;
	    for (const t in types)
	        cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
	    return cond;
	}
	dataType$1.checkDataTypes = checkDataTypes;
	const typeError = {
	    message: ({ schema }) => `must be ${schema}`,
	    params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,
	};
	function reportTypeError(it) {
	    const cxt = getTypeErrorContext(it);
	    (0, errors_1.reportError)(cxt, typeError);
	}
	dataType$1.reportTypeError = reportTypeError;
	function getTypeErrorContext(it) {
	    const { gen, data, schema } = it;
	    const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
	    return {
	        gen,
	        keyword: "type",
	        data,
	        schema: schema.type,
	        schemaCode,
	        schemaValue: schemaCode,
	        parentSchema: schema,
	        params: {},
	        it,
	    };
	}
	return dataType$1;
}

var defaults$2 = {};

var hasRequiredDefaults$1;

function requireDefaults$1 () {
	if (hasRequiredDefaults$1) return defaults$2;
	hasRequiredDefaults$1 = 1;
	Object.defineProperty(defaults$2, "__esModule", { value: true });
	defaults$2.assignDefaults = void 0;
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	function assignDefaults(it, ty) {
	    const { properties, items } = it.schema;
	    if (ty === "object" && properties) {
	        for (const key in properties) {
	            assignDefault(it, key, properties[key].default);
	        }
	    }
	    else if (ty === "array" && Array.isArray(items)) {
	        items.forEach((sch, i) => assignDefault(it, i, sch.default));
	    }
	}
	defaults$2.assignDefaults = assignDefaults;
	function assignDefault(it, prop, defaultValue) {
	    const { gen, compositeRule, data, opts } = it;
	    if (defaultValue === undefined)
	        return;
	    const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;
	    if (compositeRule) {
	        (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
	        return;
	    }
	    let condition = (0, codegen_1._) `${childData} === undefined`;
	    if (opts.useDefaults === "empty") {
	        condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`;
	    }
	    gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
	}
	return defaults$2;
}

var keyword$2 = {};

var code$3 = {};

var hasRequiredCode$3;

function requireCode$3 () {
	if (hasRequiredCode$3) return code$3;
	hasRequiredCode$3 = 1;
	Object.defineProperty(code$3, "__esModule", { value: true });
	code$3.validateUnion = code$3.validateArray = code$3.usePattern = code$3.callValidateCode = code$3.schemaProperties = code$3.allSchemaProperties = code$3.noPropertyInData = code$3.propertyInData = code$3.isOwnProperty = code$3.hasPropFunc = code$3.reportMissingProp = code$3.checkMissingProp = code$3.checkReportMissingProp = void 0;
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const names_1 = requireNames$1();
	const util_2 = requireUtil$4();
	function checkReportMissingProp(cxt, prop) {
	    const { gen, data, it } = cxt;
	    gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
	        cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);
	        cxt.error();
	    });
	}
	code$3.checkReportMissingProp = checkReportMissingProp;
	function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
	    return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));
	}
	code$3.checkMissingProp = checkMissingProp;
	function reportMissingProp(cxt, missing) {
	    cxt.setParams({ missingProperty: missing }, true);
	    cxt.error();
	}
	code$3.reportMissingProp = reportMissingProp;
	function hasPropFunc(gen) {
	    return gen.scopeValue("func", {
	        ref: Object.prototype.hasOwnProperty,
	        code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,
	    });
	}
	code$3.hasPropFunc = hasPropFunc;
	function isOwnProperty(gen, data, property) {
	    return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;
	}
	code$3.isOwnProperty = isOwnProperty;
	function propertyInData(gen, data, property, ownProperties) {
	    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
	    return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;
	}
	code$3.propertyInData = propertyInData;
	function noPropertyInData(gen, data, property, ownProperties) {
	    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;
	    return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
	}
	code$3.noPropertyInData = noPropertyInData;
	function allSchemaProperties(schemaMap) {
	    return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
	}
	code$3.allSchemaProperties = allSchemaProperties;
	function schemaProperties(it, schemaMap) {
	    return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
	}
	code$3.schemaProperties = schemaProperties;
	function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
	    const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
	    const valCxt = [
	        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
	        [names_1.default.parentData, it.parentData],
	        [names_1.default.parentDataProperty, it.parentDataProperty],
	        [names_1.default.rootData, names_1.default.rootData],
	    ];
	    if (it.opts.dynamicRef)
	        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
	    const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;
	    return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;
	}
	code$3.callValidateCode = callValidateCode;
	const newRegExp = (0, codegen_1._) `new RegExp`;
	function usePattern({ gen, it: { opts } }, pattern) {
	    const u = opts.unicodeRegExp ? "u" : "";
	    const { regExp } = opts.code;
	    const rx = regExp(pattern, u);
	    return gen.scopeValue("pattern", {
	        key: rx.toString(),
	        ref: rx,
	        code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,
	    });
	}
	code$3.usePattern = usePattern;
	function validateArray(cxt) {
	    const { gen, data, keyword, it } = cxt;
	    const valid = gen.name("valid");
	    if (it.allErrors) {
	        const validArr = gen.let("valid", true);
	        validateItems(() => gen.assign(validArr, false));
	        return validArr;
	    }
	    gen.var(valid, true);
	    validateItems(() => gen.break());
	    return valid;
	    function validateItems(notValid) {
	        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	        gen.forRange("i", 0, len, (i) => {
	            cxt.subschema({
	                keyword,
	                dataProp: i,
	                dataPropType: util_1.Type.Num,
	            }, valid);
	            gen.if((0, codegen_1.not)(valid), notValid);
	        });
	    }
	}
	code$3.validateArray = validateArray;
	function validateUnion(cxt) {
	    const { gen, schema, keyword, it } = cxt;
	    if (!Array.isArray(schema))
	        throw new Error("ajv implementation error");
	    const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
	    if (alwaysValid && !it.opts.unevaluated)
	        return;
	    const valid = gen.let("valid", false);
	    const schValid = gen.name("_valid");
	    gen.block(() => schema.forEach((_sch, i) => {
	        const schCxt = cxt.subschema({
	            keyword,
	            schemaProp: i,
	            compositeRule: true,
	        }, schValid);
	        gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);
	        const merged = cxt.mergeValidEvaluated(schCxt, schValid);
	        if (!merged)
	            gen.if((0, codegen_1.not)(valid));
	    }));
	    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
	}
	code$3.validateUnion = validateUnion;
	return code$3;
}

var hasRequiredKeyword$2;

function requireKeyword$2 () {
	if (hasRequiredKeyword$2) return keyword$2;
	hasRequiredKeyword$2 = 1;
	Object.defineProperty(keyword$2, "__esModule", { value: true });
	keyword$2.validateKeywordUsage = keyword$2.validSchemaType = keyword$2.funcKeywordCode = keyword$2.macroKeywordCode = void 0;
	const codegen_1 = requireCodegen$1();
	const names_1 = requireNames$1();
	const code_1 = requireCode$3();
	const errors_1 = requireErrors$2();
	function macroKeywordCode(cxt, def) {
	    const { gen, keyword, schema, parentSchema, it } = cxt;
	    const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
	    const schemaRef = useKeyword(gen, keyword, macroSchema);
	    if (it.opts.validateSchema !== false)
	        it.self.validateSchema(macroSchema, true);
	    const valid = gen.name("valid");
	    cxt.subschema({
	        schema: macroSchema,
	        schemaPath: codegen_1.nil,
	        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
	        topSchemaRef: schemaRef,
	        compositeRule: true,
	    }, valid);
	    cxt.pass(valid, () => cxt.error(true));
	}
	keyword$2.macroKeywordCode = macroKeywordCode;
	function funcKeywordCode(cxt, def) {
	    var _a;
	    const { gen, keyword, schema, parentSchema, $data, it } = cxt;
	    checkAsyncKeyword(it, def);
	    const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
	    const validateRef = useKeyword(gen, keyword, validate);
	    const valid = gen.let("valid");
	    cxt.block$data(valid, validateKeyword);
	    cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
	    function validateKeyword() {
	        if (def.errors === false) {
	            assignValid();
	            if (def.modifying)
	                modifyData(cxt);
	            reportErrs(() => cxt.error());
	        }
	        else {
	            const ruleErrs = def.async ? validateAsync() : validateSync();
	            if (def.modifying)
	                modifyData(cxt);
	            reportErrs(() => addErrs(cxt, ruleErrs));
	        }
	    }
	    function validateAsync() {
	        const ruleErrs = gen.let("ruleErrs", null);
	        gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));
	        return ruleErrs;
	    }
	    function validateSync() {
	        const validateErrs = (0, codegen_1._) `${validateRef}.errors`;
	        gen.assign(validateErrs, null);
	        assignValid(codegen_1.nil);
	        return validateErrs;
	    }
	    function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {
	        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
	        const passSchema = !(("compile" in def && !$data) || def.schema === false);
	        gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
	    }
	    function reportErrs(errors) {
	        var _a;
	        gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
	    }
	}
	keyword$2.funcKeywordCode = funcKeywordCode;
	function modifyData(cxt) {
	    const { gen, data, it } = cxt;
	    gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));
	}
	function addErrs(cxt, errs) {
	    const { gen } = cxt;
	    gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {
	        gen
	            .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)
	            .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
	        (0, errors_1.extendErrors)(cxt);
	    }, () => cxt.error());
	}
	function checkAsyncKeyword({ schemaEnv }, def) {
	    if (def.async && !schemaEnv.$async)
	        throw new Error("async keyword in sync schema");
	}
	function useKeyword(gen, keyword, result) {
	    if (result === undefined)
	        throw new Error(`keyword "${keyword}" failed to compile`);
	    return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
	}
	function validSchemaType(schema, schemaType, allowUndefined = false) {
	    return (!schemaType.length ||
	        schemaType.some((st) => st === "array"
	            ? Array.isArray(schema)
	            : st === "object"
	                ? schema && typeof schema == "object" && !Array.isArray(schema)
	                : typeof schema == st || (allowUndefined && typeof schema == "undefined")));
	}
	keyword$2.validSchemaType = validSchemaType;
	function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
	    if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
	        throw new Error("ajv implementation error");
	    }
	    const deps = def.dependencies;
	    if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
	        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
	    }
	    if (def.validateSchema) {
	        const valid = def.validateSchema(schema[keyword]);
	        if (!valid) {
	            const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
	                self.errorsText(def.validateSchema.errors);
	            if (opts.validateSchema === "log")
	                self.logger.error(msg);
	            else
	                throw new Error(msg);
	        }
	    }
	}
	keyword$2.validateKeywordUsage = validateKeywordUsage;
	return keyword$2;
}

var subschema$1 = {};

var hasRequiredSubschema$1;

function requireSubschema$1 () {
	if (hasRequiredSubschema$1) return subschema$1;
	hasRequiredSubschema$1 = 1;
	Object.defineProperty(subschema$1, "__esModule", { value: true });
	subschema$1.extendSubschemaMode = subschema$1.extendSubschemaData = subschema$1.getSubschema = void 0;
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
	    if (keyword !== undefined && schema !== undefined) {
	        throw new Error('both "keyword" and "schema" passed, only one allowed');
	    }
	    if (keyword !== undefined) {
	        const sch = it.schema[keyword];
	        return schemaProp === undefined
	            ? {
	                schema: sch,
	                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
	                errSchemaPath: `${it.errSchemaPath}/${keyword}`,
	            }
	            : {
	                schema: sch[schemaProp],
	                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
	                errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,
	            };
	    }
	    if (schema !== undefined) {
	        if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
	            throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
	        }
	        return {
	            schema,
	            schemaPath,
	            topSchemaRef,
	            errSchemaPath,
	        };
	    }
	    throw new Error('either "keyword" or "schema" must be passed');
	}
	subschema$1.getSubschema = getSubschema;
	function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
	    if (data !== undefined && dataProp !== undefined) {
	        throw new Error('both "data" and "dataProp" passed, only one allowed');
	    }
	    const { gen } = it;
	    if (dataProp !== undefined) {
	        const { errorPath, dataPathArr, opts } = it;
	        const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
	        dataContextProps(nextData);
	        subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
	        subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;
	        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
	    }
	    if (data !== undefined) {
	        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);
	        dataContextProps(nextData);
	        if (propertyName !== undefined)
	            subschema.propertyName = propertyName;
	    }
	    if (dataTypes)
	        subschema.dataTypes = dataTypes;
	    function dataContextProps(_nextData) {
	        subschema.data = _nextData;
	        subschema.dataLevel = it.dataLevel + 1;
	        subschema.dataTypes = [];
	        it.definedProperties = new Set();
	        subschema.parentData = it.data;
	        subschema.dataNames = [...it.dataNames, _nextData];
	    }
	}
	subschema$1.extendSubschemaData = extendSubschemaData;
	function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
	    if (compositeRule !== undefined)
	        subschema.compositeRule = compositeRule;
	    if (createErrors !== undefined)
	        subschema.createErrors = createErrors;
	    if (allErrors !== undefined)
	        subschema.allErrors = allErrors;
	    subschema.jtdDiscriminator = jtdDiscriminator;
	    subschema.jtdMetadata = jtdMetadata;
	}
	subschema$1.extendSubschemaMode = extendSubschemaMode;
	return subschema$1;
}

var resolve$1 = {};

var fastDeepEqual;
var hasRequiredFastDeepEqual;

function requireFastDeepEqual () {
	if (hasRequiredFastDeepEqual) return fastDeepEqual;
	hasRequiredFastDeepEqual = 1;
	fastDeepEqual = function equal(a, b) {
	  if (a === b) return true;
	  if (a && b && typeof a == 'object' && typeof b == 'object') {
	    if (a.constructor !== b.constructor) return false;
	    var length, i, keys;
	    if (Array.isArray(a)) {
	      length = a.length;
	      if (length != b.length) return false;
	      for (i = length; i-- !== 0;)
	        if (!equal(a[i], b[i])) return false;
	      return true;
	    }
	    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
	    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
	    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
	    keys = Object.keys(a);
	    length = keys.length;
	    if (length !== Object.keys(b).length) return false;
	    for (i = length; i-- !== 0;)
	      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
	    for (i = length; i-- !== 0;) {
	      var key = keys[i];
	      if (!equal(a[key], b[key])) return false;
	    }
	    return true;
	  }
	  return a!==a && b!==b;
	};
	return fastDeepEqual;
}

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

var hasRequiredJsonSchemaTraverse$1;

function requireJsonSchemaTraverse$1 () {
	if (hasRequiredJsonSchemaTraverse$1) return jsonSchemaTraverse$1.exports;
	hasRequiredJsonSchemaTraverse$1 = 1;
	var traverse = jsonSchemaTraverse$1.exports = function (schema, opts, cb) {
	  if (typeof opts == 'function') {
	    cb = opts;
	    opts = {};
	  }
	  cb = opts.cb || cb;
	  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
	  var post = cb.post || function() {};
	  _traverse(opts, pre, post, schema, '', schema);
	};
	traverse.keywords = {
	  additionalItems: true,
	  items: true,
	  contains: true,
	  additionalProperties: true,
	  propertyNames: true,
	  not: true,
	  if: true,
	  then: true,
	  else: true
	};
	traverse.arrayKeywords = {
	  items: true,
	  allOf: true,
	  anyOf: true,
	  oneOf: true
	};
	traverse.propsKeywords = {
	  $defs: true,
	  definitions: true,
	  properties: true,
	  patternProperties: true,
	  dependencies: true
	};
	traverse.skipKeywords = {
	  default: true,
	  enum: true,
	  const: true,
	  required: true,
	  maximum: true,
	  minimum: true,
	  exclusiveMaximum: true,
	  exclusiveMinimum: true,
	  multipleOf: true,
	  maxLength: true,
	  minLength: true,
	  pattern: true,
	  format: true,
	  maxItems: true,
	  minItems: true,
	  uniqueItems: true,
	  maxProperties: true,
	  minProperties: true
	};
	function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
	  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
	    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
	    for (var key in schema) {
	      var sch = schema[key];
	      if (Array.isArray(sch)) {
	        if (key in traverse.arrayKeywords) {
	          for (var i=0; i<sch.length; i++)
	            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
	        }
	      } else if (key in traverse.propsKeywords) {
	        if (sch && typeof sch == 'object') {
	          for (var prop in sch)
	            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
	        }
	      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
	        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
	      }
	    }
	    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
	  }
	}
	function escapeJsonPtr(str) {
	  return str.replace(/~/g, '~0').replace(/\//g, '~1');
	}
	return jsonSchemaTraverse$1.exports;
}

var hasRequiredResolve$1;

function requireResolve$1 () {
	if (hasRequiredResolve$1) return resolve$1;
	hasRequiredResolve$1 = 1;
	Object.defineProperty(resolve$1, "__esModule", { value: true });
	resolve$1.getSchemaRefs = resolve$1.resolveUrl = resolve$1.normalizeId = resolve$1._getFullPath = resolve$1.getFullPath = resolve$1.inlineRef = void 0;
	const util_1 = requireUtil$4();
	const equal = requireFastDeepEqual();
	const traverse = requireJsonSchemaTraverse$1();
	const SIMPLE_INLINED = new Set([
	    "type",
	    "format",
	    "pattern",
	    "maxLength",
	    "minLength",
	    "maxProperties",
	    "minProperties",
	    "maxItems",
	    "minItems",
	    "maximum",
	    "minimum",
	    "uniqueItems",
	    "multipleOf",
	    "required",
	    "enum",
	    "const",
	]);
	function inlineRef(schema, limit = true) {
	    if (typeof schema == "boolean")
	        return true;
	    if (limit === true)
	        return !hasRef(schema);
	    if (!limit)
	        return false;
	    return countKeys(schema) <= limit;
	}
	resolve$1.inlineRef = inlineRef;
	const REF_KEYWORDS = new Set([
	    "$ref",
	    "$recursiveRef",
	    "$recursiveAnchor",
	    "$dynamicRef",
	    "$dynamicAnchor",
	]);
	function hasRef(schema) {
	    for (const key in schema) {
	        if (REF_KEYWORDS.has(key))
	            return true;
	        const sch = schema[key];
	        if (Array.isArray(sch) && sch.some(hasRef))
	            return true;
	        if (typeof sch == "object" && hasRef(sch))
	            return true;
	    }
	    return false;
	}
	function countKeys(schema) {
	    let count = 0;
	    for (const key in schema) {
	        if (key === "$ref")
	            return Infinity;
	        count++;
	        if (SIMPLE_INLINED.has(key))
	            continue;
	        if (typeof schema[key] == "object") {
	            (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));
	        }
	        if (count === Infinity)
	            return Infinity;
	    }
	    return count;
	}
	function getFullPath(resolver, id = "", normalize) {
	    if (normalize !== false)
	        id = normalizeId(id);
	    const p = resolver.parse(id);
	    return _getFullPath(resolver, p);
	}
	resolve$1.getFullPath = getFullPath;
	function _getFullPath(resolver, p) {
	    const serialized = resolver.serialize(p);
	    return serialized.split("#")[0] + "#";
	}
	resolve$1._getFullPath = _getFullPath;
	const TRAILING_SLASH_HASH = /#\/?$/;
	function normalizeId(id) {
	    return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
	}
	resolve$1.normalizeId = normalizeId;
	function resolveUrl(resolver, baseId, id) {
	    id = normalizeId(id);
	    return resolver.resolve(baseId, id);
	}
	resolve$1.resolveUrl = resolveUrl;
	const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
	function getSchemaRefs(schema, baseId) {
	    if (typeof schema == "boolean")
	        return {};
	    const { schemaId, uriResolver } = this.opts;
	    const schId = normalizeId(schema[schemaId] || baseId);
	    const baseIds = { "": schId };
	    const pathPrefix = getFullPath(uriResolver, schId, false);
	    const localRefs = {};
	    const schemaRefs = new Set();
	    traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
	        if (parentJsonPtr === undefined)
	            return;
	        const fullPath = pathPrefix + jsonPtr;
	        let innerBaseId = baseIds[parentJsonPtr];
	        if (typeof sch[schemaId] == "string")
	            innerBaseId = addRef.call(this, sch[schemaId]);
	        addAnchor.call(this, sch.$anchor);
	        addAnchor.call(this, sch.$dynamicAnchor);
	        baseIds[jsonPtr] = innerBaseId;
	        function addRef(ref) {
	            const _resolve = this.opts.uriResolver.resolve;
	            ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
	            if (schemaRefs.has(ref))
	                throw ambiguos(ref);
	            schemaRefs.add(ref);
	            let schOrRef = this.refs[ref];
	            if (typeof schOrRef == "string")
	                schOrRef = this.refs[schOrRef];
	            if (typeof schOrRef == "object") {
	                checkAmbiguosRef(sch, schOrRef.schema, ref);
	            }
	            else if (ref !== normalizeId(fullPath)) {
	                if (ref[0] === "#") {
	                    checkAmbiguosRef(sch, localRefs[ref], ref);
	                    localRefs[ref] = sch;
	                }
	                else {
	                    this.refs[ref] = fullPath;
	                }
	            }
	            return ref;
	        }
	        function addAnchor(anchor) {
	            if (typeof anchor == "string") {
	                if (!ANCHOR.test(anchor))
	                    throw new Error(`invalid anchor "${anchor}"`);
	                addRef.call(this, `#${anchor}`);
	            }
	        }
	    });
	    return localRefs;
	    function checkAmbiguosRef(sch1, sch2, ref) {
	        if (sch2 !== undefined && !equal(sch1, sch2))
	            throw ambiguos(ref);
	    }
	    function ambiguos(ref) {
	        return new Error(`reference "${ref}" resolves to more than one schema`);
	    }
	}
	resolve$1.getSchemaRefs = getSchemaRefs;
	return resolve$1;
}

var hasRequiredValidate$1;

function requireValidate$1 () {
	if (hasRequiredValidate$1) return validate$1;
	hasRequiredValidate$1 = 1;
	Object.defineProperty(validate$1, "__esModule", { value: true });
	validate$1.getData = validate$1.KeywordCxt = validate$1.validateFunctionCode = void 0;
	const boolSchema_1 = requireBoolSchema$1();
	const dataType_1 = requireDataType$1();
	const applicability_1 = requireApplicability$1();
	const dataType_2 = requireDataType$1();
	const defaults_1 = requireDefaults$1();
	const keyword_1 = requireKeyword$2();
	const subschema_1 = requireSubschema$1();
	const codegen_1 = requireCodegen$1();
	const names_1 = requireNames$1();
	const resolve_1 = requireResolve$1();
	const util_1 = requireUtil$4();
	const errors_1 = requireErrors$2();
	function validateFunctionCode(it) {
	    if (isSchemaObj(it)) {
	        checkKeywords(it);
	        if (schemaCxtHasRules(it)) {
	            topSchemaObjCode(it);
	            return;
	        }
	    }
	    validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
	}
	validate$1.validateFunctionCode = validateFunctionCode;
	function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
	    if (opts.code.es5) {
	        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
	            gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`);
	            destructureValCxtES5(gen, opts);
	            gen.code(body);
	        });
	    }
	    else {
	        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
	    }
	}
	function destructureValCxt(opts) {
	    return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
	}
	function destructureValCxtES5(gen, opts) {
	    gen.if(names_1.default.valCxt, () => {
	        gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);
	        gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);
	        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
	        gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);
	        if (opts.dynamicRef)
	            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
	    }, () => {
	        gen.var(names_1.default.instancePath, (0, codegen_1._) `""`);
	        gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);
	        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);
	        gen.var(names_1.default.rootData, names_1.default.data);
	        if (opts.dynamicRef)
	            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);
	    });
	}
	function topSchemaObjCode(it) {
	    const { schema, opts, gen } = it;
	    validateFunction(it, () => {
	        if (opts.$comment && schema.$comment)
	            commentKeyword(it);
	        checkNoDefault(it);
	        gen.let(names_1.default.vErrors, null);
	        gen.let(names_1.default.errors, 0);
	        if (opts.unevaluated)
	            resetEvaluated(it);
	        typeAndKeywords(it);
	        returnResults(it);
	    });
	    return;
	}
	function resetEvaluated(it) {
	    const { gen, validateName } = it;
	    it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`);
	    gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));
	    gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));
	}
	function funcSourceUrl(schema, opts) {
	    const schId = typeof schema == "object" && schema[opts.schemaId];
	    return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;
	}
	function subschemaCode(it, valid) {
	    if (isSchemaObj(it)) {
	        checkKeywords(it);
	        if (schemaCxtHasRules(it)) {
	            subSchemaObjCode(it, valid);
	            return;
	        }
	    }
	    (0, boolSchema_1.boolOrEmptySchema)(it, valid);
	}
	function schemaCxtHasRules({ schema, self }) {
	    if (typeof schema == "boolean")
	        return !schema;
	    for (const key in schema)
	        if (self.RULES.all[key])
	            return true;
	    return false;
	}
	function isSchemaObj(it) {
	    return typeof it.schema != "boolean";
	}
	function subSchemaObjCode(it, valid) {
	    const { schema, gen, opts } = it;
	    if (opts.$comment && schema.$comment)
	        commentKeyword(it);
	    updateContext(it);
	    checkAsyncSchema(it);
	    const errsCount = gen.const("_errs", names_1.default.errors);
	    typeAndKeywords(it, errsCount);
	    gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
	}
	function checkKeywords(it) {
	    (0, util_1.checkUnknownRules)(it);
	    checkRefsAndKeywords(it);
	}
	function typeAndKeywords(it, errsCount) {
	    if (it.opts.jtd)
	        return schemaKeywords(it, [], false, errsCount);
	    const types = (0, dataType_1.getSchemaTypes)(it.schema);
	    const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
	    schemaKeywords(it, types, !checkedTypes, errsCount);
	}
	function checkRefsAndKeywords(it) {
	    const { schema, errSchemaPath, opts, self } = it;
	    if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
	        self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
	    }
	}
	function checkNoDefault(it) {
	    const { schema, opts } = it;
	    if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
	        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
	    }
	}
	function updateContext(it) {
	    const schId = it.schema[it.opts.schemaId];
	    if (schId)
	        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
	}
	function checkAsyncSchema(it) {
	    if (it.schema.$async && !it.schemaEnv.$async)
	        throw new Error("async schema in sync schema");
	}
	function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
	    const msg = schema.$comment;
	    if (opts.$comment === true) {
	        gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);
	    }
	    else if (typeof opts.$comment == "function") {
	        const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;
	        const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
	        gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
	    }
	}
	function returnResults(it) {
	    const { gen, schemaEnv, validateName, ValidationError, opts } = it;
	    if (schemaEnv.$async) {
	        gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));
	    }
	    else {
	        gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);
	        if (opts.unevaluated)
	            assignEvaluated(it);
	        gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);
	    }
	}
	function assignEvaluated({ gen, evaluated, props, items }) {
	    if (props instanceof codegen_1.Name)
	        gen.assign((0, codegen_1._) `${evaluated}.props`, props);
	    if (items instanceof codegen_1.Name)
	        gen.assign((0, codegen_1._) `${evaluated}.items`, items);
	}
	function schemaKeywords(it, types, typeErrors, errsCount) {
	    const { gen, schema, data, allErrors, opts, self } = it;
	    const { RULES } = self;
	    if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
	        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
	        return;
	    }
	    if (!opts.jtd)
	        checkStrictTypes(it, types);
	    gen.block(() => {
	        for (const group of RULES.rules)
	            groupKeywords(group);
	        groupKeywords(RULES.post);
	    });
	    function groupKeywords(group) {
	        if (!(0, applicability_1.shouldUseGroup)(schema, group))
	            return;
	        if (group.type) {
	            gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
	            iterateKeywords(it, group);
	            if (types.length === 1 && types[0] === group.type && typeErrors) {
	                gen.else();
	                (0, dataType_2.reportTypeError)(it);
	            }
	            gen.endIf();
	        }
	        else {
	            iterateKeywords(it, group);
	        }
	        if (!allErrors)
	            gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);
	    }
	}
	function iterateKeywords(it, group) {
	    const { gen, schema, opts: { useDefaults }, } = it;
	    if (useDefaults)
	        (0, defaults_1.assignDefaults)(it, group.type);
	    gen.block(() => {
	        for (const rule of group.rules) {
	            if ((0, applicability_1.shouldUseRule)(schema, rule)) {
	                keywordCode(it, rule.keyword, rule.definition, group.type);
	            }
	        }
	    });
	}
	function checkStrictTypes(it, types) {
	    if (it.schemaEnv.meta || !it.opts.strictTypes)
	        return;
	    checkContextTypes(it, types);
	    if (!it.opts.allowUnionTypes)
	        checkMultipleTypes(it, types);
	    checkKeywordTypes(it, it.dataTypes);
	}
	function checkContextTypes(it, types) {
	    if (!types.length)
	        return;
	    if (!it.dataTypes.length) {
	        it.dataTypes = types;
	        return;
	    }
	    types.forEach((t) => {
	        if (!includesType(it.dataTypes, t)) {
	            strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
	        }
	    });
	    narrowSchemaTypes(it, types);
	}
	function checkMultipleTypes(it, ts) {
	    if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
	        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
	    }
	}
	function checkKeywordTypes(it, ts) {
	    const rules = it.self.RULES.all;
	    for (const keyword in rules) {
	        const rule = rules[keyword];
	        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
	            const { type } = rule.definition;
	            if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
	                strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
	            }
	        }
	    }
	}
	function hasApplicableType(schTs, kwdT) {
	    return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"));
	}
	function includesType(ts, t) {
	    return ts.includes(t) || (t === "integer" && ts.includes("number"));
	}
	function narrowSchemaTypes(it, withTypes) {
	    const ts = [];
	    for (const t of it.dataTypes) {
	        if (includesType(withTypes, t))
	            ts.push(t);
	        else if (withTypes.includes("integer") && t === "number")
	            ts.push("integer");
	    }
	    it.dataTypes = ts;
	}
	function strictTypesError(it, msg) {
	    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
	    msg += ` at "${schemaPath}" (strictTypes)`;
	    (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
	}
	class KeywordCxt {
	    constructor(it, def, keyword) {
	        (0, keyword_1.validateKeywordUsage)(it, def, keyword);
	        this.gen = it.gen;
	        this.allErrors = it.allErrors;
	        this.keyword = keyword;
	        this.data = it.data;
	        this.schema = it.schema[keyword];
	        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
	        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
	        this.schemaType = def.schemaType;
	        this.parentSchema = it.schema;
	        this.params = {};
	        this.it = it;
	        this.def = def;
	        if (this.$data) {
	            this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
	        }
	        else {
	            this.schemaCode = this.schemaValue;
	            if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
	                throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
	            }
	        }
	        if ("code" in def ? def.trackErrors : def.errors !== false) {
	            this.errsCount = it.gen.const("_errs", names_1.default.errors);
	        }
	    }
	    result(condition, successAction, failAction) {
	        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
	    }
	    failResult(condition, successAction, failAction) {
	        this.gen.if(condition);
	        if (failAction)
	            failAction();
	        else
	            this.error();
	        if (successAction) {
	            this.gen.else();
	            successAction();
	            if (this.allErrors)
	                this.gen.endIf();
	        }
	        else {
	            if (this.allErrors)
	                this.gen.endIf();
	            else
	                this.gen.else();
	        }
	    }
	    pass(condition, failAction) {
	        this.failResult((0, codegen_1.not)(condition), undefined, failAction);
	    }
	    fail(condition) {
	        if (condition === undefined) {
	            this.error();
	            if (!this.allErrors)
	                this.gen.if(false);
	            return;
	        }
	        this.gen.if(condition);
	        this.error();
	        if (this.allErrors)
	            this.gen.endIf();
	        else
	            this.gen.else();
	    }
	    fail$data(condition) {
	        if (!this.$data)
	            return this.fail(condition);
	        const { schemaCode } = this;
	        this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
	    }
	    error(append, errorParams, errorPaths) {
	        if (errorParams) {
	            this.setParams(errorParams);
	            this._error(append, errorPaths);
	            this.setParams({});
	            return;
	        }
	        this._error(append, errorPaths);
	    }
	    _error(append, errorPaths) {
	        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
	    }
	    $dataError() {
	        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
	    }
	    reset() {
	        if (this.errsCount === undefined)
	            throw new Error('add "trackErrors" to keyword definition');
	        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
	    }
	    ok(cond) {
	        if (!this.allErrors)
	            this.gen.if(cond);
	    }
	    setParams(obj, assign) {
	        if (assign)
	            Object.assign(this.params, obj);
	        else
	            this.params = obj;
	    }
	    block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
	        this.gen.block(() => {
	            this.check$data(valid, $dataValid);
	            codeBlock();
	        });
	    }
	    check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
	        if (!this.$data)
	            return;
	        const { gen, schemaCode, schemaType, def } = this;
	        gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));
	        if (valid !== codegen_1.nil)
	            gen.assign(valid, true);
	        if (schemaType.length || def.validateSchema) {
	            gen.elseIf(this.invalid$data());
	            this.$dataError();
	            if (valid !== codegen_1.nil)
	                gen.assign(valid, false);
	        }
	        gen.else();
	    }
	    invalid$data() {
	        const { gen, schemaCode, schemaType, def, it } = this;
	        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
	        function wrong$DataType() {
	            if (schemaType.length) {
	                if (!(schemaCode instanceof codegen_1.Name))
	                    throw new Error("ajv implementation error");
	                const st = Array.isArray(schemaType) ? schemaType : [schemaType];
	                return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
	            }
	            return codegen_1.nil;
	        }
	        function invalid$DataSchema() {
	            if (def.validateSchema) {
	                const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
	                return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;
	            }
	            return codegen_1.nil;
	        }
	    }
	    subschema(appl, valid) {
	        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
	        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
	        (0, subschema_1.extendSubschemaMode)(subschema, appl);
	        const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };
	        subschemaCode(nextContext, valid);
	        return nextContext;
	    }
	    mergeEvaluated(schemaCxt, toName) {
	        const { it, gen } = this;
	        if (!it.opts.unevaluated)
	            return;
	        if (it.props !== true && schemaCxt.props !== undefined) {
	            it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
	        }
	        if (it.items !== true && schemaCxt.items !== undefined) {
	            it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
	        }
	    }
	    mergeValidEvaluated(schemaCxt, valid) {
	        const { it, gen } = this;
	        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
	            gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
	            return true;
	        }
	    }
	}
	validate$1.KeywordCxt = KeywordCxt;
	function keywordCode(it, keyword, def, ruleType) {
	    const cxt = new KeywordCxt(it, def, keyword);
	    if ("code" in def) {
	        def.code(cxt, ruleType);
	    }
	    else if (cxt.$data && def.validate) {
	        (0, keyword_1.funcKeywordCode)(cxt, def);
	    }
	    else if ("macro" in def) {
	        (0, keyword_1.macroKeywordCode)(cxt, def);
	    }
	    else if (def.compile || def.validate) {
	        (0, keyword_1.funcKeywordCode)(cxt, def);
	    }
	}
	const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
	const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
	function getData($data, { dataLevel, dataNames, dataPathArr }) {
	    let jsonPointer;
	    let data;
	    if ($data === "")
	        return names_1.default.rootData;
	    if ($data[0] === "/") {
	        if (!JSON_POINTER.test($data))
	            throw new Error(`Invalid JSON-pointer: ${$data}`);
	        jsonPointer = $data;
	        data = names_1.default.rootData;
	    }
	    else {
	        const matches = RELATIVE_JSON_POINTER.exec($data);
	        if (!matches)
	            throw new Error(`Invalid JSON-pointer: ${$data}`);
	        const up = +matches[1];
	        jsonPointer = matches[2];
	        if (jsonPointer === "#") {
	            if (up >= dataLevel)
	                throw new Error(errorMsg("property/index", up));
	            return dataPathArr[dataLevel - up];
	        }
	        if (up > dataLevel)
	            throw new Error(errorMsg("data", up));
	        data = dataNames[dataLevel - up];
	        if (!jsonPointer)
	            return data;
	    }
	    let expr = data;
	    const segments = jsonPointer.split("/");
	    for (const segment of segments) {
	        if (segment) {
	            data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
	            expr = (0, codegen_1._) `${expr} && ${data}`;
	        }
	    }
	    return expr;
	    function errorMsg(pointerType, up) {
	        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
	    }
	}
	validate$1.getData = getData;
	return validate$1;
}

var validation_error$1 = {};

var hasRequiredValidation_error$1;

function requireValidation_error$1 () {
	if (hasRequiredValidation_error$1) return validation_error$1;
	hasRequiredValidation_error$1 = 1;
	Object.defineProperty(validation_error$1, "__esModule", { value: true });
	class ValidationError extends Error {
	    constructor(errors) {
	        super("validation failed");
	        this.errors = errors;
	        this.ajv = this.validation = true;
	    }
	}
	validation_error$1.default = ValidationError;
	return validation_error$1;
}

var ref_error$1 = {};

var hasRequiredRef_error$1;

function requireRef_error$1 () {
	if (hasRequiredRef_error$1) return ref_error$1;
	hasRequiredRef_error$1 = 1;
	Object.defineProperty(ref_error$1, "__esModule", { value: true });
	const resolve_1 = requireResolve$1();
	class MissingRefError extends Error {
	    constructor(resolver, baseId, ref, msg) {
	        super(msg || `can't resolve reference ${ref} from id ${baseId}`);
	        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
	        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
	    }
	}
	ref_error$1.default = MissingRefError;
	return ref_error$1;
}

var compile$2 = {};

var hasRequiredCompile$2;

function requireCompile$2 () {
	if (hasRequiredCompile$2) return compile$2;
	hasRequiredCompile$2 = 1;
	Object.defineProperty(compile$2, "__esModule", { value: true });
	compile$2.resolveSchema = compile$2.getCompilingSchema = compile$2.resolveRef = compile$2.compileSchema = compile$2.SchemaEnv = void 0;
	const codegen_1 = requireCodegen$1();
	const validation_error_1 = requireValidation_error$1();
	const names_1 = requireNames$1();
	const resolve_1 = requireResolve$1();
	const util_1 = requireUtil$4();
	const validate_1 = requireValidate$1();
	class SchemaEnv {
	    constructor(env) {
	        var _a;
	        this.refs = {};
	        this.dynamicAnchors = {};
	        let schema;
	        if (typeof env.schema == "object")
	            schema = env.schema;
	        this.schema = env.schema;
	        this.schemaId = env.schemaId;
	        this.root = env.root || this;
	        this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
	        this.schemaPath = env.schemaPath;
	        this.localRefs = env.localRefs;
	        this.meta = env.meta;
	        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
	        this.refs = {};
	    }
	}
	compile$2.SchemaEnv = SchemaEnv;
	function compileSchema(sch) {
	    const _sch = getCompilingSchema.call(this, sch);
	    if (_sch)
	        return _sch;
	    const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);
	    const { es5, lines } = this.opts.code;
	    const { ownProperties } = this.opts;
	    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
	    let _ValidationError;
	    if (sch.$async) {
	        _ValidationError = gen.scopeValue("Error", {
	            ref: validation_error_1.default,
	            code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`,
	        });
	    }
	    const validateName = gen.scopeName("validate");
	    sch.validateName = validateName;
	    const schemaCxt = {
	        gen,
	        allErrors: this.opts.allErrors,
	        data: names_1.default.data,
	        parentData: names_1.default.parentData,
	        parentDataProperty: names_1.default.parentDataProperty,
	        dataNames: [names_1.default.data],
	        dataPathArr: [codegen_1.nil],
	        dataLevel: 0,
	        dataTypes: [],
	        definedProperties: new Set(),
	        topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true
	            ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }
	            : { ref: sch.schema }),
	        validateName,
	        ValidationError: _ValidationError,
	        schema: sch.schema,
	        schemaEnv: sch,
	        rootId,
	        baseId: sch.baseId || rootId,
	        schemaPath: codegen_1.nil,
	        errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
	        errorPath: (0, codegen_1._) `""`,
	        opts: this.opts,
	        self: this,
	    };
	    let sourceCode;
	    try {
	        this._compilations.add(sch);
	        (0, validate_1.validateFunctionCode)(schemaCxt);
	        gen.optimize(this.opts.code.optimize);
	        const validateCode = gen.toString();
	        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
	        if (this.opts.code.process)
	            sourceCode = this.opts.code.process(sourceCode, sch);
	        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
	        const validate = makeValidate(this, this.scope.get());
	        this.scope.value(validateName, { ref: validate });
	        validate.errors = null;
	        validate.schema = sch.schema;
	        validate.schemaEnv = sch;
	        if (sch.$async)
	            validate.$async = true;
	        if (this.opts.code.source === true) {
	            validate.source = { validateName, validateCode, scopeValues: gen._values };
	        }
	        if (this.opts.unevaluated) {
	            const { props, items } = schemaCxt;
	            validate.evaluated = {
	                props: props instanceof codegen_1.Name ? undefined : props,
	                items: items instanceof codegen_1.Name ? undefined : items,
	                dynamicProps: props instanceof codegen_1.Name,
	                dynamicItems: items instanceof codegen_1.Name,
	            };
	            if (validate.source)
	                validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
	        }
	        sch.validate = validate;
	        return sch;
	    }
	    catch (e) {
	        delete sch.validate;
	        delete sch.validateName;
	        if (sourceCode)
	            this.logger.error("Error compiling schema, function code:", sourceCode);
	        throw e;
	    }
	    finally {
	        this._compilations.delete(sch);
	    }
	}
	compile$2.compileSchema = compileSchema;
	function resolveRef(root, baseId, ref) {
	    var _a;
	    ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
	    const schOrFunc = root.refs[ref];
	    if (schOrFunc)
	        return schOrFunc;
	    let _sch = resolve.call(this, root, ref);
	    if (_sch === undefined) {
	        const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
	        const { schemaId } = this.opts;
	        if (schema)
	            _sch = new SchemaEnv({ schema, schemaId, root, baseId });
	    }
	    if (_sch === undefined)
	        return;
	    return (root.refs[ref] = inlineOrCompile.call(this, _sch));
	}
	compile$2.resolveRef = resolveRef;
	function inlineOrCompile(sch) {
	    if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
	        return sch.schema;
	    return sch.validate ? sch : compileSchema.call(this, sch);
	}
	function getCompilingSchema(schEnv) {
	    for (const sch of this._compilations) {
	        if (sameSchemaEnv(sch, schEnv))
	            return sch;
	    }
	}
	compile$2.getCompilingSchema = getCompilingSchema;
	function sameSchemaEnv(s1, s2) {
	    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
	}
	function resolve(root,
	ref
	) {
	    let sch;
	    while (typeof (sch = this.refs[ref]) == "string")
	        ref = sch;
	    return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
	}
	function resolveSchema(root,
	ref
	) {
	    const p = this.opts.uriResolver.parse(ref);
	    const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
	    let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);
	    if (Object.keys(root.schema).length > 0 && refPath === baseId) {
	        return getJsonPointer.call(this, p, root);
	    }
	    const id = (0, resolve_1.normalizeId)(refPath);
	    const schOrRef = this.refs[id] || this.schemas[id];
	    if (typeof schOrRef == "string") {
	        const sch = resolveSchema.call(this, root, schOrRef);
	        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
	            return;
	        return getJsonPointer.call(this, p, sch);
	    }
	    if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
	        return;
	    if (!schOrRef.validate)
	        compileSchema.call(this, schOrRef);
	    if (id === (0, resolve_1.normalizeId)(ref)) {
	        const { schema } = schOrRef;
	        const { schemaId } = this.opts;
	        const schId = schema[schemaId];
	        if (schId)
	            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
	        return new SchemaEnv({ schema, schemaId, root, baseId });
	    }
	    return getJsonPointer.call(this, p, schOrRef);
	}
	compile$2.resolveSchema = resolveSchema;
	const PREVENT_SCOPE_CHANGE = new Set([
	    "properties",
	    "patternProperties",
	    "enum",
	    "dependencies",
	    "definitions",
	]);
	function getJsonPointer(parsedRef, { baseId, schema, root }) {
	    var _a;
	    if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
	        return;
	    for (const part of parsedRef.fragment.slice(1).split("/")) {
	        if (typeof schema === "boolean")
	            return;
	        const partSchema = schema[(0, util_1.unescapeFragment)(part)];
	        if (partSchema === undefined)
	            return;
	        schema = partSchema;
	        const schId = typeof schema === "object" && schema[this.opts.schemaId];
	        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
	            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
	        }
	    }
	    let env;
	    if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
	        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
	        env = resolveSchema.call(this, root, $ref);
	    }
	    const { schemaId } = this.opts;
	    env = env || new SchemaEnv({ schema, schemaId, root, baseId });
	    if (env.schema !== env.root.schema)
	        return env;
	    return undefined;
	}
	return compile$2;
}

var $id$3 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#";
var description$1 = "Meta-schema for $data reference (JSON AnySchema extension proposal)";
var type$3 = "object";
var required$3 = [
	"$data"
];
var properties$5 = {
	$data: {
		type: "string",
		anyOf: [
			{
				format: "relative-json-pointer"
			},
			{
				format: "json-pointer"
			}
		]
	}
};
var additionalProperties$3 = false;
var require$$9$1 = {
	$id: $id$3,
	description: description$1,
	type: type$3,
	required: required$3,
	properties: properties$5,
	additionalProperties: additionalProperties$3
};

var uri$1 = {};

var fastUri = {exports: {}};

var utils$2;
var hasRequiredUtils$2;

function requireUtils$2 () {
	if (hasRequiredUtils$2) return utils$2;
	hasRequiredUtils$2 = 1;
	const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
	const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
	function stringArrayToHexStripped (input) {
	  let acc = '';
	  let code = 0;
	  let i = 0;
	  for (i = 0; i < input.length; i++) {
	    code = input[i].charCodeAt(0);
	    if (code === 48) {
	      continue
	    }
	    if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {
	      return ''
	    }
	    acc += input[i];
	    break
	  }
	  for (i += 1; i < input.length; i++) {
	    code = input[i].charCodeAt(0);
	    if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) {
	      return ''
	    }
	    acc += input[i];
	  }
	  return acc
	}
	const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
	function consumeIsZone (buffer) {
	  buffer.length = 0;
	  return true
	}
	function consumeHextets (buffer, address, output) {
	  if (buffer.length) {
	    const hex = stringArrayToHexStripped(buffer);
	    if (hex !== '') {
	      address.push(hex);
	    } else {
	      output.error = true;
	      return false
	    }
	    buffer.length = 0;
	  }
	  return true
	}
	function getIPV6 (input) {
	  let tokenCount = 0;
	  const output = { error: false, address: '', zone: '' };
	  const address = [];
	  const buffer = [];
	  let endipv6Encountered = false;
	  let endIpv6 = false;
	  let consume = consumeHextets;
	  for (let i = 0; i < input.length; i++) {
	    const cursor = input[i];
	    if (cursor === '[' || cursor === ']') { continue }
	    if (cursor === ':') {
	      if (endipv6Encountered === true) {
	        endIpv6 = true;
	      }
	      if (!consume(buffer, address, output)) { break }
	      if (++tokenCount > 7) {
	        output.error = true;
	        break
	      }
	      if (i > 0 && input[i - 1] === ':') {
	        endipv6Encountered = true;
	      }
	      address.push(':');
	      continue
	    } else if (cursor === '%') {
	      if (!consume(buffer, address, output)) { break }
	      consume = consumeIsZone;
	    } else {
	      buffer.push(cursor);
	      continue
	    }
	  }
	  if (buffer.length) {
	    if (consume === consumeIsZone) {
	      output.zone = buffer.join('');
	    } else if (endIpv6) {
	      address.push(buffer.join(''));
	    } else {
	      address.push(stringArrayToHexStripped(buffer));
	    }
	  }
	  output.address = address.join('');
	  return output
	}
	function normalizeIPv6 (host) {
	  if (findToken(host, ':') < 2) { return { host, isIPV6: false } }
	  const ipv6 = getIPV6(host);
	  if (!ipv6.error) {
	    let newHost = ipv6.address;
	    let escapedHost = ipv6.address;
	    if (ipv6.zone) {
	      newHost += '%' + ipv6.zone;
	      escapedHost += '%25' + ipv6.zone;
	    }
	    return { host: newHost, isIPV6: true, escapedHost }
	  } else {
	    return { host, isIPV6: false }
	  }
	}
	function findToken (str, token) {
	  let ind = 0;
	  for (let i = 0; i < str.length; i++) {
	    if (str[i] === token) ind++;
	  }
	  return ind
	}
	function removeDotSegments (path) {
	  let input = path;
	  const output = [];
	  let nextSlash = -1;
	  let len = 0;
	  while (len = input.length) {
	    if (len === 1) {
	      if (input === '.') {
	        break
	      } else if (input === '/') {
	        output.push('/');
	        break
	      } else {
	        output.push(input);
	        break
	      }
	    } else if (len === 2) {
	      if (input[0] === '.') {
	        if (input[1] === '.') {
	          break
	        } else if (input[1] === '/') {
	          input = input.slice(2);
	          continue
	        }
	      } else if (input[0] === '/') {
	        if (input[1] === '.' || input[1] === '/') {
	          output.push('/');
	          break
	        }
	      }
	    } else if (len === 3) {
	      if (input === '/..') {
	        if (output.length !== 0) {
	          output.pop();
	        }
	        output.push('/');
	        break
	      }
	    }
	    if (input[0] === '.') {
	      if (input[1] === '.') {
	        if (input[2] === '/') {
	          input = input.slice(3);
	          continue
	        }
	      } else if (input[1] === '/') {
	        input = input.slice(2);
	        continue
	      }
	    } else if (input[0] === '/') {
	      if (input[1] === '.') {
	        if (input[2] === '/') {
	          input = input.slice(2);
	          continue
	        } else if (input[2] === '.') {
	          if (input[3] === '/') {
	            input = input.slice(3);
	            if (output.length !== 0) {
	              output.pop();
	            }
	            continue
	          }
	        }
	      }
	    }
	    if ((nextSlash = input.indexOf('/', 1)) === -1) {
	      output.push(input);
	      break
	    } else {
	      output.push(input.slice(0, nextSlash));
	      input = input.slice(nextSlash);
	    }
	  }
	  return output.join('')
	}
	function normalizeComponentEncoding (component, esc) {
	  const func = esc !== true ? escape : unescape;
	  if (component.scheme !== undefined) {
	    component.scheme = func(component.scheme);
	  }
	  if (component.userinfo !== undefined) {
	    component.userinfo = func(component.userinfo);
	  }
	  if (component.host !== undefined) {
	    component.host = func(component.host);
	  }
	  if (component.path !== undefined) {
	    component.path = func(component.path);
	  }
	  if (component.query !== undefined) {
	    component.query = func(component.query);
	  }
	  if (component.fragment !== undefined) {
	    component.fragment = func(component.fragment);
	  }
	  return component
	}
	function recomposeAuthority (component) {
	  const uriTokens = [];
	  if (component.userinfo !== undefined) {
	    uriTokens.push(component.userinfo);
	    uriTokens.push('@');
	  }
	  if (component.host !== undefined) {
	    let host = unescape(component.host);
	    if (!isIPv4(host)) {
	      const ipV6res = normalizeIPv6(host);
	      if (ipV6res.isIPV6 === true) {
	        host = `[${ipV6res.escapedHost}]`;
	      } else {
	        host = component.host;
	      }
	    }
	    uriTokens.push(host);
	  }
	  if (typeof component.port === 'number' || typeof component.port === 'string') {
	    uriTokens.push(':');
	    uriTokens.push(String(component.port));
	  }
	  return uriTokens.length ? uriTokens.join('') : undefined
	}	utils$2 = {
	  nonSimpleDomain,
	  recomposeAuthority,
	  normalizeComponentEncoding,
	  removeDotSegments,
	  isIPv4,
	  isUUID,
	  normalizeIPv6,
	  stringArrayToHexStripped
	};
	return utils$2;
}

var schemes;
var hasRequiredSchemes;

function requireSchemes () {
	if (hasRequiredSchemes) return schemes;
	hasRequiredSchemes = 1;
	const { isUUID } = requireUtils$2();
	const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
	const supportedSchemeNames =  (['http', 'https', 'ws',
	  'wss', 'urn', 'urn:uuid']);
	function isValidSchemeName (name) {
	  return supportedSchemeNames.indexOf( (name)) !== -1
	}
	function wsIsSecure (wsComponent) {
	  if (wsComponent.secure === true) {
	    return true
	  } else if (wsComponent.secure === false) {
	    return false
	  } else if (wsComponent.scheme) {
	    return (
	      wsComponent.scheme.length === 3 &&
	      (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') &&
	      (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') &&
	      (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S')
	    )
	  } else {
	    return false
	  }
	}
	function httpParse (component) {
	  if (!component.host) {
	    component.error = component.error || 'HTTP URIs must have a host.';
	  }
	  return component
	}
	function httpSerialize (component) {
	  const secure = String(component.scheme).toLowerCase() === 'https';
	  if (component.port === (secure ? 443 : 80) || component.port === '') {
	    component.port = undefined;
	  }
	  if (!component.path) {
	    component.path = '/';
	  }
	  return component
	}
	function wsParse (wsComponent) {
	  wsComponent.secure = wsIsSecure(wsComponent);
	  wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : '');
	  wsComponent.path = undefined;
	  wsComponent.query = undefined;
	  return wsComponent
	}
	function wsSerialize (wsComponent) {
	  if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') {
	    wsComponent.port = undefined;
	  }
	  if (typeof wsComponent.secure === 'boolean') {
	    wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws');
	    wsComponent.secure = undefined;
	  }
	  if (wsComponent.resourceName) {
	    const [path, query] = wsComponent.resourceName.split('?');
	    wsComponent.path = (path && path !== '/' ? path : undefined);
	    wsComponent.query = query;
	    wsComponent.resourceName = undefined;
	  }
	  wsComponent.fragment = undefined;
	  return wsComponent
	}
	function urnParse (urnComponent, options) {
	  if (!urnComponent.path) {
	    urnComponent.error = 'URN can not be parsed';
	    return urnComponent
	  }
	  const matches = urnComponent.path.match(URN_REG);
	  if (matches) {
	    const scheme = options.scheme || urnComponent.scheme || 'urn';
	    urnComponent.nid = matches[1].toLowerCase();
	    urnComponent.nss = matches[2];
	    const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`;
	    const schemeHandler = getSchemeHandler(urnScheme);
	    urnComponent.path = undefined;
	    if (schemeHandler) {
	      urnComponent = schemeHandler.parse(urnComponent, options);
	    }
	  } else {
	    urnComponent.error = urnComponent.error || 'URN can not be parsed.';
	  }
	  return urnComponent
	}
	function urnSerialize (urnComponent, options) {
	  if (urnComponent.nid === undefined) {
	    throw new Error('URN without nid cannot be serialized')
	  }
	  const scheme = options.scheme || urnComponent.scheme || 'urn';
	  const nid = urnComponent.nid.toLowerCase();
	  const urnScheme = `${scheme}:${options.nid || nid}`;
	  const schemeHandler = getSchemeHandler(urnScheme);
	  if (schemeHandler) {
	    urnComponent = schemeHandler.serialize(urnComponent, options);
	  }
	  const uriComponent = urnComponent;
	  const nss = urnComponent.nss;
	  uriComponent.path = `${nid || options.nid}:${nss}`;
	  options.skipEscape = true;
	  return uriComponent
	}
	function urnuuidParse (urnComponent, options) {
	  const uuidComponent = urnComponent;
	  uuidComponent.uuid = uuidComponent.nss;
	  uuidComponent.nss = undefined;
	  if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {
	    uuidComponent.error = uuidComponent.error || 'UUID is not valid.';
	  }
	  return uuidComponent
	}
	function urnuuidSerialize (uuidComponent) {
	  const urnComponent = uuidComponent;
	  urnComponent.nss = (uuidComponent.uuid || '').toLowerCase();
	  return urnComponent
	}
	const http =  ({
	  scheme: 'http',
	  domainHost: true,
	  parse: httpParse,
	  serialize: httpSerialize
	});
	const https =  ({
	  scheme: 'https',
	  domainHost: http.domainHost,
	  parse: httpParse,
	  serialize: httpSerialize
	});
	const ws =  ({
	  scheme: 'ws',
	  domainHost: true,
	  parse: wsParse,
	  serialize: wsSerialize
	});
	const wss =  ({
	  scheme: 'wss',
	  domainHost: ws.domainHost,
	  parse: ws.parse,
	  serialize: ws.serialize
	});
	const urn =  ({
	  scheme: 'urn',
	  parse: urnParse,
	  serialize: urnSerialize,
	  skipNormalize: true
	});
	const urnuuid =  ({
	  scheme: 'urn:uuid',
	  parse: urnuuidParse,
	  serialize: urnuuidSerialize,
	  skipNormalize: true
	});
	const SCHEMES =  ({
	  http,
	  https,
	  ws,
	  wss,
	  urn,
	  'urn:uuid': urnuuid
	});
	Object.setPrototypeOf(SCHEMES, null);
	function getSchemeHandler (scheme) {
	  return (
	    scheme && (
	      SCHEMES[ (scheme)] ||
	      SCHEMES[(scheme.toLowerCase())])
	  ) ||
	    undefined
	}
	schemes = {
	  wsIsSecure,
	  SCHEMES,
	  isValidSchemeName,
	  getSchemeHandler,
	};
	return schemes;
}

var hasRequiredFastUri;

function requireFastUri () {
	if (hasRequiredFastUri) return fastUri.exports;
	hasRequiredFastUri = 1;
	const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = requireUtils$2();
	const { SCHEMES, getSchemeHandler } = requireSchemes();
	function normalize (uri, options) {
	  if (typeof uri === 'string') {
	    uri =  (serialize(parse(uri, options), options));
	  } else if (typeof uri === 'object') {
	    uri =  (parse(serialize(uri, options), options));
	  }
	  return uri
	}
	function resolve (baseURI, relativeURI, options) {
	  const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' };
	  const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
	  schemelessOptions.skipEscape = true;
	  return serialize(resolved, schemelessOptions)
	}
	function resolveComponent (base, relative, options, skipNormalization) {
	  const target = {};
	  if (!skipNormalization) {
	    base = parse(serialize(base, options), options);
	    relative = parse(serialize(relative, options), options);
	  }
	  options = options || {};
	  if (!options.tolerant && relative.scheme) {
	    target.scheme = relative.scheme;
	    target.userinfo = relative.userinfo;
	    target.host = relative.host;
	    target.port = relative.port;
	    target.path = removeDotSegments(relative.path || '');
	    target.query = relative.query;
	  } else {
	    if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
	      target.userinfo = relative.userinfo;
	      target.host = relative.host;
	      target.port = relative.port;
	      target.path = removeDotSegments(relative.path || '');
	      target.query = relative.query;
	    } else {
	      if (!relative.path) {
	        target.path = base.path;
	        if (relative.query !== undefined) {
	          target.query = relative.query;
	        } else {
	          target.query = base.query;
	        }
	      } else {
	        if (relative.path[0] === '/') {
	          target.path = removeDotSegments(relative.path);
	        } else {
	          if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
	            target.path = '/' + relative.path;
	          } else if (!base.path) {
	            target.path = relative.path;
	          } else {
	            target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path;
	          }
	          target.path = removeDotSegments(target.path);
	        }
	        target.query = relative.query;
	      }
	      target.userinfo = base.userinfo;
	      target.host = base.host;
	      target.port = base.port;
	    }
	    target.scheme = base.scheme;
	  }
	  target.fragment = relative.fragment;
	  return target
	}
	function equal (uriA, uriB, options) {
	  if (typeof uriA === 'string') {
	    uriA = unescape(uriA);
	    uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true });
	  } else if (typeof uriA === 'object') {
	    uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true });
	  }
	  if (typeof uriB === 'string') {
	    uriB = unescape(uriB);
	    uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true });
	  } else if (typeof uriB === 'object') {
	    uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true });
	  }
	  return uriA.toLowerCase() === uriB.toLowerCase()
	}
	function serialize (cmpts, opts) {
	  const component = {
	    host: cmpts.host,
	    scheme: cmpts.scheme,
	    userinfo: cmpts.userinfo,
	    port: cmpts.port,
	    path: cmpts.path,
	    query: cmpts.query,
	    nid: cmpts.nid,
	    nss: cmpts.nss,
	    uuid: cmpts.uuid,
	    fragment: cmpts.fragment,
	    reference: cmpts.reference,
	    resourceName: cmpts.resourceName,
	    secure: cmpts.secure,
	    error: ''
	  };
	  const options = Object.assign({}, opts);
	  const uriTokens = [];
	  const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
	  if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
	  if (component.path !== undefined) {
	    if (!options.skipEscape) {
	      component.path = escape(component.path);
	      if (component.scheme !== undefined) {
	        component.path = component.path.split('%3A').join(':');
	      }
	    } else {
	      component.path = unescape(component.path);
	    }
	  }
	  if (options.reference !== 'suffix' && component.scheme) {
	    uriTokens.push(component.scheme, ':');
	  }
	  const authority = recomposeAuthority(component);
	  if (authority !== undefined) {
	    if (options.reference !== 'suffix') {
	      uriTokens.push('//');
	    }
	    uriTokens.push(authority);
	    if (component.path && component.path[0] !== '/') {
	      uriTokens.push('/');
	    }
	  }
	  if (component.path !== undefined) {
	    let s = component.path;
	    if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
	      s = removeDotSegments(s);
	    }
	    if (
	      authority === undefined &&
	      s[0] === '/' &&
	      s[1] === '/'
	    ) {
	      s = '/%2F' + s.slice(2);
	    }
	    uriTokens.push(s);
	  }
	  if (component.query !== undefined) {
	    uriTokens.push('?', component.query);
	  }
	  if (component.fragment !== undefined) {
	    uriTokens.push('#', component.fragment);
	  }
	  return uriTokens.join('')
	}
	const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
	function parse (uri, opts) {
	  const options = Object.assign({}, opts);
	  const parsed = {
	    scheme: undefined,
	    userinfo: undefined,
	    host: '',
	    port: undefined,
	    path: '',
	    query: undefined,
	    fragment: undefined
	  };
	  let isIP = false;
	  if (options.reference === 'suffix') {
	    if (options.scheme) {
	      uri = options.scheme + ':' + uri;
	    } else {
	      uri = '//' + uri;
	    }
	  }
	  const matches = uri.match(URI_PARSE);
	  if (matches) {
	    parsed.scheme = matches[1];
	    parsed.userinfo = matches[3];
	    parsed.host = matches[4];
	    parsed.port = parseInt(matches[5], 10);
	    parsed.path = matches[6] || '';
	    parsed.query = matches[7];
	    parsed.fragment = matches[8];
	    if (isNaN(parsed.port)) {
	      parsed.port = matches[5];
	    }
	    if (parsed.host) {
	      const ipv4result = isIPv4(parsed.host);
	      if (ipv4result === false) {
	        const ipv6result = normalizeIPv6(parsed.host);
	        parsed.host = ipv6result.host.toLowerCase();
	        isIP = ipv6result.isIPV6;
	      } else {
	        isIP = true;
	      }
	    }
	    if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {
	      parsed.reference = 'same-document';
	    } else if (parsed.scheme === undefined) {
	      parsed.reference = 'relative';
	    } else if (parsed.fragment === undefined) {
	      parsed.reference = 'absolute';
	    } else {
	      parsed.reference = 'uri';
	    }
	    if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {
	      parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.';
	    }
	    const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
	    if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
	      if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {
	        try {
	          parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
	        } catch (e) {
	          parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
	        }
	      }
	    }
	    if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {
	      if (uri.indexOf('%') !== -1) {
	        if (parsed.scheme !== undefined) {
	          parsed.scheme = unescape(parsed.scheme);
	        }
	        if (parsed.host !== undefined) {
	          parsed.host = unescape(parsed.host);
	        }
	      }
	      if (parsed.path) {
	        parsed.path = escape(unescape(parsed.path));
	      }
	      if (parsed.fragment) {
	        parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
	      }
	    }
	    if (schemeHandler && schemeHandler.parse) {
	      schemeHandler.parse(parsed, options);
	    }
	  } else {
	    parsed.error = parsed.error || 'URI can not be parsed.';
	  }
	  return parsed
	}
	const fastUri$1 = {
	  SCHEMES,
	  normalize,
	  resolve,
	  resolveComponent,
	  equal,
	  serialize,
	  parse
	};
	fastUri.exports = fastUri$1;
	fastUri.exports.default = fastUri$1;
	fastUri.exports.fastUri = fastUri$1;
	return fastUri.exports;
}

var hasRequiredUri$1;

function requireUri$1 () {
	if (hasRequiredUri$1) return uri$1;
	hasRequiredUri$1 = 1;
	Object.defineProperty(uri$1, "__esModule", { value: true });
	const uri = requireFastUri();
	uri.code = 'require("ajv/dist/runtime/uri").default';
	uri$1.default = uri;
	return uri$1;
}

var hasRequiredCore$4;

function requireCore$4 () {
	if (hasRequiredCore$4) return core$5;
	hasRequiredCore$4 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.CodeGen = exports$1.Name = exports$1.nil = exports$1.stringify = exports$1.str = exports$1._ = exports$1.KeywordCxt = void 0;
		var validate_1 = requireValidate$1();
		Object.defineProperty(exports$1, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
		var codegen_1 = requireCodegen$1();
		Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return codegen_1._; } });
		Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return codegen_1.str; } });
		Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
		Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
		Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
		Object.defineProperty(exports$1, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
		const validation_error_1 = requireValidation_error$1();
		const ref_error_1 = requireRef_error$1();
		const rules_1 = requireRules$1();
		const compile_1 = requireCompile$2();
		const codegen_2 = requireCodegen$1();
		const resolve_1 = requireResolve$1();
		const dataType_1 = requireDataType$1();
		const util_1 = requireUtil$4();
		const $dataRefSchema = require$$9$1;
		const uri_1 = requireUri$1();
		const defaultRegExp = (str, flags) => new RegExp(str, flags);
		defaultRegExp.code = "new RegExp";
		const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
		const EXT_SCOPE_NAMES = new Set([
		    "validate",
		    "serialize",
		    "parse",
		    "wrapper",
		    "root",
		    "schema",
		    "keyword",
		    "pattern",
		    "formats",
		    "validate$data",
		    "func",
		    "obj",
		    "Error",
		]);
		const removedOptions = {
		    errorDataPath: "",
		    format: "`validateFormats: false` can be used instead.",
		    nullable: '"nullable" keyword is supported by default.',
		    jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
		    extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
		    missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
		    processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
		    sourceCode: "Use option `code: {source: true}`",
		    strictDefaults: "It is default now, see option `strict`.",
		    strictKeywords: "It is default now, see option `strict`.",
		    uniqueItems: '"uniqueItems" keyword is always validated.',
		    unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
		    cache: "Map is used as cache, schema object as key.",
		    serialize: "Map is used as cache, schema object as key.",
		    ajvErrors: "It is default now.",
		};
		const deprecatedOptions = {
		    ignoreKeywordsWithRef: "",
		    jsPropertySyntax: "",
		    unicode: '"minLength"/"maxLength" account for unicode characters by default.',
		};
		const MAX_EXPRESSION = 200;
		function requiredOptions(o) {
		    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
		    const s = o.strict;
		    const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
		    const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
		    const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
		    const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
		    return {
		        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
		        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
		        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
		        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
		        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
		        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
		        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
		        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
		        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
		        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
		        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
		        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
		        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
		        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
		        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
		        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
		        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
		        uriResolver: uriResolver,
		    };
		}
		class Ajv {
		    constructor(opts = {}) {
		        this.schemas = {};
		        this.refs = {};
		        this.formats = {};
		        this._compilations = new Set();
		        this._loading = {};
		        this._cache = new Map();
		        opts = this.opts = { ...opts, ...requiredOptions(opts) };
		        const { es5, lines } = this.opts.code;
		        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
		        this.logger = getLogger(opts.logger);
		        const formatOpt = opts.validateFormats;
		        opts.validateFormats = false;
		        this.RULES = (0, rules_1.getRules)();
		        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
		        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
		        this._metaOpts = getMetaSchemaOptions.call(this);
		        if (opts.formats)
		            addInitialFormats.call(this);
		        this._addVocabularies();
		        this._addDefaultMetaSchema();
		        if (opts.keywords)
		            addInitialKeywords.call(this, opts.keywords);
		        if (typeof opts.meta == "object")
		            this.addMetaSchema(opts.meta);
		        addInitialSchemas.call(this);
		        opts.validateFormats = formatOpt;
		    }
		    _addVocabularies() {
		        this.addKeyword("$async");
		    }
		    _addDefaultMetaSchema() {
		        const { $data, meta, schemaId } = this.opts;
		        let _dataRefSchema = $dataRefSchema;
		        if (schemaId === "id") {
		            _dataRefSchema = { ...$dataRefSchema };
		            _dataRefSchema.id = _dataRefSchema.$id;
		            delete _dataRefSchema.$id;
		        }
		        if (meta && $data)
		            this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
		    }
		    defaultMeta() {
		        const { meta, schemaId } = this.opts;
		        return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
		    }
		    validate(schemaKeyRef,
		    data
		    ) {
		        let v;
		        if (typeof schemaKeyRef == "string") {
		            v = this.getSchema(schemaKeyRef);
		            if (!v)
		                throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
		        }
		        else {
		            v = this.compile(schemaKeyRef);
		        }
		        const valid = v(data);
		        if (!("$async" in v))
		            this.errors = v.errors;
		        return valid;
		    }
		    compile(schema, _meta) {
		        const sch = this._addSchema(schema, _meta);
		        return (sch.validate || this._compileSchemaEnv(sch));
		    }
		    compileAsync(schema, meta) {
		        if (typeof this.opts.loadSchema != "function") {
		            throw new Error("options.loadSchema should be a function");
		        }
		        const { loadSchema } = this.opts;
		        return runCompileAsync.call(this, schema, meta);
		        async function runCompileAsync(_schema, _meta) {
		            await loadMetaSchema.call(this, _schema.$schema);
		            const sch = this._addSchema(_schema, _meta);
		            return sch.validate || _compileAsync.call(this, sch);
		        }
		        async function loadMetaSchema($ref) {
		            if ($ref && !this.getSchema($ref)) {
		                await runCompileAsync.call(this, { $ref }, true);
		            }
		        }
		        async function _compileAsync(sch) {
		            try {
		                return this._compileSchemaEnv(sch);
		            }
		            catch (e) {
		                if (!(e instanceof ref_error_1.default))
		                    throw e;
		                checkLoaded.call(this, e);
		                await loadMissingSchema.call(this, e.missingSchema);
		                return _compileAsync.call(this, sch);
		            }
		        }
		        function checkLoaded({ missingSchema: ref, missingRef }) {
		            if (this.refs[ref]) {
		                throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
		            }
		        }
		        async function loadMissingSchema(ref) {
		            const _schema = await _loadSchema.call(this, ref);
		            if (!this.refs[ref])
		                await loadMetaSchema.call(this, _schema.$schema);
		            if (!this.refs[ref])
		                this.addSchema(_schema, ref, meta);
		        }
		        async function _loadSchema(ref) {
		            const p = this._loading[ref];
		            if (p)
		                return p;
		            try {
		                return await (this._loading[ref] = loadSchema(ref));
		            }
		            finally {
		                delete this._loading[ref];
		            }
		        }
		    }
		    addSchema(schema,
		    key,
		    _meta,
		    _validateSchema = this.opts.validateSchema
		    ) {
		        if (Array.isArray(schema)) {
		            for (const sch of schema)
		                this.addSchema(sch, undefined, _meta, _validateSchema);
		            return this;
		        }
		        let id;
		        if (typeof schema === "object") {
		            const { schemaId } = this.opts;
		            id = schema[schemaId];
		            if (id !== undefined && typeof id != "string") {
		                throw new Error(`schema ${schemaId} must be string`);
		            }
		        }
		        key = (0, resolve_1.normalizeId)(key || id);
		        this._checkUnique(key);
		        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
		        return this;
		    }
		    addMetaSchema(schema, key,
		    _validateSchema = this.opts.validateSchema
		    ) {
		        this.addSchema(schema, key, true, _validateSchema);
		        return this;
		    }
		    validateSchema(schema, throwOrLogError) {
		        if (typeof schema == "boolean")
		            return true;
		        let $schema;
		        $schema = schema.$schema;
		        if ($schema !== undefined && typeof $schema != "string") {
		            throw new Error("$schema must be a string");
		        }
		        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
		        if (!$schema) {
		            this.logger.warn("meta-schema not available");
		            this.errors = null;
		            return true;
		        }
		        const valid = this.validate($schema, schema);
		        if (!valid && throwOrLogError) {
		            const message = "schema is invalid: " + this.errorsText();
		            if (this.opts.validateSchema === "log")
		                this.logger.error(message);
		            else
		                throw new Error(message);
		        }
		        return valid;
		    }
		    getSchema(keyRef) {
		        let sch;
		        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
		            keyRef = sch;
		        if (sch === undefined) {
		            const { schemaId } = this.opts;
		            const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
		            sch = compile_1.resolveSchema.call(this, root, keyRef);
		            if (!sch)
		                return;
		            this.refs[keyRef] = sch;
		        }
		        return (sch.validate || this._compileSchemaEnv(sch));
		    }
		    removeSchema(schemaKeyRef) {
		        if (schemaKeyRef instanceof RegExp) {
		            this._removeAllSchemas(this.schemas, schemaKeyRef);
		            this._removeAllSchemas(this.refs, schemaKeyRef);
		            return this;
		        }
		        switch (typeof schemaKeyRef) {
		            case "undefined":
		                this._removeAllSchemas(this.schemas);
		                this._removeAllSchemas(this.refs);
		                this._cache.clear();
		                return this;
		            case "string": {
		                const sch = getSchEnv.call(this, schemaKeyRef);
		                if (typeof sch == "object")
		                    this._cache.delete(sch.schema);
		                delete this.schemas[schemaKeyRef];
		                delete this.refs[schemaKeyRef];
		                return this;
		            }
		            case "object": {
		                const cacheKey = schemaKeyRef;
		                this._cache.delete(cacheKey);
		                let id = schemaKeyRef[this.opts.schemaId];
		                if (id) {
		                    id = (0, resolve_1.normalizeId)(id);
		                    delete this.schemas[id];
		                    delete this.refs[id];
		                }
		                return this;
		            }
		            default:
		                throw new Error("ajv.removeSchema: invalid parameter");
		        }
		    }
		    addVocabulary(definitions) {
		        for (const def of definitions)
		            this.addKeyword(def);
		        return this;
		    }
		    addKeyword(kwdOrDef, def
		    ) {
		        let keyword;
		        if (typeof kwdOrDef == "string") {
		            keyword = kwdOrDef;
		            if (typeof def == "object") {
		                this.logger.warn("these parameters are deprecated, see docs for addKeyword");
		                def.keyword = keyword;
		            }
		        }
		        else if (typeof kwdOrDef == "object" && def === undefined) {
		            def = kwdOrDef;
		            keyword = def.keyword;
		            if (Array.isArray(keyword) && !keyword.length) {
		                throw new Error("addKeywords: keyword must be string or non-empty array");
		            }
		        }
		        else {
		            throw new Error("invalid addKeywords parameters");
		        }
		        checkKeyword.call(this, keyword, def);
		        if (!def) {
		            (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
		            return this;
		        }
		        keywordMetaschema.call(this, def);
		        const definition = {
		            ...def,
		            type: (0, dataType_1.getJSONTypes)(def.type),
		            schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
		        };
		        (0, util_1.eachItem)(keyword, definition.type.length === 0
		            ? (k) => addRule.call(this, k, definition)
		            : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
		        return this;
		    }
		    getKeyword(keyword) {
		        const rule = this.RULES.all[keyword];
		        return typeof rule == "object" ? rule.definition : !!rule;
		    }
		    removeKeyword(keyword) {
		        const { RULES } = this;
		        delete RULES.keywords[keyword];
		        delete RULES.all[keyword];
		        for (const group of RULES.rules) {
		            const i = group.rules.findIndex((rule) => rule.keyword === keyword);
		            if (i >= 0)
		                group.rules.splice(i, 1);
		        }
		        return this;
		    }
		    addFormat(name, format) {
		        if (typeof format == "string")
		            format = new RegExp(format);
		        this.formats[name] = format;
		        return this;
		    }
		    errorsText(errors = this.errors,
		    { separator = ", ", dataVar = "data" } = {}
		    ) {
		        if (!errors || errors.length === 0)
		            return "No errors";
		        return errors
		            .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
		            .reduce((text, msg) => text + separator + msg);
		    }
		    $dataMetaSchema(metaSchema, keywordsJsonPointers) {
		        const rules = this.RULES.all;
		        metaSchema = JSON.parse(JSON.stringify(metaSchema));
		        for (const jsonPointer of keywordsJsonPointers) {
		            const segments = jsonPointer.split("/").slice(1);
		            let keywords = metaSchema;
		            for (const seg of segments)
		                keywords = keywords[seg];
		            for (const key in rules) {
		                const rule = rules[key];
		                if (typeof rule != "object")
		                    continue;
		                const { $data } = rule.definition;
		                const schema = keywords[key];
		                if ($data && schema)
		                    keywords[key] = schemaOrData(schema);
		            }
		        }
		        return metaSchema;
		    }
		    _removeAllSchemas(schemas, regex) {
		        for (const keyRef in schemas) {
		            const sch = schemas[keyRef];
		            if (!regex || regex.test(keyRef)) {
		                if (typeof sch == "string") {
		                    delete schemas[keyRef];
		                }
		                else if (sch && !sch.meta) {
		                    this._cache.delete(sch.schema);
		                    delete schemas[keyRef];
		                }
		            }
		        }
		    }
		    _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
		        let id;
		        const { schemaId } = this.opts;
		        if (typeof schema == "object") {
		            id = schema[schemaId];
		        }
		        else {
		            if (this.opts.jtd)
		                throw new Error("schema must be object");
		            else if (typeof schema != "boolean")
		                throw new Error("schema must be object or boolean");
		        }
		        let sch = this._cache.get(schema);
		        if (sch !== undefined)
		            return sch;
		        baseId = (0, resolve_1.normalizeId)(id || baseId);
		        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
		        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
		        this._cache.set(sch.schema, sch);
		        if (addSchema && !baseId.startsWith("#")) {
		            if (baseId)
		                this._checkUnique(baseId);
		            this.refs[baseId] = sch;
		        }
		        if (validateSchema)
		            this.validateSchema(schema, true);
		        return sch;
		    }
		    _checkUnique(id) {
		        if (this.schemas[id] || this.refs[id]) {
		            throw new Error(`schema with key or id "${id}" already exists`);
		        }
		    }
		    _compileSchemaEnv(sch) {
		        if (sch.meta)
		            this._compileMetaSchema(sch);
		        else
		            compile_1.compileSchema.call(this, sch);
		        if (!sch.validate)
		            throw new Error("ajv implementation error");
		        return sch.validate;
		    }
		    _compileMetaSchema(sch) {
		        const currentOpts = this.opts;
		        this.opts = this._metaOpts;
		        try {
		            compile_1.compileSchema.call(this, sch);
		        }
		        finally {
		            this.opts = currentOpts;
		        }
		    }
		}
		Ajv.ValidationError = validation_error_1.default;
		Ajv.MissingRefError = ref_error_1.default;
		exports$1.default = Ajv;
		function checkOptions(checkOpts, options, msg, log = "error") {
		    for (const key in checkOpts) {
		        const opt = key;
		        if (opt in options)
		            this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
		    }
		}
		function getSchEnv(keyRef) {
		    keyRef = (0, resolve_1.normalizeId)(keyRef);
		    return this.schemas[keyRef] || this.refs[keyRef];
		}
		function addInitialSchemas() {
		    const optsSchemas = this.opts.schemas;
		    if (!optsSchemas)
		        return;
		    if (Array.isArray(optsSchemas))
		        this.addSchema(optsSchemas);
		    else
		        for (const key in optsSchemas)
		            this.addSchema(optsSchemas[key], key);
		}
		function addInitialFormats() {
		    for (const name in this.opts.formats) {
		        const format = this.opts.formats[name];
		        if (format)
		            this.addFormat(name, format);
		    }
		}
		function addInitialKeywords(defs) {
		    if (Array.isArray(defs)) {
		        this.addVocabulary(defs);
		        return;
		    }
		    this.logger.warn("keywords option as map is deprecated, pass array");
		    for (const keyword in defs) {
		        const def = defs[keyword];
		        if (!def.keyword)
		            def.keyword = keyword;
		        this.addKeyword(def);
		    }
		}
		function getMetaSchemaOptions() {
		    const metaOpts = { ...this.opts };
		    for (const opt of META_IGNORE_OPTIONS)
		        delete metaOpts[opt];
		    return metaOpts;
		}
		const noLogs = { log() { }, warn() { }, error() { } };
		function getLogger(logger) {
		    if (logger === false)
		        return noLogs;
		    if (logger === undefined)
		        return console;
		    if (logger.log && logger.warn && logger.error)
		        return logger;
		    throw new Error("logger must implement log, warn and error methods");
		}
		const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
		function checkKeyword(keyword, def) {
		    const { RULES } = this;
		    (0, util_1.eachItem)(keyword, (kwd) => {
		        if (RULES.keywords[kwd])
		            throw new Error(`Keyword ${kwd} is already defined`);
		        if (!KEYWORD_NAME.test(kwd))
		            throw new Error(`Keyword ${kwd} has invalid name`);
		    });
		    if (!def)
		        return;
		    if (def.$data && !("code" in def || "validate" in def)) {
		        throw new Error('$data keyword must have "code" or "validate" function');
		    }
		}
		function addRule(keyword, definition, dataType) {
		    var _a;
		    const post = definition === null || definition === void 0 ? void 0 : definition.post;
		    if (dataType && post)
		        throw new Error('keyword with "post" flag cannot have "type"');
		    const { RULES } = this;
		    let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
		    if (!ruleGroup) {
		        ruleGroup = { type: dataType, rules: [] };
		        RULES.rules.push(ruleGroup);
		    }
		    RULES.keywords[keyword] = true;
		    if (!definition)
		        return;
		    const rule = {
		        keyword,
		        definition: {
		            ...definition,
		            type: (0, dataType_1.getJSONTypes)(definition.type),
		            schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
		        },
		    };
		    if (definition.before)
		        addBeforeRule.call(this, ruleGroup, rule, definition.before);
		    else
		        ruleGroup.rules.push(rule);
		    RULES.all[keyword] = rule;
		    (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
		}
		function addBeforeRule(ruleGroup, rule, before) {
		    const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
		    if (i >= 0) {
		        ruleGroup.rules.splice(i, 0, rule);
		    }
		    else {
		        ruleGroup.rules.push(rule);
		        this.logger.warn(`rule ${before} is not defined`);
		    }
		}
		function keywordMetaschema(def) {
		    let { metaSchema } = def;
		    if (metaSchema === undefined)
		        return;
		    if (def.$data && this.opts.$data)
		        metaSchema = schemaOrData(metaSchema);
		    def.validateSchema = this.compile(metaSchema, true);
		}
		const $dataRef = {
		    $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
		};
		function schemaOrData(schema) {
		    return { anyOf: [schema, $dataRef] };
		} 
	} (core$5));
	return core$5;
}

var draft7$1 = {};

var core$4 = {};

var id$1 = {};

var hasRequiredId$1;

function requireId$1 () {
	if (hasRequiredId$1) return id$1;
	hasRequiredId$1 = 1;
	Object.defineProperty(id$1, "__esModule", { value: true });
	const def = {
	    keyword: "id",
	    code() {
	        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
	    },
	};
	id$1.default = def;
	return id$1;
}

var ref$1 = {};

var hasRequiredRef$1;

function requireRef$1 () {
	if (hasRequiredRef$1) return ref$1;
	hasRequiredRef$1 = 1;
	Object.defineProperty(ref$1, "__esModule", { value: true });
	ref$1.callRef = ref$1.getValidate = void 0;
	const ref_error_1 = requireRef_error$1();
	const code_1 = requireCode$3();
	const codegen_1 = requireCodegen$1();
	const names_1 = requireNames$1();
	const compile_1 = requireCompile$2();
	const util_1 = requireUtil$4();
	const def = {
	    keyword: "$ref",
	    schemaType: "string",
	    code(cxt) {
	        const { gen, schema: $ref, it } = cxt;
	        const { baseId, schemaEnv: env, validateName, opts, self } = it;
	        const { root } = env;
	        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
	            return callRootRef();
	        const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
	        if (schOrEnv === undefined)
	            throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
	        if (schOrEnv instanceof compile_1.SchemaEnv)
	            return callValidate(schOrEnv);
	        return inlineRefSchema(schOrEnv);
	        function callRootRef() {
	            if (env === root)
	                return callRef(cxt, validateName, env, env.$async);
	            const rootName = gen.scopeValue("root", { ref: root });
	            return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);
	        }
	        function callValidate(sch) {
	            const v = getValidate(cxt, sch);
	            callRef(cxt, v, sch, sch.$async);
	        }
	        function inlineRefSchema(sch) {
	            const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
	            const valid = gen.name("valid");
	            const schCxt = cxt.subschema({
	                schema: sch,
	                dataTypes: [],
	                schemaPath: codegen_1.nil,
	                topSchemaRef: schName,
	                errSchemaPath: $ref,
	            }, valid);
	            cxt.mergeEvaluated(schCxt);
	            cxt.ok(valid);
	        }
	    },
	};
	function getValidate(cxt, sch) {
	    const { gen } = cxt;
	    return sch.validate
	        ? gen.scopeValue("validate", { ref: sch.validate })
	        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`;
	}
	ref$1.getValidate = getValidate;
	function callRef(cxt, v, sch, $async) {
	    const { gen, it } = cxt;
	    const { allErrors, schemaEnv: env, opts } = it;
	    const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
	    if ($async)
	        callAsyncRef();
	    else
	        callSyncRef();
	    function callAsyncRef() {
	        if (!env.$async)
	            throw new Error("async schema referenced by sync schema");
	        const valid = gen.let("valid");
	        gen.try(() => {
	            gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
	            addEvaluatedFrom(v);
	            if (!allErrors)
	                gen.assign(valid, true);
	        }, (e) => {
	            gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
	            addErrorsFrom(e);
	            if (!allErrors)
	                gen.assign(valid, false);
	        });
	        cxt.ok(valid);
	    }
	    function callSyncRef() {
	        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
	    }
	    function addErrorsFrom(source) {
	        const errs = (0, codegen_1._) `${source}.errors`;
	        gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
	        gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
	    }
	    function addEvaluatedFrom(source) {
	        var _a;
	        if (!it.opts.unevaluated)
	            return;
	        const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
	        if (it.props !== true) {
	            if (schEvaluated && !schEvaluated.dynamicProps) {
	                if (schEvaluated.props !== undefined) {
	                    it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
	                }
	            }
	            else {
	                const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`);
	                it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
	            }
	        }
	        if (it.items !== true) {
	            if (schEvaluated && !schEvaluated.dynamicItems) {
	                if (schEvaluated.items !== undefined) {
	                    it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
	                }
	            }
	            else {
	                const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`);
	                it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
	            }
	        }
	    }
	}
	ref$1.callRef = callRef;
	ref$1.default = def;
	return ref$1;
}

var hasRequiredCore$3;

function requireCore$3 () {
	if (hasRequiredCore$3) return core$4;
	hasRequiredCore$3 = 1;
	Object.defineProperty(core$4, "__esModule", { value: true });
	const id_1 = requireId$1();
	const ref_1 = requireRef$1();
	const core = [
	    "$schema",
	    "$id",
	    "$defs",
	    "$vocabulary",
	    { keyword: "$comment" },
	    "definitions",
	    id_1.default,
	    ref_1.default,
	];
	core$4.default = core;
	return core$4;
}

var validation$2 = {};

var limitNumber$1 = {};

var hasRequiredLimitNumber$1;

function requireLimitNumber$1 () {
	if (hasRequiredLimitNumber$1) return limitNumber$1;
	hasRequiredLimitNumber$1 = 1;
	Object.defineProperty(limitNumber$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const ops = codegen_1.operators;
	const KWDs = {
	    maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
	    minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
	    exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
	    exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
	};
	const error = {
	    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,
	    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: Object.keys(KWDs),
	    type: "number",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode } = cxt;
	        cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
	    },
	};
	limitNumber$1.default = def;
	return limitNumber$1;
}

var multipleOf$1 = {};

var hasRequiredMultipleOf$1;

function requireMultipleOf$1 () {
	if (hasRequiredMultipleOf$1) return multipleOf$1;
	hasRequiredMultipleOf$1 = 1;
	Object.defineProperty(multipleOf$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const error = {
	    message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,
	    params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,
	};
	const def = {
	    keyword: "multipleOf",
	    type: "number",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, schemaCode, it } = cxt;
	        const prec = it.opts.multipleOfPrecision;
	        const res = gen.let("res");
	        const invalid = prec
	            ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
	            : (0, codegen_1._) `${res} !== parseInt(${res})`;
	        cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
	    },
	};
	multipleOf$1.default = def;
	return multipleOf$1;
}

var limitLength$1 = {};

var ucs2length$1 = {};

var hasRequiredUcs2length$1;

function requireUcs2length$1 () {
	if (hasRequiredUcs2length$1) return ucs2length$1;
	hasRequiredUcs2length$1 = 1;
	Object.defineProperty(ucs2length$1, "__esModule", { value: true });
	function ucs2length(str) {
	    const len = str.length;
	    let length = 0;
	    let pos = 0;
	    let value;
	    while (pos < len) {
	        length++;
	        value = str.charCodeAt(pos++);
	        if (value >= 0xd800 && value <= 0xdbff && pos < len) {
	            value = str.charCodeAt(pos);
	            if ((value & 0xfc00) === 0xdc00)
	                pos++;
	        }
	    }
	    return length;
	}
	ucs2length$1.default = ucs2length;
	ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
	return ucs2length$1;
}

var hasRequiredLimitLength$1;

function requireLimitLength$1 () {
	if (hasRequiredLimitLength$1) return limitLength$1;
	hasRequiredLimitLength$1 = 1;
	Object.defineProperty(limitLength$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const ucs2length_1 = requireUcs2length$1();
	const error = {
	    message({ keyword, schemaCode }) {
	        const comp = keyword === "maxLength" ? "more" : "fewer";
	        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;
	    },
	    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: ["maxLength", "minLength"],
	    type: "string",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode, it } = cxt;
	        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
	        const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
	        cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);
	    },
	};
	limitLength$1.default = def;
	return limitLength$1;
}

var pattern$1 = {};

var hasRequiredPattern$1;

function requirePattern$1 () {
	if (hasRequiredPattern$1) return pattern$1;
	hasRequiredPattern$1 = 1;
	Object.defineProperty(pattern$1, "__esModule", { value: true });
	const code_1 = requireCode$3();
	const codegen_1 = requireCodegen$1();
	const error = {
	    message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`,
	    params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,
	};
	const def = {
	    keyword: "pattern",
	    type: "string",
	    schemaType: "string",
	    $data: true,
	    error,
	    code(cxt) {
	        const { data, $data, schema, schemaCode, it } = cxt;
	        const u = it.opts.unicodeRegExp ? "u" : "";
	        const regExp = $data ? (0, codegen_1._) `(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema);
	        cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);
	    },
	};
	pattern$1.default = def;
	return pattern$1;
}

var limitProperties$1 = {};

var hasRequiredLimitProperties$1;

function requireLimitProperties$1 () {
	if (hasRequiredLimitProperties$1) return limitProperties$1;
	hasRequiredLimitProperties$1 = 1;
	Object.defineProperty(limitProperties$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const error = {
	    message({ keyword, schemaCode }) {
	        const comp = keyword === "maxProperties" ? "more" : "fewer";
	        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;
	    },
	    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: ["maxProperties", "minProperties"],
	    type: "object",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode } = cxt;
	        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
	        cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);
	    },
	};
	limitProperties$1.default = def;
	return limitProperties$1;
}

var required$2 = {};

var hasRequiredRequired$1;

function requireRequired$1 () {
	if (hasRequiredRequired$1) return required$2;
	hasRequiredRequired$1 = 1;
	Object.defineProperty(required$2, "__esModule", { value: true });
	const code_1 = requireCode$3();
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const error = {
	    message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,
	    params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,
	};
	const def = {
	    keyword: "required",
	    type: "object",
	    schemaType: "array",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, schema, schemaCode, data, $data, it } = cxt;
	        const { opts } = it;
	        if (!$data && schema.length === 0)
	            return;
	        const useLoop = schema.length >= opts.loopRequired;
	        if (it.allErrors)
	            allErrorsMode();
	        else
	            exitOnErrorMode();
	        if (opts.strictRequired) {
	            const props = cxt.parentSchema.properties;
	            const { definedProperties } = cxt.it;
	            for (const requiredKey of schema) {
	                if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {
	                    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
	                    const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
	                    (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
	                }
	            }
	        }
	        function allErrorsMode() {
	            if (useLoop || $data) {
	                cxt.block$data(codegen_1.nil, loopAllRequired);
	            }
	            else {
	                for (const prop of schema) {
	                    (0, code_1.checkReportMissingProp)(cxt, prop);
	                }
	            }
	        }
	        function exitOnErrorMode() {
	            const missing = gen.let("missing");
	            if (useLoop || $data) {
	                const valid = gen.let("valid", true);
	                cxt.block$data(valid, () => loopUntilMissing(missing, valid));
	                cxt.ok(valid);
	            }
	            else {
	                gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
	                (0, code_1.reportMissingProp)(cxt, missing);
	                gen.else();
	            }
	        }
	        function loopAllRequired() {
	            gen.forOf("prop", schemaCode, (prop) => {
	                cxt.setParams({ missingProperty: prop });
	                gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
	            });
	        }
	        function loopUntilMissing(missing, valid) {
	            cxt.setParams({ missingProperty: missing });
	            gen.forOf(missing, schemaCode, () => {
	                gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
	                gen.if((0, codegen_1.not)(valid), () => {
	                    cxt.error();
	                    gen.break();
	                });
	            }, codegen_1.nil);
	        }
	    },
	};
	required$2.default = def;
	return required$2;
}

var limitItems$1 = {};

var hasRequiredLimitItems$1;

function requireLimitItems$1 () {
	if (hasRequiredLimitItems$1) return limitItems$1;
	hasRequiredLimitItems$1 = 1;
	Object.defineProperty(limitItems$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const error = {
	    message({ keyword, schemaCode }) {
	        const comp = keyword === "maxItems" ? "more" : "fewer";
	        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;
	    },
	    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: ["maxItems", "minItems"],
	    type: "array",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode } = cxt;
	        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
	        cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);
	    },
	};
	limitItems$1.default = def;
	return limitItems$1;
}

var uniqueItems$1 = {};

var equal$1 = {};

var hasRequiredEqual$1;

function requireEqual$1 () {
	if (hasRequiredEqual$1) return equal$1;
	hasRequiredEqual$1 = 1;
	Object.defineProperty(equal$1, "__esModule", { value: true });
	const equal = requireFastDeepEqual();
	equal.code = 'require("ajv/dist/runtime/equal").default';
	equal$1.default = equal;
	return equal$1;
}

var hasRequiredUniqueItems$1;

function requireUniqueItems$1 () {
	if (hasRequiredUniqueItems$1) return uniqueItems$1;
	hasRequiredUniqueItems$1 = 1;
	Object.defineProperty(uniqueItems$1, "__esModule", { value: true });
	const dataType_1 = requireDataType$1();
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const equal_1 = requireEqual$1();
	const error = {
	    message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
	    params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,
	};
	const def = {
	    keyword: "uniqueItems",
	    type: "array",
	    schemaType: "boolean",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
	        if (!$data && !schema)
	            return;
	        const valid = gen.let("valid");
	        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
	        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);
	        cxt.ok(valid);
	        function validateUniqueItems() {
	            const i = gen.let("i", (0, codegen_1._) `${data}.length`);
	            const j = gen.let("j");
	            cxt.setParams({ i, j });
	            gen.assign(valid, true);
	            gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
	        }
	        function canOptimize() {
	            return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
	        }
	        function loopN(i, j) {
	            const item = gen.name("item");
	            const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
	            const indices = gen.const("indices", (0, codegen_1._) `{}`);
	            gen.for((0, codegen_1._) `;${i}--;`, () => {
	                gen.let(item, (0, codegen_1._) `${data}[${i}]`);
	                gen.if(wrongType, (0, codegen_1._) `continue`);
	                if (itemTypes.length > 1)
	                    gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`);
	                gen
	                    .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => {
	                    gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);
	                    cxt.error();
	                    gen.assign(valid, false).break();
	                })
	                    .code((0, codegen_1._) `${indices}[${item}] = ${i}`);
	            });
	        }
	        function loopN2(i, j) {
	            const eql = (0, util_1.useFunc)(gen, equal_1.default);
	            const outer = gen.name("outer");
	            gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {
	                cxt.error();
	                gen.assign(valid, false).break(outer);
	            })));
	        }
	    },
	};
	uniqueItems$1.default = def;
	return uniqueItems$1;
}

var _const$1 = {};

var hasRequired_const$1;

function require_const$1 () {
	if (hasRequired_const$1) return _const$1;
	hasRequired_const$1 = 1;
	Object.defineProperty(_const$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const equal_1 = requireEqual$1();
	const error = {
	    message: "must be equal to constant",
	    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,
	};
	const def = {
	    keyword: "const",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, $data, schemaCode, schema } = cxt;
	        if ($data || (schema && typeof schema == "object")) {
	            cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
	        }
	        else {
	            cxt.fail((0, codegen_1._) `${schema} !== ${data}`);
	        }
	    },
	};
	_const$1.default = def;
	return _const$1;
}

var _enum$1 = {};

var hasRequired_enum$1;

function require_enum$1 () {
	if (hasRequired_enum$1) return _enum$1;
	hasRequired_enum$1 = 1;
	Object.defineProperty(_enum$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const equal_1 = requireEqual$1();
	const error = {
	    message: "must be equal to one of the allowed values",
	    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
	};
	const def = {
	    keyword: "enum",
	    schemaType: "array",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, $data, schema, schemaCode, it } = cxt;
	        if (!$data && schema.length === 0)
	            throw new Error("enum must have non-empty array");
	        const useLoop = schema.length >= it.opts.loopEnum;
	        let eql;
	        const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));
	        let valid;
	        if (useLoop || $data) {
	            valid = gen.let("valid");
	            cxt.block$data(valid, loopEnum);
	        }
	        else {
	            if (!Array.isArray(schema))
	                throw new Error("ajv implementation error");
	            const vSchema = gen.const("vSchema", schemaCode);
	            valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
	        }
	        cxt.pass(valid);
	        function loopEnum() {
	            gen.assign(valid, false);
	            gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
	        }
	        function equalCode(vSchema, i) {
	            const sch = schema[i];
	            return typeof sch === "object" && sch !== null
	                ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`
	                : (0, codegen_1._) `${data} === ${sch}`;
	        }
	    },
	};
	_enum$1.default = def;
	return _enum$1;
}

var hasRequiredValidation$2;

function requireValidation$2 () {
	if (hasRequiredValidation$2) return validation$2;
	hasRequiredValidation$2 = 1;
	Object.defineProperty(validation$2, "__esModule", { value: true });
	const limitNumber_1 = requireLimitNumber$1();
	const multipleOf_1 = requireMultipleOf$1();
	const limitLength_1 = requireLimitLength$1();
	const pattern_1 = requirePattern$1();
	const limitProperties_1 = requireLimitProperties$1();
	const required_1 = requireRequired$1();
	const limitItems_1 = requireLimitItems$1();
	const uniqueItems_1 = requireUniqueItems$1();
	const const_1 = require_const$1();
	const enum_1 = require_enum$1();
	const validation = [
	    limitNumber_1.default,
	    multipleOf_1.default,
	    limitLength_1.default,
	    pattern_1.default,
	    limitProperties_1.default,
	    required_1.default,
	    limitItems_1.default,
	    uniqueItems_1.default,
	    { keyword: "type", schemaType: ["string", "array"] },
	    { keyword: "nullable", schemaType: "boolean" },
	    const_1.default,
	    enum_1.default,
	];
	validation$2.default = validation;
	return validation$2;
}

var applicator$1 = {};

var additionalItems$1 = {};

var hasRequiredAdditionalItems$1;

function requireAdditionalItems$1 () {
	if (hasRequiredAdditionalItems$1) return additionalItems$1;
	hasRequiredAdditionalItems$1 = 1;
	Object.defineProperty(additionalItems$1, "__esModule", { value: true });
	additionalItems$1.validateAdditionalItems = void 0;
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const error = {
	    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
	    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
	};
	const def = {
	    keyword: "additionalItems",
	    type: "array",
	    schemaType: ["boolean", "object"],
	    before: "uniqueItems",
	    error,
	    code(cxt) {
	        const { parentSchema, it } = cxt;
	        const { items } = parentSchema;
	        if (!Array.isArray(items)) {
	            (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
	            return;
	        }
	        validateAdditionalItems(cxt, items);
	    },
	};
	function validateAdditionalItems(cxt, items) {
	    const { gen, schema, data, keyword, it } = cxt;
	    it.items = true;
	    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	    if (schema === false) {
	        cxt.setParams({ len: items.length });
	        cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);
	    }
	    else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
	        const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`);
	        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
	        cxt.ok(valid);
	    }
	    function validateItems(valid) {
	        gen.forRange("i", items.length, len, (i) => {
	            cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
	            if (!it.allErrors)
	                gen.if((0, codegen_1.not)(valid), () => gen.break());
	        });
	    }
	}
	additionalItems$1.validateAdditionalItems = validateAdditionalItems;
	additionalItems$1.default = def;
	return additionalItems$1;
}

var prefixItems$1 = {};

var items$1 = {};

var hasRequiredItems$1;

function requireItems$1 () {
	if (hasRequiredItems$1) return items$1;
	hasRequiredItems$1 = 1;
	Object.defineProperty(items$1, "__esModule", { value: true });
	items$1.validateTuple = void 0;
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const code_1 = requireCode$3();
	const def = {
	    keyword: "items",
	    type: "array",
	    schemaType: ["object", "array", "boolean"],
	    before: "uniqueItems",
	    code(cxt) {
	        const { schema, it } = cxt;
	        if (Array.isArray(schema))
	            return validateTuple(cxt, "additionalItems", schema);
	        it.items = true;
	        if ((0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        cxt.ok((0, code_1.validateArray)(cxt));
	    },
	};
	function validateTuple(cxt, extraItems, schArr = cxt.schema) {
	    const { gen, parentSchema, data, keyword, it } = cxt;
	    checkStrictTuple(parentSchema);
	    if (it.opts.unevaluated && schArr.length && it.items !== true) {
	        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
	    }
	    const valid = gen.name("valid");
	    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	    schArr.forEach((sch, i) => {
	        if ((0, util_1.alwaysValidSchema)(it, sch))
	            return;
	        gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({
	            keyword,
	            schemaProp: i,
	            dataProp: i,
	        }, valid));
	        cxt.ok(valid);
	    });
	    function checkStrictTuple(sch) {
	        const { opts, errSchemaPath } = it;
	        const l = schArr.length;
	        const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
	        if (opts.strictTuples && !fullTuple) {
	            const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
	            (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
	        }
	    }
	}
	items$1.validateTuple = validateTuple;
	items$1.default = def;
	return items$1;
}

var hasRequiredPrefixItems$1;

function requirePrefixItems$1 () {
	if (hasRequiredPrefixItems$1) return prefixItems$1;
	hasRequiredPrefixItems$1 = 1;
	Object.defineProperty(prefixItems$1, "__esModule", { value: true });
	const items_1 = requireItems$1();
	const def = {
	    keyword: "prefixItems",
	    type: "array",
	    schemaType: ["array"],
	    before: "uniqueItems",
	    code: (cxt) => (0, items_1.validateTuple)(cxt, "items"),
	};
	prefixItems$1.default = def;
	return prefixItems$1;
}

var items2020$1 = {};

var hasRequiredItems2020$1;

function requireItems2020$1 () {
	if (hasRequiredItems2020$1) return items2020$1;
	hasRequiredItems2020$1 = 1;
	Object.defineProperty(items2020$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const code_1 = requireCode$3();
	const additionalItems_1 = requireAdditionalItems$1();
	const error = {
	    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
	    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
	};
	const def = {
	    keyword: "items",
	    type: "array",
	    schemaType: ["object", "boolean"],
	    before: "uniqueItems",
	    error,
	    code(cxt) {
	        const { schema, parentSchema, it } = cxt;
	        const { prefixItems } = parentSchema;
	        it.items = true;
	        if ((0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        if (prefixItems)
	            (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
	        else
	            cxt.ok((0, code_1.validateArray)(cxt));
	    },
	};
	items2020$1.default = def;
	return items2020$1;
}

var contains$2 = {};

var hasRequiredContains$1;

function requireContains$1 () {
	if (hasRequiredContains$1) return contains$2;
	hasRequiredContains$1 = 1;
	Object.defineProperty(contains$2, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const error = {
	    message: ({ params: { min, max } }) => max === undefined
	        ? (0, codegen_1.str) `must contain at least ${min} valid item(s)`
	        : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,
	    params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,
	};
	const def = {
	    keyword: "contains",
	    type: "array",
	    schemaType: ["object", "boolean"],
	    before: "uniqueItems",
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, schema, parentSchema, data, it } = cxt;
	        let min;
	        let max;
	        const { minContains, maxContains } = parentSchema;
	        if (it.opts.next) {
	            min = minContains === undefined ? 1 : minContains;
	            max = maxContains;
	        }
	        else {
	            min = 1;
	        }
	        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	        cxt.setParams({ min, max });
	        if (max === undefined && min === 0) {
	            (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
	            return;
	        }
	        if (max !== undefined && min > max) {
	            (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
	            cxt.fail();
	            return;
	        }
	        if ((0, util_1.alwaysValidSchema)(it, schema)) {
	            let cond = (0, codegen_1._) `${len} >= ${min}`;
	            if (max !== undefined)
	                cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;
	            cxt.pass(cond);
	            return;
	        }
	        it.items = true;
	        const valid = gen.name("valid");
	        if (max === undefined && min === 1) {
	            validateItems(valid, () => gen.if(valid, () => gen.break()));
	        }
	        else if (min === 0) {
	            gen.let(valid, true);
	            if (max !== undefined)
	                gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);
	        }
	        else {
	            gen.let(valid, false);
	            validateItemsWithCount();
	        }
	        cxt.result(valid, () => cxt.reset());
	        function validateItemsWithCount() {
	            const schValid = gen.name("_valid");
	            const count = gen.let("count", 0);
	            validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
	        }
	        function validateItems(_valid, block) {
	            gen.forRange("i", 0, len, (i) => {
	                cxt.subschema({
	                    keyword: "contains",
	                    dataProp: i,
	                    dataPropType: util_1.Type.Num,
	                    compositeRule: true,
	                }, _valid);
	                block();
	            });
	        }
	        function checkLimits(count) {
	            gen.code((0, codegen_1._) `${count}++`);
	            if (max === undefined) {
	                gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());
	            }
	            else {
	                gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());
	                if (min === 1)
	                    gen.assign(valid, true);
	                else
	                    gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));
	            }
	        }
	    },
	};
	contains$2.default = def;
	return contains$2;
}

var dependencies$1 = {};

var hasRequiredDependencies$1;

function requireDependencies$1 () {
	if (hasRequiredDependencies$1) return dependencies$1;
	hasRequiredDependencies$1 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.validateSchemaDeps = exports$1.validatePropertyDeps = exports$1.error = void 0;
		const codegen_1 = requireCodegen$1();
		const util_1 = requireUtil$4();
		const code_1 = requireCode$3();
		exports$1.error = {
		    message: ({ params: { property, depsCount, deps } }) => {
		        const property_ies = depsCount === 1 ? "property" : "properties";
		        return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;
		    },
		    params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`,
		};
		const def = {
		    keyword: "dependencies",
		    type: "object",
		    schemaType: "object",
		    error: exports$1.error,
		    code(cxt) {
		        const [propDeps, schDeps] = splitDependencies(cxt);
		        validatePropertyDeps(cxt, propDeps);
		        validateSchemaDeps(cxt, schDeps);
		    },
		};
		function splitDependencies({ schema }) {
		    const propertyDeps = {};
		    const schemaDeps = {};
		    for (const key in schema) {
		        if (key === "__proto__")
		            continue;
		        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
		        deps[key] = schema[key];
		    }
		    return [propertyDeps, schemaDeps];
		}
		function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
		    const { gen, data, it } = cxt;
		    if (Object.keys(propertyDeps).length === 0)
		        return;
		    const missing = gen.let("missing");
		    for (const prop in propertyDeps) {
		        const deps = propertyDeps[prop];
		        if (deps.length === 0)
		            continue;
		        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
		        cxt.setParams({
		            property: prop,
		            depsCount: deps.length,
		            deps: deps.join(", "),
		        });
		        if (it.allErrors) {
		            gen.if(hasProperty, () => {
		                for (const depProp of deps) {
		                    (0, code_1.checkReportMissingProp)(cxt, depProp);
		                }
		            });
		        }
		        else {
		            gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
		            (0, code_1.reportMissingProp)(cxt, missing);
		            gen.else();
		        }
		    }
		}
		exports$1.validatePropertyDeps = validatePropertyDeps;
		function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
		    const { gen, data, keyword, it } = cxt;
		    const valid = gen.name("valid");
		    for (const prop in schemaDeps) {
		        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
		            continue;
		        gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
		            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
		            cxt.mergeValidEvaluated(schCxt, valid);
		        }, () => gen.var(valid, true)
		        );
		        cxt.ok(valid);
		    }
		}
		exports$1.validateSchemaDeps = validateSchemaDeps;
		exports$1.default = def; 
	} (dependencies$1));
	return dependencies$1;
}

var propertyNames$1 = {};

var hasRequiredPropertyNames$1;

function requirePropertyNames$1 () {
	if (hasRequiredPropertyNames$1) return propertyNames$1;
	hasRequiredPropertyNames$1 = 1;
	Object.defineProperty(propertyNames$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const error = {
	    message: "property name must be valid",
	    params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,
	};
	const def = {
	    keyword: "propertyNames",
	    type: "object",
	    schemaType: ["object", "boolean"],
	    error,
	    code(cxt) {
	        const { gen, schema, data, it } = cxt;
	        if ((0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        const valid = gen.name("valid");
	        gen.forIn("key", data, (key) => {
	            cxt.setParams({ propertyName: key });
	            cxt.subschema({
	                keyword: "propertyNames",
	                data: key,
	                dataTypes: ["string"],
	                propertyName: key,
	                compositeRule: true,
	            }, valid);
	            gen.if((0, codegen_1.not)(valid), () => {
	                cxt.error(true);
	                if (!it.allErrors)
	                    gen.break();
	            });
	        });
	        cxt.ok(valid);
	    },
	};
	propertyNames$1.default = def;
	return propertyNames$1;
}

var additionalProperties$2 = {};

var hasRequiredAdditionalProperties$1;

function requireAdditionalProperties$1 () {
	if (hasRequiredAdditionalProperties$1) return additionalProperties$2;
	hasRequiredAdditionalProperties$1 = 1;
	Object.defineProperty(additionalProperties$2, "__esModule", { value: true });
	const code_1 = requireCode$3();
	const codegen_1 = requireCodegen$1();
	const names_1 = requireNames$1();
	const util_1 = requireUtil$4();
	const error = {
	    message: "must NOT have additional properties",
	    params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,
	};
	const def = {
	    keyword: "additionalProperties",
	    type: ["object"],
	    schemaType: ["boolean", "object"],
	    allowUndefined: true,
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
	        if (!errsCount)
	            throw new Error("ajv implementation error");
	        const { allErrors, opts } = it;
	        it.props = true;
	        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
	        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
	        checkAdditionalProperties();
	        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
	        function checkAdditionalProperties() {
	            gen.forIn("key", data, (key) => {
	                if (!props.length && !patProps.length)
	                    additionalPropertyCode(key);
	                else
	                    gen.if(isAdditional(key), () => additionalPropertyCode(key));
	            });
	        }
	        function isAdditional(key) {
	            let definedProp;
	            if (props.length > 8) {
	                const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
	                definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
	            }
	            else if (props.length) {
	                definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));
	            }
	            else {
	                definedProp = codegen_1.nil;
	            }
	            if (patProps.length) {
	                definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
	            }
	            return (0, codegen_1.not)(definedProp);
	        }
	        function deleteAdditional(key) {
	            gen.code((0, codegen_1._) `delete ${data}[${key}]`);
	        }
	        function additionalPropertyCode(key) {
	            if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
	                deleteAdditional(key);
	                return;
	            }
	            if (schema === false) {
	                cxt.setParams({ additionalProperty: key });
	                cxt.error();
	                if (!allErrors)
	                    gen.break();
	                return;
	            }
	            if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
	                const valid = gen.name("valid");
	                if (opts.removeAdditional === "failing") {
	                    applyAdditionalSchema(key, valid, false);
	                    gen.if((0, codegen_1.not)(valid), () => {
	                        cxt.reset();
	                        deleteAdditional(key);
	                    });
	                }
	                else {
	                    applyAdditionalSchema(key, valid);
	                    if (!allErrors)
	                        gen.if((0, codegen_1.not)(valid), () => gen.break());
	                }
	            }
	        }
	        function applyAdditionalSchema(key, valid, errors) {
	            const subschema = {
	                keyword: "additionalProperties",
	                dataProp: key,
	                dataPropType: util_1.Type.Str,
	            };
	            if (errors === false) {
	                Object.assign(subschema, {
	                    compositeRule: true,
	                    createErrors: false,
	                    allErrors: false,
	                });
	            }
	            cxt.subschema(subschema, valid);
	        }
	    },
	};
	additionalProperties$2.default = def;
	return additionalProperties$2;
}

var properties$4 = {};

var hasRequiredProperties$1;

function requireProperties$1 () {
	if (hasRequiredProperties$1) return properties$4;
	hasRequiredProperties$1 = 1;
	Object.defineProperty(properties$4, "__esModule", { value: true });
	const validate_1 = requireValidate$1();
	const code_1 = requireCode$3();
	const util_1 = requireUtil$4();
	const additionalProperties_1 = requireAdditionalProperties$1();
	const def = {
	    keyword: "properties",
	    type: "object",
	    schemaType: "object",
	    code(cxt) {
	        const { gen, schema, parentSchema, data, it } = cxt;
	        if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
	            additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
	        }
	        const allProps = (0, code_1.allSchemaProperties)(schema);
	        for (const prop of allProps) {
	            it.definedProperties.add(prop);
	        }
	        if (it.opts.unevaluated && allProps.length && it.props !== true) {
	            it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
	        }
	        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
	        if (properties.length === 0)
	            return;
	        const valid = gen.name("valid");
	        for (const prop of properties) {
	            if (hasDefault(prop)) {
	                applyPropertySchema(prop);
	            }
	            else {
	                gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
	                applyPropertySchema(prop);
	                if (!it.allErrors)
	                    gen.else().var(valid, true);
	                gen.endIf();
	            }
	            cxt.it.definedProperties.add(prop);
	            cxt.ok(valid);
	        }
	        function hasDefault(prop) {
	            return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;
	        }
	        function applyPropertySchema(prop) {
	            cxt.subschema({
	                keyword: "properties",
	                schemaProp: prop,
	                dataProp: prop,
	            }, valid);
	        }
	    },
	};
	properties$4.default = def;
	return properties$4;
}

var patternProperties$1 = {};

var hasRequiredPatternProperties$1;

function requirePatternProperties$1 () {
	if (hasRequiredPatternProperties$1) return patternProperties$1;
	hasRequiredPatternProperties$1 = 1;
	Object.defineProperty(patternProperties$1, "__esModule", { value: true });
	const code_1 = requireCode$3();
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const util_2 = requireUtil$4();
	const def = {
	    keyword: "patternProperties",
	    type: "object",
	    schemaType: "object",
	    code(cxt) {
	        const { gen, schema, data, parentSchema, it } = cxt;
	        const { opts } = it;
	        const patterns = (0, code_1.allSchemaProperties)(schema);
	        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
	        if (patterns.length === 0 ||
	            (alwaysValidPatterns.length === patterns.length &&
	                (!it.opts.unevaluated || it.props === true))) {
	            return;
	        }
	        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
	        const valid = gen.name("valid");
	        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
	            it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
	        }
	        const { props } = it;
	        validatePatternProperties();
	        function validatePatternProperties() {
	            for (const pat of patterns) {
	                if (checkProperties)
	                    checkMatchingProperties(pat);
	                if (it.allErrors) {
	                    validateProperties(pat);
	                }
	                else {
	                    gen.var(valid, true);
	                    validateProperties(pat);
	                    gen.if(valid);
	                }
	            }
	        }
	        function checkMatchingProperties(pat) {
	            for (const prop in checkProperties) {
	                if (new RegExp(pat).test(prop)) {
	                    (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
	                }
	            }
	        }
	        function validateProperties(pat) {
	            gen.forIn("key", data, (key) => {
	                gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
	                    const alwaysValid = alwaysValidPatterns.includes(pat);
	                    if (!alwaysValid) {
	                        cxt.subschema({
	                            keyword: "patternProperties",
	                            schemaProp: pat,
	                            dataProp: key,
	                            dataPropType: util_2.Type.Str,
	                        }, valid);
	                    }
	                    if (it.opts.unevaluated && props !== true) {
	                        gen.assign((0, codegen_1._) `${props}[${key}]`, true);
	                    }
	                    else if (!alwaysValid && !it.allErrors) {
	                        gen.if((0, codegen_1.not)(valid), () => gen.break());
	                    }
	                });
	            });
	        }
	    },
	};
	patternProperties$1.default = def;
	return patternProperties$1;
}

var not$1 = {};

var hasRequiredNot$1;

function requireNot$1 () {
	if (hasRequiredNot$1) return not$1;
	hasRequiredNot$1 = 1;
	Object.defineProperty(not$1, "__esModule", { value: true });
	const util_1 = requireUtil$4();
	const def = {
	    keyword: "not",
	    schemaType: ["object", "boolean"],
	    trackErrors: true,
	    code(cxt) {
	        const { gen, schema, it } = cxt;
	        if ((0, util_1.alwaysValidSchema)(it, schema)) {
	            cxt.fail();
	            return;
	        }
	        const valid = gen.name("valid");
	        cxt.subschema({
	            keyword: "not",
	            compositeRule: true,
	            createErrors: false,
	            allErrors: false,
	        }, valid);
	        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
	    },
	    error: { message: "must NOT be valid" },
	};
	not$1.default = def;
	return not$1;
}

var anyOf$1 = {};

var hasRequiredAnyOf$1;

function requireAnyOf$1 () {
	if (hasRequiredAnyOf$1) return anyOf$1;
	hasRequiredAnyOf$1 = 1;
	Object.defineProperty(anyOf$1, "__esModule", { value: true });
	const code_1 = requireCode$3();
	const def = {
	    keyword: "anyOf",
	    schemaType: "array",
	    trackErrors: true,
	    code: code_1.validateUnion,
	    error: { message: "must match a schema in anyOf" },
	};
	anyOf$1.default = def;
	return anyOf$1;
}

var oneOf$1 = {};

var hasRequiredOneOf$1;

function requireOneOf$1 () {
	if (hasRequiredOneOf$1) return oneOf$1;
	hasRequiredOneOf$1 = 1;
	Object.defineProperty(oneOf$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const error = {
	    message: "must match exactly one schema in oneOf",
	    params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,
	};
	const def = {
	    keyword: "oneOf",
	    schemaType: "array",
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, schema, parentSchema, it } = cxt;
	        if (!Array.isArray(schema))
	            throw new Error("ajv implementation error");
	        if (it.opts.discriminator && parentSchema.discriminator)
	            return;
	        const schArr = schema;
	        const valid = gen.let("valid", false);
	        const passing = gen.let("passing", null);
	        const schValid = gen.name("_valid");
	        cxt.setParams({ passing });
	        gen.block(validateOneOf);
	        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
	        function validateOneOf() {
	            schArr.forEach((sch, i) => {
	                let schCxt;
	                if ((0, util_1.alwaysValidSchema)(it, sch)) {
	                    gen.var(schValid, true);
	                }
	                else {
	                    schCxt = cxt.subschema({
	                        keyword: "oneOf",
	                        schemaProp: i,
	                        compositeRule: true,
	                    }, schValid);
	                }
	                if (i > 0) {
	                    gen
	                        .if((0, codegen_1._) `${schValid} && ${valid}`)
	                        .assign(valid, false)
	                        .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)
	                        .else();
	                }
	                gen.if(schValid, () => {
	                    gen.assign(valid, true);
	                    gen.assign(passing, i);
	                    if (schCxt)
	                        cxt.mergeEvaluated(schCxt, codegen_1.Name);
	                });
	            });
	        }
	    },
	};
	oneOf$1.default = def;
	return oneOf$1;
}

var allOf$1 = {};

var hasRequiredAllOf$1;

function requireAllOf$1 () {
	if (hasRequiredAllOf$1) return allOf$1;
	hasRequiredAllOf$1 = 1;
	Object.defineProperty(allOf$1, "__esModule", { value: true });
	const util_1 = requireUtil$4();
	const def = {
	    keyword: "allOf",
	    schemaType: "array",
	    code(cxt) {
	        const { gen, schema, it } = cxt;
	        if (!Array.isArray(schema))
	            throw new Error("ajv implementation error");
	        const valid = gen.name("valid");
	        schema.forEach((sch, i) => {
	            if ((0, util_1.alwaysValidSchema)(it, sch))
	                return;
	            const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
	            cxt.ok(valid);
	            cxt.mergeEvaluated(schCxt);
	        });
	    },
	};
	allOf$1.default = def;
	return allOf$1;
}

var _if$1 = {};

var hasRequired_if$1;

function require_if$1 () {
	if (hasRequired_if$1) return _if$1;
	hasRequired_if$1 = 1;
	Object.defineProperty(_if$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const util_1 = requireUtil$4();
	const error = {
	    message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`,
	    params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,
	};
	const def = {
	    keyword: "if",
	    schemaType: ["object", "boolean"],
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, parentSchema, it } = cxt;
	        if (parentSchema.then === undefined && parentSchema.else === undefined) {
	            (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
	        }
	        const hasThen = hasSchema(it, "then");
	        const hasElse = hasSchema(it, "else");
	        if (!hasThen && !hasElse)
	            return;
	        const valid = gen.let("valid", true);
	        const schValid = gen.name("_valid");
	        validateIf();
	        cxt.reset();
	        if (hasThen && hasElse) {
	            const ifClause = gen.let("ifClause");
	            cxt.setParams({ ifClause });
	            gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
	        }
	        else if (hasThen) {
	            gen.if(schValid, validateClause("then"));
	        }
	        else {
	            gen.if((0, codegen_1.not)(schValid), validateClause("else"));
	        }
	        cxt.pass(valid, () => cxt.error(true));
	        function validateIf() {
	            const schCxt = cxt.subschema({
	                keyword: "if",
	                compositeRule: true,
	                createErrors: false,
	                allErrors: false,
	            }, schValid);
	            cxt.mergeEvaluated(schCxt);
	        }
	        function validateClause(keyword, ifClause) {
	            return () => {
	                const schCxt = cxt.subschema({ keyword }, schValid);
	                gen.assign(valid, schValid);
	                cxt.mergeValidEvaluated(schCxt, valid);
	                if (ifClause)
	                    gen.assign(ifClause, (0, codegen_1._) `${keyword}`);
	                else
	                    cxt.setParams({ ifClause: keyword });
	            };
	        }
	    },
	};
	function hasSchema(it, keyword) {
	    const schema = it.schema[keyword];
	    return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);
	}
	_if$1.default = def;
	return _if$1;
}

var thenElse$1 = {};

var hasRequiredThenElse$1;

function requireThenElse$1 () {
	if (hasRequiredThenElse$1) return thenElse$1;
	hasRequiredThenElse$1 = 1;
	Object.defineProperty(thenElse$1, "__esModule", { value: true });
	const util_1 = requireUtil$4();
	const def = {
	    keyword: ["then", "else"],
	    schemaType: ["object", "boolean"],
	    code({ keyword, parentSchema, it }) {
	        if (parentSchema.if === undefined)
	            (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
	    },
	};
	thenElse$1.default = def;
	return thenElse$1;
}

var hasRequiredApplicator$1;

function requireApplicator$1 () {
	if (hasRequiredApplicator$1) return applicator$1;
	hasRequiredApplicator$1 = 1;
	Object.defineProperty(applicator$1, "__esModule", { value: true });
	const additionalItems_1 = requireAdditionalItems$1();
	const prefixItems_1 = requirePrefixItems$1();
	const items_1 = requireItems$1();
	const items2020_1 = requireItems2020$1();
	const contains_1 = requireContains$1();
	const dependencies_1 = requireDependencies$1();
	const propertyNames_1 = requirePropertyNames$1();
	const additionalProperties_1 = requireAdditionalProperties$1();
	const properties_1 = requireProperties$1();
	const patternProperties_1 = requirePatternProperties$1();
	const not_1 = requireNot$1();
	const anyOf_1 = requireAnyOf$1();
	const oneOf_1 = requireOneOf$1();
	const allOf_1 = requireAllOf$1();
	const if_1 = require_if$1();
	const thenElse_1 = requireThenElse$1();
	function getApplicator(draft2020 = false) {
	    const applicator = [
	        not_1.default,
	        anyOf_1.default,
	        oneOf_1.default,
	        allOf_1.default,
	        if_1.default,
	        thenElse_1.default,
	        propertyNames_1.default,
	        additionalProperties_1.default,
	        dependencies_1.default,
	        properties_1.default,
	        patternProperties_1.default,
	    ];
	    if (draft2020)
	        applicator.push(prefixItems_1.default, items2020_1.default);
	    else
	        applicator.push(additionalItems_1.default, items_1.default);
	    applicator.push(contains_1.default);
	    return applicator;
	}
	applicator$1.default = getApplicator;
	return applicator$1;
}

var format$4 = {};

var format$3 = {};

var hasRequiredFormat$3;

function requireFormat$3 () {
	if (hasRequiredFormat$3) return format$3;
	hasRequiredFormat$3 = 1;
	Object.defineProperty(format$3, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const error = {
	    message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`,
	    params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,
	};
	const def = {
	    keyword: "format",
	    type: ["number", "string"],
	    schemaType: "string",
	    $data: true,
	    error,
	    code(cxt, ruleType) {
	        const { gen, data, $data, schema, schemaCode, it } = cxt;
	        const { opts, errSchemaPath, schemaEnv, self } = it;
	        if (!opts.validateFormats)
	            return;
	        if ($data)
	            validate$DataFormat();
	        else
	            validateFormat();
	        function validate$DataFormat() {
	            const fmts = gen.scopeValue("formats", {
	                ref: self.formats,
	                code: opts.code.formats,
	            });
	            const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`);
	            const fType = gen.let("fType");
	            const format = gen.let("format");
	            gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef));
	            cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
	            function unknownFmt() {
	                if (opts.strictSchema === false)
	                    return codegen_1.nil;
	                return (0, codegen_1._) `${schemaCode} && !${format}`;
	            }
	            function invalidFmt() {
	                const callFormat = schemaEnv.$async
	                    ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
	                    : (0, codegen_1._) `${format}(${data})`;
	                const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
	                return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
	            }
	        }
	        function validateFormat() {
	            const formatDef = self.formats[schema];
	            if (!formatDef) {
	                unknownFormat();
	                return;
	            }
	            if (formatDef === true)
	                return;
	            const [fmtType, format, fmtRef] = getFormat(formatDef);
	            if (fmtType === ruleType)
	                cxt.pass(validCondition());
	            function unknownFormat() {
	                if (opts.strictSchema === false) {
	                    self.logger.warn(unknownMsg());
	                    return;
	                }
	                throw new Error(unknownMsg());
	                function unknownMsg() {
	                    return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
	                }
	            }
	            function getFormat(fmtDef) {
	                const code = fmtDef instanceof RegExp
	                    ? (0, codegen_1.regexpCode)(fmtDef)
	                    : opts.code.formats
	                        ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`
	                        : undefined;
	                const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
	                if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
	                    return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];
	                }
	                return ["string", fmtDef, fmt];
	            }
	            function validCondition() {
	                if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
	                    if (!schemaEnv.$async)
	                        throw new Error("async format in sync schema");
	                    return (0, codegen_1._) `await ${fmtRef}(${data})`;
	                }
	                return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;
	            }
	        }
	    },
	};
	format$3.default = def;
	return format$3;
}

var hasRequiredFormat$2;

function requireFormat$2 () {
	if (hasRequiredFormat$2) return format$4;
	hasRequiredFormat$2 = 1;
	Object.defineProperty(format$4, "__esModule", { value: true });
	const format_1 = requireFormat$3();
	const format = [format_1.default];
	format$4.default = format;
	return format$4;
}

var metadata$1 = {};

var hasRequiredMetadata$1;

function requireMetadata$1 () {
	if (hasRequiredMetadata$1) return metadata$1;
	hasRequiredMetadata$1 = 1;
	Object.defineProperty(metadata$1, "__esModule", { value: true });
	metadata$1.contentVocabulary = metadata$1.metadataVocabulary = void 0;
	metadata$1.metadataVocabulary = [
	    "title",
	    "description",
	    "default",
	    "deprecated",
	    "readOnly",
	    "writeOnly",
	    "examples",
	];
	metadata$1.contentVocabulary = [
	    "contentMediaType",
	    "contentEncoding",
	    "contentSchema",
	];
	return metadata$1;
}

var hasRequiredDraft7$1;

function requireDraft7$1 () {
	if (hasRequiredDraft7$1) return draft7$1;
	hasRequiredDraft7$1 = 1;
	Object.defineProperty(draft7$1, "__esModule", { value: true });
	const core_1 = requireCore$3();
	const validation_1 = requireValidation$2();
	const applicator_1 = requireApplicator$1();
	const format_1 = requireFormat$2();
	const metadata_1 = requireMetadata$1();
	const draft7Vocabularies = [
	    core_1.default,
	    validation_1.default,
	    (0, applicator_1.default)(),
	    format_1.default,
	    metadata_1.metadataVocabulary,
	    metadata_1.contentVocabulary,
	];
	draft7$1.default = draft7Vocabularies;
	return draft7$1;
}

var discriminator$1 = {};

var types$7 = {};

var hasRequiredTypes$3;

function requireTypes$3 () {
	if (hasRequiredTypes$3) return types$7;
	hasRequiredTypes$3 = 1;
	Object.defineProperty(types$7, "__esModule", { value: true });
	types$7.DiscrError = void 0;
	var DiscrError;
	(function (DiscrError) {
	    DiscrError["Tag"] = "tag";
	    DiscrError["Mapping"] = "mapping";
	})(DiscrError || (types$7.DiscrError = DiscrError = {}));
	return types$7;
}

var hasRequiredDiscriminator$1;

function requireDiscriminator$1 () {
	if (hasRequiredDiscriminator$1) return discriminator$1;
	hasRequiredDiscriminator$1 = 1;
	Object.defineProperty(discriminator$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen$1();
	const types_1 = requireTypes$3();
	const compile_1 = requireCompile$2();
	const ref_error_1 = requireRef_error$1();
	const util_1 = requireUtil$4();
	const error = {
	    message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag
	        ? `tag "${tagName}" must be string`
	        : `value of tag "${tagName}" must be in oneOf`,
	    params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
	};
	const def = {
	    keyword: "discriminator",
	    type: "object",
	    schemaType: "object",
	    error,
	    code(cxt) {
	        const { gen, data, schema, parentSchema, it } = cxt;
	        const { oneOf } = parentSchema;
	        if (!it.opts.discriminator) {
	            throw new Error("discriminator: requires discriminator option");
	        }
	        const tagName = schema.propertyName;
	        if (typeof tagName != "string")
	            throw new Error("discriminator: requires propertyName");
	        if (schema.mapping)
	            throw new Error("discriminator: mapping is not supported");
	        if (!oneOf)
	            throw new Error("discriminator: requires oneOf keyword");
	        const valid = gen.let("valid", false);
	        const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);
	        gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
	        cxt.ok(valid);
	        function validateMapping() {
	            const mapping = getMapping();
	            gen.if(false);
	            for (const tagValue in mapping) {
	                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
	                gen.assign(valid, applyTagSchema(mapping[tagValue]));
	            }
	            gen.else();
	            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
	            gen.endIf();
	        }
	        function applyTagSchema(schemaProp) {
	            const _valid = gen.name("valid");
	            const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
	            cxt.mergeEvaluated(schCxt, codegen_1.Name);
	            return _valid;
	        }
	        function getMapping() {
	            var _a;
	            const oneOfMapping = {};
	            const topRequired = hasRequired(parentSchema);
	            let tagRequired = true;
	            for (let i = 0; i < oneOf.length; i++) {
	                let sch = oneOf[i];
	                if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
	                    const ref = sch.$ref;
	                    sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
	                    if (sch instanceof compile_1.SchemaEnv)
	                        sch = sch.schema;
	                    if (sch === undefined)
	                        throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
	                }
	                const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
	                if (typeof propSch != "object") {
	                    throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
	                }
	                tagRequired = tagRequired && (topRequired || hasRequired(sch));
	                addMappings(propSch, i);
	            }
	            if (!tagRequired)
	                throw new Error(`discriminator: "${tagName}" must be required`);
	            return oneOfMapping;
	            function hasRequired({ required }) {
	                return Array.isArray(required) && required.includes(tagName);
	            }
	            function addMappings(sch, i) {
	                if (sch.const) {
	                    addMapping(sch.const, i);
	                }
	                else if (sch.enum) {
	                    for (const tagValue of sch.enum) {
	                        addMapping(tagValue, i);
	                    }
	                }
	                else {
	                    throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
	                }
	            }
	            function addMapping(tagValue, i) {
	                if (typeof tagValue != "string" || tagValue in oneOfMapping) {
	                    throw new Error(`discriminator: "${tagName}" values must be unique strings`);
	                }
	                oneOfMapping[tagValue] = i;
	            }
	        }
	    },
	};
	discriminator$1.default = def;
	return discriminator$1;
}

var $schema$1 = "http://json-schema.org/draft-07/schema#";
var $id$2 = "http://json-schema.org/draft-07/schema#";
var title$1 = "Core schema meta-schema";
var definitions$1 = {
	schemaArray: {
		type: "array",
		minItems: 1,
		items: {
			$ref: "#"
		}
	},
	nonNegativeInteger: {
		type: "integer",
		minimum: 0
	},
	nonNegativeIntegerDefault0: {
		allOf: [
			{
				$ref: "#/definitions/nonNegativeInteger"
			},
			{
				"default": 0
			}
		]
	},
	simpleTypes: {
		"enum": [
			"array",
			"boolean",
			"integer",
			"null",
			"number",
			"object",
			"string"
		]
	},
	stringArray: {
		type: "array",
		items: {
			type: "string"
		},
		uniqueItems: true,
		"default": [
		]
	}
};
var type$2 = [
	"object",
	"boolean"
];
var properties$3 = {
	$id: {
		type: "string",
		format: "uri-reference"
	},
	$schema: {
		type: "string",
		format: "uri"
	},
	$ref: {
		type: "string",
		format: "uri-reference"
	},
	$comment: {
		type: "string"
	},
	title: {
		type: "string"
	},
	description: {
		type: "string"
	},
	"default": true,
	readOnly: {
		type: "boolean",
		"default": false
	},
	examples: {
		type: "array",
		items: true
	},
	multipleOf: {
		type: "number",
		exclusiveMinimum: 0
	},
	maximum: {
		type: "number"
	},
	exclusiveMaximum: {
		type: "number"
	},
	minimum: {
		type: "number"
	},
	exclusiveMinimum: {
		type: "number"
	},
	maxLength: {
		$ref: "#/definitions/nonNegativeInteger"
	},
	minLength: {
		$ref: "#/definitions/nonNegativeIntegerDefault0"
	},
	pattern: {
		type: "string",
		format: "regex"
	},
	additionalItems: {
		$ref: "#"
	},
	items: {
		anyOf: [
			{
				$ref: "#"
			},
			{
				$ref: "#/definitions/schemaArray"
			}
		],
		"default": true
	},
	maxItems: {
		$ref: "#/definitions/nonNegativeInteger"
	},
	minItems: {
		$ref: "#/definitions/nonNegativeIntegerDefault0"
	},
	uniqueItems: {
		type: "boolean",
		"default": false
	},
	contains: {
		$ref: "#"
	},
	maxProperties: {
		$ref: "#/definitions/nonNegativeInteger"
	},
	minProperties: {
		$ref: "#/definitions/nonNegativeIntegerDefault0"
	},
	required: {
		$ref: "#/definitions/stringArray"
	},
	additionalProperties: {
		$ref: "#"
	},
	definitions: {
		type: "object",
		additionalProperties: {
			$ref: "#"
		},
		"default": {
		}
	},
	properties: {
		type: "object",
		additionalProperties: {
			$ref: "#"
		},
		"default": {
		}
	},
	patternProperties: {
		type: "object",
		additionalProperties: {
			$ref: "#"
		},
		propertyNames: {
			format: "regex"
		},
		"default": {
		}
	},
	dependencies: {
		type: "object",
		additionalProperties: {
			anyOf: [
				{
					$ref: "#"
				},
				{
					$ref: "#/definitions/stringArray"
				}
			]
		}
	},
	propertyNames: {
		$ref: "#"
	},
	"const": true,
	"enum": {
		type: "array",
		items: true,
		minItems: 1,
		uniqueItems: true
	},
	type: {
		anyOf: [
			{
				$ref: "#/definitions/simpleTypes"
			},
			{
				type: "array",
				items: {
					$ref: "#/definitions/simpleTypes"
				},
				minItems: 1,
				uniqueItems: true
			}
		]
	},
	format: {
		type: "string"
	},
	contentMediaType: {
		type: "string"
	},
	contentEncoding: {
		type: "string"
	},
	"if": {
		$ref: "#"
	},
	then: {
		$ref: "#"
	},
	"else": {
		$ref: "#"
	},
	allOf: {
		$ref: "#/definitions/schemaArray"
	},
	anyOf: {
		$ref: "#/definitions/schemaArray"
	},
	oneOf: {
		$ref: "#/definitions/schemaArray"
	},
	not: {
		$ref: "#"
	}
};
var require$$3$2 = {
	$schema: $schema$1,
	$id: $id$2,
	title: title$1,
	definitions: definitions$1,
	type: type$2,
	properties: properties$3,
	"default": true
};

var hasRequiredAjv$1;

function requireAjv$1 () {
	if (hasRequiredAjv$1) return ajv$1.exports;
	hasRequiredAjv$1 = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.MissingRefError = exports$1.ValidationError = exports$1.CodeGen = exports$1.Name = exports$1.nil = exports$1.stringify = exports$1.str = exports$1._ = exports$1.KeywordCxt = exports$1.Ajv = void 0;
		const core_1 = requireCore$4();
		const draft7_1 = requireDraft7$1();
		const discriminator_1 = requireDiscriminator$1();
		const draft7MetaSchema = require$$3$2;
		const META_SUPPORT_DATA = ["/properties"];
		const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
		class Ajv extends core_1.default {
		    _addVocabularies() {
		        super._addVocabularies();
		        draft7_1.default.forEach((v) => this.addVocabulary(v));
		        if (this.opts.discriminator)
		            this.addKeyword(discriminator_1.default);
		    }
		    _addDefaultMetaSchema() {
		        super._addDefaultMetaSchema();
		        if (!this.opts.meta)
		            return;
		        const metaSchema = this.opts.$data
		            ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
		            : draft7MetaSchema;
		        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
		        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
		    }
		    defaultMeta() {
		        return (this.opts.defaultMeta =
		            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
		    }
		}
		exports$1.Ajv = Ajv;
		module.exports = exports$1 = Ajv;
		module.exports.Ajv = Ajv;
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.default = Ajv;
		var validate_1 = requireValidate$1();
		Object.defineProperty(exports$1, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
		var codegen_1 = requireCodegen$1();
		Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return codegen_1._; } });
		Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return codegen_1.str; } });
		Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
		Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
		Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
		Object.defineProperty(exports$1, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
		var validation_error_1 = requireValidation_error$1();
		Object.defineProperty(exports$1, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
		var ref_error_1 = requireRef_error$1();
		Object.defineProperty(exports$1, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); 
	} (ajv$1, ajv$1.exports));
	return ajv$1.exports;
}

var ajvExports = requireAjv$1();
var Ajv = /*@__PURE__*/getDefaultExportFromCjs(ajvExports);

var dist$c = {exports: {}};

var formats = {};

var hasRequiredFormats;

function requireFormats () {
	if (hasRequiredFormats) return formats;
	hasRequiredFormats = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.formatNames = exports$1.fastFormats = exports$1.fullFormats = void 0;
		function fmtDef(validate, compare) {
		    return { validate, compare };
		}
		exports$1.fullFormats = {
		    date: fmtDef(date, compareDate),
		    time: fmtDef(getTime(true), compareTime),
		    "date-time": fmtDef(getDateTime(true), compareDateTime),
		    "iso-time": fmtDef(getTime(), compareIsoTime),
		    "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),
		    duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
		    uri,
		    "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
		    "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
		    url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
		    email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
		    hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
		    ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,
		    ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,
		    regex,
		    uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
		    "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
		    "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
		    "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
		    byte,
		    int32: { type: "number", validate: validateInt32 },
		    int64: { type: "number", validate: validateInt64 },
		    float: { type: "number", validate: validateNumber },
		    double: { type: "number", validate: validateNumber },
		    password: true,
		    binary: true,
		};
		exports$1.fastFormats = {
		    ...exports$1.fullFormats,
		    date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
		    time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime),
		    "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),
		    "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime),
		    "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime),
		    uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
		    "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
		    email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
		};
		exports$1.formatNames = Object.keys(exports$1.fullFormats);
		function isLeapYear(year) {
		    return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
		}
		const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
		const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
		function date(str) {
		    const matches = DATE.exec(str);
		    if (!matches)
		        return false;
		    const year = +matches[1];
		    const month = +matches[2];
		    const day = +matches[3];
		    return (month >= 1 &&
		        month <= 12 &&
		        day >= 1 &&
		        day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]));
		}
		function compareDate(d1, d2) {
		    if (!(d1 && d2))
		        return undefined;
		    if (d1 > d2)
		        return 1;
		    if (d1 < d2)
		        return -1;
		    return 0;
		}
		const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
		function getTime(strictTimeZone) {
		    return function time(str) {
		        const matches = TIME.exec(str);
		        if (!matches)
		            return false;
		        const hr = +matches[1];
		        const min = +matches[2];
		        const sec = +matches[3];
		        const tz = matches[4];
		        const tzSign = matches[5] === "-" ? -1 : 1;
		        const tzH = +(matches[6] || 0);
		        const tzM = +(matches[7] || 0);
		        if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz))
		            return false;
		        if (hr <= 23 && min <= 59 && sec < 60)
		            return true;
		        const utcMin = min - tzM * tzSign;
		        const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);
		        return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
		    };
		}
		function compareTime(s1, s2) {
		    if (!(s1 && s2))
		        return undefined;
		    const t1 = new Date("2020-01-01T" + s1).valueOf();
		    const t2 = new Date("2020-01-01T" + s2).valueOf();
		    if (!(t1 && t2))
		        return undefined;
		    return t1 - t2;
		}
		function compareIsoTime(t1, t2) {
		    if (!(t1 && t2))
		        return undefined;
		    const a1 = TIME.exec(t1);
		    const a2 = TIME.exec(t2);
		    if (!(a1 && a2))
		        return undefined;
		    t1 = a1[1] + a1[2] + a1[3];
		    t2 = a2[1] + a2[2] + a2[3];
		    if (t1 > t2)
		        return 1;
		    if (t1 < t2)
		        return -1;
		    return 0;
		}
		const DATE_TIME_SEPARATOR = /t|\s/i;
		function getDateTime(strictTimeZone) {
		    const time = getTime(strictTimeZone);
		    return function date_time(str) {
		        const dateTime = str.split(DATE_TIME_SEPARATOR);
		        return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]);
		    };
		}
		function compareDateTime(dt1, dt2) {
		    if (!(dt1 && dt2))
		        return undefined;
		    const d1 = new Date(dt1).valueOf();
		    const d2 = new Date(dt2).valueOf();
		    if (!(d1 && d2))
		        return undefined;
		    return d1 - d2;
		}
		function compareIsoDateTime(dt1, dt2) {
		    if (!(dt1 && dt2))
		        return undefined;
		    const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
		    const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);
		    const res = compareDate(d1, d2);
		    if (res === undefined)
		        return undefined;
		    return res || compareTime(t1, t2);
		}
		const NOT_URI_FRAGMENT = /\/|:/;
		const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
		function uri(str) {
		    return NOT_URI_FRAGMENT.test(str) && URI.test(str);
		}
		const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
		function byte(str) {
		    BYTE.lastIndex = 0;
		    return BYTE.test(str);
		}
		const MIN_INT32 = -2147483648;
		const MAX_INT32 = 2 ** 31 - 1;
		function validateInt32(value) {
		    return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
		}
		function validateInt64(value) {
		    return Number.isInteger(value);
		}
		function validateNumber() {
		    return true;
		}
		const Z_ANCHOR = /[^\\]\\Z/;
		function regex(str) {
		    if (Z_ANCHOR.test(str))
		        return false;
		    try {
		        new RegExp(str);
		        return true;
		    }
		    catch (e) {
		        return false;
		    }
		} 
	} (formats));
	return formats;
}

var limit = {};

var ajv = {exports: {}};

var core$3 = {};

var validate = {};

var boolSchema = {};

var errors$1 = {};

var codegen = {};

var code$2 = {};

var hasRequiredCode$2;

function requireCode$2 () {
	if (hasRequiredCode$2) return code$2;
	hasRequiredCode$2 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.regexpCode = exports$1.getEsmExportName = exports$1.getProperty = exports$1.safeStringify = exports$1.stringify = exports$1.strConcat = exports$1.addCodeArg = exports$1.str = exports$1._ = exports$1.nil = exports$1._Code = exports$1.Name = exports$1.IDENTIFIER = exports$1._CodeOrName = void 0;
		class _CodeOrName {
		}
		exports$1._CodeOrName = _CodeOrName;
		exports$1.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
		class Name extends _CodeOrName {
		    constructor(s) {
		        super();
		        if (!exports$1.IDENTIFIER.test(s))
		            throw new Error("CodeGen: name must be a valid identifier");
		        this.str = s;
		    }
		    toString() {
		        return this.str;
		    }
		    emptyStr() {
		        return false;
		    }
		    get names() {
		        return { [this.str]: 1 };
		    }
		}
		exports$1.Name = Name;
		class _Code extends _CodeOrName {
		    constructor(code) {
		        super();
		        this._items = typeof code === "string" ? [code] : code;
		    }
		    toString() {
		        return this.str;
		    }
		    emptyStr() {
		        if (this._items.length > 1)
		            return false;
		        const item = this._items[0];
		        return item === "" || item === '""';
		    }
		    get str() {
		        var _a;
		        return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
		    }
		    get names() {
		        var _a;
		        return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
		            if (c instanceof Name)
		                names[c.str] = (names[c.str] || 0) + 1;
		            return names;
		        }, {})));
		    }
		}
		exports$1._Code = _Code;
		exports$1.nil = new _Code("");
		function _(strs, ...args) {
		    const code = [strs[0]];
		    let i = 0;
		    while (i < args.length) {
		        addCodeArg(code, args[i]);
		        code.push(strs[++i]);
		    }
		    return new _Code(code);
		}
		exports$1._ = _;
		const plus = new _Code("+");
		function str(strs, ...args) {
		    const expr = [safeStringify(strs[0])];
		    let i = 0;
		    while (i < args.length) {
		        expr.push(plus);
		        addCodeArg(expr, args[i]);
		        expr.push(plus, safeStringify(strs[++i]));
		    }
		    optimize(expr);
		    return new _Code(expr);
		}
		exports$1.str = str;
		function addCodeArg(code, arg) {
		    if (arg instanceof _Code)
		        code.push(...arg._items);
		    else if (arg instanceof Name)
		        code.push(arg);
		    else
		        code.push(interpolate(arg));
		}
		exports$1.addCodeArg = addCodeArg;
		function optimize(expr) {
		    let i = 1;
		    while (i < expr.length - 1) {
		        if (expr[i] === plus) {
		            const res = mergeExprItems(expr[i - 1], expr[i + 1]);
		            if (res !== undefined) {
		                expr.splice(i - 1, 3, res);
		                continue;
		            }
		            expr[i++] = "+";
		        }
		        i++;
		    }
		}
		function mergeExprItems(a, b) {
		    if (b === '""')
		        return a;
		    if (a === '""')
		        return b;
		    if (typeof a == "string") {
		        if (b instanceof Name || a[a.length - 1] !== '"')
		            return;
		        if (typeof b != "string")
		            return `${a.slice(0, -1)}${b}"`;
		        if (b[0] === '"')
		            return a.slice(0, -1) + b.slice(1);
		        return;
		    }
		    if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
		        return `"${a}${b.slice(1)}`;
		    return;
		}
		function strConcat(c1, c2) {
		    return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
		}
		exports$1.strConcat = strConcat;
		function interpolate(x) {
		    return typeof x == "number" || typeof x == "boolean" || x === null
		        ? x
		        : safeStringify(Array.isArray(x) ? x.join(",") : x);
		}
		function stringify(x) {
		    return new _Code(safeStringify(x));
		}
		exports$1.stringify = stringify;
		function safeStringify(x) {
		    return JSON.stringify(x)
		        .replace(/\u2028/g, "\\u2028")
		        .replace(/\u2029/g, "\\u2029");
		}
		exports$1.safeStringify = safeStringify;
		function getProperty(key) {
		    return typeof key == "string" && exports$1.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
		}
		exports$1.getProperty = getProperty;
		function getEsmExportName(key) {
		    if (typeof key == "string" && exports$1.IDENTIFIER.test(key)) {
		        return new _Code(`${key}`);
		    }
		    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
		}
		exports$1.getEsmExportName = getEsmExportName;
		function regexpCode(rx) {
		    return new _Code(rx.toString());
		}
		exports$1.regexpCode = regexpCode; 
	} (code$2));
	return code$2;
}

var scope$1 = {};

var hasRequiredScope$1;

function requireScope$1 () {
	if (hasRequiredScope$1) return scope$1;
	hasRequiredScope$1 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.ValueScope = exports$1.ValueScopeName = exports$1.Scope = exports$1.varKinds = exports$1.UsedValueState = void 0;
		const code_1 = requireCode$2();
		class ValueError extends Error {
		    constructor(name) {
		        super(`CodeGen: "code" for ${name} not defined`);
		        this.value = name.value;
		    }
		}
		var UsedValueState;
		(function (UsedValueState) {
		    UsedValueState[UsedValueState["Started"] = 0] = "Started";
		    UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
		})(UsedValueState || (exports$1.UsedValueState = UsedValueState = {}));
		exports$1.varKinds = {
		    const: new code_1.Name("const"),
		    let: new code_1.Name("let"),
		    var: new code_1.Name("var"),
		};
		class Scope {
		    constructor({ prefixes, parent } = {}) {
		        this._names = {};
		        this._prefixes = prefixes;
		        this._parent = parent;
		    }
		    toName(nameOrPrefix) {
		        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
		    }
		    name(prefix) {
		        return new code_1.Name(this._newName(prefix));
		    }
		    _newName(prefix) {
		        const ng = this._names[prefix] || this._nameGroup(prefix);
		        return `${prefix}${ng.index++}`;
		    }
		    _nameGroup(prefix) {
		        var _a, _b;
		        if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {
		            throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
		        }
		        return (this._names[prefix] = { prefix, index: 0 });
		    }
		}
		exports$1.Scope = Scope;
		class ValueScopeName extends code_1.Name {
		    constructor(prefix, nameStr) {
		        super(nameStr);
		        this.prefix = prefix;
		    }
		    setValue(value, { property, itemIndex }) {
		        this.value = value;
		        this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;
		    }
		}
		exports$1.ValueScopeName = ValueScopeName;
		const line = (0, code_1._) `\n`;
		class ValueScope extends Scope {
		    constructor(opts) {
		        super(opts);
		        this._values = {};
		        this._scope = opts.scope;
		        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
		    }
		    get() {
		        return this._scope;
		    }
		    name(prefix) {
		        return new ValueScopeName(prefix, this._newName(prefix));
		    }
		    value(nameOrPrefix, value) {
		        var _a;
		        if (value.ref === undefined)
		            throw new Error("CodeGen: ref must be passed in value");
		        const name = this.toName(nameOrPrefix);
		        const { prefix } = name;
		        const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
		        let vs = this._values[prefix];
		        if (vs) {
		            const _name = vs.get(valueKey);
		            if (_name)
		                return _name;
		        }
		        else {
		            vs = this._values[prefix] = new Map();
		        }
		        vs.set(valueKey, name);
		        const s = this._scope[prefix] || (this._scope[prefix] = []);
		        const itemIndex = s.length;
		        s[itemIndex] = value.ref;
		        name.setValue(value, { property: prefix, itemIndex });
		        return name;
		    }
		    getValue(prefix, keyOrRef) {
		        const vs = this._values[prefix];
		        if (!vs)
		            return;
		        return vs.get(keyOrRef);
		    }
		    scopeRefs(scopeName, values = this._values) {
		        return this._reduceValues(values, (name) => {
		            if (name.scopePath === undefined)
		                throw new Error(`CodeGen: name "${name}" has no value`);
		            return (0, code_1._) `${scopeName}${name.scopePath}`;
		        });
		    }
		    scopeCode(values = this._values, usedValues, getCode) {
		        return this._reduceValues(values, (name) => {
		            if (name.value === undefined)
		                throw new Error(`CodeGen: name "${name}" has no value`);
		            return name.value.code;
		        }, usedValues, getCode);
		    }
		    _reduceValues(values, valueCode, usedValues = {}, getCode) {
		        let code = code_1.nil;
		        for (const prefix in values) {
		            const vs = values[prefix];
		            if (!vs)
		                continue;
		            const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());
		            vs.forEach((name) => {
		                if (nameSet.has(name))
		                    return;
		                nameSet.set(name, UsedValueState.Started);
		                let c = valueCode(name);
		                if (c) {
		                    const def = this.opts.es5 ? exports$1.varKinds.var : exports$1.varKinds.const;
		                    code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;
		                }
		                else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {
		                    code = (0, code_1._) `${code}${c}${this.opts._n}`;
		                }
		                else {
		                    throw new ValueError(name);
		                }
		                nameSet.set(name, UsedValueState.Completed);
		            });
		        }
		        return code;
		    }
		}
		exports$1.ValueScope = ValueScope; 
	} (scope$1));
	return scope$1;
}

var hasRequiredCodegen;

function requireCodegen () {
	if (hasRequiredCodegen) return codegen;
	hasRequiredCodegen = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.or = exports$1.and = exports$1.not = exports$1.CodeGen = exports$1.operators = exports$1.varKinds = exports$1.ValueScopeName = exports$1.ValueScope = exports$1.Scope = exports$1.Name = exports$1.regexpCode = exports$1.stringify = exports$1.getProperty = exports$1.nil = exports$1.strConcat = exports$1.str = exports$1._ = void 0;
		const code_1 = requireCode$2();
		const scope_1 = requireScope$1();
		var code_2 = requireCode$2();
		Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return code_2._; } });
		Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return code_2.str; } });
		Object.defineProperty(exports$1, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } });
		Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return code_2.nil; } });
		Object.defineProperty(exports$1, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } });
		Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return code_2.stringify; } });
		Object.defineProperty(exports$1, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } });
		Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return code_2.Name; } });
		var scope_2 = requireScope$1();
		Object.defineProperty(exports$1, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } });
		Object.defineProperty(exports$1, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } });
		Object.defineProperty(exports$1, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });
		Object.defineProperty(exports$1, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } });
		exports$1.operators = {
		    GT: new code_1._Code(">"),
		    GTE: new code_1._Code(">="),
		    LT: new code_1._Code("<"),
		    LTE: new code_1._Code("<="),
		    EQ: new code_1._Code("==="),
		    NEQ: new code_1._Code("!=="),
		    NOT: new code_1._Code("!"),
		    OR: new code_1._Code("||"),
		    AND: new code_1._Code("&&"),
		    ADD: new code_1._Code("+"),
		};
		class Node {
		    optimizeNodes() {
		        return this;
		    }
		    optimizeNames(_names, _constants) {
		        return this;
		    }
		}
		class Def extends Node {
		    constructor(varKind, name, rhs) {
		        super();
		        this.varKind = varKind;
		        this.name = name;
		        this.rhs = rhs;
		    }
		    render({ es5, _n }) {
		        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
		        const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
		        return `${varKind} ${this.name}${rhs};` + _n;
		    }
		    optimizeNames(names, constants) {
		        if (!names[this.name.str])
		            return;
		        if (this.rhs)
		            this.rhs = optimizeExpr(this.rhs, names, constants);
		        return this;
		    }
		    get names() {
		        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
		    }
		}
		class Assign extends Node {
		    constructor(lhs, rhs, sideEffects) {
		        super();
		        this.lhs = lhs;
		        this.rhs = rhs;
		        this.sideEffects = sideEffects;
		    }
		    render({ _n }) {
		        return `${this.lhs} = ${this.rhs};` + _n;
		    }
		    optimizeNames(names, constants) {
		        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
		            return;
		        this.rhs = optimizeExpr(this.rhs, names, constants);
		        return this;
		    }
		    get names() {
		        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
		        return addExprNames(names, this.rhs);
		    }
		}
		class AssignOp extends Assign {
		    constructor(lhs, op, rhs, sideEffects) {
		        super(lhs, rhs, sideEffects);
		        this.op = op;
		    }
		    render({ _n }) {
		        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
		    }
		}
		class Label extends Node {
		    constructor(label) {
		        super();
		        this.label = label;
		        this.names = {};
		    }
		    render({ _n }) {
		        return `${this.label}:` + _n;
		    }
		}
		class Break extends Node {
		    constructor(label) {
		        super();
		        this.label = label;
		        this.names = {};
		    }
		    render({ _n }) {
		        const label = this.label ? ` ${this.label}` : "";
		        return `break${label};` + _n;
		    }
		}
		class Throw extends Node {
		    constructor(error) {
		        super();
		        this.error = error;
		    }
		    render({ _n }) {
		        return `throw ${this.error};` + _n;
		    }
		    get names() {
		        return this.error.names;
		    }
		}
		class AnyCode extends Node {
		    constructor(code) {
		        super();
		        this.code = code;
		    }
		    render({ _n }) {
		        return `${this.code};` + _n;
		    }
		    optimizeNodes() {
		        return `${this.code}` ? this : undefined;
		    }
		    optimizeNames(names, constants) {
		        this.code = optimizeExpr(this.code, names, constants);
		        return this;
		    }
		    get names() {
		        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
		    }
		}
		class ParentNode extends Node {
		    constructor(nodes = []) {
		        super();
		        this.nodes = nodes;
		    }
		    render(opts) {
		        return this.nodes.reduce((code, n) => code + n.render(opts), "");
		    }
		    optimizeNodes() {
		        const { nodes } = this;
		        let i = nodes.length;
		        while (i--) {
		            const n = nodes[i].optimizeNodes();
		            if (Array.isArray(n))
		                nodes.splice(i, 1, ...n);
		            else if (n)
		                nodes[i] = n;
		            else
		                nodes.splice(i, 1);
		        }
		        return nodes.length > 0 ? this : undefined;
		    }
		    optimizeNames(names, constants) {
		        const { nodes } = this;
		        let i = nodes.length;
		        while (i--) {
		            const n = nodes[i];
		            if (n.optimizeNames(names, constants))
		                continue;
		            subtractNames(names, n.names);
		            nodes.splice(i, 1);
		        }
		        return nodes.length > 0 ? this : undefined;
		    }
		    get names() {
		        return this.nodes.reduce((names, n) => addNames(names, n.names), {});
		    }
		}
		class BlockNode extends ParentNode {
		    render(opts) {
		        return "{" + opts._n + super.render(opts) + "}" + opts._n;
		    }
		}
		class Root extends ParentNode {
		}
		class Else extends BlockNode {
		}
		Else.kind = "else";
		class If extends BlockNode {
		    constructor(condition, nodes) {
		        super(nodes);
		        this.condition = condition;
		    }
		    render(opts) {
		        let code = `if(${this.condition})` + super.render(opts);
		        if (this.else)
		            code += "else " + this.else.render(opts);
		        return code;
		    }
		    optimizeNodes() {
		        super.optimizeNodes();
		        const cond = this.condition;
		        if (cond === true)
		            return this.nodes;
		        let e = this.else;
		        if (e) {
		            const ns = e.optimizeNodes();
		            e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
		        }
		        if (e) {
		            if (cond === false)
		                return e instanceof If ? e : e.nodes;
		            if (this.nodes.length)
		                return this;
		            return new If(not(cond), e instanceof If ? [e] : e.nodes);
		        }
		        if (cond === false || !this.nodes.length)
		            return undefined;
		        return this;
		    }
		    optimizeNames(names, constants) {
		        var _a;
		        this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
		        if (!(super.optimizeNames(names, constants) || this.else))
		            return;
		        this.condition = optimizeExpr(this.condition, names, constants);
		        return this;
		    }
		    get names() {
		        const names = super.names;
		        addExprNames(names, this.condition);
		        if (this.else)
		            addNames(names, this.else.names);
		        return names;
		    }
		}
		If.kind = "if";
		class For extends BlockNode {
		}
		For.kind = "for";
		class ForLoop extends For {
		    constructor(iteration) {
		        super();
		        this.iteration = iteration;
		    }
		    render(opts) {
		        return `for(${this.iteration})` + super.render(opts);
		    }
		    optimizeNames(names, constants) {
		        if (!super.optimizeNames(names, constants))
		            return;
		        this.iteration = optimizeExpr(this.iteration, names, constants);
		        return this;
		    }
		    get names() {
		        return addNames(super.names, this.iteration.names);
		    }
		}
		class ForRange extends For {
		    constructor(varKind, name, from, to) {
		        super();
		        this.varKind = varKind;
		        this.name = name;
		        this.from = from;
		        this.to = to;
		    }
		    render(opts) {
		        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
		        const { name, from, to } = this;
		        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
		    }
		    get names() {
		        const names = addExprNames(super.names, this.from);
		        return addExprNames(names, this.to);
		    }
		}
		class ForIter extends For {
		    constructor(loop, varKind, name, iterable) {
		        super();
		        this.loop = loop;
		        this.varKind = varKind;
		        this.name = name;
		        this.iterable = iterable;
		    }
		    render(opts) {
		        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
		    }
		    optimizeNames(names, constants) {
		        if (!super.optimizeNames(names, constants))
		            return;
		        this.iterable = optimizeExpr(this.iterable, names, constants);
		        return this;
		    }
		    get names() {
		        return addNames(super.names, this.iterable.names);
		    }
		}
		class Func extends BlockNode {
		    constructor(name, args, async) {
		        super();
		        this.name = name;
		        this.args = args;
		        this.async = async;
		    }
		    render(opts) {
		        const _async = this.async ? "async " : "";
		        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
		    }
		}
		Func.kind = "func";
		class Return extends ParentNode {
		    render(opts) {
		        return "return " + super.render(opts);
		    }
		}
		Return.kind = "return";
		class Try extends BlockNode {
		    render(opts) {
		        let code = "try" + super.render(opts);
		        if (this.catch)
		            code += this.catch.render(opts);
		        if (this.finally)
		            code += this.finally.render(opts);
		        return code;
		    }
		    optimizeNodes() {
		        var _a, _b;
		        super.optimizeNodes();
		        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
		        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
		        return this;
		    }
		    optimizeNames(names, constants) {
		        var _a, _b;
		        super.optimizeNames(names, constants);
		        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
		        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
		        return this;
		    }
		    get names() {
		        const names = super.names;
		        if (this.catch)
		            addNames(names, this.catch.names);
		        if (this.finally)
		            addNames(names, this.finally.names);
		        return names;
		    }
		}
		class Catch extends BlockNode {
		    constructor(error) {
		        super();
		        this.error = error;
		    }
		    render(opts) {
		        return `catch(${this.error})` + super.render(opts);
		    }
		}
		Catch.kind = "catch";
		class Finally extends BlockNode {
		    render(opts) {
		        return "finally" + super.render(opts);
		    }
		}
		Finally.kind = "finally";
		class CodeGen {
		    constructor(extScope, opts = {}) {
		        this._values = {};
		        this._blockStarts = [];
		        this._constants = {};
		        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
		        this._extScope = extScope;
		        this._scope = new scope_1.Scope({ parent: extScope });
		        this._nodes = [new Root()];
		    }
		    toString() {
		        return this._root.render(this.opts);
		    }
		    name(prefix) {
		        return this._scope.name(prefix);
		    }
		    scopeName(prefix) {
		        return this._extScope.name(prefix);
		    }
		    scopeValue(prefixOrName, value) {
		        const name = this._extScope.value(prefixOrName, value);
		        const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
		        vs.add(name);
		        return name;
		    }
		    getScopeValue(prefix, keyOrRef) {
		        return this._extScope.getValue(prefix, keyOrRef);
		    }
		    scopeRefs(scopeName) {
		        return this._extScope.scopeRefs(scopeName, this._values);
		    }
		    scopeCode() {
		        return this._extScope.scopeCode(this._values);
		    }
		    _def(varKind, nameOrPrefix, rhs, constant) {
		        const name = this._scope.toName(nameOrPrefix);
		        if (rhs !== undefined && constant)
		            this._constants[name.str] = rhs;
		        this._leafNode(new Def(varKind, name, rhs));
		        return name;
		    }
		    const(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
		    }
		    let(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
		    }
		    var(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
		    }
		    assign(lhs, rhs, sideEffects) {
		        return this._leafNode(new Assign(lhs, rhs, sideEffects));
		    }
		    add(lhs, rhs) {
		        return this._leafNode(new AssignOp(lhs, exports$1.operators.ADD, rhs));
		    }
		    code(c) {
		        if (typeof c == "function")
		            c();
		        else if (c !== code_1.nil)
		            this._leafNode(new AnyCode(c));
		        return this;
		    }
		    object(...keyValues) {
		        const code = ["{"];
		        for (const [key, value] of keyValues) {
		            if (code.length > 1)
		                code.push(",");
		            code.push(key);
		            if (key !== value || this.opts.es5) {
		                code.push(":");
		                (0, code_1.addCodeArg)(code, value);
		            }
		        }
		        code.push("}");
		        return new code_1._Code(code);
		    }
		    if(condition, thenBody, elseBody) {
		        this._blockNode(new If(condition));
		        if (thenBody && elseBody) {
		            this.code(thenBody).else().code(elseBody).endIf();
		        }
		        else if (thenBody) {
		            this.code(thenBody).endIf();
		        }
		        else if (elseBody) {
		            throw new Error('CodeGen: "else" body without "then" body');
		        }
		        return this;
		    }
		    elseIf(condition) {
		        return this._elseNode(new If(condition));
		    }
		    else() {
		        return this._elseNode(new Else());
		    }
		    endIf() {
		        return this._endBlockNode(If, Else);
		    }
		    _for(node, forBody) {
		        this._blockNode(node);
		        if (forBody)
		            this.code(forBody).endFor();
		        return this;
		    }
		    for(iteration, forBody) {
		        return this._for(new ForLoop(iteration), forBody);
		    }
		    forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
		        const name = this._scope.toName(nameOrPrefix);
		        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
		    }
		    forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
		        const name = this._scope.toName(nameOrPrefix);
		        if (this.opts.es5) {
		            const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
		            return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => {
		                this.var(name, (0, code_1._) `${arr}[${i}]`);
		                forBody(name);
		            });
		        }
		        return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
		    }
		    forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
		        if (this.opts.ownProperties) {
		            return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);
		        }
		        const name = this._scope.toName(nameOrPrefix);
		        return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
		    }
		    endFor() {
		        return this._endBlockNode(For);
		    }
		    label(label) {
		        return this._leafNode(new Label(label));
		    }
		    break(label) {
		        return this._leafNode(new Break(label));
		    }
		    return(value) {
		        const node = new Return();
		        this._blockNode(node);
		        this.code(value);
		        if (node.nodes.length !== 1)
		            throw new Error('CodeGen: "return" should have one node');
		        return this._endBlockNode(Return);
		    }
		    try(tryBody, catchCode, finallyCode) {
		        if (!catchCode && !finallyCode)
		            throw new Error('CodeGen: "try" without "catch" and "finally"');
		        const node = new Try();
		        this._blockNode(node);
		        this.code(tryBody);
		        if (catchCode) {
		            const error = this.name("e");
		            this._currNode = node.catch = new Catch(error);
		            catchCode(error);
		        }
		        if (finallyCode) {
		            this._currNode = node.finally = new Finally();
		            this.code(finallyCode);
		        }
		        return this._endBlockNode(Catch, Finally);
		    }
		    throw(error) {
		        return this._leafNode(new Throw(error));
		    }
		    block(body, nodeCount) {
		        this._blockStarts.push(this._nodes.length);
		        if (body)
		            this.code(body).endBlock(nodeCount);
		        return this;
		    }
		    endBlock(nodeCount) {
		        const len = this._blockStarts.pop();
		        if (len === undefined)
		            throw new Error("CodeGen: not in self-balancing block");
		        const toClose = this._nodes.length - len;
		        if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
		            throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
		        }
		        this._nodes.length = len;
		        return this;
		    }
		    func(name, args = code_1.nil, async, funcBody) {
		        this._blockNode(new Func(name, args, async));
		        if (funcBody)
		            this.code(funcBody).endFunc();
		        return this;
		    }
		    endFunc() {
		        return this._endBlockNode(Func);
		    }
		    optimize(n = 1) {
		        while (n-- > 0) {
		            this._root.optimizeNodes();
		            this._root.optimizeNames(this._root.names, this._constants);
		        }
		    }
		    _leafNode(node) {
		        this._currNode.nodes.push(node);
		        return this;
		    }
		    _blockNode(node) {
		        this._currNode.nodes.push(node);
		        this._nodes.push(node);
		    }
		    _endBlockNode(N1, N2) {
		        const n = this._currNode;
		        if (n instanceof N1 || (N2 && n instanceof N2)) {
		            this._nodes.pop();
		            return this;
		        }
		        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
		    }
		    _elseNode(node) {
		        const n = this._currNode;
		        if (!(n instanceof If)) {
		            throw new Error('CodeGen: "else" without "if"');
		        }
		        this._currNode = n.else = node;
		        return this;
		    }
		    get _root() {
		        return this._nodes[0];
		    }
		    get _currNode() {
		        const ns = this._nodes;
		        return ns[ns.length - 1];
		    }
		    set _currNode(node) {
		        const ns = this._nodes;
		        ns[ns.length - 1] = node;
		    }
		}
		exports$1.CodeGen = CodeGen;
		function addNames(names, from) {
		    for (const n in from)
		        names[n] = (names[n] || 0) + (from[n] || 0);
		    return names;
		}
		function addExprNames(names, from) {
		    return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
		}
		function optimizeExpr(expr, names, constants) {
		    if (expr instanceof code_1.Name)
		        return replaceName(expr);
		    if (!canOptimize(expr))
		        return expr;
		    return new code_1._Code(expr._items.reduce((items, c) => {
		        if (c instanceof code_1.Name)
		            c = replaceName(c);
		        if (c instanceof code_1._Code)
		            items.push(...c._items);
		        else
		            items.push(c);
		        return items;
		    }, []));
		    function replaceName(n) {
		        const c = constants[n.str];
		        if (c === undefined || names[n.str] !== 1)
		            return n;
		        delete names[n.str];
		        return c;
		    }
		    function canOptimize(e) {
		        return (e instanceof code_1._Code &&
		            e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
		    }
		}
		function subtractNames(names, from) {
		    for (const n in from)
		        names[n] = (names[n] || 0) - (from[n] || 0);
		}
		function not(x) {
		    return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`;
		}
		exports$1.not = not;
		const andCode = mappend(exports$1.operators.AND);
		function and(...args) {
		    return args.reduce(andCode);
		}
		exports$1.and = and;
		const orCode = mappend(exports$1.operators.OR);
		function or(...args) {
		    return args.reduce(orCode);
		}
		exports$1.or = or;
		function mappend(op) {
		    return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);
		}
		function par(x) {
		    return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;
		} 
	} (codegen));
	return codegen;
}

var util$3 = {};

var hasRequiredUtil$3;

function requireUtil$3 () {
	if (hasRequiredUtil$3) return util$3;
	hasRequiredUtil$3 = 1;
	Object.defineProperty(util$3, "__esModule", { value: true });
	util$3.checkStrictMode = util$3.getErrorPath = util$3.Type = util$3.useFunc = util$3.setEvaluated = util$3.evaluatedPropsToName = util$3.mergeEvaluated = util$3.eachItem = util$3.unescapeJsonPointer = util$3.escapeJsonPointer = util$3.escapeFragment = util$3.unescapeFragment = util$3.schemaRefOrVal = util$3.schemaHasRulesButRef = util$3.schemaHasRules = util$3.checkUnknownRules = util$3.alwaysValidSchema = util$3.toHash = void 0;
	const codegen_1 = requireCodegen();
	const code_1 = requireCode$2();
	function toHash(arr) {
	    const hash = {};
	    for (const item of arr)
	        hash[item] = true;
	    return hash;
	}
	util$3.toHash = toHash;
	function alwaysValidSchema(it, schema) {
	    if (typeof schema == "boolean")
	        return schema;
	    if (Object.keys(schema).length === 0)
	        return true;
	    checkUnknownRules(it, schema);
	    return !schemaHasRules(schema, it.self.RULES.all);
	}
	util$3.alwaysValidSchema = alwaysValidSchema;
	function checkUnknownRules(it, schema = it.schema) {
	    const { opts, self } = it;
	    if (!opts.strictSchema)
	        return;
	    if (typeof schema === "boolean")
	        return;
	    const rules = self.RULES.keywords;
	    for (const key in schema) {
	        if (!rules[key])
	            checkStrictMode(it, `unknown keyword: "${key}"`);
	    }
	}
	util$3.checkUnknownRules = checkUnknownRules;
	function schemaHasRules(schema, rules) {
	    if (typeof schema == "boolean")
	        return !schema;
	    for (const key in schema)
	        if (rules[key])
	            return true;
	    return false;
	}
	util$3.schemaHasRules = schemaHasRules;
	function schemaHasRulesButRef(schema, RULES) {
	    if (typeof schema == "boolean")
	        return !schema;
	    for (const key in schema)
	        if (key !== "$ref" && RULES.all[key])
	            return true;
	    return false;
	}
	util$3.schemaHasRulesButRef = schemaHasRulesButRef;
	function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
	    if (!$data) {
	        if (typeof schema == "number" || typeof schema == "boolean")
	            return schema;
	        if (typeof schema == "string")
	            return (0, codegen_1._) `${schema}`;
	    }
	    return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
	}
	util$3.schemaRefOrVal = schemaRefOrVal;
	function unescapeFragment(str) {
	    return unescapeJsonPointer(decodeURIComponent(str));
	}
	util$3.unescapeFragment = unescapeFragment;
	function escapeFragment(str) {
	    return encodeURIComponent(escapeJsonPointer(str));
	}
	util$3.escapeFragment = escapeFragment;
	function escapeJsonPointer(str) {
	    if (typeof str == "number")
	        return `${str}`;
	    return str.replace(/~/g, "~0").replace(/\//g, "~1");
	}
	util$3.escapeJsonPointer = escapeJsonPointer;
	function unescapeJsonPointer(str) {
	    return str.replace(/~1/g, "/").replace(/~0/g, "~");
	}
	util$3.unescapeJsonPointer = unescapeJsonPointer;
	function eachItem(xs, f) {
	    if (Array.isArray(xs)) {
	        for (const x of xs)
	            f(x);
	    }
	    else {
	        f(xs);
	    }
	}
	util$3.eachItem = eachItem;
	function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {
	    return (gen, from, to, toName) => {
	        const res = to === undefined
	            ? from
	            : to instanceof codegen_1.Name
	                ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
	                : from instanceof codegen_1.Name
	                    ? (mergeToName(gen, to, from), from)
	                    : mergeValues(from, to);
	        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
	    };
	}
	util$3.mergeEvaluated = {
	    props: makeMergeEvaluated({
	        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {
	            gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`));
	        }),
	        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {
	            if (from === true) {
	                gen.assign(to, true);
	            }
	            else {
	                gen.assign(to, (0, codegen_1._) `${to} || {}`);
	                setEvaluated(gen, to, from);
	            }
	        }),
	        mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),
	        resultToName: evaluatedPropsToName,
	    }),
	    items: makeMergeEvaluated({
	        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
	        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),
	        mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
	        resultToName: (gen, items) => gen.var("items", items),
	    }),
	};
	function evaluatedPropsToName(gen, ps) {
	    if (ps === true)
	        return gen.var("props", true);
	    const props = gen.var("props", (0, codegen_1._) `{}`);
	    if (ps !== undefined)
	        setEvaluated(gen, props, ps);
	    return props;
	}
	util$3.evaluatedPropsToName = evaluatedPropsToName;
	function setEvaluated(gen, props, ps) {
	    Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));
	}
	util$3.setEvaluated = setEvaluated;
	const snippets = {};
	function useFunc(gen, f) {
	    return gen.scopeValue("func", {
	        ref: f,
	        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),
	    });
	}
	util$3.useFunc = useFunc;
	var Type;
	(function (Type) {
	    Type[Type["Num"] = 0] = "Num";
	    Type[Type["Str"] = 1] = "Str";
	})(Type || (util$3.Type = Type = {}));
	function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
	    if (dataProp instanceof codegen_1.Name) {
	        const isNumber = dataPropType === Type.Num;
	        return jsPropertySyntax
	            ? isNumber
	                ? (0, codegen_1._) `"[" + ${dataProp} + "]"`
	                : (0, codegen_1._) `"['" + ${dataProp} + "']"`
	            : isNumber
	                ? (0, codegen_1._) `"/" + ${dataProp}`
	                : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
	    }
	    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
	}
	util$3.getErrorPath = getErrorPath;
	function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
	    if (!mode)
	        return;
	    msg = `strict mode: ${msg}`;
	    if (mode === true)
	        throw new Error(msg);
	    it.self.logger.warn(msg);
	}
	util$3.checkStrictMode = checkStrictMode;
	return util$3;
}

var names = {};

var hasRequiredNames;

function requireNames () {
	if (hasRequiredNames) return names;
	hasRequiredNames = 1;
	Object.defineProperty(names, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const names$1 = {
	    data: new codegen_1.Name("data"),
	    valCxt: new codegen_1.Name("valCxt"),
	    instancePath: new codegen_1.Name("instancePath"),
	    parentData: new codegen_1.Name("parentData"),
	    parentDataProperty: new codegen_1.Name("parentDataProperty"),
	    rootData: new codegen_1.Name("rootData"),
	    dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
	    vErrors: new codegen_1.Name("vErrors"),
	    errors: new codegen_1.Name("errors"),
	    this: new codegen_1.Name("this"),
	    self: new codegen_1.Name("self"),
	    scope: new codegen_1.Name("scope"),
	    json: new codegen_1.Name("json"),
	    jsonPos: new codegen_1.Name("jsonPos"),
	    jsonLen: new codegen_1.Name("jsonLen"),
	    jsonPart: new codegen_1.Name("jsonPart"),
	};
	names.default = names$1;
	return names;
}

var hasRequiredErrors$1;

function requireErrors$1 () {
	if (hasRequiredErrors$1) return errors$1;
	hasRequiredErrors$1 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.extendErrors = exports$1.resetErrorsCount = exports$1.reportExtraError = exports$1.reportError = exports$1.keyword$DataError = exports$1.keywordError = void 0;
		const codegen_1 = requireCodegen();
		const util_1 = requireUtil$3();
		const names_1 = requireNames();
		exports$1.keywordError = {
		    message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`,
		};
		exports$1.keyword$DataError = {
		    message: ({ keyword, schemaType }) => schemaType
		        ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)`
		        : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`,
		};
		function reportError(cxt, error = exports$1.keywordError, errorPaths, overrideAllErrors) {
		    const { it } = cxt;
		    const { gen, compositeRule, allErrors } = it;
		    const errObj = errorObjectCode(cxt, error, errorPaths);
		    if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {
		        addError(gen, errObj);
		    }
		    else {
		        returnErrors(it, (0, codegen_1._) `[${errObj}]`);
		    }
		}
		exports$1.reportError = reportError;
		function reportExtraError(cxt, error = exports$1.keywordError, errorPaths) {
		    const { it } = cxt;
		    const { gen, compositeRule, allErrors } = it;
		    const errObj = errorObjectCode(cxt, error, errorPaths);
		    addError(gen, errObj);
		    if (!(compositeRule || allErrors)) {
		        returnErrors(it, names_1.default.vErrors);
		    }
		}
		exports$1.reportExtraError = reportExtraError;
		function resetErrorsCount(gen, errsCount) {
		    gen.assign(names_1.default.errors, errsCount);
		    gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
		}
		exports$1.resetErrorsCount = resetErrorsCount;
		function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
		    if (errsCount === undefined)
		        throw new Error("ajv implementation error");
		    const err = gen.name("err");
		    gen.forRange("i", errsCount, names_1.default.errors, (i) => {
		        gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);
		        gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
		        gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);
		        if (it.opts.verbose) {
		            gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);
		            gen.assign((0, codegen_1._) `${err}.data`, data);
		        }
		    });
		}
		exports$1.extendErrors = extendErrors;
		function addError(gen, errObj) {
		    const err = gen.const("err", errObj);
		    gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`);
		    gen.code((0, codegen_1._) `${names_1.default.errors}++`);
		}
		function returnErrors(it, errs) {
		    const { gen, validateName, schemaEnv } = it;
		    if (schemaEnv.$async) {
		        gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);
		    }
		    else {
		        gen.assign((0, codegen_1._) `${validateName}.errors`, errs);
		        gen.return(false);
		    }
		}
		const E = {
		    keyword: new codegen_1.Name("keyword"),
		    schemaPath: new codegen_1.Name("schemaPath"),
		    params: new codegen_1.Name("params"),
		    propertyName: new codegen_1.Name("propertyName"),
		    message: new codegen_1.Name("message"),
		    schema: new codegen_1.Name("schema"),
		    parentSchema: new codegen_1.Name("parentSchema"),
		};
		function errorObjectCode(cxt, error, errorPaths) {
		    const { createErrors } = cxt.it;
		    if (createErrors === false)
		        return (0, codegen_1._) `{}`;
		    return errorObject(cxt, error, errorPaths);
		}
		function errorObject(cxt, error, errorPaths = {}) {
		    const { gen, it } = cxt;
		    const keyValues = [
		        errorInstancePath(it, errorPaths),
		        errorSchemaPath(cxt, errorPaths),
		    ];
		    extraErrorProps(cxt, error, keyValues);
		    return gen.object(...keyValues);
		}
		function errorInstancePath({ errorPath }, { instancePath }) {
		    const instPath = instancePath
		        ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`
		        : errorPath;
		    return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
		}
		function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
		    let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;
		    if (schemaPath) {
		        schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
		    }
		    return [E.schemaPath, schPath];
		}
		function extraErrorProps(cxt, { params, message }, keyValues) {
		    const { keyword, data, schemaValue, it } = cxt;
		    const { opts, propertyName, topSchemaRef, schemaPath } = it;
		    keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]);
		    if (opts.messages) {
		        keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
		    }
		    if (opts.verbose) {
		        keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
		    }
		    if (propertyName)
		        keyValues.push([E.propertyName, propertyName]);
		} 
	} (errors$1));
	return errors$1;
}

var hasRequiredBoolSchema;

function requireBoolSchema () {
	if (hasRequiredBoolSchema) return boolSchema;
	hasRequiredBoolSchema = 1;
	Object.defineProperty(boolSchema, "__esModule", { value: true });
	boolSchema.boolOrEmptySchema = boolSchema.topBoolOrEmptySchema = void 0;
	const errors_1 = requireErrors$1();
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const boolError = {
	    message: "boolean schema is false",
	};
	function topBoolOrEmptySchema(it) {
	    const { gen, schema, validateName } = it;
	    if (schema === false) {
	        falseSchemaError(it, false);
	    }
	    else if (typeof schema == "object" && schema.$async === true) {
	        gen.return(names_1.default.data);
	    }
	    else {
	        gen.assign((0, codegen_1._) `${validateName}.errors`, null);
	        gen.return(true);
	    }
	}
	boolSchema.topBoolOrEmptySchema = topBoolOrEmptySchema;
	function boolOrEmptySchema(it, valid) {
	    const { gen, schema } = it;
	    if (schema === false) {
	        gen.var(valid, false);
	        falseSchemaError(it);
	    }
	    else {
	        gen.var(valid, true);
	    }
	}
	boolSchema.boolOrEmptySchema = boolOrEmptySchema;
	function falseSchemaError(it, overrideAllErrors) {
	    const { gen, data } = it;
	    const cxt = {
	        gen,
	        keyword: "false schema",
	        data,
	        schema: false,
	        schemaCode: false,
	        schemaValue: false,
	        params: {},
	        it,
	    };
	    (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);
	}
	return boolSchema;
}

var dataType = {};

var rules = {};

var hasRequiredRules;

function requireRules () {
	if (hasRequiredRules) return rules;
	hasRequiredRules = 1;
	Object.defineProperty(rules, "__esModule", { value: true });
	rules.getRules = rules.isJSONType = void 0;
	const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
	const jsonTypes = new Set(_jsonTypes);
	function isJSONType(x) {
	    return typeof x == "string" && jsonTypes.has(x);
	}
	rules.isJSONType = isJSONType;
	function getRules() {
	    const groups = {
	        number: { type: "number", rules: [] },
	        string: { type: "string", rules: [] },
	        array: { type: "array", rules: [] },
	        object: { type: "object", rules: [] },
	    };
	    return {
	        types: { ...groups, integer: true, boolean: true, null: true },
	        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
	        post: { rules: [] },
	        all: {},
	        keywords: {},
	    };
	}
	rules.getRules = getRules;
	return rules;
}

var applicability = {};

var hasRequiredApplicability;

function requireApplicability () {
	if (hasRequiredApplicability) return applicability;
	hasRequiredApplicability = 1;
	Object.defineProperty(applicability, "__esModule", { value: true });
	applicability.shouldUseRule = applicability.shouldUseGroup = applicability.schemaHasRulesForType = void 0;
	function schemaHasRulesForType({ schema, self }, type) {
	    const group = self.RULES.types[type];
	    return group && group !== true && shouldUseGroup(schema, group);
	}
	applicability.schemaHasRulesForType = schemaHasRulesForType;
	function shouldUseGroup(schema, group) {
	    return group.rules.some((rule) => shouldUseRule(schema, rule));
	}
	applicability.shouldUseGroup = shouldUseGroup;
	function shouldUseRule(schema, rule) {
	    var _a;
	    return (schema[rule.keyword] !== undefined ||
	        ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));
	}
	applicability.shouldUseRule = shouldUseRule;
	return applicability;
}

var hasRequiredDataType;

function requireDataType () {
	if (hasRequiredDataType) return dataType;
	hasRequiredDataType = 1;
	Object.defineProperty(dataType, "__esModule", { value: true });
	dataType.reportTypeError = dataType.checkDataTypes = dataType.checkDataType = dataType.coerceAndCheckDataType = dataType.getJSONTypes = dataType.getSchemaTypes = dataType.DataType = void 0;
	const rules_1 = requireRules();
	const applicability_1 = requireApplicability();
	const errors_1 = requireErrors$1();
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	var DataType;
	(function (DataType) {
	    DataType[DataType["Correct"] = 0] = "Correct";
	    DataType[DataType["Wrong"] = 1] = "Wrong";
	})(DataType || (dataType.DataType = DataType = {}));
	function getSchemaTypes(schema) {
	    const types = getJSONTypes(schema.type);
	    const hasNull = types.includes("null");
	    if (hasNull) {
	        if (schema.nullable === false)
	            throw new Error("type: null contradicts nullable: false");
	    }
	    else {
	        if (!types.length && schema.nullable !== undefined) {
	            throw new Error('"nullable" cannot be used without "type"');
	        }
	        if (schema.nullable === true)
	            types.push("null");
	    }
	    return types;
	}
	dataType.getSchemaTypes = getSchemaTypes;
	function getJSONTypes(ts) {
	    const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
	    if (types.every(rules_1.isJSONType))
	        return types;
	    throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
	}
	dataType.getJSONTypes = getJSONTypes;
	function coerceAndCheckDataType(it, types) {
	    const { gen, data, opts } = it;
	    const coerceTo = coerceToTypes(types, opts.coerceTypes);
	    const checkTypes = types.length > 0 &&
	        !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
	    if (checkTypes) {
	        const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
	        gen.if(wrongType, () => {
	            if (coerceTo.length)
	                coerceData(it, types, coerceTo);
	            else
	                reportTypeError(it);
	        });
	    }
	    return checkTypes;
	}
	dataType.coerceAndCheckDataType = coerceAndCheckDataType;
	const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]);
	function coerceToTypes(types, coerceTypes) {
	    return coerceTypes
	        ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
	        : [];
	}
	function coerceData(it, types, coerceTo) {
	    const { gen, data, opts } = it;
	    const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`);
	    const coerced = gen.let("coerced", (0, codegen_1._) `undefined`);
	    if (opts.coerceTypes === "array") {
	        gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen
	            .assign(data, (0, codegen_1._) `${data}[0]`)
	            .assign(dataType, (0, codegen_1._) `typeof ${data}`)
	            .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
	    }
	    gen.if((0, codegen_1._) `${coerced} !== undefined`);
	    for (const t of coerceTo) {
	        if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
	            coerceSpecificType(t);
	        }
	    }
	    gen.else();
	    reportTypeError(it);
	    gen.endIf();
	    gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {
	        gen.assign(data, coerced);
	        assignParentData(it, coerced);
	    });
	    function coerceSpecificType(t) {
	        switch (t) {
	            case "string":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`)
	                    .assign(coerced, (0, codegen_1._) `"" + ${data}`)
	                    .elseIf((0, codegen_1._) `${data} === null`)
	                    .assign(coerced, (0, codegen_1._) `""`);
	                return;
	            case "number":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`)
	                    .assign(coerced, (0, codegen_1._) `+${data}`);
	                return;
	            case "integer":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`)
	                    .assign(coerced, (0, codegen_1._) `+${data}`);
	                return;
	            case "boolean":
	                gen
	                    .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`)
	                    .assign(coerced, false)
	                    .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`)
	                    .assign(coerced, true);
	                return;
	            case "null":
	                gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`);
	                gen.assign(coerced, null);
	                return;
	            case "array":
	                gen
	                    .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`)
	                    .assign(coerced, (0, codegen_1._) `[${data}]`);
	        }
	    }
	}
	function assignParentData({ gen, parentData, parentDataProperty }, expr) {
	    gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));
	}
	function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
	    const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
	    let cond;
	    switch (dataType) {
	        case "null":
	            return (0, codegen_1._) `${data} ${EQ} null`;
	        case "array":
	            cond = (0, codegen_1._) `Array.isArray(${data})`;
	            break;
	        case "object":
	            cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
	            break;
	        case "integer":
	            cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);
	            break;
	        case "number":
	            cond = numCond();
	            break;
	        default:
	            return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;
	    }
	    return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
	    function numCond(_cond = codegen_1.nil) {
	        return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);
	    }
	}
	dataType.checkDataType = checkDataType;
	function checkDataTypes(dataTypes, data, strictNums, correct) {
	    if (dataTypes.length === 1) {
	        return checkDataType(dataTypes[0], data, strictNums, correct);
	    }
	    let cond;
	    const types = (0, util_1.toHash)(dataTypes);
	    if (types.array && types.object) {
	        const notObj = (0, codegen_1._) `typeof ${data} != "object"`;
	        cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;
	        delete types.null;
	        delete types.array;
	        delete types.object;
	    }
	    else {
	        cond = codegen_1.nil;
	    }
	    if (types.number)
	        delete types.integer;
	    for (const t in types)
	        cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
	    return cond;
	}
	dataType.checkDataTypes = checkDataTypes;
	const typeError = {
	    message: ({ schema }) => `must be ${schema}`,
	    params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,
	};
	function reportTypeError(it) {
	    const cxt = getTypeErrorContext(it);
	    (0, errors_1.reportError)(cxt, typeError);
	}
	dataType.reportTypeError = reportTypeError;
	function getTypeErrorContext(it) {
	    const { gen, data, schema } = it;
	    const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
	    return {
	        gen,
	        keyword: "type",
	        data,
	        schema: schema.type,
	        schemaCode,
	        schemaValue: schemaCode,
	        parentSchema: schema,
	        params: {},
	        it,
	    };
	}
	return dataType;
}

var defaults$1 = {};

var hasRequiredDefaults;

function requireDefaults () {
	if (hasRequiredDefaults) return defaults$1;
	hasRequiredDefaults = 1;
	Object.defineProperty(defaults$1, "__esModule", { value: true });
	defaults$1.assignDefaults = void 0;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	function assignDefaults(it, ty) {
	    const { properties, items } = it.schema;
	    if (ty === "object" && properties) {
	        for (const key in properties) {
	            assignDefault(it, key, properties[key].default);
	        }
	    }
	    else if (ty === "array" && Array.isArray(items)) {
	        items.forEach((sch, i) => assignDefault(it, i, sch.default));
	    }
	}
	defaults$1.assignDefaults = assignDefaults;
	function assignDefault(it, prop, defaultValue) {
	    const { gen, compositeRule, data, opts } = it;
	    if (defaultValue === undefined)
	        return;
	    const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;
	    if (compositeRule) {
	        (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
	        return;
	    }
	    let condition = (0, codegen_1._) `${childData} === undefined`;
	    if (opts.useDefaults === "empty") {
	        condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`;
	    }
	    gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
	}
	return defaults$1;
}

var keyword$1 = {};

var code$1 = {};

var hasRequiredCode$1;

function requireCode$1 () {
	if (hasRequiredCode$1) return code$1;
	hasRequiredCode$1 = 1;
	Object.defineProperty(code$1, "__esModule", { value: true });
	code$1.validateUnion = code$1.validateArray = code$1.usePattern = code$1.callValidateCode = code$1.schemaProperties = code$1.allSchemaProperties = code$1.noPropertyInData = code$1.propertyInData = code$1.isOwnProperty = code$1.hasPropFunc = code$1.reportMissingProp = code$1.checkMissingProp = code$1.checkReportMissingProp = void 0;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const names_1 = requireNames();
	const util_2 = requireUtil$3();
	function checkReportMissingProp(cxt, prop) {
	    const { gen, data, it } = cxt;
	    gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
	        cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);
	        cxt.error();
	    });
	}
	code$1.checkReportMissingProp = checkReportMissingProp;
	function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
	    return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));
	}
	code$1.checkMissingProp = checkMissingProp;
	function reportMissingProp(cxt, missing) {
	    cxt.setParams({ missingProperty: missing }, true);
	    cxt.error();
	}
	code$1.reportMissingProp = reportMissingProp;
	function hasPropFunc(gen) {
	    return gen.scopeValue("func", {
	        ref: Object.prototype.hasOwnProperty,
	        code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,
	    });
	}
	code$1.hasPropFunc = hasPropFunc;
	function isOwnProperty(gen, data, property) {
	    return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;
	}
	code$1.isOwnProperty = isOwnProperty;
	function propertyInData(gen, data, property, ownProperties) {
	    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
	    return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;
	}
	code$1.propertyInData = propertyInData;
	function noPropertyInData(gen, data, property, ownProperties) {
	    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;
	    return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
	}
	code$1.noPropertyInData = noPropertyInData;
	function allSchemaProperties(schemaMap) {
	    return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
	}
	code$1.allSchemaProperties = allSchemaProperties;
	function schemaProperties(it, schemaMap) {
	    return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
	}
	code$1.schemaProperties = schemaProperties;
	function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
	    const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
	    const valCxt = [
	        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
	        [names_1.default.parentData, it.parentData],
	        [names_1.default.parentDataProperty, it.parentDataProperty],
	        [names_1.default.rootData, names_1.default.rootData],
	    ];
	    if (it.opts.dynamicRef)
	        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
	    const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;
	    return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;
	}
	code$1.callValidateCode = callValidateCode;
	const newRegExp = (0, codegen_1._) `new RegExp`;
	function usePattern({ gen, it: { opts } }, pattern) {
	    const u = opts.unicodeRegExp ? "u" : "";
	    const { regExp } = opts.code;
	    const rx = regExp(pattern, u);
	    return gen.scopeValue("pattern", {
	        key: rx.toString(),
	        ref: rx,
	        code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,
	    });
	}
	code$1.usePattern = usePattern;
	function validateArray(cxt) {
	    const { gen, data, keyword, it } = cxt;
	    const valid = gen.name("valid");
	    if (it.allErrors) {
	        const validArr = gen.let("valid", true);
	        validateItems(() => gen.assign(validArr, false));
	        return validArr;
	    }
	    gen.var(valid, true);
	    validateItems(() => gen.break());
	    return valid;
	    function validateItems(notValid) {
	        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	        gen.forRange("i", 0, len, (i) => {
	            cxt.subschema({
	                keyword,
	                dataProp: i,
	                dataPropType: util_1.Type.Num,
	            }, valid);
	            gen.if((0, codegen_1.not)(valid), notValid);
	        });
	    }
	}
	code$1.validateArray = validateArray;
	function validateUnion(cxt) {
	    const { gen, schema, keyword, it } = cxt;
	    if (!Array.isArray(schema))
	        throw new Error("ajv implementation error");
	    const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
	    if (alwaysValid && !it.opts.unevaluated)
	        return;
	    const valid = gen.let("valid", false);
	    const schValid = gen.name("_valid");
	    gen.block(() => schema.forEach((_sch, i) => {
	        const schCxt = cxt.subschema({
	            keyword,
	            schemaProp: i,
	            compositeRule: true,
	        }, schValid);
	        gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);
	        const merged = cxt.mergeValidEvaluated(schCxt, schValid);
	        if (!merged)
	            gen.if((0, codegen_1.not)(valid));
	    }));
	    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
	}
	code$1.validateUnion = validateUnion;
	return code$1;
}

var hasRequiredKeyword$1;

function requireKeyword$1 () {
	if (hasRequiredKeyword$1) return keyword$1;
	hasRequiredKeyword$1 = 1;
	Object.defineProperty(keyword$1, "__esModule", { value: true });
	keyword$1.validateKeywordUsage = keyword$1.validSchemaType = keyword$1.funcKeywordCode = keyword$1.macroKeywordCode = void 0;
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const code_1 = requireCode$1();
	const errors_1 = requireErrors$1();
	function macroKeywordCode(cxt, def) {
	    const { gen, keyword, schema, parentSchema, it } = cxt;
	    const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
	    const schemaRef = useKeyword(gen, keyword, macroSchema);
	    if (it.opts.validateSchema !== false)
	        it.self.validateSchema(macroSchema, true);
	    const valid = gen.name("valid");
	    cxt.subschema({
	        schema: macroSchema,
	        schemaPath: codegen_1.nil,
	        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
	        topSchemaRef: schemaRef,
	        compositeRule: true,
	    }, valid);
	    cxt.pass(valid, () => cxt.error(true));
	}
	keyword$1.macroKeywordCode = macroKeywordCode;
	function funcKeywordCode(cxt, def) {
	    var _a;
	    const { gen, keyword, schema, parentSchema, $data, it } = cxt;
	    checkAsyncKeyword(it, def);
	    const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
	    const validateRef = useKeyword(gen, keyword, validate);
	    const valid = gen.let("valid");
	    cxt.block$data(valid, validateKeyword);
	    cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
	    function validateKeyword() {
	        if (def.errors === false) {
	            assignValid();
	            if (def.modifying)
	                modifyData(cxt);
	            reportErrs(() => cxt.error());
	        }
	        else {
	            const ruleErrs = def.async ? validateAsync() : validateSync();
	            if (def.modifying)
	                modifyData(cxt);
	            reportErrs(() => addErrs(cxt, ruleErrs));
	        }
	    }
	    function validateAsync() {
	        const ruleErrs = gen.let("ruleErrs", null);
	        gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));
	        return ruleErrs;
	    }
	    function validateSync() {
	        const validateErrs = (0, codegen_1._) `${validateRef}.errors`;
	        gen.assign(validateErrs, null);
	        assignValid(codegen_1.nil);
	        return validateErrs;
	    }
	    function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {
	        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
	        const passSchema = !(("compile" in def && !$data) || def.schema === false);
	        gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
	    }
	    function reportErrs(errors) {
	        var _a;
	        gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
	    }
	}
	keyword$1.funcKeywordCode = funcKeywordCode;
	function modifyData(cxt) {
	    const { gen, data, it } = cxt;
	    gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));
	}
	function addErrs(cxt, errs) {
	    const { gen } = cxt;
	    gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {
	        gen
	            .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)
	            .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
	        (0, errors_1.extendErrors)(cxt);
	    }, () => cxt.error());
	}
	function checkAsyncKeyword({ schemaEnv }, def) {
	    if (def.async && !schemaEnv.$async)
	        throw new Error("async keyword in sync schema");
	}
	function useKeyword(gen, keyword, result) {
	    if (result === undefined)
	        throw new Error(`keyword "${keyword}" failed to compile`);
	    return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
	}
	function validSchemaType(schema, schemaType, allowUndefined = false) {
	    return (!schemaType.length ||
	        schemaType.some((st) => st === "array"
	            ? Array.isArray(schema)
	            : st === "object"
	                ? schema && typeof schema == "object" && !Array.isArray(schema)
	                : typeof schema == st || (allowUndefined && typeof schema == "undefined")));
	}
	keyword$1.validSchemaType = validSchemaType;
	function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
	    if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
	        throw new Error("ajv implementation error");
	    }
	    const deps = def.dependencies;
	    if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
	        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
	    }
	    if (def.validateSchema) {
	        const valid = def.validateSchema(schema[keyword]);
	        if (!valid) {
	            const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
	                self.errorsText(def.validateSchema.errors);
	            if (opts.validateSchema === "log")
	                self.logger.error(msg);
	            else
	                throw new Error(msg);
	        }
	    }
	}
	keyword$1.validateKeywordUsage = validateKeywordUsage;
	return keyword$1;
}

var subschema = {};

var hasRequiredSubschema;

function requireSubschema () {
	if (hasRequiredSubschema) return subschema;
	hasRequiredSubschema = 1;
	Object.defineProperty(subschema, "__esModule", { value: true });
	subschema.extendSubschemaMode = subschema.extendSubschemaData = subschema.getSubschema = void 0;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
	    if (keyword !== undefined && schema !== undefined) {
	        throw new Error('both "keyword" and "schema" passed, only one allowed');
	    }
	    if (keyword !== undefined) {
	        const sch = it.schema[keyword];
	        return schemaProp === undefined
	            ? {
	                schema: sch,
	                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
	                errSchemaPath: `${it.errSchemaPath}/${keyword}`,
	            }
	            : {
	                schema: sch[schemaProp],
	                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
	                errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,
	            };
	    }
	    if (schema !== undefined) {
	        if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
	            throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
	        }
	        return {
	            schema,
	            schemaPath,
	            topSchemaRef,
	            errSchemaPath,
	        };
	    }
	    throw new Error('either "keyword" or "schema" must be passed');
	}
	subschema.getSubschema = getSubschema;
	function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
	    if (data !== undefined && dataProp !== undefined) {
	        throw new Error('both "data" and "dataProp" passed, only one allowed');
	    }
	    const { gen } = it;
	    if (dataProp !== undefined) {
	        const { errorPath, dataPathArr, opts } = it;
	        const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
	        dataContextProps(nextData);
	        subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
	        subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;
	        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
	    }
	    if (data !== undefined) {
	        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);
	        dataContextProps(nextData);
	        if (propertyName !== undefined)
	            subschema.propertyName = propertyName;
	    }
	    if (dataTypes)
	        subschema.dataTypes = dataTypes;
	    function dataContextProps(_nextData) {
	        subschema.data = _nextData;
	        subschema.dataLevel = it.dataLevel + 1;
	        subschema.dataTypes = [];
	        it.definedProperties = new Set();
	        subschema.parentData = it.data;
	        subschema.dataNames = [...it.dataNames, _nextData];
	    }
	}
	subschema.extendSubschemaData = extendSubschemaData;
	function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
	    if (compositeRule !== undefined)
	        subschema.compositeRule = compositeRule;
	    if (createErrors !== undefined)
	        subschema.createErrors = createErrors;
	    if (allErrors !== undefined)
	        subschema.allErrors = allErrors;
	    subschema.jtdDiscriminator = jtdDiscriminator;
	    subschema.jtdMetadata = jtdMetadata;
	}
	subschema.extendSubschemaMode = extendSubschemaMode;
	return subschema;
}

var resolve = {};

var jsonSchemaTraverse = {exports: {}};

var hasRequiredJsonSchemaTraverse;

function requireJsonSchemaTraverse () {
	if (hasRequiredJsonSchemaTraverse) return jsonSchemaTraverse.exports;
	hasRequiredJsonSchemaTraverse = 1;
	var traverse = jsonSchemaTraverse.exports = function (schema, opts, cb) {
	  if (typeof opts == 'function') {
	    cb = opts;
	    opts = {};
	  }
	  cb = opts.cb || cb;
	  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
	  var post = cb.post || function() {};
	  _traverse(opts, pre, post, schema, '', schema);
	};
	traverse.keywords = {
	  additionalItems: true,
	  items: true,
	  contains: true,
	  additionalProperties: true,
	  propertyNames: true,
	  not: true,
	  if: true,
	  then: true,
	  else: true
	};
	traverse.arrayKeywords = {
	  items: true,
	  allOf: true,
	  anyOf: true,
	  oneOf: true
	};
	traverse.propsKeywords = {
	  $defs: true,
	  definitions: true,
	  properties: true,
	  patternProperties: true,
	  dependencies: true
	};
	traverse.skipKeywords = {
	  default: true,
	  enum: true,
	  const: true,
	  required: true,
	  maximum: true,
	  minimum: true,
	  exclusiveMaximum: true,
	  exclusiveMinimum: true,
	  multipleOf: true,
	  maxLength: true,
	  minLength: true,
	  pattern: true,
	  format: true,
	  maxItems: true,
	  minItems: true,
	  uniqueItems: true,
	  maxProperties: true,
	  minProperties: true
	};
	function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
	  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
	    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
	    for (var key in schema) {
	      var sch = schema[key];
	      if (Array.isArray(sch)) {
	        if (key in traverse.arrayKeywords) {
	          for (var i=0; i<sch.length; i++)
	            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
	        }
	      } else if (key in traverse.propsKeywords) {
	        if (sch && typeof sch == 'object') {
	          for (var prop in sch)
	            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
	        }
	      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
	        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
	      }
	    }
	    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
	  }
	}
	function escapeJsonPtr(str) {
	  return str.replace(/~/g, '~0').replace(/\//g, '~1');
	}
	return jsonSchemaTraverse.exports;
}

var hasRequiredResolve;

function requireResolve () {
	if (hasRequiredResolve) return resolve;
	hasRequiredResolve = 1;
	Object.defineProperty(resolve, "__esModule", { value: true });
	resolve.getSchemaRefs = resolve.resolveUrl = resolve.normalizeId = resolve._getFullPath = resolve.getFullPath = resolve.inlineRef = void 0;
	const util_1 = requireUtil$3();
	const equal = requireFastDeepEqual();
	const traverse = requireJsonSchemaTraverse();
	const SIMPLE_INLINED = new Set([
	    "type",
	    "format",
	    "pattern",
	    "maxLength",
	    "minLength",
	    "maxProperties",
	    "minProperties",
	    "maxItems",
	    "minItems",
	    "maximum",
	    "minimum",
	    "uniqueItems",
	    "multipleOf",
	    "required",
	    "enum",
	    "const",
	]);
	function inlineRef(schema, limit = true) {
	    if (typeof schema == "boolean")
	        return true;
	    if (limit === true)
	        return !hasRef(schema);
	    if (!limit)
	        return false;
	    return countKeys(schema) <= limit;
	}
	resolve.inlineRef = inlineRef;
	const REF_KEYWORDS = new Set([
	    "$ref",
	    "$recursiveRef",
	    "$recursiveAnchor",
	    "$dynamicRef",
	    "$dynamicAnchor",
	]);
	function hasRef(schema) {
	    for (const key in schema) {
	        if (REF_KEYWORDS.has(key))
	            return true;
	        const sch = schema[key];
	        if (Array.isArray(sch) && sch.some(hasRef))
	            return true;
	        if (typeof sch == "object" && hasRef(sch))
	            return true;
	    }
	    return false;
	}
	function countKeys(schema) {
	    let count = 0;
	    for (const key in schema) {
	        if (key === "$ref")
	            return Infinity;
	        count++;
	        if (SIMPLE_INLINED.has(key))
	            continue;
	        if (typeof schema[key] == "object") {
	            (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));
	        }
	        if (count === Infinity)
	            return Infinity;
	    }
	    return count;
	}
	function getFullPath(resolver, id = "", normalize) {
	    if (normalize !== false)
	        id = normalizeId(id);
	    const p = resolver.parse(id);
	    return _getFullPath(resolver, p);
	}
	resolve.getFullPath = getFullPath;
	function _getFullPath(resolver, p) {
	    const serialized = resolver.serialize(p);
	    return serialized.split("#")[0] + "#";
	}
	resolve._getFullPath = _getFullPath;
	const TRAILING_SLASH_HASH = /#\/?$/;
	function normalizeId(id) {
	    return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
	}
	resolve.normalizeId = normalizeId;
	function resolveUrl(resolver, baseId, id) {
	    id = normalizeId(id);
	    return resolver.resolve(baseId, id);
	}
	resolve.resolveUrl = resolveUrl;
	const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
	function getSchemaRefs(schema, baseId) {
	    if (typeof schema == "boolean")
	        return {};
	    const { schemaId, uriResolver } = this.opts;
	    const schId = normalizeId(schema[schemaId] || baseId);
	    const baseIds = { "": schId };
	    const pathPrefix = getFullPath(uriResolver, schId, false);
	    const localRefs = {};
	    const schemaRefs = new Set();
	    traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
	        if (parentJsonPtr === undefined)
	            return;
	        const fullPath = pathPrefix + jsonPtr;
	        let innerBaseId = baseIds[parentJsonPtr];
	        if (typeof sch[schemaId] == "string")
	            innerBaseId = addRef.call(this, sch[schemaId]);
	        addAnchor.call(this, sch.$anchor);
	        addAnchor.call(this, sch.$dynamicAnchor);
	        baseIds[jsonPtr] = innerBaseId;
	        function addRef(ref) {
	            const _resolve = this.opts.uriResolver.resolve;
	            ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
	            if (schemaRefs.has(ref))
	                throw ambiguos(ref);
	            schemaRefs.add(ref);
	            let schOrRef = this.refs[ref];
	            if (typeof schOrRef == "string")
	                schOrRef = this.refs[schOrRef];
	            if (typeof schOrRef == "object") {
	                checkAmbiguosRef(sch, schOrRef.schema, ref);
	            }
	            else if (ref !== normalizeId(fullPath)) {
	                if (ref[0] === "#") {
	                    checkAmbiguosRef(sch, localRefs[ref], ref);
	                    localRefs[ref] = sch;
	                }
	                else {
	                    this.refs[ref] = fullPath;
	                }
	            }
	            return ref;
	        }
	        function addAnchor(anchor) {
	            if (typeof anchor == "string") {
	                if (!ANCHOR.test(anchor))
	                    throw new Error(`invalid anchor "${anchor}"`);
	                addRef.call(this, `#${anchor}`);
	            }
	        }
	    });
	    return localRefs;
	    function checkAmbiguosRef(sch1, sch2, ref) {
	        if (sch2 !== undefined && !equal(sch1, sch2))
	            throw ambiguos(ref);
	    }
	    function ambiguos(ref) {
	        return new Error(`reference "${ref}" resolves to more than one schema`);
	    }
	}
	resolve.getSchemaRefs = getSchemaRefs;
	return resolve;
}

var hasRequiredValidate;

function requireValidate () {
	if (hasRequiredValidate) return validate;
	hasRequiredValidate = 1;
	Object.defineProperty(validate, "__esModule", { value: true });
	validate.getData = validate.KeywordCxt = validate.validateFunctionCode = void 0;
	const boolSchema_1 = requireBoolSchema();
	const dataType_1 = requireDataType();
	const applicability_1 = requireApplicability();
	const dataType_2 = requireDataType();
	const defaults_1 = requireDefaults();
	const keyword_1 = requireKeyword$1();
	const subschema_1 = requireSubschema();
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const resolve_1 = requireResolve();
	const util_1 = requireUtil$3();
	const errors_1 = requireErrors$1();
	function validateFunctionCode(it) {
	    if (isSchemaObj(it)) {
	        checkKeywords(it);
	        if (schemaCxtHasRules(it)) {
	            topSchemaObjCode(it);
	            return;
	        }
	    }
	    validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
	}
	validate.validateFunctionCode = validateFunctionCode;
	function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
	    if (opts.code.es5) {
	        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
	            gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`);
	            destructureValCxtES5(gen, opts);
	            gen.code(body);
	        });
	    }
	    else {
	        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
	    }
	}
	function destructureValCxt(opts) {
	    return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
	}
	function destructureValCxtES5(gen, opts) {
	    gen.if(names_1.default.valCxt, () => {
	        gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);
	        gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);
	        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
	        gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);
	        if (opts.dynamicRef)
	            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
	    }, () => {
	        gen.var(names_1.default.instancePath, (0, codegen_1._) `""`);
	        gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);
	        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);
	        gen.var(names_1.default.rootData, names_1.default.data);
	        if (opts.dynamicRef)
	            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);
	    });
	}
	function topSchemaObjCode(it) {
	    const { schema, opts, gen } = it;
	    validateFunction(it, () => {
	        if (opts.$comment && schema.$comment)
	            commentKeyword(it);
	        checkNoDefault(it);
	        gen.let(names_1.default.vErrors, null);
	        gen.let(names_1.default.errors, 0);
	        if (opts.unevaluated)
	            resetEvaluated(it);
	        typeAndKeywords(it);
	        returnResults(it);
	    });
	    return;
	}
	function resetEvaluated(it) {
	    const { gen, validateName } = it;
	    it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`);
	    gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));
	    gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));
	}
	function funcSourceUrl(schema, opts) {
	    const schId = typeof schema == "object" && schema[opts.schemaId];
	    return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;
	}
	function subschemaCode(it, valid) {
	    if (isSchemaObj(it)) {
	        checkKeywords(it);
	        if (schemaCxtHasRules(it)) {
	            subSchemaObjCode(it, valid);
	            return;
	        }
	    }
	    (0, boolSchema_1.boolOrEmptySchema)(it, valid);
	}
	function schemaCxtHasRules({ schema, self }) {
	    if (typeof schema == "boolean")
	        return !schema;
	    for (const key in schema)
	        if (self.RULES.all[key])
	            return true;
	    return false;
	}
	function isSchemaObj(it) {
	    return typeof it.schema != "boolean";
	}
	function subSchemaObjCode(it, valid) {
	    const { schema, gen, opts } = it;
	    if (opts.$comment && schema.$comment)
	        commentKeyword(it);
	    updateContext(it);
	    checkAsyncSchema(it);
	    const errsCount = gen.const("_errs", names_1.default.errors);
	    typeAndKeywords(it, errsCount);
	    gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
	}
	function checkKeywords(it) {
	    (0, util_1.checkUnknownRules)(it);
	    checkRefsAndKeywords(it);
	}
	function typeAndKeywords(it, errsCount) {
	    if (it.opts.jtd)
	        return schemaKeywords(it, [], false, errsCount);
	    const types = (0, dataType_1.getSchemaTypes)(it.schema);
	    const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
	    schemaKeywords(it, types, !checkedTypes, errsCount);
	}
	function checkRefsAndKeywords(it) {
	    const { schema, errSchemaPath, opts, self } = it;
	    if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
	        self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
	    }
	}
	function checkNoDefault(it) {
	    const { schema, opts } = it;
	    if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
	        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
	    }
	}
	function updateContext(it) {
	    const schId = it.schema[it.opts.schemaId];
	    if (schId)
	        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
	}
	function checkAsyncSchema(it) {
	    if (it.schema.$async && !it.schemaEnv.$async)
	        throw new Error("async schema in sync schema");
	}
	function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
	    const msg = schema.$comment;
	    if (opts.$comment === true) {
	        gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);
	    }
	    else if (typeof opts.$comment == "function") {
	        const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;
	        const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
	        gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
	    }
	}
	function returnResults(it) {
	    const { gen, schemaEnv, validateName, ValidationError, opts } = it;
	    if (schemaEnv.$async) {
	        gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));
	    }
	    else {
	        gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);
	        if (opts.unevaluated)
	            assignEvaluated(it);
	        gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);
	    }
	}
	function assignEvaluated({ gen, evaluated, props, items }) {
	    if (props instanceof codegen_1.Name)
	        gen.assign((0, codegen_1._) `${evaluated}.props`, props);
	    if (items instanceof codegen_1.Name)
	        gen.assign((0, codegen_1._) `${evaluated}.items`, items);
	}
	function schemaKeywords(it, types, typeErrors, errsCount) {
	    const { gen, schema, data, allErrors, opts, self } = it;
	    const { RULES } = self;
	    if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
	        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
	        return;
	    }
	    if (!opts.jtd)
	        checkStrictTypes(it, types);
	    gen.block(() => {
	        for (const group of RULES.rules)
	            groupKeywords(group);
	        groupKeywords(RULES.post);
	    });
	    function groupKeywords(group) {
	        if (!(0, applicability_1.shouldUseGroup)(schema, group))
	            return;
	        if (group.type) {
	            gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
	            iterateKeywords(it, group);
	            if (types.length === 1 && types[0] === group.type && typeErrors) {
	                gen.else();
	                (0, dataType_2.reportTypeError)(it);
	            }
	            gen.endIf();
	        }
	        else {
	            iterateKeywords(it, group);
	        }
	        if (!allErrors)
	            gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);
	    }
	}
	function iterateKeywords(it, group) {
	    const { gen, schema, opts: { useDefaults }, } = it;
	    if (useDefaults)
	        (0, defaults_1.assignDefaults)(it, group.type);
	    gen.block(() => {
	        for (const rule of group.rules) {
	            if ((0, applicability_1.shouldUseRule)(schema, rule)) {
	                keywordCode(it, rule.keyword, rule.definition, group.type);
	            }
	        }
	    });
	}
	function checkStrictTypes(it, types) {
	    if (it.schemaEnv.meta || !it.opts.strictTypes)
	        return;
	    checkContextTypes(it, types);
	    if (!it.opts.allowUnionTypes)
	        checkMultipleTypes(it, types);
	    checkKeywordTypes(it, it.dataTypes);
	}
	function checkContextTypes(it, types) {
	    if (!types.length)
	        return;
	    if (!it.dataTypes.length) {
	        it.dataTypes = types;
	        return;
	    }
	    types.forEach((t) => {
	        if (!includesType(it.dataTypes, t)) {
	            strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
	        }
	    });
	    narrowSchemaTypes(it, types);
	}
	function checkMultipleTypes(it, ts) {
	    if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
	        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
	    }
	}
	function checkKeywordTypes(it, ts) {
	    const rules = it.self.RULES.all;
	    for (const keyword in rules) {
	        const rule = rules[keyword];
	        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
	            const { type } = rule.definition;
	            if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
	                strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
	            }
	        }
	    }
	}
	function hasApplicableType(schTs, kwdT) {
	    return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"));
	}
	function includesType(ts, t) {
	    return ts.includes(t) || (t === "integer" && ts.includes("number"));
	}
	function narrowSchemaTypes(it, withTypes) {
	    const ts = [];
	    for (const t of it.dataTypes) {
	        if (includesType(withTypes, t))
	            ts.push(t);
	        else if (withTypes.includes("integer") && t === "number")
	            ts.push("integer");
	    }
	    it.dataTypes = ts;
	}
	function strictTypesError(it, msg) {
	    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
	    msg += ` at "${schemaPath}" (strictTypes)`;
	    (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
	}
	class KeywordCxt {
	    constructor(it, def, keyword) {
	        (0, keyword_1.validateKeywordUsage)(it, def, keyword);
	        this.gen = it.gen;
	        this.allErrors = it.allErrors;
	        this.keyword = keyword;
	        this.data = it.data;
	        this.schema = it.schema[keyword];
	        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
	        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
	        this.schemaType = def.schemaType;
	        this.parentSchema = it.schema;
	        this.params = {};
	        this.it = it;
	        this.def = def;
	        if (this.$data) {
	            this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
	        }
	        else {
	            this.schemaCode = this.schemaValue;
	            if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
	                throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
	            }
	        }
	        if ("code" in def ? def.trackErrors : def.errors !== false) {
	            this.errsCount = it.gen.const("_errs", names_1.default.errors);
	        }
	    }
	    result(condition, successAction, failAction) {
	        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
	    }
	    failResult(condition, successAction, failAction) {
	        this.gen.if(condition);
	        if (failAction)
	            failAction();
	        else
	            this.error();
	        if (successAction) {
	            this.gen.else();
	            successAction();
	            if (this.allErrors)
	                this.gen.endIf();
	        }
	        else {
	            if (this.allErrors)
	                this.gen.endIf();
	            else
	                this.gen.else();
	        }
	    }
	    pass(condition, failAction) {
	        this.failResult((0, codegen_1.not)(condition), undefined, failAction);
	    }
	    fail(condition) {
	        if (condition === undefined) {
	            this.error();
	            if (!this.allErrors)
	                this.gen.if(false);
	            return;
	        }
	        this.gen.if(condition);
	        this.error();
	        if (this.allErrors)
	            this.gen.endIf();
	        else
	            this.gen.else();
	    }
	    fail$data(condition) {
	        if (!this.$data)
	            return this.fail(condition);
	        const { schemaCode } = this;
	        this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
	    }
	    error(append, errorParams, errorPaths) {
	        if (errorParams) {
	            this.setParams(errorParams);
	            this._error(append, errorPaths);
	            this.setParams({});
	            return;
	        }
	        this._error(append, errorPaths);
	    }
	    _error(append, errorPaths) {
	        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
	    }
	    $dataError() {
	        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
	    }
	    reset() {
	        if (this.errsCount === undefined)
	            throw new Error('add "trackErrors" to keyword definition');
	        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
	    }
	    ok(cond) {
	        if (!this.allErrors)
	            this.gen.if(cond);
	    }
	    setParams(obj, assign) {
	        if (assign)
	            Object.assign(this.params, obj);
	        else
	            this.params = obj;
	    }
	    block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
	        this.gen.block(() => {
	            this.check$data(valid, $dataValid);
	            codeBlock();
	        });
	    }
	    check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
	        if (!this.$data)
	            return;
	        const { gen, schemaCode, schemaType, def } = this;
	        gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));
	        if (valid !== codegen_1.nil)
	            gen.assign(valid, true);
	        if (schemaType.length || def.validateSchema) {
	            gen.elseIf(this.invalid$data());
	            this.$dataError();
	            if (valid !== codegen_1.nil)
	                gen.assign(valid, false);
	        }
	        gen.else();
	    }
	    invalid$data() {
	        const { gen, schemaCode, schemaType, def, it } = this;
	        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
	        function wrong$DataType() {
	            if (schemaType.length) {
	                if (!(schemaCode instanceof codegen_1.Name))
	                    throw new Error("ajv implementation error");
	                const st = Array.isArray(schemaType) ? schemaType : [schemaType];
	                return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
	            }
	            return codegen_1.nil;
	        }
	        function invalid$DataSchema() {
	            if (def.validateSchema) {
	                const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
	                return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;
	            }
	            return codegen_1.nil;
	        }
	    }
	    subschema(appl, valid) {
	        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
	        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
	        (0, subschema_1.extendSubschemaMode)(subschema, appl);
	        const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };
	        subschemaCode(nextContext, valid);
	        return nextContext;
	    }
	    mergeEvaluated(schemaCxt, toName) {
	        const { it, gen } = this;
	        if (!it.opts.unevaluated)
	            return;
	        if (it.props !== true && schemaCxt.props !== undefined) {
	            it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
	        }
	        if (it.items !== true && schemaCxt.items !== undefined) {
	            it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
	        }
	    }
	    mergeValidEvaluated(schemaCxt, valid) {
	        const { it, gen } = this;
	        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
	            gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
	            return true;
	        }
	    }
	}
	validate.KeywordCxt = KeywordCxt;
	function keywordCode(it, keyword, def, ruleType) {
	    const cxt = new KeywordCxt(it, def, keyword);
	    if ("code" in def) {
	        def.code(cxt, ruleType);
	    }
	    else if (cxt.$data && def.validate) {
	        (0, keyword_1.funcKeywordCode)(cxt, def);
	    }
	    else if ("macro" in def) {
	        (0, keyword_1.macroKeywordCode)(cxt, def);
	    }
	    else if (def.compile || def.validate) {
	        (0, keyword_1.funcKeywordCode)(cxt, def);
	    }
	}
	const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
	const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
	function getData($data, { dataLevel, dataNames, dataPathArr }) {
	    let jsonPointer;
	    let data;
	    if ($data === "")
	        return names_1.default.rootData;
	    if ($data[0] === "/") {
	        if (!JSON_POINTER.test($data))
	            throw new Error(`Invalid JSON-pointer: ${$data}`);
	        jsonPointer = $data;
	        data = names_1.default.rootData;
	    }
	    else {
	        const matches = RELATIVE_JSON_POINTER.exec($data);
	        if (!matches)
	            throw new Error(`Invalid JSON-pointer: ${$data}`);
	        const up = +matches[1];
	        jsonPointer = matches[2];
	        if (jsonPointer === "#") {
	            if (up >= dataLevel)
	                throw new Error(errorMsg("property/index", up));
	            return dataPathArr[dataLevel - up];
	        }
	        if (up > dataLevel)
	            throw new Error(errorMsg("data", up));
	        data = dataNames[dataLevel - up];
	        if (!jsonPointer)
	            return data;
	    }
	    let expr = data;
	    const segments = jsonPointer.split("/");
	    for (const segment of segments) {
	        if (segment) {
	            data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
	            expr = (0, codegen_1._) `${expr} && ${data}`;
	        }
	    }
	    return expr;
	    function errorMsg(pointerType, up) {
	        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
	    }
	}
	validate.getData = getData;
	return validate;
}

var validation_error = {};

var hasRequiredValidation_error;

function requireValidation_error () {
	if (hasRequiredValidation_error) return validation_error;
	hasRequiredValidation_error = 1;
	Object.defineProperty(validation_error, "__esModule", { value: true });
	class ValidationError extends Error {
	    constructor(errors) {
	        super("validation failed");
	        this.errors = errors;
	        this.ajv = this.validation = true;
	    }
	}
	validation_error.default = ValidationError;
	return validation_error;
}

var ref_error = {};

var hasRequiredRef_error;

function requireRef_error () {
	if (hasRequiredRef_error) return ref_error;
	hasRequiredRef_error = 1;
	Object.defineProperty(ref_error, "__esModule", { value: true });
	const resolve_1 = requireResolve();
	class MissingRefError extends Error {
	    constructor(resolver, baseId, ref, msg) {
	        super(msg || `can't resolve reference ${ref} from id ${baseId}`);
	        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
	        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
	    }
	}
	ref_error.default = MissingRefError;
	return ref_error;
}

var compile$1 = {};

var hasRequiredCompile$1;

function requireCompile$1 () {
	if (hasRequiredCompile$1) return compile$1;
	hasRequiredCompile$1 = 1;
	Object.defineProperty(compile$1, "__esModule", { value: true });
	compile$1.resolveSchema = compile$1.getCompilingSchema = compile$1.resolveRef = compile$1.compileSchema = compile$1.SchemaEnv = void 0;
	const codegen_1 = requireCodegen();
	const validation_error_1 = requireValidation_error();
	const names_1 = requireNames();
	const resolve_1 = requireResolve();
	const util_1 = requireUtil$3();
	const validate_1 = requireValidate();
	class SchemaEnv {
	    constructor(env) {
	        var _a;
	        this.refs = {};
	        this.dynamicAnchors = {};
	        let schema;
	        if (typeof env.schema == "object")
	            schema = env.schema;
	        this.schema = env.schema;
	        this.schemaId = env.schemaId;
	        this.root = env.root || this;
	        this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
	        this.schemaPath = env.schemaPath;
	        this.localRefs = env.localRefs;
	        this.meta = env.meta;
	        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
	        this.refs = {};
	    }
	}
	compile$1.SchemaEnv = SchemaEnv;
	function compileSchema(sch) {
	    const _sch = getCompilingSchema.call(this, sch);
	    if (_sch)
	        return _sch;
	    const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);
	    const { es5, lines } = this.opts.code;
	    const { ownProperties } = this.opts;
	    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
	    let _ValidationError;
	    if (sch.$async) {
	        _ValidationError = gen.scopeValue("Error", {
	            ref: validation_error_1.default,
	            code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`,
	        });
	    }
	    const validateName = gen.scopeName("validate");
	    sch.validateName = validateName;
	    const schemaCxt = {
	        gen,
	        allErrors: this.opts.allErrors,
	        data: names_1.default.data,
	        parentData: names_1.default.parentData,
	        parentDataProperty: names_1.default.parentDataProperty,
	        dataNames: [names_1.default.data],
	        dataPathArr: [codegen_1.nil],
	        dataLevel: 0,
	        dataTypes: [],
	        definedProperties: new Set(),
	        topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true
	            ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }
	            : { ref: sch.schema }),
	        validateName,
	        ValidationError: _ValidationError,
	        schema: sch.schema,
	        schemaEnv: sch,
	        rootId,
	        baseId: sch.baseId || rootId,
	        schemaPath: codegen_1.nil,
	        errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
	        errorPath: (0, codegen_1._) `""`,
	        opts: this.opts,
	        self: this,
	    };
	    let sourceCode;
	    try {
	        this._compilations.add(sch);
	        (0, validate_1.validateFunctionCode)(schemaCxt);
	        gen.optimize(this.opts.code.optimize);
	        const validateCode = gen.toString();
	        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
	        if (this.opts.code.process)
	            sourceCode = this.opts.code.process(sourceCode, sch);
	        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
	        const validate = makeValidate(this, this.scope.get());
	        this.scope.value(validateName, { ref: validate });
	        validate.errors = null;
	        validate.schema = sch.schema;
	        validate.schemaEnv = sch;
	        if (sch.$async)
	            validate.$async = true;
	        if (this.opts.code.source === true) {
	            validate.source = { validateName, validateCode, scopeValues: gen._values };
	        }
	        if (this.opts.unevaluated) {
	            const { props, items } = schemaCxt;
	            validate.evaluated = {
	                props: props instanceof codegen_1.Name ? undefined : props,
	                items: items instanceof codegen_1.Name ? undefined : items,
	                dynamicProps: props instanceof codegen_1.Name,
	                dynamicItems: items instanceof codegen_1.Name,
	            };
	            if (validate.source)
	                validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
	        }
	        sch.validate = validate;
	        return sch;
	    }
	    catch (e) {
	        delete sch.validate;
	        delete sch.validateName;
	        if (sourceCode)
	            this.logger.error("Error compiling schema, function code:", sourceCode);
	        throw e;
	    }
	    finally {
	        this._compilations.delete(sch);
	    }
	}
	compile$1.compileSchema = compileSchema;
	function resolveRef(root, baseId, ref) {
	    var _a;
	    ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
	    const schOrFunc = root.refs[ref];
	    if (schOrFunc)
	        return schOrFunc;
	    let _sch = resolve.call(this, root, ref);
	    if (_sch === undefined) {
	        const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
	        const { schemaId } = this.opts;
	        if (schema)
	            _sch = new SchemaEnv({ schema, schemaId, root, baseId });
	    }
	    if (_sch === undefined)
	        return;
	    return (root.refs[ref] = inlineOrCompile.call(this, _sch));
	}
	compile$1.resolveRef = resolveRef;
	function inlineOrCompile(sch) {
	    if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
	        return sch.schema;
	    return sch.validate ? sch : compileSchema.call(this, sch);
	}
	function getCompilingSchema(schEnv) {
	    for (const sch of this._compilations) {
	        if (sameSchemaEnv(sch, schEnv))
	            return sch;
	    }
	}
	compile$1.getCompilingSchema = getCompilingSchema;
	function sameSchemaEnv(s1, s2) {
	    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
	}
	function resolve(root,
	ref
	) {
	    let sch;
	    while (typeof (sch = this.refs[ref]) == "string")
	        ref = sch;
	    return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
	}
	function resolveSchema(root,
	ref
	) {
	    const p = this.opts.uriResolver.parse(ref);
	    const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
	    let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);
	    if (Object.keys(root.schema).length > 0 && refPath === baseId) {
	        return getJsonPointer.call(this, p, root);
	    }
	    const id = (0, resolve_1.normalizeId)(refPath);
	    const schOrRef = this.refs[id] || this.schemas[id];
	    if (typeof schOrRef == "string") {
	        const sch = resolveSchema.call(this, root, schOrRef);
	        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
	            return;
	        return getJsonPointer.call(this, p, sch);
	    }
	    if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
	        return;
	    if (!schOrRef.validate)
	        compileSchema.call(this, schOrRef);
	    if (id === (0, resolve_1.normalizeId)(ref)) {
	        const { schema } = schOrRef;
	        const { schemaId } = this.opts;
	        const schId = schema[schemaId];
	        if (schId)
	            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
	        return new SchemaEnv({ schema, schemaId, root, baseId });
	    }
	    return getJsonPointer.call(this, p, schOrRef);
	}
	compile$1.resolveSchema = resolveSchema;
	const PREVENT_SCOPE_CHANGE = new Set([
	    "properties",
	    "patternProperties",
	    "enum",
	    "dependencies",
	    "definitions",
	]);
	function getJsonPointer(parsedRef, { baseId, schema, root }) {
	    var _a;
	    if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
	        return;
	    for (const part of parsedRef.fragment.slice(1).split("/")) {
	        if (typeof schema === "boolean")
	            return;
	        const partSchema = schema[(0, util_1.unescapeFragment)(part)];
	        if (partSchema === undefined)
	            return;
	        schema = partSchema;
	        const schId = typeof schema === "object" && schema[this.opts.schemaId];
	        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
	            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
	        }
	    }
	    let env;
	    if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
	        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
	        env = resolveSchema.call(this, root, $ref);
	    }
	    const { schemaId } = this.opts;
	    env = env || new SchemaEnv({ schema, schemaId, root, baseId });
	    if (env.schema !== env.root.schema)
	        return env;
	    return undefined;
	}
	return compile$1;
}

var $id$1 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#";
var description = "Meta-schema for $data reference (JSON AnySchema extension proposal)";
var type$1 = "object";
var required$1 = [
	"$data"
];
var properties$2 = {
	$data: {
		type: "string",
		anyOf: [
			{
				format: "relative-json-pointer"
			},
			{
				format: "json-pointer"
			}
		]
	}
};
var additionalProperties$1 = false;
var require$$9 = {
	$id: $id$1,
	description: description,
	type: type$1,
	required: required$1,
	properties: properties$2,
	additionalProperties: additionalProperties$1
};

var uri = {};

var hasRequiredUri;

function requireUri () {
	if (hasRequiredUri) return uri;
	hasRequiredUri = 1;
	Object.defineProperty(uri, "__esModule", { value: true });
	const uri$1 = requireFastUri();
	uri$1.code = 'require("ajv/dist/runtime/uri").default';
	uri.default = uri$1;
	return uri;
}

var hasRequiredCore$2;

function requireCore$2 () {
	if (hasRequiredCore$2) return core$3;
	hasRequiredCore$2 = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.CodeGen = exports$1.Name = exports$1.nil = exports$1.stringify = exports$1.str = exports$1._ = exports$1.KeywordCxt = void 0;
		var validate_1 = requireValidate();
		Object.defineProperty(exports$1, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
		var codegen_1 = requireCodegen();
		Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return codegen_1._; } });
		Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return codegen_1.str; } });
		Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
		Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
		Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
		Object.defineProperty(exports$1, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
		const validation_error_1 = requireValidation_error();
		const ref_error_1 = requireRef_error();
		const rules_1 = requireRules();
		const compile_1 = requireCompile$1();
		const codegen_2 = requireCodegen();
		const resolve_1 = requireResolve();
		const dataType_1 = requireDataType();
		const util_1 = requireUtil$3();
		const $dataRefSchema = require$$9;
		const uri_1 = requireUri();
		const defaultRegExp = (str, flags) => new RegExp(str, flags);
		defaultRegExp.code = "new RegExp";
		const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
		const EXT_SCOPE_NAMES = new Set([
		    "validate",
		    "serialize",
		    "parse",
		    "wrapper",
		    "root",
		    "schema",
		    "keyword",
		    "pattern",
		    "formats",
		    "validate$data",
		    "func",
		    "obj",
		    "Error",
		]);
		const removedOptions = {
		    errorDataPath: "",
		    format: "`validateFormats: false` can be used instead.",
		    nullable: '"nullable" keyword is supported by default.',
		    jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
		    extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
		    missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
		    processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
		    sourceCode: "Use option `code: {source: true}`",
		    strictDefaults: "It is default now, see option `strict`.",
		    strictKeywords: "It is default now, see option `strict`.",
		    uniqueItems: '"uniqueItems" keyword is always validated.',
		    unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
		    cache: "Map is used as cache, schema object as key.",
		    serialize: "Map is used as cache, schema object as key.",
		    ajvErrors: "It is default now.",
		};
		const deprecatedOptions = {
		    ignoreKeywordsWithRef: "",
		    jsPropertySyntax: "",
		    unicode: '"minLength"/"maxLength" account for unicode characters by default.',
		};
		const MAX_EXPRESSION = 200;
		function requiredOptions(o) {
		    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
		    const s = o.strict;
		    const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
		    const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
		    const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
		    const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
		    return {
		        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
		        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
		        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
		        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
		        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
		        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
		        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
		        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
		        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
		        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
		        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
		        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
		        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
		        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
		        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
		        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
		        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
		        uriResolver: uriResolver,
		    };
		}
		class Ajv {
		    constructor(opts = {}) {
		        this.schemas = {};
		        this.refs = {};
		        this.formats = {};
		        this._compilations = new Set();
		        this._loading = {};
		        this._cache = new Map();
		        opts = this.opts = { ...opts, ...requiredOptions(opts) };
		        const { es5, lines } = this.opts.code;
		        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
		        this.logger = getLogger(opts.logger);
		        const formatOpt = opts.validateFormats;
		        opts.validateFormats = false;
		        this.RULES = (0, rules_1.getRules)();
		        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
		        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
		        this._metaOpts = getMetaSchemaOptions.call(this);
		        if (opts.formats)
		            addInitialFormats.call(this);
		        this._addVocabularies();
		        this._addDefaultMetaSchema();
		        if (opts.keywords)
		            addInitialKeywords.call(this, opts.keywords);
		        if (typeof opts.meta == "object")
		            this.addMetaSchema(opts.meta);
		        addInitialSchemas.call(this);
		        opts.validateFormats = formatOpt;
		    }
		    _addVocabularies() {
		        this.addKeyword("$async");
		    }
		    _addDefaultMetaSchema() {
		        const { $data, meta, schemaId } = this.opts;
		        let _dataRefSchema = $dataRefSchema;
		        if (schemaId === "id") {
		            _dataRefSchema = { ...$dataRefSchema };
		            _dataRefSchema.id = _dataRefSchema.$id;
		            delete _dataRefSchema.$id;
		        }
		        if (meta && $data)
		            this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
		    }
		    defaultMeta() {
		        const { meta, schemaId } = this.opts;
		        return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
		    }
		    validate(schemaKeyRef,
		    data
		    ) {
		        let v;
		        if (typeof schemaKeyRef == "string") {
		            v = this.getSchema(schemaKeyRef);
		            if (!v)
		                throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
		        }
		        else {
		            v = this.compile(schemaKeyRef);
		        }
		        const valid = v(data);
		        if (!("$async" in v))
		            this.errors = v.errors;
		        return valid;
		    }
		    compile(schema, _meta) {
		        const sch = this._addSchema(schema, _meta);
		        return (sch.validate || this._compileSchemaEnv(sch));
		    }
		    compileAsync(schema, meta) {
		        if (typeof this.opts.loadSchema != "function") {
		            throw new Error("options.loadSchema should be a function");
		        }
		        const { loadSchema } = this.opts;
		        return runCompileAsync.call(this, schema, meta);
		        async function runCompileAsync(_schema, _meta) {
		            await loadMetaSchema.call(this, _schema.$schema);
		            const sch = this._addSchema(_schema, _meta);
		            return sch.validate || _compileAsync.call(this, sch);
		        }
		        async function loadMetaSchema($ref) {
		            if ($ref && !this.getSchema($ref)) {
		                await runCompileAsync.call(this, { $ref }, true);
		            }
		        }
		        async function _compileAsync(sch) {
		            try {
		                return this._compileSchemaEnv(sch);
		            }
		            catch (e) {
		                if (!(e instanceof ref_error_1.default))
		                    throw e;
		                checkLoaded.call(this, e);
		                await loadMissingSchema.call(this, e.missingSchema);
		                return _compileAsync.call(this, sch);
		            }
		        }
		        function checkLoaded({ missingSchema: ref, missingRef }) {
		            if (this.refs[ref]) {
		                throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
		            }
		        }
		        async function loadMissingSchema(ref) {
		            const _schema = await _loadSchema.call(this, ref);
		            if (!this.refs[ref])
		                await loadMetaSchema.call(this, _schema.$schema);
		            if (!this.refs[ref])
		                this.addSchema(_schema, ref, meta);
		        }
		        async function _loadSchema(ref) {
		            const p = this._loading[ref];
		            if (p)
		                return p;
		            try {
		                return await (this._loading[ref] = loadSchema(ref));
		            }
		            finally {
		                delete this._loading[ref];
		            }
		        }
		    }
		    addSchema(schema,
		    key,
		    _meta,
		    _validateSchema = this.opts.validateSchema
		    ) {
		        if (Array.isArray(schema)) {
		            for (const sch of schema)
		                this.addSchema(sch, undefined, _meta, _validateSchema);
		            return this;
		        }
		        let id;
		        if (typeof schema === "object") {
		            const { schemaId } = this.opts;
		            id = schema[schemaId];
		            if (id !== undefined && typeof id != "string") {
		                throw new Error(`schema ${schemaId} must be string`);
		            }
		        }
		        key = (0, resolve_1.normalizeId)(key || id);
		        this._checkUnique(key);
		        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
		        return this;
		    }
		    addMetaSchema(schema, key,
		    _validateSchema = this.opts.validateSchema
		    ) {
		        this.addSchema(schema, key, true, _validateSchema);
		        return this;
		    }
		    validateSchema(schema, throwOrLogError) {
		        if (typeof schema == "boolean")
		            return true;
		        let $schema;
		        $schema = schema.$schema;
		        if ($schema !== undefined && typeof $schema != "string") {
		            throw new Error("$schema must be a string");
		        }
		        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
		        if (!$schema) {
		            this.logger.warn("meta-schema not available");
		            this.errors = null;
		            return true;
		        }
		        const valid = this.validate($schema, schema);
		        if (!valid && throwOrLogError) {
		            const message = "schema is invalid: " + this.errorsText();
		            if (this.opts.validateSchema === "log")
		                this.logger.error(message);
		            else
		                throw new Error(message);
		        }
		        return valid;
		    }
		    getSchema(keyRef) {
		        let sch;
		        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
		            keyRef = sch;
		        if (sch === undefined) {
		            const { schemaId } = this.opts;
		            const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
		            sch = compile_1.resolveSchema.call(this, root, keyRef);
		            if (!sch)
		                return;
		            this.refs[keyRef] = sch;
		        }
		        return (sch.validate || this._compileSchemaEnv(sch));
		    }
		    removeSchema(schemaKeyRef) {
		        if (schemaKeyRef instanceof RegExp) {
		            this._removeAllSchemas(this.schemas, schemaKeyRef);
		            this._removeAllSchemas(this.refs, schemaKeyRef);
		            return this;
		        }
		        switch (typeof schemaKeyRef) {
		            case "undefined":
		                this._removeAllSchemas(this.schemas);
		                this._removeAllSchemas(this.refs);
		                this._cache.clear();
		                return this;
		            case "string": {
		                const sch = getSchEnv.call(this, schemaKeyRef);
		                if (typeof sch == "object")
		                    this._cache.delete(sch.schema);
		                delete this.schemas[schemaKeyRef];
		                delete this.refs[schemaKeyRef];
		                return this;
		            }
		            case "object": {
		                const cacheKey = schemaKeyRef;
		                this._cache.delete(cacheKey);
		                let id = schemaKeyRef[this.opts.schemaId];
		                if (id) {
		                    id = (0, resolve_1.normalizeId)(id);
		                    delete this.schemas[id];
		                    delete this.refs[id];
		                }
		                return this;
		            }
		            default:
		                throw new Error("ajv.removeSchema: invalid parameter");
		        }
		    }
		    addVocabulary(definitions) {
		        for (const def of definitions)
		            this.addKeyword(def);
		        return this;
		    }
		    addKeyword(kwdOrDef, def
		    ) {
		        let keyword;
		        if (typeof kwdOrDef == "string") {
		            keyword = kwdOrDef;
		            if (typeof def == "object") {
		                this.logger.warn("these parameters are deprecated, see docs for addKeyword");
		                def.keyword = keyword;
		            }
		        }
		        else if (typeof kwdOrDef == "object" && def === undefined) {
		            def = kwdOrDef;
		            keyword = def.keyword;
		            if (Array.isArray(keyword) && !keyword.length) {
		                throw new Error("addKeywords: keyword must be string or non-empty array");
		            }
		        }
		        else {
		            throw new Error("invalid addKeywords parameters");
		        }
		        checkKeyword.call(this, keyword, def);
		        if (!def) {
		            (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
		            return this;
		        }
		        keywordMetaschema.call(this, def);
		        const definition = {
		            ...def,
		            type: (0, dataType_1.getJSONTypes)(def.type),
		            schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
		        };
		        (0, util_1.eachItem)(keyword, definition.type.length === 0
		            ? (k) => addRule.call(this, k, definition)
		            : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
		        return this;
		    }
		    getKeyword(keyword) {
		        const rule = this.RULES.all[keyword];
		        return typeof rule == "object" ? rule.definition : !!rule;
		    }
		    removeKeyword(keyword) {
		        const { RULES } = this;
		        delete RULES.keywords[keyword];
		        delete RULES.all[keyword];
		        for (const group of RULES.rules) {
		            const i = group.rules.findIndex((rule) => rule.keyword === keyword);
		            if (i >= 0)
		                group.rules.splice(i, 1);
		        }
		        return this;
		    }
		    addFormat(name, format) {
		        if (typeof format == "string")
		            format = new RegExp(format);
		        this.formats[name] = format;
		        return this;
		    }
		    errorsText(errors = this.errors,
		    { separator = ", ", dataVar = "data" } = {}
		    ) {
		        if (!errors || errors.length === 0)
		            return "No errors";
		        return errors
		            .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
		            .reduce((text, msg) => text + separator + msg);
		    }
		    $dataMetaSchema(metaSchema, keywordsJsonPointers) {
		        const rules = this.RULES.all;
		        metaSchema = JSON.parse(JSON.stringify(metaSchema));
		        for (const jsonPointer of keywordsJsonPointers) {
		            const segments = jsonPointer.split("/").slice(1);
		            let keywords = metaSchema;
		            for (const seg of segments)
		                keywords = keywords[seg];
		            for (const key in rules) {
		                const rule = rules[key];
		                if (typeof rule != "object")
		                    continue;
		                const { $data } = rule.definition;
		                const schema = keywords[key];
		                if ($data && schema)
		                    keywords[key] = schemaOrData(schema);
		            }
		        }
		        return metaSchema;
		    }
		    _removeAllSchemas(schemas, regex) {
		        for (const keyRef in schemas) {
		            const sch = schemas[keyRef];
		            if (!regex || regex.test(keyRef)) {
		                if (typeof sch == "string") {
		                    delete schemas[keyRef];
		                }
		                else if (sch && !sch.meta) {
		                    this._cache.delete(sch.schema);
		                    delete schemas[keyRef];
		                }
		            }
		        }
		    }
		    _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
		        let id;
		        const { schemaId } = this.opts;
		        if (typeof schema == "object") {
		            id = schema[schemaId];
		        }
		        else {
		            if (this.opts.jtd)
		                throw new Error("schema must be object");
		            else if (typeof schema != "boolean")
		                throw new Error("schema must be object or boolean");
		        }
		        let sch = this._cache.get(schema);
		        if (sch !== undefined)
		            return sch;
		        baseId = (0, resolve_1.normalizeId)(id || baseId);
		        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
		        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
		        this._cache.set(sch.schema, sch);
		        if (addSchema && !baseId.startsWith("#")) {
		            if (baseId)
		                this._checkUnique(baseId);
		            this.refs[baseId] = sch;
		        }
		        if (validateSchema)
		            this.validateSchema(schema, true);
		        return sch;
		    }
		    _checkUnique(id) {
		        if (this.schemas[id] || this.refs[id]) {
		            throw new Error(`schema with key or id "${id}" already exists`);
		        }
		    }
		    _compileSchemaEnv(sch) {
		        if (sch.meta)
		            this._compileMetaSchema(sch);
		        else
		            compile_1.compileSchema.call(this, sch);
		        if (!sch.validate)
		            throw new Error("ajv implementation error");
		        return sch.validate;
		    }
		    _compileMetaSchema(sch) {
		        const currentOpts = this.opts;
		        this.opts = this._metaOpts;
		        try {
		            compile_1.compileSchema.call(this, sch);
		        }
		        finally {
		            this.opts = currentOpts;
		        }
		    }
		}
		Ajv.ValidationError = validation_error_1.default;
		Ajv.MissingRefError = ref_error_1.default;
		exports$1.default = Ajv;
		function checkOptions(checkOpts, options, msg, log = "error") {
		    for (const key in checkOpts) {
		        const opt = key;
		        if (opt in options)
		            this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
		    }
		}
		function getSchEnv(keyRef) {
		    keyRef = (0, resolve_1.normalizeId)(keyRef);
		    return this.schemas[keyRef] || this.refs[keyRef];
		}
		function addInitialSchemas() {
		    const optsSchemas = this.opts.schemas;
		    if (!optsSchemas)
		        return;
		    if (Array.isArray(optsSchemas))
		        this.addSchema(optsSchemas);
		    else
		        for (const key in optsSchemas)
		            this.addSchema(optsSchemas[key], key);
		}
		function addInitialFormats() {
		    for (const name in this.opts.formats) {
		        const format = this.opts.formats[name];
		        if (format)
		            this.addFormat(name, format);
		    }
		}
		function addInitialKeywords(defs) {
		    if (Array.isArray(defs)) {
		        this.addVocabulary(defs);
		        return;
		    }
		    this.logger.warn("keywords option as map is deprecated, pass array");
		    for (const keyword in defs) {
		        const def = defs[keyword];
		        if (!def.keyword)
		            def.keyword = keyword;
		        this.addKeyword(def);
		    }
		}
		function getMetaSchemaOptions() {
		    const metaOpts = { ...this.opts };
		    for (const opt of META_IGNORE_OPTIONS)
		        delete metaOpts[opt];
		    return metaOpts;
		}
		const noLogs = { log() { }, warn() { }, error() { } };
		function getLogger(logger) {
		    if (logger === false)
		        return noLogs;
		    if (logger === undefined)
		        return console;
		    if (logger.log && logger.warn && logger.error)
		        return logger;
		    throw new Error("logger must implement log, warn and error methods");
		}
		const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
		function checkKeyword(keyword, def) {
		    const { RULES } = this;
		    (0, util_1.eachItem)(keyword, (kwd) => {
		        if (RULES.keywords[kwd])
		            throw new Error(`Keyword ${kwd} is already defined`);
		        if (!KEYWORD_NAME.test(kwd))
		            throw new Error(`Keyword ${kwd} has invalid name`);
		    });
		    if (!def)
		        return;
		    if (def.$data && !("code" in def || "validate" in def)) {
		        throw new Error('$data keyword must have "code" or "validate" function');
		    }
		}
		function addRule(keyword, definition, dataType) {
		    var _a;
		    const post = definition === null || definition === void 0 ? void 0 : definition.post;
		    if (dataType && post)
		        throw new Error('keyword with "post" flag cannot have "type"');
		    const { RULES } = this;
		    let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
		    if (!ruleGroup) {
		        ruleGroup = { type: dataType, rules: [] };
		        RULES.rules.push(ruleGroup);
		    }
		    RULES.keywords[keyword] = true;
		    if (!definition)
		        return;
		    const rule = {
		        keyword,
		        definition: {
		            ...definition,
		            type: (0, dataType_1.getJSONTypes)(definition.type),
		            schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
		        },
		    };
		    if (definition.before)
		        addBeforeRule.call(this, ruleGroup, rule, definition.before);
		    else
		        ruleGroup.rules.push(rule);
		    RULES.all[keyword] = rule;
		    (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
		}
		function addBeforeRule(ruleGroup, rule, before) {
		    const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
		    if (i >= 0) {
		        ruleGroup.rules.splice(i, 0, rule);
		    }
		    else {
		        ruleGroup.rules.push(rule);
		        this.logger.warn(`rule ${before} is not defined`);
		    }
		}
		function keywordMetaschema(def) {
		    let { metaSchema } = def;
		    if (metaSchema === undefined)
		        return;
		    if (def.$data && this.opts.$data)
		        metaSchema = schemaOrData(metaSchema);
		    def.validateSchema = this.compile(metaSchema, true);
		}
		const $dataRef = {
		    $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
		};
		function schemaOrData(schema) {
		    return { anyOf: [schema, $dataRef] };
		} 
	} (core$3));
	return core$3;
}

var draft7 = {};

var core$2 = {};

var id = {};

var hasRequiredId;

function requireId () {
	if (hasRequiredId) return id;
	hasRequiredId = 1;
	Object.defineProperty(id, "__esModule", { value: true });
	const def = {
	    keyword: "id",
	    code() {
	        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
	    },
	};
	id.default = def;
	return id;
}

var ref = {};

var hasRequiredRef;

function requireRef () {
	if (hasRequiredRef) return ref;
	hasRequiredRef = 1;
	Object.defineProperty(ref, "__esModule", { value: true });
	ref.callRef = ref.getValidate = void 0;
	const ref_error_1 = requireRef_error();
	const code_1 = requireCode$1();
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const compile_1 = requireCompile$1();
	const util_1 = requireUtil$3();
	const def = {
	    keyword: "$ref",
	    schemaType: "string",
	    code(cxt) {
	        const { gen, schema: $ref, it } = cxt;
	        const { baseId, schemaEnv: env, validateName, opts, self } = it;
	        const { root } = env;
	        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
	            return callRootRef();
	        const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
	        if (schOrEnv === undefined)
	            throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
	        if (schOrEnv instanceof compile_1.SchemaEnv)
	            return callValidate(schOrEnv);
	        return inlineRefSchema(schOrEnv);
	        function callRootRef() {
	            if (env === root)
	                return callRef(cxt, validateName, env, env.$async);
	            const rootName = gen.scopeValue("root", { ref: root });
	            return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);
	        }
	        function callValidate(sch) {
	            const v = getValidate(cxt, sch);
	            callRef(cxt, v, sch, sch.$async);
	        }
	        function inlineRefSchema(sch) {
	            const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
	            const valid = gen.name("valid");
	            const schCxt = cxt.subschema({
	                schema: sch,
	                dataTypes: [],
	                schemaPath: codegen_1.nil,
	                topSchemaRef: schName,
	                errSchemaPath: $ref,
	            }, valid);
	            cxt.mergeEvaluated(schCxt);
	            cxt.ok(valid);
	        }
	    },
	};
	function getValidate(cxt, sch) {
	    const { gen } = cxt;
	    return sch.validate
	        ? gen.scopeValue("validate", { ref: sch.validate })
	        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`;
	}
	ref.getValidate = getValidate;
	function callRef(cxt, v, sch, $async) {
	    const { gen, it } = cxt;
	    const { allErrors, schemaEnv: env, opts } = it;
	    const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
	    if ($async)
	        callAsyncRef();
	    else
	        callSyncRef();
	    function callAsyncRef() {
	        if (!env.$async)
	            throw new Error("async schema referenced by sync schema");
	        const valid = gen.let("valid");
	        gen.try(() => {
	            gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
	            addEvaluatedFrom(v);
	            if (!allErrors)
	                gen.assign(valid, true);
	        }, (e) => {
	            gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
	            addErrorsFrom(e);
	            if (!allErrors)
	                gen.assign(valid, false);
	        });
	        cxt.ok(valid);
	    }
	    function callSyncRef() {
	        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
	    }
	    function addErrorsFrom(source) {
	        const errs = (0, codegen_1._) `${source}.errors`;
	        gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
	        gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
	    }
	    function addEvaluatedFrom(source) {
	        var _a;
	        if (!it.opts.unevaluated)
	            return;
	        const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
	        if (it.props !== true) {
	            if (schEvaluated && !schEvaluated.dynamicProps) {
	                if (schEvaluated.props !== undefined) {
	                    it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
	                }
	            }
	            else {
	                const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`);
	                it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
	            }
	        }
	        if (it.items !== true) {
	            if (schEvaluated && !schEvaluated.dynamicItems) {
	                if (schEvaluated.items !== undefined) {
	                    it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
	                }
	            }
	            else {
	                const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`);
	                it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
	            }
	        }
	    }
	}
	ref.callRef = callRef;
	ref.default = def;
	return ref;
}

var hasRequiredCore$1;

function requireCore$1 () {
	if (hasRequiredCore$1) return core$2;
	hasRequiredCore$1 = 1;
	Object.defineProperty(core$2, "__esModule", { value: true });
	const id_1 = requireId();
	const ref_1 = requireRef();
	const core = [
	    "$schema",
	    "$id",
	    "$defs",
	    "$vocabulary",
	    { keyword: "$comment" },
	    "definitions",
	    id_1.default,
	    ref_1.default,
	];
	core$2.default = core;
	return core$2;
}

var validation$1 = {};

var limitNumber = {};

var hasRequiredLimitNumber;

function requireLimitNumber () {
	if (hasRequiredLimitNumber) return limitNumber;
	hasRequiredLimitNumber = 1;
	Object.defineProperty(limitNumber, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const ops = codegen_1.operators;
	const KWDs = {
	    maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
	    minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
	    exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
	    exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
	};
	const error = {
	    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,
	    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: Object.keys(KWDs),
	    type: "number",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode } = cxt;
	        cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
	    },
	};
	limitNumber.default = def;
	return limitNumber;
}

var multipleOf = {};

var hasRequiredMultipleOf;

function requireMultipleOf () {
	if (hasRequiredMultipleOf) return multipleOf;
	hasRequiredMultipleOf = 1;
	Object.defineProperty(multipleOf, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const error = {
	    message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,
	    params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,
	};
	const def = {
	    keyword: "multipleOf",
	    type: "number",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, schemaCode, it } = cxt;
	        const prec = it.opts.multipleOfPrecision;
	        const res = gen.let("res");
	        const invalid = prec
	            ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
	            : (0, codegen_1._) `${res} !== parseInt(${res})`;
	        cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
	    },
	};
	multipleOf.default = def;
	return multipleOf;
}

var limitLength = {};

var ucs2length = {};

var hasRequiredUcs2length;

function requireUcs2length () {
	if (hasRequiredUcs2length) return ucs2length;
	hasRequiredUcs2length = 1;
	Object.defineProperty(ucs2length, "__esModule", { value: true });
	function ucs2length$1(str) {
	    const len = str.length;
	    let length = 0;
	    let pos = 0;
	    let value;
	    while (pos < len) {
	        length++;
	        value = str.charCodeAt(pos++);
	        if (value >= 0xd800 && value <= 0xdbff && pos < len) {
	            value = str.charCodeAt(pos);
	            if ((value & 0xfc00) === 0xdc00)
	                pos++;
	        }
	    }
	    return length;
	}
	ucs2length.default = ucs2length$1;
	ucs2length$1.code = 'require("ajv/dist/runtime/ucs2length").default';
	return ucs2length;
}

var hasRequiredLimitLength;

function requireLimitLength () {
	if (hasRequiredLimitLength) return limitLength;
	hasRequiredLimitLength = 1;
	Object.defineProperty(limitLength, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const ucs2length_1 = requireUcs2length();
	const error = {
	    message({ keyword, schemaCode }) {
	        const comp = keyword === "maxLength" ? "more" : "fewer";
	        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;
	    },
	    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: ["maxLength", "minLength"],
	    type: "string",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode, it } = cxt;
	        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
	        const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
	        cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);
	    },
	};
	limitLength.default = def;
	return limitLength;
}

var pattern = {};

var hasRequiredPattern;

function requirePattern () {
	if (hasRequiredPattern) return pattern;
	hasRequiredPattern = 1;
	Object.defineProperty(pattern, "__esModule", { value: true });
	const code_1 = requireCode$1();
	const codegen_1 = requireCodegen();
	const error = {
	    message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`,
	    params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,
	};
	const def = {
	    keyword: "pattern",
	    type: "string",
	    schemaType: "string",
	    $data: true,
	    error,
	    code(cxt) {
	        const { data, $data, schema, schemaCode, it } = cxt;
	        const u = it.opts.unicodeRegExp ? "u" : "";
	        const regExp = $data ? (0, codegen_1._) `(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema);
	        cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);
	    },
	};
	pattern.default = def;
	return pattern;
}

var limitProperties = {};

var hasRequiredLimitProperties;

function requireLimitProperties () {
	if (hasRequiredLimitProperties) return limitProperties;
	hasRequiredLimitProperties = 1;
	Object.defineProperty(limitProperties, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const error = {
	    message({ keyword, schemaCode }) {
	        const comp = keyword === "maxProperties" ? "more" : "fewer";
	        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;
	    },
	    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: ["maxProperties", "minProperties"],
	    type: "object",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode } = cxt;
	        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
	        cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);
	    },
	};
	limitProperties.default = def;
	return limitProperties;
}

var required = {};

var hasRequiredRequired;

function requireRequired () {
	if (hasRequiredRequired) return required;
	hasRequiredRequired = 1;
	Object.defineProperty(required, "__esModule", { value: true });
	const code_1 = requireCode$1();
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const error = {
	    message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,
	    params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,
	};
	const def = {
	    keyword: "required",
	    type: "object",
	    schemaType: "array",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, schema, schemaCode, data, $data, it } = cxt;
	        const { opts } = it;
	        if (!$data && schema.length === 0)
	            return;
	        const useLoop = schema.length >= opts.loopRequired;
	        if (it.allErrors)
	            allErrorsMode();
	        else
	            exitOnErrorMode();
	        if (opts.strictRequired) {
	            const props = cxt.parentSchema.properties;
	            const { definedProperties } = cxt.it;
	            for (const requiredKey of schema) {
	                if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {
	                    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
	                    const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
	                    (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
	                }
	            }
	        }
	        function allErrorsMode() {
	            if (useLoop || $data) {
	                cxt.block$data(codegen_1.nil, loopAllRequired);
	            }
	            else {
	                for (const prop of schema) {
	                    (0, code_1.checkReportMissingProp)(cxt, prop);
	                }
	            }
	        }
	        function exitOnErrorMode() {
	            const missing = gen.let("missing");
	            if (useLoop || $data) {
	                const valid = gen.let("valid", true);
	                cxt.block$data(valid, () => loopUntilMissing(missing, valid));
	                cxt.ok(valid);
	            }
	            else {
	                gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
	                (0, code_1.reportMissingProp)(cxt, missing);
	                gen.else();
	            }
	        }
	        function loopAllRequired() {
	            gen.forOf("prop", schemaCode, (prop) => {
	                cxt.setParams({ missingProperty: prop });
	                gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
	            });
	        }
	        function loopUntilMissing(missing, valid) {
	            cxt.setParams({ missingProperty: missing });
	            gen.forOf(missing, schemaCode, () => {
	                gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
	                gen.if((0, codegen_1.not)(valid), () => {
	                    cxt.error();
	                    gen.break();
	                });
	            }, codegen_1.nil);
	        }
	    },
	};
	required.default = def;
	return required;
}

var limitItems = {};

var hasRequiredLimitItems;

function requireLimitItems () {
	if (hasRequiredLimitItems) return limitItems;
	hasRequiredLimitItems = 1;
	Object.defineProperty(limitItems, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const error = {
	    message({ keyword, schemaCode }) {
	        const comp = keyword === "maxItems" ? "more" : "fewer";
	        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;
	    },
	    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
	};
	const def = {
	    keyword: ["maxItems", "minItems"],
	    type: "array",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { keyword, data, schemaCode } = cxt;
	        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
	        cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);
	    },
	};
	limitItems.default = def;
	return limitItems;
}

var uniqueItems = {};

var equal = {};

var hasRequiredEqual;

function requireEqual () {
	if (hasRequiredEqual) return equal;
	hasRequiredEqual = 1;
	Object.defineProperty(equal, "__esModule", { value: true });
	const equal$1 = requireFastDeepEqual();
	equal$1.code = 'require("ajv/dist/runtime/equal").default';
	equal.default = equal$1;
	return equal;
}

var hasRequiredUniqueItems;

function requireUniqueItems () {
	if (hasRequiredUniqueItems) return uniqueItems;
	hasRequiredUniqueItems = 1;
	Object.defineProperty(uniqueItems, "__esModule", { value: true });
	const dataType_1 = requireDataType();
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const equal_1 = requireEqual();
	const error = {
	    message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
	    params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,
	};
	const def = {
	    keyword: "uniqueItems",
	    type: "array",
	    schemaType: "boolean",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
	        if (!$data && !schema)
	            return;
	        const valid = gen.let("valid");
	        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
	        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);
	        cxt.ok(valid);
	        function validateUniqueItems() {
	            const i = gen.let("i", (0, codegen_1._) `${data}.length`);
	            const j = gen.let("j");
	            cxt.setParams({ i, j });
	            gen.assign(valid, true);
	            gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
	        }
	        function canOptimize() {
	            return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
	        }
	        function loopN(i, j) {
	            const item = gen.name("item");
	            const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
	            const indices = gen.const("indices", (0, codegen_1._) `{}`);
	            gen.for((0, codegen_1._) `;${i}--;`, () => {
	                gen.let(item, (0, codegen_1._) `${data}[${i}]`);
	                gen.if(wrongType, (0, codegen_1._) `continue`);
	                if (itemTypes.length > 1)
	                    gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`);
	                gen
	                    .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => {
	                    gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);
	                    cxt.error();
	                    gen.assign(valid, false).break();
	                })
	                    .code((0, codegen_1._) `${indices}[${item}] = ${i}`);
	            });
	        }
	        function loopN2(i, j) {
	            const eql = (0, util_1.useFunc)(gen, equal_1.default);
	            const outer = gen.name("outer");
	            gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {
	                cxt.error();
	                gen.assign(valid, false).break(outer);
	            })));
	        }
	    },
	};
	uniqueItems.default = def;
	return uniqueItems;
}

var _const = {};

var hasRequired_const;

function require_const () {
	if (hasRequired_const) return _const;
	hasRequired_const = 1;
	Object.defineProperty(_const, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const equal_1 = requireEqual();
	const error = {
	    message: "must be equal to constant",
	    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,
	};
	const def = {
	    keyword: "const",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, $data, schemaCode, schema } = cxt;
	        if ($data || (schema && typeof schema == "object")) {
	            cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
	        }
	        else {
	            cxt.fail((0, codegen_1._) `${schema} !== ${data}`);
	        }
	    },
	};
	_const.default = def;
	return _const;
}

var _enum = {};

var hasRequired_enum;

function require_enum () {
	if (hasRequired_enum) return _enum;
	hasRequired_enum = 1;
	Object.defineProperty(_enum, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const equal_1 = requireEqual();
	const error = {
	    message: "must be equal to one of the allowed values",
	    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
	};
	const def = {
	    keyword: "enum",
	    schemaType: "array",
	    $data: true,
	    error,
	    code(cxt) {
	        const { gen, data, $data, schema, schemaCode, it } = cxt;
	        if (!$data && schema.length === 0)
	            throw new Error("enum must have non-empty array");
	        const useLoop = schema.length >= it.opts.loopEnum;
	        let eql;
	        const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));
	        let valid;
	        if (useLoop || $data) {
	            valid = gen.let("valid");
	            cxt.block$data(valid, loopEnum);
	        }
	        else {
	            if (!Array.isArray(schema))
	                throw new Error("ajv implementation error");
	            const vSchema = gen.const("vSchema", schemaCode);
	            valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
	        }
	        cxt.pass(valid);
	        function loopEnum() {
	            gen.assign(valid, false);
	            gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
	        }
	        function equalCode(vSchema, i) {
	            const sch = schema[i];
	            return typeof sch === "object" && sch !== null
	                ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`
	                : (0, codegen_1._) `${data} === ${sch}`;
	        }
	    },
	};
	_enum.default = def;
	return _enum;
}

var hasRequiredValidation$1;

function requireValidation$1 () {
	if (hasRequiredValidation$1) return validation$1;
	hasRequiredValidation$1 = 1;
	Object.defineProperty(validation$1, "__esModule", { value: true });
	const limitNumber_1 = requireLimitNumber();
	const multipleOf_1 = requireMultipleOf();
	const limitLength_1 = requireLimitLength();
	const pattern_1 = requirePattern();
	const limitProperties_1 = requireLimitProperties();
	const required_1 = requireRequired();
	const limitItems_1 = requireLimitItems();
	const uniqueItems_1 = requireUniqueItems();
	const const_1 = require_const();
	const enum_1 = require_enum();
	const validation = [
	    limitNumber_1.default,
	    multipleOf_1.default,
	    limitLength_1.default,
	    pattern_1.default,
	    limitProperties_1.default,
	    required_1.default,
	    limitItems_1.default,
	    uniqueItems_1.default,
	    { keyword: "type", schemaType: ["string", "array"] },
	    { keyword: "nullable", schemaType: "boolean" },
	    const_1.default,
	    enum_1.default,
	];
	validation$1.default = validation;
	return validation$1;
}

var applicator = {};

var additionalItems = {};

var hasRequiredAdditionalItems;

function requireAdditionalItems () {
	if (hasRequiredAdditionalItems) return additionalItems;
	hasRequiredAdditionalItems = 1;
	Object.defineProperty(additionalItems, "__esModule", { value: true });
	additionalItems.validateAdditionalItems = void 0;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const error = {
	    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
	    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
	};
	const def = {
	    keyword: "additionalItems",
	    type: "array",
	    schemaType: ["boolean", "object"],
	    before: "uniqueItems",
	    error,
	    code(cxt) {
	        const { parentSchema, it } = cxt;
	        const { items } = parentSchema;
	        if (!Array.isArray(items)) {
	            (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
	            return;
	        }
	        validateAdditionalItems(cxt, items);
	    },
	};
	function validateAdditionalItems(cxt, items) {
	    const { gen, schema, data, keyword, it } = cxt;
	    it.items = true;
	    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	    if (schema === false) {
	        cxt.setParams({ len: items.length });
	        cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);
	    }
	    else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
	        const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`);
	        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
	        cxt.ok(valid);
	    }
	    function validateItems(valid) {
	        gen.forRange("i", items.length, len, (i) => {
	            cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
	            if (!it.allErrors)
	                gen.if((0, codegen_1.not)(valid), () => gen.break());
	        });
	    }
	}
	additionalItems.validateAdditionalItems = validateAdditionalItems;
	additionalItems.default = def;
	return additionalItems;
}

var prefixItems = {};

var items = {};

var hasRequiredItems;

function requireItems () {
	if (hasRequiredItems) return items;
	hasRequiredItems = 1;
	Object.defineProperty(items, "__esModule", { value: true });
	items.validateTuple = void 0;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const code_1 = requireCode$1();
	const def = {
	    keyword: "items",
	    type: "array",
	    schemaType: ["object", "array", "boolean"],
	    before: "uniqueItems",
	    code(cxt) {
	        const { schema, it } = cxt;
	        if (Array.isArray(schema))
	            return validateTuple(cxt, "additionalItems", schema);
	        it.items = true;
	        if ((0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        cxt.ok((0, code_1.validateArray)(cxt));
	    },
	};
	function validateTuple(cxt, extraItems, schArr = cxt.schema) {
	    const { gen, parentSchema, data, keyword, it } = cxt;
	    checkStrictTuple(parentSchema);
	    if (it.opts.unevaluated && schArr.length && it.items !== true) {
	        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
	    }
	    const valid = gen.name("valid");
	    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	    schArr.forEach((sch, i) => {
	        if ((0, util_1.alwaysValidSchema)(it, sch))
	            return;
	        gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({
	            keyword,
	            schemaProp: i,
	            dataProp: i,
	        }, valid));
	        cxt.ok(valid);
	    });
	    function checkStrictTuple(sch) {
	        const { opts, errSchemaPath } = it;
	        const l = schArr.length;
	        const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
	        if (opts.strictTuples && !fullTuple) {
	            const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
	            (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
	        }
	    }
	}
	items.validateTuple = validateTuple;
	items.default = def;
	return items;
}

var hasRequiredPrefixItems;

function requirePrefixItems () {
	if (hasRequiredPrefixItems) return prefixItems;
	hasRequiredPrefixItems = 1;
	Object.defineProperty(prefixItems, "__esModule", { value: true });
	const items_1 = requireItems();
	const def = {
	    keyword: "prefixItems",
	    type: "array",
	    schemaType: ["array"],
	    before: "uniqueItems",
	    code: (cxt) => (0, items_1.validateTuple)(cxt, "items"),
	};
	prefixItems.default = def;
	return prefixItems;
}

var items2020 = {};

var hasRequiredItems2020;

function requireItems2020 () {
	if (hasRequiredItems2020) return items2020;
	hasRequiredItems2020 = 1;
	Object.defineProperty(items2020, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const code_1 = requireCode$1();
	const additionalItems_1 = requireAdditionalItems();
	const error = {
	    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
	    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
	};
	const def = {
	    keyword: "items",
	    type: "array",
	    schemaType: ["object", "boolean"],
	    before: "uniqueItems",
	    error,
	    code(cxt) {
	        const { schema, parentSchema, it } = cxt;
	        const { prefixItems } = parentSchema;
	        it.items = true;
	        if ((0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        if (prefixItems)
	            (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
	        else
	            cxt.ok((0, code_1.validateArray)(cxt));
	    },
	};
	items2020.default = def;
	return items2020;
}

var contains$1 = {};

var hasRequiredContains;

function requireContains () {
	if (hasRequiredContains) return contains$1;
	hasRequiredContains = 1;
	Object.defineProperty(contains$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const error = {
	    message: ({ params: { min, max } }) => max === undefined
	        ? (0, codegen_1.str) `must contain at least ${min} valid item(s)`
	        : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,
	    params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,
	};
	const def = {
	    keyword: "contains",
	    type: "array",
	    schemaType: ["object", "boolean"],
	    before: "uniqueItems",
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, schema, parentSchema, data, it } = cxt;
	        let min;
	        let max;
	        const { minContains, maxContains } = parentSchema;
	        if (it.opts.next) {
	            min = minContains === undefined ? 1 : minContains;
	            max = maxContains;
	        }
	        else {
	            min = 1;
	        }
	        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	        cxt.setParams({ min, max });
	        if (max === undefined && min === 0) {
	            (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
	            return;
	        }
	        if (max !== undefined && min > max) {
	            (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
	            cxt.fail();
	            return;
	        }
	        if ((0, util_1.alwaysValidSchema)(it, schema)) {
	            let cond = (0, codegen_1._) `${len} >= ${min}`;
	            if (max !== undefined)
	                cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;
	            cxt.pass(cond);
	            return;
	        }
	        it.items = true;
	        const valid = gen.name("valid");
	        if (max === undefined && min === 1) {
	            validateItems(valid, () => gen.if(valid, () => gen.break()));
	        }
	        else if (min === 0) {
	            gen.let(valid, true);
	            if (max !== undefined)
	                gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);
	        }
	        else {
	            gen.let(valid, false);
	            validateItemsWithCount();
	        }
	        cxt.result(valid, () => cxt.reset());
	        function validateItemsWithCount() {
	            const schValid = gen.name("_valid");
	            const count = gen.let("count", 0);
	            validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
	        }
	        function validateItems(_valid, block) {
	            gen.forRange("i", 0, len, (i) => {
	                cxt.subschema({
	                    keyword: "contains",
	                    dataProp: i,
	                    dataPropType: util_1.Type.Num,
	                    compositeRule: true,
	                }, _valid);
	                block();
	            });
	        }
	        function checkLimits(count) {
	            gen.code((0, codegen_1._) `${count}++`);
	            if (max === undefined) {
	                gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());
	            }
	            else {
	                gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());
	                if (min === 1)
	                    gen.assign(valid, true);
	                else
	                    gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));
	            }
	        }
	    },
	};
	contains$1.default = def;
	return contains$1;
}

var dependencies = {};

var hasRequiredDependencies;

function requireDependencies () {
	if (hasRequiredDependencies) return dependencies;
	hasRequiredDependencies = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.validateSchemaDeps = exports$1.validatePropertyDeps = exports$1.error = void 0;
		const codegen_1 = requireCodegen();
		const util_1 = requireUtil$3();
		const code_1 = requireCode$1();
		exports$1.error = {
		    message: ({ params: { property, depsCount, deps } }) => {
		        const property_ies = depsCount === 1 ? "property" : "properties";
		        return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;
		    },
		    params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`,
		};
		const def = {
		    keyword: "dependencies",
		    type: "object",
		    schemaType: "object",
		    error: exports$1.error,
		    code(cxt) {
		        const [propDeps, schDeps] = splitDependencies(cxt);
		        validatePropertyDeps(cxt, propDeps);
		        validateSchemaDeps(cxt, schDeps);
		    },
		};
		function splitDependencies({ schema }) {
		    const propertyDeps = {};
		    const schemaDeps = {};
		    for (const key in schema) {
		        if (key === "__proto__")
		            continue;
		        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
		        deps[key] = schema[key];
		    }
		    return [propertyDeps, schemaDeps];
		}
		function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
		    const { gen, data, it } = cxt;
		    if (Object.keys(propertyDeps).length === 0)
		        return;
		    const missing = gen.let("missing");
		    for (const prop in propertyDeps) {
		        const deps = propertyDeps[prop];
		        if (deps.length === 0)
		            continue;
		        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
		        cxt.setParams({
		            property: prop,
		            depsCount: deps.length,
		            deps: deps.join(", "),
		        });
		        if (it.allErrors) {
		            gen.if(hasProperty, () => {
		                for (const depProp of deps) {
		                    (0, code_1.checkReportMissingProp)(cxt, depProp);
		                }
		            });
		        }
		        else {
		            gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
		            (0, code_1.reportMissingProp)(cxt, missing);
		            gen.else();
		        }
		    }
		}
		exports$1.validatePropertyDeps = validatePropertyDeps;
		function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
		    const { gen, data, keyword, it } = cxt;
		    const valid = gen.name("valid");
		    for (const prop in schemaDeps) {
		        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
		            continue;
		        gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
		            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
		            cxt.mergeValidEvaluated(schCxt, valid);
		        }, () => gen.var(valid, true)
		        );
		        cxt.ok(valid);
		    }
		}
		exports$1.validateSchemaDeps = validateSchemaDeps;
		exports$1.default = def; 
	} (dependencies));
	return dependencies;
}

var propertyNames = {};

var hasRequiredPropertyNames;

function requirePropertyNames () {
	if (hasRequiredPropertyNames) return propertyNames;
	hasRequiredPropertyNames = 1;
	Object.defineProperty(propertyNames, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const error = {
	    message: "property name must be valid",
	    params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,
	};
	const def = {
	    keyword: "propertyNames",
	    type: "object",
	    schemaType: ["object", "boolean"],
	    error,
	    code(cxt) {
	        const { gen, schema, data, it } = cxt;
	        if ((0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        const valid = gen.name("valid");
	        gen.forIn("key", data, (key) => {
	            cxt.setParams({ propertyName: key });
	            cxt.subschema({
	                keyword: "propertyNames",
	                data: key,
	                dataTypes: ["string"],
	                propertyName: key,
	                compositeRule: true,
	            }, valid);
	            gen.if((0, codegen_1.not)(valid), () => {
	                cxt.error(true);
	                if (!it.allErrors)
	                    gen.break();
	            });
	        });
	        cxt.ok(valid);
	    },
	};
	propertyNames.default = def;
	return propertyNames;
}

var additionalProperties = {};

var hasRequiredAdditionalProperties;

function requireAdditionalProperties () {
	if (hasRequiredAdditionalProperties) return additionalProperties;
	hasRequiredAdditionalProperties = 1;
	Object.defineProperty(additionalProperties, "__esModule", { value: true });
	const code_1 = requireCode$1();
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const util_1 = requireUtil$3();
	const error = {
	    message: "must NOT have additional properties",
	    params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,
	};
	const def = {
	    keyword: "additionalProperties",
	    type: ["object"],
	    schemaType: ["boolean", "object"],
	    allowUndefined: true,
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
	        if (!errsCount)
	            throw new Error("ajv implementation error");
	        const { allErrors, opts } = it;
	        it.props = true;
	        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
	            return;
	        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
	        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
	        checkAdditionalProperties();
	        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
	        function checkAdditionalProperties() {
	            gen.forIn("key", data, (key) => {
	                if (!props.length && !patProps.length)
	                    additionalPropertyCode(key);
	                else
	                    gen.if(isAdditional(key), () => additionalPropertyCode(key));
	            });
	        }
	        function isAdditional(key) {
	            let definedProp;
	            if (props.length > 8) {
	                const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
	                definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
	            }
	            else if (props.length) {
	                definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));
	            }
	            else {
	                definedProp = codegen_1.nil;
	            }
	            if (patProps.length) {
	                definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
	            }
	            return (0, codegen_1.not)(definedProp);
	        }
	        function deleteAdditional(key) {
	            gen.code((0, codegen_1._) `delete ${data}[${key}]`);
	        }
	        function additionalPropertyCode(key) {
	            if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
	                deleteAdditional(key);
	                return;
	            }
	            if (schema === false) {
	                cxt.setParams({ additionalProperty: key });
	                cxt.error();
	                if (!allErrors)
	                    gen.break();
	                return;
	            }
	            if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
	                const valid = gen.name("valid");
	                if (opts.removeAdditional === "failing") {
	                    applyAdditionalSchema(key, valid, false);
	                    gen.if((0, codegen_1.not)(valid), () => {
	                        cxt.reset();
	                        deleteAdditional(key);
	                    });
	                }
	                else {
	                    applyAdditionalSchema(key, valid);
	                    if (!allErrors)
	                        gen.if((0, codegen_1.not)(valid), () => gen.break());
	                }
	            }
	        }
	        function applyAdditionalSchema(key, valid, errors) {
	            const subschema = {
	                keyword: "additionalProperties",
	                dataProp: key,
	                dataPropType: util_1.Type.Str,
	            };
	            if (errors === false) {
	                Object.assign(subschema, {
	                    compositeRule: true,
	                    createErrors: false,
	                    allErrors: false,
	                });
	            }
	            cxt.subschema(subschema, valid);
	        }
	    },
	};
	additionalProperties.default = def;
	return additionalProperties;
}

var properties$1 = {};

var hasRequiredProperties;

function requireProperties () {
	if (hasRequiredProperties) return properties$1;
	hasRequiredProperties = 1;
	Object.defineProperty(properties$1, "__esModule", { value: true });
	const validate_1 = requireValidate();
	const code_1 = requireCode$1();
	const util_1 = requireUtil$3();
	const additionalProperties_1 = requireAdditionalProperties();
	const def = {
	    keyword: "properties",
	    type: "object",
	    schemaType: "object",
	    code(cxt) {
	        const { gen, schema, parentSchema, data, it } = cxt;
	        if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
	            additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
	        }
	        const allProps = (0, code_1.allSchemaProperties)(schema);
	        for (const prop of allProps) {
	            it.definedProperties.add(prop);
	        }
	        if (it.opts.unevaluated && allProps.length && it.props !== true) {
	            it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
	        }
	        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
	        if (properties.length === 0)
	            return;
	        const valid = gen.name("valid");
	        for (const prop of properties) {
	            if (hasDefault(prop)) {
	                applyPropertySchema(prop);
	            }
	            else {
	                gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
	                applyPropertySchema(prop);
	                if (!it.allErrors)
	                    gen.else().var(valid, true);
	                gen.endIf();
	            }
	            cxt.it.definedProperties.add(prop);
	            cxt.ok(valid);
	        }
	        function hasDefault(prop) {
	            return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;
	        }
	        function applyPropertySchema(prop) {
	            cxt.subschema({
	                keyword: "properties",
	                schemaProp: prop,
	                dataProp: prop,
	            }, valid);
	        }
	    },
	};
	properties$1.default = def;
	return properties$1;
}

var patternProperties = {};

var hasRequiredPatternProperties;

function requirePatternProperties () {
	if (hasRequiredPatternProperties) return patternProperties;
	hasRequiredPatternProperties = 1;
	Object.defineProperty(patternProperties, "__esModule", { value: true });
	const code_1 = requireCode$1();
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const util_2 = requireUtil$3();
	const def = {
	    keyword: "patternProperties",
	    type: "object",
	    schemaType: "object",
	    code(cxt) {
	        const { gen, schema, data, parentSchema, it } = cxt;
	        const { opts } = it;
	        const patterns = (0, code_1.allSchemaProperties)(schema);
	        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
	        if (patterns.length === 0 ||
	            (alwaysValidPatterns.length === patterns.length &&
	                (!it.opts.unevaluated || it.props === true))) {
	            return;
	        }
	        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
	        const valid = gen.name("valid");
	        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
	            it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
	        }
	        const { props } = it;
	        validatePatternProperties();
	        function validatePatternProperties() {
	            for (const pat of patterns) {
	                if (checkProperties)
	                    checkMatchingProperties(pat);
	                if (it.allErrors) {
	                    validateProperties(pat);
	                }
	                else {
	                    gen.var(valid, true);
	                    validateProperties(pat);
	                    gen.if(valid);
	                }
	            }
	        }
	        function checkMatchingProperties(pat) {
	            for (const prop in checkProperties) {
	                if (new RegExp(pat).test(prop)) {
	                    (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
	                }
	            }
	        }
	        function validateProperties(pat) {
	            gen.forIn("key", data, (key) => {
	                gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
	                    const alwaysValid = alwaysValidPatterns.includes(pat);
	                    if (!alwaysValid) {
	                        cxt.subschema({
	                            keyword: "patternProperties",
	                            schemaProp: pat,
	                            dataProp: key,
	                            dataPropType: util_2.Type.Str,
	                        }, valid);
	                    }
	                    if (it.opts.unevaluated && props !== true) {
	                        gen.assign((0, codegen_1._) `${props}[${key}]`, true);
	                    }
	                    else if (!alwaysValid && !it.allErrors) {
	                        gen.if((0, codegen_1.not)(valid), () => gen.break());
	                    }
	                });
	            });
	        }
	    },
	};
	patternProperties.default = def;
	return patternProperties;
}

var not = {};

var hasRequiredNot;

function requireNot () {
	if (hasRequiredNot) return not;
	hasRequiredNot = 1;
	Object.defineProperty(not, "__esModule", { value: true });
	const util_1 = requireUtil$3();
	const def = {
	    keyword: "not",
	    schemaType: ["object", "boolean"],
	    trackErrors: true,
	    code(cxt) {
	        const { gen, schema, it } = cxt;
	        if ((0, util_1.alwaysValidSchema)(it, schema)) {
	            cxt.fail();
	            return;
	        }
	        const valid = gen.name("valid");
	        cxt.subschema({
	            keyword: "not",
	            compositeRule: true,
	            createErrors: false,
	            allErrors: false,
	        }, valid);
	        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
	    },
	    error: { message: "must NOT be valid" },
	};
	not.default = def;
	return not;
}

var anyOf = {};

var hasRequiredAnyOf;

function requireAnyOf () {
	if (hasRequiredAnyOf) return anyOf;
	hasRequiredAnyOf = 1;
	Object.defineProperty(anyOf, "__esModule", { value: true });
	const code_1 = requireCode$1();
	const def = {
	    keyword: "anyOf",
	    schemaType: "array",
	    trackErrors: true,
	    code: code_1.validateUnion,
	    error: { message: "must match a schema in anyOf" },
	};
	anyOf.default = def;
	return anyOf;
}

var oneOf = {};

var hasRequiredOneOf;

function requireOneOf () {
	if (hasRequiredOneOf) return oneOf;
	hasRequiredOneOf = 1;
	Object.defineProperty(oneOf, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const error = {
	    message: "must match exactly one schema in oneOf",
	    params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,
	};
	const def = {
	    keyword: "oneOf",
	    schemaType: "array",
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, schema, parentSchema, it } = cxt;
	        if (!Array.isArray(schema))
	            throw new Error("ajv implementation error");
	        if (it.opts.discriminator && parentSchema.discriminator)
	            return;
	        const schArr = schema;
	        const valid = gen.let("valid", false);
	        const passing = gen.let("passing", null);
	        const schValid = gen.name("_valid");
	        cxt.setParams({ passing });
	        gen.block(validateOneOf);
	        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
	        function validateOneOf() {
	            schArr.forEach((sch, i) => {
	                let schCxt;
	                if ((0, util_1.alwaysValidSchema)(it, sch)) {
	                    gen.var(schValid, true);
	                }
	                else {
	                    schCxt = cxt.subschema({
	                        keyword: "oneOf",
	                        schemaProp: i,
	                        compositeRule: true,
	                    }, schValid);
	                }
	                if (i > 0) {
	                    gen
	                        .if((0, codegen_1._) `${schValid} && ${valid}`)
	                        .assign(valid, false)
	                        .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)
	                        .else();
	                }
	                gen.if(schValid, () => {
	                    gen.assign(valid, true);
	                    gen.assign(passing, i);
	                    if (schCxt)
	                        cxt.mergeEvaluated(schCxt, codegen_1.Name);
	                });
	            });
	        }
	    },
	};
	oneOf.default = def;
	return oneOf;
}

var allOf = {};

var hasRequiredAllOf;

function requireAllOf () {
	if (hasRequiredAllOf) return allOf;
	hasRequiredAllOf = 1;
	Object.defineProperty(allOf, "__esModule", { value: true });
	const util_1 = requireUtil$3();
	const def = {
	    keyword: "allOf",
	    schemaType: "array",
	    code(cxt) {
	        const { gen, schema, it } = cxt;
	        if (!Array.isArray(schema))
	            throw new Error("ajv implementation error");
	        const valid = gen.name("valid");
	        schema.forEach((sch, i) => {
	            if ((0, util_1.alwaysValidSchema)(it, sch))
	                return;
	            const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
	            cxt.ok(valid);
	            cxt.mergeEvaluated(schCxt);
	        });
	    },
	};
	allOf.default = def;
	return allOf;
}

var _if = {};

var hasRequired_if;

function require_if () {
	if (hasRequired_if) return _if;
	hasRequired_if = 1;
	Object.defineProperty(_if, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil$3();
	const error = {
	    message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`,
	    params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,
	};
	const def = {
	    keyword: "if",
	    schemaType: ["object", "boolean"],
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, parentSchema, it } = cxt;
	        if (parentSchema.then === undefined && parentSchema.else === undefined) {
	            (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
	        }
	        const hasThen = hasSchema(it, "then");
	        const hasElse = hasSchema(it, "else");
	        if (!hasThen && !hasElse)
	            return;
	        const valid = gen.let("valid", true);
	        const schValid = gen.name("_valid");
	        validateIf();
	        cxt.reset();
	        if (hasThen && hasElse) {
	            const ifClause = gen.let("ifClause");
	            cxt.setParams({ ifClause });
	            gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
	        }
	        else if (hasThen) {
	            gen.if(schValid, validateClause("then"));
	        }
	        else {
	            gen.if((0, codegen_1.not)(schValid), validateClause("else"));
	        }
	        cxt.pass(valid, () => cxt.error(true));
	        function validateIf() {
	            const schCxt = cxt.subschema({
	                keyword: "if",
	                compositeRule: true,
	                createErrors: false,
	                allErrors: false,
	            }, schValid);
	            cxt.mergeEvaluated(schCxt);
	        }
	        function validateClause(keyword, ifClause) {
	            return () => {
	                const schCxt = cxt.subschema({ keyword }, schValid);
	                gen.assign(valid, schValid);
	                cxt.mergeValidEvaluated(schCxt, valid);
	                if (ifClause)
	                    gen.assign(ifClause, (0, codegen_1._) `${keyword}`);
	                else
	                    cxt.setParams({ ifClause: keyword });
	            };
	        }
	    },
	};
	function hasSchema(it, keyword) {
	    const schema = it.schema[keyword];
	    return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);
	}
	_if.default = def;
	return _if;
}

var thenElse = {};

var hasRequiredThenElse;

function requireThenElse () {
	if (hasRequiredThenElse) return thenElse;
	hasRequiredThenElse = 1;
	Object.defineProperty(thenElse, "__esModule", { value: true });
	const util_1 = requireUtil$3();
	const def = {
	    keyword: ["then", "else"],
	    schemaType: ["object", "boolean"],
	    code({ keyword, parentSchema, it }) {
	        if (parentSchema.if === undefined)
	            (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
	    },
	};
	thenElse.default = def;
	return thenElse;
}

var hasRequiredApplicator;

function requireApplicator () {
	if (hasRequiredApplicator) return applicator;
	hasRequiredApplicator = 1;
	Object.defineProperty(applicator, "__esModule", { value: true });
	const additionalItems_1 = requireAdditionalItems();
	const prefixItems_1 = requirePrefixItems();
	const items_1 = requireItems();
	const items2020_1 = requireItems2020();
	const contains_1 = requireContains();
	const dependencies_1 = requireDependencies();
	const propertyNames_1 = requirePropertyNames();
	const additionalProperties_1 = requireAdditionalProperties();
	const properties_1 = requireProperties();
	const patternProperties_1 = requirePatternProperties();
	const not_1 = requireNot();
	const anyOf_1 = requireAnyOf();
	const oneOf_1 = requireOneOf();
	const allOf_1 = requireAllOf();
	const if_1 = require_if();
	const thenElse_1 = requireThenElse();
	function getApplicator(draft2020 = false) {
	    const applicator = [
	        not_1.default,
	        anyOf_1.default,
	        oneOf_1.default,
	        allOf_1.default,
	        if_1.default,
	        thenElse_1.default,
	        propertyNames_1.default,
	        additionalProperties_1.default,
	        dependencies_1.default,
	        properties_1.default,
	        patternProperties_1.default,
	    ];
	    if (draft2020)
	        applicator.push(prefixItems_1.default, items2020_1.default);
	    else
	        applicator.push(additionalItems_1.default, items_1.default);
	    applicator.push(contains_1.default);
	    return applicator;
	}
	applicator.default = getApplicator;
	return applicator;
}

var format$2 = {};

var format$1 = {};

var hasRequiredFormat$1;

function requireFormat$1 () {
	if (hasRequiredFormat$1) return format$1;
	hasRequiredFormat$1 = 1;
	Object.defineProperty(format$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const error = {
	    message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`,
	    params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,
	};
	const def = {
	    keyword: "format",
	    type: ["number", "string"],
	    schemaType: "string",
	    $data: true,
	    error,
	    code(cxt, ruleType) {
	        const { gen, data, $data, schema, schemaCode, it } = cxt;
	        const { opts, errSchemaPath, schemaEnv, self } = it;
	        if (!opts.validateFormats)
	            return;
	        if ($data)
	            validate$DataFormat();
	        else
	            validateFormat();
	        function validate$DataFormat() {
	            const fmts = gen.scopeValue("formats", {
	                ref: self.formats,
	                code: opts.code.formats,
	            });
	            const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`);
	            const fType = gen.let("fType");
	            const format = gen.let("format");
	            gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef));
	            cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
	            function unknownFmt() {
	                if (opts.strictSchema === false)
	                    return codegen_1.nil;
	                return (0, codegen_1._) `${schemaCode} && !${format}`;
	            }
	            function invalidFmt() {
	                const callFormat = schemaEnv.$async
	                    ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
	                    : (0, codegen_1._) `${format}(${data})`;
	                const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
	                return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
	            }
	        }
	        function validateFormat() {
	            const formatDef = self.formats[schema];
	            if (!formatDef) {
	                unknownFormat();
	                return;
	            }
	            if (formatDef === true)
	                return;
	            const [fmtType, format, fmtRef] = getFormat(formatDef);
	            if (fmtType === ruleType)
	                cxt.pass(validCondition());
	            function unknownFormat() {
	                if (opts.strictSchema === false) {
	                    self.logger.warn(unknownMsg());
	                    return;
	                }
	                throw new Error(unknownMsg());
	                function unknownMsg() {
	                    return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
	                }
	            }
	            function getFormat(fmtDef) {
	                const code = fmtDef instanceof RegExp
	                    ? (0, codegen_1.regexpCode)(fmtDef)
	                    : opts.code.formats
	                        ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`
	                        : undefined;
	                const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
	                if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
	                    return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];
	                }
	                return ["string", fmtDef, fmt];
	            }
	            function validCondition() {
	                if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
	                    if (!schemaEnv.$async)
	                        throw new Error("async format in sync schema");
	                    return (0, codegen_1._) `await ${fmtRef}(${data})`;
	                }
	                return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;
	            }
	        }
	    },
	};
	format$1.default = def;
	return format$1;
}

var hasRequiredFormat;

function requireFormat () {
	if (hasRequiredFormat) return format$2;
	hasRequiredFormat = 1;
	Object.defineProperty(format$2, "__esModule", { value: true });
	const format_1 = requireFormat$1();
	const format = [format_1.default];
	format$2.default = format;
	return format$2;
}

var metadata = {};

var hasRequiredMetadata;

function requireMetadata () {
	if (hasRequiredMetadata) return metadata;
	hasRequiredMetadata = 1;
	Object.defineProperty(metadata, "__esModule", { value: true });
	metadata.contentVocabulary = metadata.metadataVocabulary = void 0;
	metadata.metadataVocabulary = [
	    "title",
	    "description",
	    "default",
	    "deprecated",
	    "readOnly",
	    "writeOnly",
	    "examples",
	];
	metadata.contentVocabulary = [
	    "contentMediaType",
	    "contentEncoding",
	    "contentSchema",
	];
	return metadata;
}

var hasRequiredDraft7;

function requireDraft7 () {
	if (hasRequiredDraft7) return draft7;
	hasRequiredDraft7 = 1;
	Object.defineProperty(draft7, "__esModule", { value: true });
	const core_1 = requireCore$1();
	const validation_1 = requireValidation$1();
	const applicator_1 = requireApplicator();
	const format_1 = requireFormat();
	const metadata_1 = requireMetadata();
	const draft7Vocabularies = [
	    core_1.default,
	    validation_1.default,
	    (0, applicator_1.default)(),
	    format_1.default,
	    metadata_1.metadataVocabulary,
	    metadata_1.contentVocabulary,
	];
	draft7.default = draft7Vocabularies;
	return draft7;
}

var discriminator = {};

var types$6 = {};

var hasRequiredTypes$2;

function requireTypes$2 () {
	if (hasRequiredTypes$2) return types$6;
	hasRequiredTypes$2 = 1;
	Object.defineProperty(types$6, "__esModule", { value: true });
	types$6.DiscrError = void 0;
	var DiscrError;
	(function (DiscrError) {
	    DiscrError["Tag"] = "tag";
	    DiscrError["Mapping"] = "mapping";
	})(DiscrError || (types$6.DiscrError = DiscrError = {}));
	return types$6;
}

var hasRequiredDiscriminator;

function requireDiscriminator () {
	if (hasRequiredDiscriminator) return discriminator;
	hasRequiredDiscriminator = 1;
	Object.defineProperty(discriminator, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const types_1 = requireTypes$2();
	const compile_1 = requireCompile$1();
	const ref_error_1 = requireRef_error();
	const util_1 = requireUtil$3();
	const error = {
	    message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag
	        ? `tag "${tagName}" must be string`
	        : `value of tag "${tagName}" must be in oneOf`,
	    params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
	};
	const def = {
	    keyword: "discriminator",
	    type: "object",
	    schemaType: "object",
	    error,
	    code(cxt) {
	        const { gen, data, schema, parentSchema, it } = cxt;
	        const { oneOf } = parentSchema;
	        if (!it.opts.discriminator) {
	            throw new Error("discriminator: requires discriminator option");
	        }
	        const tagName = schema.propertyName;
	        if (typeof tagName != "string")
	            throw new Error("discriminator: requires propertyName");
	        if (schema.mapping)
	            throw new Error("discriminator: mapping is not supported");
	        if (!oneOf)
	            throw new Error("discriminator: requires oneOf keyword");
	        const valid = gen.let("valid", false);
	        const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);
	        gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
	        cxt.ok(valid);
	        function validateMapping() {
	            const mapping = getMapping();
	            gen.if(false);
	            for (const tagValue in mapping) {
	                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
	                gen.assign(valid, applyTagSchema(mapping[tagValue]));
	            }
	            gen.else();
	            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
	            gen.endIf();
	        }
	        function applyTagSchema(schemaProp) {
	            const _valid = gen.name("valid");
	            const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
	            cxt.mergeEvaluated(schCxt, codegen_1.Name);
	            return _valid;
	        }
	        function getMapping() {
	            var _a;
	            const oneOfMapping = {};
	            const topRequired = hasRequired(parentSchema);
	            let tagRequired = true;
	            for (let i = 0; i < oneOf.length; i++) {
	                let sch = oneOf[i];
	                if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
	                    const ref = sch.$ref;
	                    sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
	                    if (sch instanceof compile_1.SchemaEnv)
	                        sch = sch.schema;
	                    if (sch === undefined)
	                        throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
	                }
	                const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
	                if (typeof propSch != "object") {
	                    throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
	                }
	                tagRequired = tagRequired && (topRequired || hasRequired(sch));
	                addMappings(propSch, i);
	            }
	            if (!tagRequired)
	                throw new Error(`discriminator: "${tagName}" must be required`);
	            return oneOfMapping;
	            function hasRequired({ required }) {
	                return Array.isArray(required) && required.includes(tagName);
	            }
	            function addMappings(sch, i) {
	                if (sch.const) {
	                    addMapping(sch.const, i);
	                }
	                else if (sch.enum) {
	                    for (const tagValue of sch.enum) {
	                        addMapping(tagValue, i);
	                    }
	                }
	                else {
	                    throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
	                }
	            }
	            function addMapping(tagValue, i) {
	                if (typeof tagValue != "string" || tagValue in oneOfMapping) {
	                    throw new Error(`discriminator: "${tagName}" values must be unique strings`);
	                }
	                oneOfMapping[tagValue] = i;
	            }
	        }
	    },
	};
	discriminator.default = def;
	return discriminator;
}

var $schema = "http://json-schema.org/draft-07/schema#";
var $id = "http://json-schema.org/draft-07/schema#";
var title = "Core schema meta-schema";
var definitions = {
	schemaArray: {
		type: "array",
		minItems: 1,
		items: {
			$ref: "#"
		}
	},
	nonNegativeInteger: {
		type: "integer",
		minimum: 0
	},
	nonNegativeIntegerDefault0: {
		allOf: [
			{
				$ref: "#/definitions/nonNegativeInteger"
			},
			{
				"default": 0
			}
		]
	},
	simpleTypes: {
		"enum": [
			"array",
			"boolean",
			"integer",
			"null",
			"number",
			"object",
			"string"
		]
	},
	stringArray: {
		type: "array",
		items: {
			type: "string"
		},
		uniqueItems: true,
		"default": [
		]
	}
};
var type = [
	"object",
	"boolean"
];
var properties = {
	$id: {
		type: "string",
		format: "uri-reference"
	},
	$schema: {
		type: "string",
		format: "uri"
	},
	$ref: {
		type: "string",
		format: "uri-reference"
	},
	$comment: {
		type: "string"
	},
	title: {
		type: "string"
	},
	description: {
		type: "string"
	},
	"default": true,
	readOnly: {
		type: "boolean",
		"default": false
	},
	examples: {
		type: "array",
		items: true
	},
	multipleOf: {
		type: "number",
		exclusiveMinimum: 0
	},
	maximum: {
		type: "number"
	},
	exclusiveMaximum: {
		type: "number"
	},
	minimum: {
		type: "number"
	},
	exclusiveMinimum: {
		type: "number"
	},
	maxLength: {
		$ref: "#/definitions/nonNegativeInteger"
	},
	minLength: {
		$ref: "#/definitions/nonNegativeIntegerDefault0"
	},
	pattern: {
		type: "string",
		format: "regex"
	},
	additionalItems: {
		$ref: "#"
	},
	items: {
		anyOf: [
			{
				$ref: "#"
			},
			{
				$ref: "#/definitions/schemaArray"
			}
		],
		"default": true
	},
	maxItems: {
		$ref: "#/definitions/nonNegativeInteger"
	},
	minItems: {
		$ref: "#/definitions/nonNegativeIntegerDefault0"
	},
	uniqueItems: {
		type: "boolean",
		"default": false
	},
	contains: {
		$ref: "#"
	},
	maxProperties: {
		$ref: "#/definitions/nonNegativeInteger"
	},
	minProperties: {
		$ref: "#/definitions/nonNegativeIntegerDefault0"
	},
	required: {
		$ref: "#/definitions/stringArray"
	},
	additionalProperties: {
		$ref: "#"
	},
	definitions: {
		type: "object",
		additionalProperties: {
			$ref: "#"
		},
		"default": {
		}
	},
	properties: {
		type: "object",
		additionalProperties: {
			$ref: "#"
		},
		"default": {
		}
	},
	patternProperties: {
		type: "object",
		additionalProperties: {
			$ref: "#"
		},
		propertyNames: {
			format: "regex"
		},
		"default": {
		}
	},
	dependencies: {
		type: "object",
		additionalProperties: {
			anyOf: [
				{
					$ref: "#"
				},
				{
					$ref: "#/definitions/stringArray"
				}
			]
		}
	},
	propertyNames: {
		$ref: "#"
	},
	"const": true,
	"enum": {
		type: "array",
		items: true,
		minItems: 1,
		uniqueItems: true
	},
	type: {
		anyOf: [
			{
				$ref: "#/definitions/simpleTypes"
			},
			{
				type: "array",
				items: {
					$ref: "#/definitions/simpleTypes"
				},
				minItems: 1,
				uniqueItems: true
			}
		]
	},
	format: {
		type: "string"
	},
	contentMediaType: {
		type: "string"
	},
	contentEncoding: {
		type: "string"
	},
	"if": {
		$ref: "#"
	},
	then: {
		$ref: "#"
	},
	"else": {
		$ref: "#"
	},
	allOf: {
		$ref: "#/definitions/schemaArray"
	},
	anyOf: {
		$ref: "#/definitions/schemaArray"
	},
	oneOf: {
		$ref: "#/definitions/schemaArray"
	},
	not: {
		$ref: "#"
	}
};
var require$$3$1 = {
	$schema: $schema,
	$id: $id,
	title: title,
	definitions: definitions,
	type: type,
	properties: properties,
	"default": true
};

var hasRequiredAjv;

function requireAjv () {
	if (hasRequiredAjv) return ajv.exports;
	hasRequiredAjv = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.MissingRefError = exports$1.ValidationError = exports$1.CodeGen = exports$1.Name = exports$1.nil = exports$1.stringify = exports$1.str = exports$1._ = exports$1.KeywordCxt = exports$1.Ajv = void 0;
		const core_1 = requireCore$2();
		const draft7_1 = requireDraft7();
		const discriminator_1 = requireDiscriminator();
		const draft7MetaSchema = require$$3$1;
		const META_SUPPORT_DATA = ["/properties"];
		const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
		class Ajv extends core_1.default {
		    _addVocabularies() {
		        super._addVocabularies();
		        draft7_1.default.forEach((v) => this.addVocabulary(v));
		        if (this.opts.discriminator)
		            this.addKeyword(discriminator_1.default);
		    }
		    _addDefaultMetaSchema() {
		        super._addDefaultMetaSchema();
		        if (!this.opts.meta)
		            return;
		        const metaSchema = this.opts.$data
		            ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
		            : draft7MetaSchema;
		        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
		        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
		    }
		    defaultMeta() {
		        return (this.opts.defaultMeta =
		            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
		    }
		}
		exports$1.Ajv = Ajv;
		module.exports = exports$1 = Ajv;
		module.exports.Ajv = Ajv;
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.default = Ajv;
		var validate_1 = requireValidate();
		Object.defineProperty(exports$1, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
		var codegen_1 = requireCodegen();
		Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return codegen_1._; } });
		Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return codegen_1.str; } });
		Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
		Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
		Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
		Object.defineProperty(exports$1, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
		var validation_error_1 = requireValidation_error();
		Object.defineProperty(exports$1, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
		var ref_error_1 = requireRef_error();
		Object.defineProperty(exports$1, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); 
	} (ajv, ajv.exports));
	return ajv.exports;
}

var hasRequiredLimit;

function requireLimit () {
	if (hasRequiredLimit) return limit;
	hasRequiredLimit = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.formatLimitDefinition = void 0;
		const ajv_1 = requireAjv();
		const codegen_1 = requireCodegen();
		const ops = codegen_1.operators;
		const KWDs = {
		    formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
		    formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
		    formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
		    formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
		};
		const error = {
		    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `should be ${KWDs[keyword].okStr} ${schemaCode}`,
		    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
		};
		exports$1.formatLimitDefinition = {
		    keyword: Object.keys(KWDs),
		    type: "string",
		    schemaType: "string",
		    $data: true,
		    error,
		    code(cxt) {
		        const { gen, data, schemaCode, keyword, it } = cxt;
		        const { opts, self } = it;
		        if (!opts.validateFormats)
		            return;
		        const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format");
		        if (fCxt.$data)
		            validate$DataFormat();
		        else
		            validateFormat();
		        function validate$DataFormat() {
		            const fmts = gen.scopeValue("formats", {
		                ref: self.formats,
		                code: opts.code.formats,
		            });
		            const fmt = gen.const("fmt", (0, codegen_1._) `${fmts}[${fCxt.schemaCode}]`);
		            cxt.fail$data((0, codegen_1.or)((0, codegen_1._) `typeof ${fmt} != "object"`, (0, codegen_1._) `${fmt} instanceof RegExp`, (0, codegen_1._) `typeof ${fmt}.compare != "function"`, compareCode(fmt)));
		        }
		        function validateFormat() {
		            const format = fCxt.schema;
		            const fmtDef = self.formats[format];
		            if (!fmtDef || fmtDef === true)
		                return;
		            if (typeof fmtDef != "object" ||
		                fmtDef instanceof RegExp ||
		                typeof fmtDef.compare != "function") {
		                throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);
		            }
		            const fmt = gen.scopeValue("formats", {
		                key: format,
		                ref: fmtDef,
		                code: opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : undefined,
		            });
		            cxt.fail$data(compareCode(fmt));
		        }
		        function compareCode(fmt) {
		            return (0, codegen_1._) `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
		        }
		    },
		    dependencies: ["format"],
		};
		const formatLimitPlugin = (ajv) => {
		    ajv.addKeyword(exports$1.formatLimitDefinition);
		    return ajv;
		};
		exports$1.default = formatLimitPlugin; 
	} (limit));
	return limit;
}

var hasRequiredDist$c;

function requireDist$c () {
	if (hasRequiredDist$c) return dist$c.exports;
	hasRequiredDist$c = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		const formats_1 = requireFormats();
		const limit_1 = requireLimit();
		const codegen_1 = requireCodegen();
		const fullName = new codegen_1.Name("fullFormats");
		const fastName = new codegen_1.Name("fastFormats");
		const formatsPlugin = (ajv, opts = { keywords: true }) => {
		    if (Array.isArray(opts)) {
		        addFormats(ajv, opts, formats_1.fullFormats, fullName);
		        return ajv;
		    }
		    const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
		    const list = opts.formats || formats_1.formatNames;
		    addFormats(ajv, list, formats, exportName);
		    if (opts.keywords)
		        (0, limit_1.default)(ajv);
		    return ajv;
		};
		formatsPlugin.get = (name, mode = "full") => {
		    const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
		    const f = formats[name];
		    if (!f)
		        throw new Error(`Unknown format "${name}"`);
		    return f;
		};
		function addFormats(ajv, list, fs, exportName) {
		    var _a;
		    var _b;
		    (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = (0, codegen_1._) `require("ajv-formats/dist/formats").${exportName}`);
		    for (const f of list)
		        ajv.addFormat(f, fs[f]);
		}
		module.exports = exports$1 = formatsPlugin;
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.default = formatsPlugin; 
	} (dist$c, dist$c.exports));
	return dist$c.exports;
}

var distExports$1 = requireDist$c();
var _addFormats = /*@__PURE__*/getDefaultExportFromCjs(distExports$1);

function createDefaultAjvInstance() {
    const ajv = new Ajv({
        strict: false,
        validateFormats: true,
        validateSchema: false,
        allErrors: true
    });
    const addFormats = _addFormats;
    addFormats(ajv);
    return ajv;
}
class AjvJsonSchemaValidator {
    constructor(ajv) {
        this._ajv = ajv ?? createDefaultAjvInstance();
    }
    getValidator(schema) {
        const ajvValidator = '$id' in schema && typeof schema.$id === 'string'
            ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema))
            : this._ajv.compile(schema);
        return (input) => {
            const valid = ajvValidator(input);
            if (valid) {
                return {
                    valid: true,
                    data: input,
                    errorMessage: undefined
                };
            }
            else {
                return {
                    valid: false,
                    data: undefined,
                    errorMessage: this._ajv.errorsText(ajvValidator.errors)
                };
            }
        };
    }
}

class ExperimentalServerTasks {
    constructor(_server) {
        this._server = _server;
    }
    requestStream(request, resultSchema, options) {
        return this._server.requestStream(request, resultSchema, options);
    }
    createMessageStream(params, options) {
        const clientCapabilities = this._server.getClientCapabilities();
        if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) {
            throw new Error('Client does not support sampling tools capability.');
        }
        if (params.messages.length > 0) {
            const lastMessage = params.messages[params.messages.length - 1];
            const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
            const hasToolResults = lastContent.some(c => c.type === 'tool_result');
            const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined;
            const previousContent = previousMessage
                ? Array.isArray(previousMessage.content)
                    ? previousMessage.content
                    : [previousMessage.content]
                : [];
            const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use');
            if (hasToolResults) {
                if (lastContent.some(c => c.type !== 'tool_result')) {
                    throw new Error('The last message must contain only tool_result content if any is present');
                }
                if (!hasPreviousToolUse) {
                    throw new Error('tool_result blocks are not matching any tool_use from the previous message');
                }
            }
            if (hasPreviousToolUse) {
                const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id));
                const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId));
                if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) {
                    throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match');
                }
            }
        }
        return this.requestStream({
            method: 'sampling/createMessage',
            params
        }, CreateMessageResultSchema, options);
    }
    elicitInputStream(params, options) {
        const clientCapabilities = this._server.getClientCapabilities();
        const mode = params.mode ?? 'form';
        switch (mode) {
            case 'url': {
                if (!clientCapabilities?.elicitation?.url) {
                    throw new Error('Client does not support url elicitation.');
                }
                break;
            }
            case 'form': {
                if (!clientCapabilities?.elicitation?.form) {
                    throw new Error('Client does not support form elicitation.');
                }
                break;
            }
        }
        const normalizedParams = mode === 'form' && params.mode === undefined ? { ...params, mode: 'form' } : params;
        return this.requestStream({
            method: 'elicitation/create',
            params: normalizedParams
        }, ElicitResultSchema, options);
    }
    async getTask(taskId, options) {
        return this._server.getTask({ taskId }, options);
    }
    async getTaskResult(taskId, resultSchema, options) {
        return this._server.getTaskResult({ taskId }, resultSchema, options);
    }
    async listTasks(cursor, options) {
        return this._server.listTasks(cursor ? { cursor } : undefined, options);
    }
    async cancelTask(taskId, options) {
        return this._server.cancelTask({ taskId }, options);
    }
}

function assertToolsCallTaskCapability(requests, method, entityName) {
    if (!requests) {
        throw new Error(`${entityName} does not support task creation (required for ${method})`);
    }
    switch (method) {
        case 'tools/call':
            if (!requests.tools?.call) {
                throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
            }
            break;
    }
}
function assertClientRequestTaskCapability(requests, method, entityName) {
    if (!requests) {
        throw new Error(`${entityName} does not support task creation (required for ${method})`);
    }
    switch (method) {
        case 'sampling/createMessage':
            if (!requests.sampling?.createMessage) {
                throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
            }
            break;
        case 'elicitation/create':
            if (!requests.elicitation?.create) {
                throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
            }
            break;
    }
}

class Server extends Protocol {
    constructor(_serverInfo, options) {
        super(options);
        this._serverInfo = _serverInfo;
        this._loggingLevels = new Map();
        this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));
        this.isMessageIgnored = (level, sessionId) => {
            const currentLevel = this._loggingLevels.get(sessionId);
            return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;
        };
        this._capabilities = options?.capabilities ?? {};
        this._instructions = options?.instructions;
        this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
        this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request));
        this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());
        if (this._capabilities.logging) {
            this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {
                const transportSessionId = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] || undefined;
                const { level } = request.params;
                const parseResult = LoggingLevelSchema.safeParse(level);
                if (parseResult.success) {
                    this._loggingLevels.set(transportSessionId, parseResult.data);
                }
                return {};
            });
        }
    }
    get experimental() {
        if (!this._experimental) {
            this._experimental = {
                tasks: new ExperimentalServerTasks(this)
            };
        }
        return this._experimental;
    }
    registerCapabilities(capabilities) {
        if (this.transport) {
            throw new Error('Cannot register capabilities after connecting to transport');
        }
        this._capabilities = mergeCapabilities(this._capabilities, capabilities);
    }
    setRequestHandler(requestSchema, handler) {
        const shape = getObjectShape(requestSchema);
        const methodSchema = shape?.method;
        if (!methodSchema) {
            throw new Error('Schema is missing a method literal');
        }
        let methodValue;
        if (isZ4Schema(methodSchema)) {
            const v4Schema = methodSchema;
            const v4Def = v4Schema._zod?.def;
            methodValue = v4Def?.value ?? v4Schema.value;
        }
        else {
            const v3Schema = methodSchema;
            const legacyDef = v3Schema._def;
            methodValue = legacyDef?.value ?? v3Schema.value;
        }
        if (typeof methodValue !== 'string') {
            throw new Error('Schema method literal must be a string');
        }
        const method = methodValue;
        if (method === 'tools/call') {
            const wrappedHandler = async (request, extra) => {
                const validatedRequest = safeParse$1(CallToolRequestSchema, request);
                if (!validatedRequest.success) {
                    const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
                    throw new McpError(ErrorCode$1.InvalidParams, `Invalid tools/call request: ${errorMessage}`);
                }
                const { params } = validatedRequest.data;
                const result = await Promise.resolve(handler(request, extra));
                if (params.task) {
                    const taskValidationResult = safeParse$1(CreateTaskResultSchema, result);
                    if (!taskValidationResult.success) {
                        const errorMessage = taskValidationResult.error instanceof Error
                            ? taskValidationResult.error.message
                            : String(taskValidationResult.error);
                        throw new McpError(ErrorCode$1.InvalidParams, `Invalid task creation result: ${errorMessage}`);
                    }
                    return taskValidationResult.data;
                }
                const validationResult = safeParse$1(CallToolResultSchema, result);
                if (!validationResult.success) {
                    const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
                    throw new McpError(ErrorCode$1.InvalidParams, `Invalid tools/call result: ${errorMessage}`);
                }
                return validationResult.data;
            };
            return super.setRequestHandler(requestSchema, wrappedHandler);
        }
        return super.setRequestHandler(requestSchema, handler);
    }
    assertCapabilityForMethod(method) {
        switch (method) {
            case 'sampling/createMessage':
                if (!this._clientCapabilities?.sampling) {
                    throw new Error(`Client does not support sampling (required for ${method})`);
                }
                break;
            case 'elicitation/create':
                if (!this._clientCapabilities?.elicitation) {
                    throw new Error(`Client does not support elicitation (required for ${method})`);
                }
                break;
            case 'roots/list':
                if (!this._clientCapabilities?.roots) {
                    throw new Error(`Client does not support listing roots (required for ${method})`);
                }
                break;
        }
    }
    assertNotificationCapability(method) {
        switch (method) {
            case 'notifications/message':
                if (!this._capabilities.logging) {
                    throw new Error(`Server does not support logging (required for ${method})`);
                }
                break;
            case 'notifications/resources/updated':
            case 'notifications/resources/list_changed':
                if (!this._capabilities.resources) {
                    throw new Error(`Server does not support notifying about resources (required for ${method})`);
                }
                break;
            case 'notifications/tools/list_changed':
                if (!this._capabilities.tools) {
                    throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);
                }
                break;
            case 'notifications/prompts/list_changed':
                if (!this._capabilities.prompts) {
                    throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
                }
                break;
            case 'notifications/elicitation/complete':
                if (!this._clientCapabilities?.elicitation?.url) {
                    throw new Error(`Client does not support URL elicitation (required for ${method})`);
                }
                break;
        }
    }
    assertRequestHandlerCapability(method) {
        if (!this._capabilities) {
            return;
        }
        switch (method) {
            case 'completion/complete':
                if (!this._capabilities.completions) {
                    throw new Error(`Server does not support completions (required for ${method})`);
                }
                break;
            case 'logging/setLevel':
                if (!this._capabilities.logging) {
                    throw new Error(`Server does not support logging (required for ${method})`);
                }
                break;
            case 'prompts/get':
            case 'prompts/list':
                if (!this._capabilities.prompts) {
                    throw new Error(`Server does not support prompts (required for ${method})`);
                }
                break;
            case 'resources/list':
            case 'resources/templates/list':
            case 'resources/read':
                if (!this._capabilities.resources) {
                    throw new Error(`Server does not support resources (required for ${method})`);
                }
                break;
            case 'tools/call':
            case 'tools/list':
                if (!this._capabilities.tools) {
                    throw new Error(`Server does not support tools (required for ${method})`);
                }
                break;
            case 'tasks/get':
            case 'tasks/list':
            case 'tasks/result':
            case 'tasks/cancel':
                if (!this._capabilities.tasks) {
                    throw new Error(`Server does not support tasks capability (required for ${method})`);
                }
                break;
        }
    }
    assertTaskCapability(method) {
        assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, 'Client');
    }
    assertTaskHandlerCapability(method) {
        if (!this._capabilities) {
            return;
        }
        assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, 'Server');
    }
    async _oninitialize(request) {
        const requestedVersion = request.params.protocolVersion;
        this._clientCapabilities = request.params.capabilities;
        this._clientVersion = request.params.clientInfo;
        const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;
        return {
            protocolVersion,
            capabilities: this.getCapabilities(),
            serverInfo: this._serverInfo,
            ...(this._instructions && { instructions: this._instructions })
        };
    }
    getClientCapabilities() {
        return this._clientCapabilities;
    }
    getClientVersion() {
        return this._clientVersion;
    }
    getCapabilities() {
        return this._capabilities;
    }
    async ping() {
        return this.request({ method: 'ping' }, EmptyResultSchema);
    }
    async createMessage(params, options) {
        if (params.tools || params.toolChoice) {
            if (!this._clientCapabilities?.sampling?.tools) {
                throw new Error('Client does not support sampling tools capability.');
            }
        }
        if (params.messages.length > 0) {
            const lastMessage = params.messages[params.messages.length - 1];
            const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
            const hasToolResults = lastContent.some(c => c.type === 'tool_result');
            const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined;
            const previousContent = previousMessage
                ? Array.isArray(previousMessage.content)
                    ? previousMessage.content
                    : [previousMessage.content]
                : [];
            const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use');
            if (hasToolResults) {
                if (lastContent.some(c => c.type !== 'tool_result')) {
                    throw new Error('The last message must contain only tool_result content if any is present');
                }
                if (!hasPreviousToolUse) {
                    throw new Error('tool_result blocks are not matching any tool_use from the previous message');
                }
            }
            if (hasPreviousToolUse) {
                const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id));
                const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId));
                if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) {
                    throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match');
                }
            }
        }
        if (params.tools) {
            return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultWithToolsSchema, options);
        }
        return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options);
    }
    async elicitInput(params, options) {
        const mode = (params.mode ?? 'form');
        switch (mode) {
            case 'url': {
                if (!this._clientCapabilities?.elicitation?.url) {
                    throw new Error('Client does not support url elicitation.');
                }
                const urlParams = params;
                return this.request({ method: 'elicitation/create', params: urlParams }, ElicitResultSchema, options);
            }
            case 'form': {
                if (!this._clientCapabilities?.elicitation?.form) {
                    throw new Error('Client does not support form elicitation.');
                }
                const formParams = params.mode === 'form' ? params : { ...params, mode: 'form' };
                const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options);
                if (result.action === 'accept' && result.content && formParams.requestedSchema) {
                    try {
                        const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema);
                        const validationResult = validator(result.content);
                        if (!validationResult.valid) {
                            throw new McpError(ErrorCode$1.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);
                        }
                    }
                    catch (error) {
                        if (error instanceof McpError) {
                            throw error;
                        }
                        throw new McpError(ErrorCode$1.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`);
                    }
                }
                return result;
            }
        }
    }
    createElicitationCompletionNotifier(elicitationId, options) {
        if (!this._clientCapabilities?.elicitation?.url) {
            throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)');
        }
        return () => this.notification({
            method: 'notifications/elicitation/complete',
            params: {
                elicitationId
            }
        }, options);
    }
    async listRoots(params, options) {
        return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options);
    }
    async sendLoggingMessage(params, sessionId) {
        if (this._capabilities.logging) {
            if (!this.isMessageIgnored(params.level, sessionId)) {
                return this.notification({ method: 'notifications/message', params });
            }
        }
    }
    async sendResourceUpdated(params) {
        return this.notification({
            method: 'notifications/resources/updated',
            params
        });
    }
    async sendResourceListChanged() {
        return this.notification({
            method: 'notifications/resources/list_changed'
        });
    }
    async sendToolListChanged() {
        return this.notification({ method: 'notifications/tools/list_changed' });
    }
    async sendPromptListChanged() {
        return this.notification({ method: 'notifications/prompts/list_changed' });
    }
}

const COMPLETABLE_SYMBOL = Symbol.for('mcp.completable');
function isCompletable(schema) {
    return !!schema && typeof schema === 'object' && COMPLETABLE_SYMBOL in schema;
}
function getCompleter(schema) {
    const meta = schema[COMPLETABLE_SYMBOL];
    return meta?.complete;
}
var McpZodTypeKind;
(function (McpZodTypeKind) {
    McpZodTypeKind["Completable"] = "McpCompletable";
})(McpZodTypeKind || (McpZodTypeKind = {}));

const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;
function validateToolName(name) {
    const warnings = [];
    if (name.length === 0) {
        return {
            isValid: false,
            warnings: ['Tool name cannot be empty']
        };
    }
    if (name.length > 128) {
        return {
            isValid: false,
            warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]
        };
    }
    if (name.includes(' ')) {
        warnings.push('Tool name contains spaces, which may cause parsing issues');
    }
    if (name.includes(',')) {
        warnings.push('Tool name contains commas, which may cause parsing issues');
    }
    if (name.startsWith('-') || name.endsWith('-')) {
        warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts');
    }
    if (name.startsWith('.') || name.endsWith('.')) {
        warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts');
    }
    if (!TOOL_NAME_REGEX.test(name)) {
        const invalidChars = name
            .split('')
            .filter(char => !/[A-Za-z0-9._-]/.test(char))
            .filter((char, index, arr) => arr.indexOf(char) === index);
        warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c => `"${c}"`).join(', ')}`, 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)');
        return {
            isValid: false,
            warnings
        };
    }
    return {
        isValid: true,
        warnings
    };
}
function issueToolNameWarning(name, warnings) {
    if (warnings.length > 0) {
        console.warn(`Tool name validation warning for "${name}":`);
        for (const warning of warnings) {
            console.warn(`  - ${warning}`);
        }
        console.warn('Tool registration will proceed, but this may cause compatibility issues.');
        console.warn('Consider updating the tool name to conform to the MCP tool naming standard.');
        console.warn('See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.');
    }
}
function validateAndWarnToolName(name) {
    const result = validateToolName(name);
    issueToolNameWarning(name, result.warnings);
    return result.isValid;
}

class ExperimentalMcpServerTasks {
    constructor(_mcpServer) {
        this._mcpServer = _mcpServer;
    }
    registerToolTask(name, config, handler) {
        const execution = { taskSupport: 'required', ...config.execution };
        if (execution.taskSupport === 'forbidden') {
            throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);
        }
        const mcpServerInternal = this._mcpServer;
        return mcpServerInternal._createRegisteredTool(name, config.title, config.description, config.inputSchema, config.outputSchema, config.annotations, execution, config._meta, handler);
    }
}

class McpServer {
    constructor(serverInfo, options) {
        this._registeredResources = {};
        this._registeredResourceTemplates = {};
        this._registeredTools = {};
        this._registeredPrompts = {};
        this._toolHandlersInitialized = false;
        this._completionHandlerInitialized = false;
        this._resourceHandlersInitialized = false;
        this._promptHandlersInitialized = false;
        this.server = new Server(serverInfo, options);
    }
    get experimental() {
        if (!this._experimental) {
            this._experimental = {
                tasks: new ExperimentalMcpServerTasks(this)
            };
        }
        return this._experimental;
    }
    async connect(transport) {
        return await this.server.connect(transport);
    }
    async close() {
        await this.server.close();
    }
    setToolRequestHandlers() {
        if (this._toolHandlersInitialized) {
            return;
        }
        this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));
        this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));
        this.server.registerCapabilities({
            tools: {
                listChanged: true
            }
        });
        this.server.setRequestHandler(ListToolsRequestSchema, () => ({
            tools: Object.entries(this._registeredTools)
                .filter(([, tool]) => tool.enabled)
                .map(([name, tool]) => {
                const toolDefinition = {
                    name,
                    title: tool.title,
                    description: tool.description,
                    inputSchema: (() => {
                        const obj = normalizeObjectSchema(tool.inputSchema);
                        return obj
                            ? toJsonSchemaCompat(obj, {
                                strictUnions: true,
                                pipeStrategy: 'input'
                            })
                            : EMPTY_OBJECT_JSON_SCHEMA;
                    })(),
                    annotations: tool.annotations,
                    execution: tool.execution,
                    _meta: tool._meta
                };
                if (tool.outputSchema) {
                    const obj = normalizeObjectSchema(tool.outputSchema);
                    if (obj) {
                        toolDefinition.outputSchema = toJsonSchemaCompat(obj, {
                            strictUnions: true,
                            pipeStrategy: 'output'
                        });
                    }
                }
                return toolDefinition;
            })
        }));
        this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
            try {
                const tool = this._registeredTools[request.params.name];
                if (!tool) {
                    throw new McpError(ErrorCode$1.InvalidParams, `Tool ${request.params.name} not found`);
                }
                if (!tool.enabled) {
                    throw new McpError(ErrorCode$1.InvalidParams, `Tool ${request.params.name} disabled`);
                }
                const isTaskRequest = !!request.params.task;
                const taskSupport = tool.execution?.taskSupport;
                const isTaskHandler = 'createTask' in tool.handler;
                if ((taskSupport === 'required' || taskSupport === 'optional') && !isTaskHandler) {
                    throw new McpError(ErrorCode$1.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);
                }
                if (taskSupport === 'required' && !isTaskRequest) {
                    throw new McpError(ErrorCode$1.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);
                }
                if (taskSupport === 'optional' && !isTaskRequest && isTaskHandler) {
                    return await this.handleAutomaticTaskPolling(tool, request, extra);
                }
                const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
                const result = await this.executeToolHandler(tool, args, extra);
                if (isTaskRequest) {
                    return result;
                }
                await this.validateToolOutput(tool, result, request.params.name);
                return result;
            }
            catch (error) {
                if (error instanceof McpError) {
                    if (error.code === ErrorCode$1.UrlElicitationRequired) {
                        throw error;
                    }
                }
                return this.createToolError(error instanceof Error ? error.message : String(error));
            }
        });
        this._toolHandlersInitialized = true;
    }
    createToolError(errorMessage) {
        return {
            content: [
                {
                    type: 'text',
                    text: errorMessage
                }
            ],
            isError: true
        };
    }
    async validateToolInput(tool, args, toolName) {
        if (!tool.inputSchema) {
            return undefined;
        }
        const inputObj = normalizeObjectSchema(tool.inputSchema);
        const schemaToParse = inputObj ?? tool.inputSchema;
        const parseResult = await safeParseAsync$1(schemaToParse, args);
        if (!parseResult.success) {
            const error = 'error' in parseResult ? parseResult.error : 'Unknown error';
            const errorMessage = getParseErrorMessage(error);
            throw new McpError(ErrorCode$1.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);
        }
        return parseResult.data;
    }
    async validateToolOutput(tool, result, toolName) {
        if (!tool.outputSchema) {
            return;
        }
        if (!('content' in result)) {
            return;
        }
        if (result.isError) {
            return;
        }
        if (!result.structuredContent) {
            throw new McpError(ErrorCode$1.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);
        }
        const outputObj = normalizeObjectSchema(tool.outputSchema);
        const parseResult = await safeParseAsync$1(outputObj, result.structuredContent);
        if (!parseResult.success) {
            const error = 'error' in parseResult ? parseResult.error : 'Unknown error';
            const errorMessage = getParseErrorMessage(error);
            throw new McpError(ErrorCode$1.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);
        }
    }
    async executeToolHandler(tool, args, extra) {
        const handler = tool.handler;
        const isTaskHandler = 'createTask' in handler;
        if (isTaskHandler) {
            if (!extra.taskStore) {
                throw new Error('No task store provided.');
            }
            const taskExtra = { ...extra, taskStore: extra.taskStore };
            if (tool.inputSchema) {
                const typedHandler = handler;
                return await Promise.resolve(typedHandler.createTask(args, taskExtra));
            }
            else {
                const typedHandler = handler;
                return await Promise.resolve(typedHandler.createTask(taskExtra));
            }
        }
        if (tool.inputSchema) {
            const typedHandler = handler;
            return await Promise.resolve(typedHandler(args, extra));
        }
        else {
            const typedHandler = handler;
            return await Promise.resolve(typedHandler(extra));
        }
    }
    async handleAutomaticTaskPolling(tool, request, extra) {
        if (!extra.taskStore) {
            throw new Error('No task store provided for task-capable tool.');
        }
        const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
        const handler = tool.handler;
        const taskExtra = { ...extra, taskStore: extra.taskStore };
        const createTaskResult = args
            ? await Promise.resolve(handler.createTask(args, taskExtra))
            :
                await Promise.resolve(handler.createTask(taskExtra));
        const taskId = createTaskResult.task.taskId;
        let task = createTaskResult.task;
        const pollInterval = task.pollInterval ?? 5000;
        while (task.status !== 'completed' && task.status !== 'failed' && task.status !== 'cancelled') {
            await new Promise(resolve => setTimeout(resolve, pollInterval));
            const updatedTask = await extra.taskStore.getTask(taskId);
            if (!updatedTask) {
                throw new McpError(ErrorCode$1.InternalError, `Task ${taskId} not found during polling`);
            }
            task = updatedTask;
        }
        return (await extra.taskStore.getTaskResult(taskId));
    }
    setCompletionRequestHandler() {
        if (this._completionHandlerInitialized) {
            return;
        }
        this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));
        this.server.registerCapabilities({
            completions: {}
        });
        this.server.setRequestHandler(CompleteRequestSchema, async (request) => {
            switch (request.params.ref.type) {
                case 'ref/prompt':
                    assertCompleteRequestPrompt(request);
                    return this.handlePromptCompletion(request, request.params.ref);
                case 'ref/resource':
                    assertCompleteRequestResourceTemplate(request);
                    return this.handleResourceCompletion(request, request.params.ref);
                default:
                    throw new McpError(ErrorCode$1.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
            }
        });
        this._completionHandlerInitialized = true;
    }
    async handlePromptCompletion(request, ref) {
        const prompt = this._registeredPrompts[ref.name];
        if (!prompt) {
            throw new McpError(ErrorCode$1.InvalidParams, `Prompt ${ref.name} not found`);
        }
        if (!prompt.enabled) {
            throw new McpError(ErrorCode$1.InvalidParams, `Prompt ${ref.name} disabled`);
        }
        if (!prompt.argsSchema) {
            return EMPTY_COMPLETION_RESULT;
        }
        const promptShape = getObjectShape(prompt.argsSchema);
        const field = promptShape?.[request.params.argument.name];
        if (!isCompletable(field)) {
            return EMPTY_COMPLETION_RESULT;
        }
        const completer = getCompleter(field);
        if (!completer) {
            return EMPTY_COMPLETION_RESULT;
        }
        const suggestions = await completer(request.params.argument.value, request.params.context);
        return createCompletionResult(suggestions);
    }
    async handleResourceCompletion(request, ref) {
        const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri);
        if (!template) {
            if (this._registeredResources[ref.uri]) {
                return EMPTY_COMPLETION_RESULT;
            }
            throw new McpError(ErrorCode$1.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
        }
        const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
        if (!completer) {
            return EMPTY_COMPLETION_RESULT;
        }
        const suggestions = await completer(request.params.argument.value, request.params.context);
        return createCompletionResult(suggestions);
    }
    setResourceRequestHandlers() {
        if (this._resourceHandlersInitialized) {
            return;
        }
        this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));
        this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));
        this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));
        this.server.registerCapabilities({
            resources: {
                listChanged: true
            }
        });
        this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {
            const resources = Object.entries(this._registeredResources)
                .filter(([_, resource]) => resource.enabled)
                .map(([uri, resource]) => ({
                uri,
                name: resource.name,
                ...resource.metadata
            }));
            const templateResources = [];
            for (const template of Object.values(this._registeredResourceTemplates)) {
                if (!template.resourceTemplate.listCallback) {
                    continue;
                }
                const result = await template.resourceTemplate.listCallback(extra);
                for (const resource of result.resources) {
                    templateResources.push({
                        ...template.metadata,
                        ...resource
                    });
                }
            }
            return { resources: [...resources, ...templateResources] };
        });
        this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
            const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
                name,
                uriTemplate: template.resourceTemplate.uriTemplate.toString(),
                ...template.metadata
            }));
            return { resourceTemplates };
        });
        this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
            const uri = new URL(request.params.uri);
            const resource = this._registeredResources[uri.toString()];
            if (resource) {
                if (!resource.enabled) {
                    throw new McpError(ErrorCode$1.InvalidParams, `Resource ${uri} disabled`);
                }
                return resource.readCallback(uri, extra);
            }
            for (const template of Object.values(this._registeredResourceTemplates)) {
                const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
                if (variables) {
                    return template.readCallback(uri, variables, extra);
                }
            }
            throw new McpError(ErrorCode$1.InvalidParams, `Resource ${uri} not found`);
        });
        this._resourceHandlersInitialized = true;
    }
    setPromptRequestHandlers() {
        if (this._promptHandlersInitialized) {
            return;
        }
        this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));
        this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));
        this.server.registerCapabilities({
            prompts: {
                listChanged: true
            }
        });
        this.server.setRequestHandler(ListPromptsRequestSchema, () => ({
            prompts: Object.entries(this._registeredPrompts)
                .filter(([, prompt]) => prompt.enabled)
                .map(([name, prompt]) => {
                return {
                    name,
                    title: prompt.title,
                    description: prompt.description,
                    arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined
                };
            })
        }));
        this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {
            const prompt = this._registeredPrompts[request.params.name];
            if (!prompt) {
                throw new McpError(ErrorCode$1.InvalidParams, `Prompt ${request.params.name} not found`);
            }
            if (!prompt.enabled) {
                throw new McpError(ErrorCode$1.InvalidParams, `Prompt ${request.params.name} disabled`);
            }
            if (prompt.argsSchema) {
                const argsObj = normalizeObjectSchema(prompt.argsSchema);
                const parseResult = await safeParseAsync$1(argsObj, request.params.arguments);
                if (!parseResult.success) {
                    const error = 'error' in parseResult ? parseResult.error : 'Unknown error';
                    const errorMessage = getParseErrorMessage(error);
                    throw new McpError(ErrorCode$1.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`);
                }
                const args = parseResult.data;
                const cb = prompt.callback;
                return await Promise.resolve(cb(args, extra));
            }
            else {
                const cb = prompt.callback;
                return await Promise.resolve(cb(extra));
            }
        });
        this._promptHandlersInitialized = true;
    }
    resource(name, uriOrTemplate, ...rest) {
        let metadata;
        if (typeof rest[0] === 'object') {
            metadata = rest.shift();
        }
        const readCallback = rest[0];
        if (typeof uriOrTemplate === 'string') {
            if (this._registeredResources[uriOrTemplate]) {
                throw new Error(`Resource ${uriOrTemplate} is already registered`);
            }
            const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback);
            this.setResourceRequestHandlers();
            this.sendResourceListChanged();
            return registeredResource;
        }
        else {
            if (this._registeredResourceTemplates[name]) {
                throw new Error(`Resource template ${name} is already registered`);
            }
            const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback);
            this.setResourceRequestHandlers();
            this.sendResourceListChanged();
            return registeredResourceTemplate;
        }
    }
    registerResource(name, uriOrTemplate, config, readCallback) {
        if (typeof uriOrTemplate === 'string') {
            if (this._registeredResources[uriOrTemplate]) {
                throw new Error(`Resource ${uriOrTemplate} is already registered`);
            }
            const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback);
            this.setResourceRequestHandlers();
            this.sendResourceListChanged();
            return registeredResource;
        }
        else {
            if (this._registeredResourceTemplates[name]) {
                throw new Error(`Resource template ${name} is already registered`);
            }
            const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback);
            this.setResourceRequestHandlers();
            this.sendResourceListChanged();
            return registeredResourceTemplate;
        }
    }
    _createRegisteredResource(name, title, uri, metadata, readCallback) {
        const registeredResource = {
            name,
            title,
            metadata,
            readCallback,
            enabled: true,
            disable: () => registeredResource.update({ enabled: false }),
            enable: () => registeredResource.update({ enabled: true }),
            remove: () => registeredResource.update({ uri: null }),
            update: updates => {
                if (typeof updates.uri !== 'undefined' && updates.uri !== uri) {
                    delete this._registeredResources[uri];
                    if (updates.uri)
                        this._registeredResources[updates.uri] = registeredResource;
                }
                if (typeof updates.name !== 'undefined')
                    registeredResource.name = updates.name;
                if (typeof updates.title !== 'undefined')
                    registeredResource.title = updates.title;
                if (typeof updates.metadata !== 'undefined')
                    registeredResource.metadata = updates.metadata;
                if (typeof updates.callback !== 'undefined')
                    registeredResource.readCallback = updates.callback;
                if (typeof updates.enabled !== 'undefined')
                    registeredResource.enabled = updates.enabled;
                this.sendResourceListChanged();
            }
        };
        this._registeredResources[uri] = registeredResource;
        return registeredResource;
    }
    _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
        const registeredResourceTemplate = {
            resourceTemplate: template,
            title,
            metadata,
            readCallback,
            enabled: true,
            disable: () => registeredResourceTemplate.update({ enabled: false }),
            enable: () => registeredResourceTemplate.update({ enabled: true }),
            remove: () => registeredResourceTemplate.update({ name: null }),
            update: updates => {
                if (typeof updates.name !== 'undefined' && updates.name !== name) {
                    delete this._registeredResourceTemplates[name];
                    if (updates.name)
                        this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
                }
                if (typeof updates.title !== 'undefined')
                    registeredResourceTemplate.title = updates.title;
                if (typeof updates.template !== 'undefined')
                    registeredResourceTemplate.resourceTemplate = updates.template;
                if (typeof updates.metadata !== 'undefined')
                    registeredResourceTemplate.metadata = updates.metadata;
                if (typeof updates.callback !== 'undefined')
                    registeredResourceTemplate.readCallback = updates.callback;
                if (typeof updates.enabled !== 'undefined')
                    registeredResourceTemplate.enabled = updates.enabled;
                this.sendResourceListChanged();
            }
        };
        this._registeredResourceTemplates[name] = registeredResourceTemplate;
        const variableNames = template.uriTemplate.variableNames;
        const hasCompleter = Array.isArray(variableNames) && variableNames.some(v => !!template.completeCallback(v));
        if (hasCompleter) {
            this.setCompletionRequestHandler();
        }
        return registeredResourceTemplate;
    }
    _createRegisteredPrompt(name, title, description, argsSchema, callback) {
        const registeredPrompt = {
            title,
            description,
            argsSchema: argsSchema === undefined ? undefined : objectFromShape(argsSchema),
            callback,
            enabled: true,
            disable: () => registeredPrompt.update({ enabled: false }),
            enable: () => registeredPrompt.update({ enabled: true }),
            remove: () => registeredPrompt.update({ name: null }),
            update: updates => {
                if (typeof updates.name !== 'undefined' && updates.name !== name) {
                    delete this._registeredPrompts[name];
                    if (updates.name)
                        this._registeredPrompts[updates.name] = registeredPrompt;
                }
                if (typeof updates.title !== 'undefined')
                    registeredPrompt.title = updates.title;
                if (typeof updates.description !== 'undefined')
                    registeredPrompt.description = updates.description;
                if (typeof updates.argsSchema !== 'undefined')
                    registeredPrompt.argsSchema = objectFromShape(updates.argsSchema);
                if (typeof updates.callback !== 'undefined')
                    registeredPrompt.callback = updates.callback;
                if (typeof updates.enabled !== 'undefined')
                    registeredPrompt.enabled = updates.enabled;
                this.sendPromptListChanged();
            }
        };
        this._registeredPrompts[name] = registeredPrompt;
        if (argsSchema) {
            const hasCompletable = Object.values(argsSchema).some(field => {
                const inner = field instanceof ZodOptional$1 ? field._def?.innerType : field;
                return isCompletable(inner);
            });
            if (hasCompletable) {
                this.setCompletionRequestHandler();
            }
        }
        return registeredPrompt;
    }
    _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) {
        validateAndWarnToolName(name);
        const registeredTool = {
            title,
            description,
            inputSchema: getZodSchemaObject(inputSchema),
            outputSchema: getZodSchemaObject(outputSchema),
            annotations,
            execution,
            _meta,
            handler: handler,
            enabled: true,
            disable: () => registeredTool.update({ enabled: false }),
            enable: () => registeredTool.update({ enabled: true }),
            remove: () => registeredTool.update({ name: null }),
            update: updates => {
                if (typeof updates.name !== 'undefined' && updates.name !== name) {
                    if (typeof updates.name === 'string') {
                        validateAndWarnToolName(updates.name);
                    }
                    delete this._registeredTools[name];
                    if (updates.name)
                        this._registeredTools[updates.name] = registeredTool;
                }
                if (typeof updates.title !== 'undefined')
                    registeredTool.title = updates.title;
                if (typeof updates.description !== 'undefined')
                    registeredTool.description = updates.description;
                if (typeof updates.paramsSchema !== 'undefined')
                    registeredTool.inputSchema = objectFromShape(updates.paramsSchema);
                if (typeof updates.outputSchema !== 'undefined')
                    registeredTool.outputSchema = objectFromShape(updates.outputSchema);
                if (typeof updates.callback !== 'undefined')
                    registeredTool.handler = updates.callback;
                if (typeof updates.annotations !== 'undefined')
                    registeredTool.annotations = updates.annotations;
                if (typeof updates._meta !== 'undefined')
                    registeredTool._meta = updates._meta;
                if (typeof updates.enabled !== 'undefined')
                    registeredTool.enabled = updates.enabled;
                this.sendToolListChanged();
            }
        };
        this._registeredTools[name] = registeredTool;
        this.setToolRequestHandlers();
        this.sendToolListChanged();
        return registeredTool;
    }
    tool(name, ...rest) {
        if (this._registeredTools[name]) {
            throw new Error(`Tool ${name} is already registered`);
        }
        let description;
        let inputSchema;
        let outputSchema;
        let annotations;
        if (typeof rest[0] === 'string') {
            description = rest.shift();
        }
        if (rest.length > 1) {
            const firstArg = rest[0];
            if (isZodRawShapeCompat(firstArg)) {
                inputSchema = rest.shift();
                if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShapeCompat(rest[0])) {
                    annotations = rest.shift();
                }
            }
            else if (typeof firstArg === 'object' && firstArg !== null) {
                annotations = rest.shift();
            }
        }
        const callback = rest[0];
        return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, undefined, callback);
    }
    registerTool(name, config, cb) {
        if (this._registeredTools[name]) {
            throw new Error(`Tool ${name} is already registered`);
        }
        const { title, description, inputSchema, outputSchema, annotations, _meta } = config;
        return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, _meta, cb);
    }
    prompt(name, ...rest) {
        if (this._registeredPrompts[name]) {
            throw new Error(`Prompt ${name} is already registered`);
        }
        let description;
        if (typeof rest[0] === 'string') {
            description = rest.shift();
        }
        let argsSchema;
        if (rest.length > 1) {
            argsSchema = rest.shift();
        }
        const cb = rest[0];
        const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb);
        this.setPromptRequestHandlers();
        this.sendPromptListChanged();
        return registeredPrompt;
    }
    registerPrompt(name, config, cb) {
        if (this._registeredPrompts[name]) {
            throw new Error(`Prompt ${name} is already registered`);
        }
        const { title, description, argsSchema } = config;
        const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb);
        this.setPromptRequestHandlers();
        this.sendPromptListChanged();
        return registeredPrompt;
    }
    isConnected() {
        return this.server.transport !== undefined;
    }
    async sendLoggingMessage(params, sessionId) {
        return this.server.sendLoggingMessage(params, sessionId);
    }
    sendResourceListChanged() {
        if (this.isConnected()) {
            this.server.sendResourceListChanged();
        }
    }
    sendToolListChanged() {
        if (this.isConnected()) {
            this.server.sendToolListChanged();
        }
    }
    sendPromptListChanged() {
        if (this.isConnected()) {
            this.server.sendPromptListChanged();
        }
    }
}
const EMPTY_OBJECT_JSON_SCHEMA = {
    type: 'object',
    properties: {}
};
function isZodTypeLike(value) {
    return (value !== null &&
        typeof value === 'object' &&
        'parse' in value &&
        typeof value.parse === 'function' &&
        'safeParse' in value &&
        typeof value.safeParse === 'function');
}
function isZodSchemaInstance(obj) {
    return '_def' in obj || '_zod' in obj || isZodTypeLike(obj);
}
function isZodRawShapeCompat(obj) {
    if (typeof obj !== 'object' || obj === null) {
        return false;
    }
    if (isZodSchemaInstance(obj)) {
        return false;
    }
    if (Object.keys(obj).length === 0) {
        return true;
    }
    return Object.values(obj).some(isZodTypeLike);
}
function getZodSchemaObject(schema) {
    if (!schema) {
        return undefined;
    }
    if (isZodRawShapeCompat(schema)) {
        return objectFromShape(schema);
    }
    return schema;
}
function promptArgumentsFromSchema(schema) {
    const shape = getObjectShape(schema);
    if (!shape)
        return [];
    return Object.entries(shape).map(([name, field]) => {
        const description = getSchemaDescription(field);
        const isOptional = isSchemaOptional(field);
        return {
            name,
            description,
            required: !isOptional
        };
    });
}
function getMethodValue(schema) {
    const shape = getObjectShape(schema);
    const methodSchema = shape?.method;
    if (!methodSchema) {
        throw new Error('Schema is missing a method literal');
    }
    const value = getLiteralValue(methodSchema);
    if (typeof value === 'string') {
        return value;
    }
    throw new Error('Schema method literal must be a string');
}
function createCompletionResult(suggestions) {
    return {
        completion: {
            values: suggestions.slice(0, 100),
            total: suggestions.length,
            hasMore: suggestions.length > 100
        }
    };
}
const EMPTY_COMPLETION_RESULT = {
    completion: {
        values: [],
        hasMore: false
    }
};

class ReadBuffer {
    append(chunk) {
        this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
    }
    readMessage() {
        if (!this._buffer) {
            return null;
        }
        const index = this._buffer.indexOf('\n');
        if (index === -1) {
            return null;
        }
        const line = this._buffer.toString('utf8', 0, index).replace(/\r$/, '');
        this._buffer = this._buffer.subarray(index + 1);
        return deserializeMessage(line);
    }
    clear() {
        this._buffer = undefined;
    }
}
function deserializeMessage(line) {
    return JSONRPCMessageSchema.parse(JSON.parse(line));
}
function serializeMessage(message) {
    return JSON.stringify(message) + '\n';
}

class StdioServerTransport {
    constructor(_stdin = process$2.stdin, _stdout = process$2.stdout) {
        this._stdin = _stdin;
        this._stdout = _stdout;
        this._readBuffer = new ReadBuffer();
        this._started = false;
        this._ondata = (chunk) => {
            this._readBuffer.append(chunk);
            this.processReadBuffer();
        };
        this._onerror = (error) => {
            this.onerror?.(error);
        };
    }
    async start() {
        if (this._started) {
            throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.');
        }
        this._started = true;
        this._stdin.on('data', this._ondata);
        this._stdin.on('error', this._onerror);
    }
    processReadBuffer() {
        while (true) {
            try {
                const message = this._readBuffer.readMessage();
                if (message === null) {
                    break;
                }
                this.onmessage?.(message);
            }
            catch (error) {
                this.onerror?.(error);
            }
        }
    }
    async close() {
        this._stdin.off('data', this._ondata);
        this._stdin.off('error', this._onerror);
        const remainingDataListeners = this._stdin.listenerCount('data');
        if (remainingDataListeners === 0) {
            this._stdin.pause();
        }
        this._readBuffer.clear();
        this.onclose?.();
    }
    send(message) {
        return new Promise(resolve => {
            const json = serializeMessage(message);
            if (this._stdout.write(json)) {
                resolve();
            }
            else {
                this._stdout.once('drain', resolve);
            }
        });
    }
}

var crossSpawn = {exports: {}};

var windows;
var hasRequiredWindows;

function requireWindows () {
	if (hasRequiredWindows) return windows;
	hasRequiredWindows = 1;
	windows = isexe;
	isexe.sync = sync;
	var fs = require$$0$3;
	function checkPathExt (path, options) {
	  var pathext = options.pathExt !== undefined ?
	    options.pathExt : process.env.PATHEXT;
	  if (!pathext) {
	    return true
	  }
	  pathext = pathext.split(';');
	  if (pathext.indexOf('') !== -1) {
	    return true
	  }
	  for (var i = 0; i < pathext.length; i++) {
	    var p = pathext[i].toLowerCase();
	    if (p && path.substr(-p.length).toLowerCase() === p) {
	      return true
	    }
	  }
	  return false
	}
	function checkStat (stat, path, options) {
	  if (!stat.isSymbolicLink() && !stat.isFile()) {
	    return false
	  }
	  return checkPathExt(path, options)
	}
	function isexe (path, options, cb) {
	  fs.stat(path, function (er, stat) {
	    cb(er, er ? false : checkStat(stat, path, options));
	  });
	}
	function sync (path, options) {
	  return checkStat(fs.statSync(path), path, options)
	}
	return windows;
}

var mode;
var hasRequiredMode;

function requireMode () {
	if (hasRequiredMode) return mode;
	hasRequiredMode = 1;
	mode = isexe;
	isexe.sync = sync;
	var fs = require$$0$3;
	function isexe (path, options, cb) {
	  fs.stat(path, function (er, stat) {
	    cb(er, er ? false : checkStat(stat, options));
	  });
	}
	function sync (path, options) {
	  return checkStat(fs.statSync(path), options)
	}
	function checkStat (stat, options) {
	  return stat.isFile() && checkMode(stat, options)
	}
	function checkMode (stat, options) {
	  var mod = stat.mode;
	  var uid = stat.uid;
	  var gid = stat.gid;
	  var myUid = options.uid !== undefined ?
	    options.uid : process.getuid && process.getuid();
	  var myGid = options.gid !== undefined ?
	    options.gid : process.getgid && process.getgid();
	  var u = parseInt('100', 8);
	  var g = parseInt('010', 8);
	  var o = parseInt('001', 8);
	  var ug = u | g;
	  var ret = (mod & o) ||
	    (mod & g) && gid === myGid ||
	    (mod & u) && uid === myUid ||
	    (mod & ug) && myUid === 0;
	  return ret
	}
	return mode;
}

var isexe_1;
var hasRequiredIsexe;

function requireIsexe () {
	if (hasRequiredIsexe) return isexe_1;
	hasRequiredIsexe = 1;
	var core;
	if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) {
	  core = requireWindows();
	} else {
	  core = requireMode();
	}
	isexe_1 = isexe;
	isexe.sync = sync;
	function isexe (path, options, cb) {
	  if (typeof options === 'function') {
	    cb = options;
	    options = {};
	  }
	  if (!cb) {
	    if (typeof Promise !== 'function') {
	      throw new TypeError('callback not provided')
	    }
	    return new Promise(function (resolve, reject) {
	      isexe(path, options || {}, function (er, is) {
	        if (er) {
	          reject(er);
	        } else {
	          resolve(is);
	        }
	      });
	    })
	  }
	  core(path, options || {}, function (er, is) {
	    if (er) {
	      if (er.code === 'EACCES' || options && options.ignoreErrors) {
	        er = null;
	        is = false;
	      }
	    }
	    cb(er, is);
	  });
	}
	function sync (path, options) {
	  try {
	    return core.sync(path, options || {})
	  } catch (er) {
	    if (options && options.ignoreErrors || er.code === 'EACCES') {
	      return false
	    } else {
	      throw er
	    }
	  }
	}
	return isexe_1;
}

var which_1;
var hasRequiredWhich;

function requireWhich () {
	if (hasRequiredWhich) return which_1;
	hasRequiredWhich = 1;
	const isWindows = process.platform === 'win32' ||
	    process.env.OSTYPE === 'cygwin' ||
	    process.env.OSTYPE === 'msys';
	const path = require$$0$4;
	const COLON = isWindows ? ';' : ':';
	const isexe = requireIsexe();
	const getNotFoundError = (cmd) =>
	  Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' });
	const getPathInfo = (cmd, opt) => {
	  const colon = opt.colon || COLON;
	  const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
	    : (
	      [
	        ...(isWindows ? [process.cwd()] : []),
	        ...(opt.path || process.env.PATH ||
	           '').split(colon),
	      ]
	    );
	  const pathExtExe = isWindows
	    ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
	    : '';
	  const pathExt = isWindows ? pathExtExe.split(colon) : [''];
	  if (isWindows) {
	    if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
	      pathExt.unshift('');
	  }
	  return {
	    pathEnv,
	    pathExt,
	    pathExtExe,
	  }
	};
	const which = (cmd, opt, cb) => {
	  if (typeof opt === 'function') {
	    cb = opt;
	    opt = {};
	  }
	  if (!opt)
	    opt = {};
	  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
	  const found = [];
	  const step = i => new Promise((resolve, reject) => {
	    if (i === pathEnv.length)
	      return opt.all && found.length ? resolve(found)
	        : reject(getNotFoundError(cmd))
	    const ppRaw = pathEnv[i];
	    const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
	    const pCmd = path.join(pathPart, cmd);
	    const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
	      : pCmd;
	    resolve(subStep(p, i, 0));
	  });
	  const subStep = (p, i, ii) => new Promise((resolve, reject) => {
	    if (ii === pathExt.length)
	      return resolve(step(i + 1))
	    const ext = pathExt[ii];
	    isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
	      if (!er && is) {
	        if (opt.all)
	          found.push(p + ext);
	        else
	          return resolve(p + ext)
	      }
	      return resolve(subStep(p, i, ii + 1))
	    });
	  });
	  return cb ? step(0).then(res => cb(null, res), cb) : step(0)
	};
	const whichSync = (cmd, opt) => {
	  opt = opt || {};
	  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
	  const found = [];
	  for (let i = 0; i < pathEnv.length; i ++) {
	    const ppRaw = pathEnv[i];
	    const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
	    const pCmd = path.join(pathPart, cmd);
	    const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
	      : pCmd;
	    for (let j = 0; j < pathExt.length; j ++) {
	      const cur = p + pathExt[j];
	      try {
	        const is = isexe.sync(cur, { pathExt: pathExtExe });
	        if (is) {
	          if (opt.all)
	            found.push(cur);
	          else
	            return cur
	        }
	      } catch (ex) {}
	    }
	  }
	  if (opt.all && found.length)
	    return found
	  if (opt.nothrow)
	    return null
	  throw getNotFoundError(cmd)
	};
	which_1 = which;
	which.sync = whichSync;
	return which_1;
}

var pathKey = {exports: {}};

var hasRequiredPathKey;

function requirePathKey () {
	if (hasRequiredPathKey) return pathKey.exports;
	hasRequiredPathKey = 1;
	const pathKey$1 = (options = {}) => {
		const environment = options.env || process.env;
		const platform = options.platform || process.platform;
		if (platform !== 'win32') {
			return 'PATH';
		}
		return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
	};
	pathKey.exports = pathKey$1;
	pathKey.exports.default = pathKey$1;
	return pathKey.exports;
}

var resolveCommand_1;
var hasRequiredResolveCommand;

function requireResolveCommand () {
	if (hasRequiredResolveCommand) return resolveCommand_1;
	hasRequiredResolveCommand = 1;
	const path = require$$0$4;
	const which = requireWhich();
	const getPathKey = requirePathKey();
	function resolveCommandAttempt(parsed, withoutPathExt) {
	    const env = parsed.options.env || process.env;
	    const cwd = process.cwd();
	    const hasCustomCwd = parsed.options.cwd != null;
	    const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
	    if (shouldSwitchCwd) {
	        try {
	            process.chdir(parsed.options.cwd);
	        } catch (err) {
	        }
	    }
	    let resolved;
	    try {
	        resolved = which.sync(parsed.command, {
	            path: env[getPathKey({ env })],
	            pathExt: withoutPathExt ? path.delimiter : undefined,
	        });
	    } catch (e) {
	    } finally {
	        if (shouldSwitchCwd) {
	            process.chdir(cwd);
	        }
	    }
	    if (resolved) {
	        resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
	    }
	    return resolved;
	}
	function resolveCommand(parsed) {
	    return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
	}
	resolveCommand_1 = resolveCommand;
	return resolveCommand_1;
}

var _escape = {};

var hasRequired_escape;

function require_escape () {
	if (hasRequired_escape) return _escape;
	hasRequired_escape = 1;
	const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
	function escapeCommand(arg) {
	    arg = arg.replace(metaCharsRegExp, '^$1');
	    return arg;
	}
	function escapeArgument(arg, doubleEscapeMetaChars) {
	    arg = `${arg}`;
	    arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
	    arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1');
	    arg = `"${arg}"`;
	    arg = arg.replace(metaCharsRegExp, '^$1');
	    if (doubleEscapeMetaChars) {
	        arg = arg.replace(metaCharsRegExp, '^$1');
	    }
	    return arg;
	}
	_escape.command = escapeCommand;
	_escape.argument = escapeArgument;
	return _escape;
}

var shebangRegex;
var hasRequiredShebangRegex;

function requireShebangRegex () {
	if (hasRequiredShebangRegex) return shebangRegex;
	hasRequiredShebangRegex = 1;
	shebangRegex = /^#!(.*)/;
	return shebangRegex;
}

var shebangCommand;
var hasRequiredShebangCommand;

function requireShebangCommand () {
	if (hasRequiredShebangCommand) return shebangCommand;
	hasRequiredShebangCommand = 1;
	const shebangRegex = requireShebangRegex();
	shebangCommand = (string = '') => {
		const match = string.match(shebangRegex);
		if (!match) {
			return null;
		}
		const [path, argument] = match[0].replace(/#! ?/, '').split(' ');
		const binary = path.split('/').pop();
		if (binary === 'env') {
			return argument;
		}
		return argument ? `${binary} ${argument}` : binary;
	};
	return shebangCommand;
}

var readShebang_1;
var hasRequiredReadShebang;

function requireReadShebang () {
	if (hasRequiredReadShebang) return readShebang_1;
	hasRequiredReadShebang = 1;
	const fs = require$$0$3;
	const shebangCommand = requireShebangCommand();
	function readShebang(command) {
	    const size = 150;
	    const buffer = Buffer.alloc(size);
	    let fd;
	    try {
	        fd = fs.openSync(command, 'r');
	        fs.readSync(fd, buffer, 0, size, 0);
	        fs.closeSync(fd);
	    } catch (e) {  }
	    return shebangCommand(buffer.toString());
	}
	readShebang_1 = readShebang;
	return readShebang_1;
}

var parse_1$1;
var hasRequiredParse$1;

function requireParse$1 () {
	if (hasRequiredParse$1) return parse_1$1;
	hasRequiredParse$1 = 1;
	const path = require$$0$4;
	const resolveCommand = requireResolveCommand();
	const escape = require_escape();
	const readShebang = requireReadShebang();
	const isWin = process.platform === 'win32';
	const isExecutableRegExp = /\.(?:com|exe)$/i;
	const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
	function detectShebang(parsed) {
	    parsed.file = resolveCommand(parsed);
	    const shebang = parsed.file && readShebang(parsed.file);
	    if (shebang) {
	        parsed.args.unshift(parsed.file);
	        parsed.command = shebang;
	        return resolveCommand(parsed);
	    }
	    return parsed.file;
	}
	function parseNonShell(parsed) {
	    if (!isWin) {
	        return parsed;
	    }
	    const commandFile = detectShebang(parsed);
	    const needsShell = !isExecutableRegExp.test(commandFile);
	    if (parsed.options.forceShell || needsShell) {
	        const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
	        parsed.command = path.normalize(parsed.command);
	        parsed.command = escape.command(parsed.command);
	        parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
	        const shellCommand = [parsed.command].concat(parsed.args).join(' ');
	        parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
	        parsed.command = process.env.comspec || 'cmd.exe';
	        parsed.options.windowsVerbatimArguments = true;
	    }
	    return parsed;
	}
	function parse(command, args, options) {
	    if (args && !Array.isArray(args)) {
	        options = args;
	        args = null;
	    }
	    args = args ? args.slice(0) : [];
	    options = Object.assign({}, options);
	    const parsed = {
	        command,
	        args,
	        options,
	        file: undefined,
	        original: {
	            command,
	            args,
	        },
	    };
	    return options.shell ? parsed : parseNonShell(parsed);
	}
	parse_1$1 = parse;
	return parse_1$1;
}

var enoent;
var hasRequiredEnoent;

function requireEnoent () {
	if (hasRequiredEnoent) return enoent;
	hasRequiredEnoent = 1;
	const isWin = process.platform === 'win32';
	function notFoundError(original, syscall) {
	    return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
	        code: 'ENOENT',
	        errno: 'ENOENT',
	        syscall: `${syscall} ${original.command}`,
	        path: original.command,
	        spawnargs: original.args,
	    });
	}
	function hookChildProcess(cp, parsed) {
	    if (!isWin) {
	        return;
	    }
	    const originalEmit = cp.emit;
	    cp.emit = function (name, arg1) {
	        if (name === 'exit') {
	            const err = verifyENOENT(arg1, parsed);
	            if (err) {
	                return originalEmit.call(cp, 'error', err);
	            }
	        }
	        return originalEmit.apply(cp, arguments);
	    };
	}
	function verifyENOENT(status, parsed) {
	    if (isWin && status === 1 && !parsed.file) {
	        return notFoundError(parsed.original, 'spawn');
	    }
	    return null;
	}
	function verifyENOENTSync(status, parsed) {
	    if (isWin && status === 1 && !parsed.file) {
	        return notFoundError(parsed.original, 'spawnSync');
	    }
	    return null;
	}
	enoent = {
	    hookChildProcess,
	    verifyENOENT,
	    verifyENOENTSync,
	    notFoundError,
	};
	return enoent;
}

var hasRequiredCrossSpawn;

function requireCrossSpawn () {
	if (hasRequiredCrossSpawn) return crossSpawn.exports;
	hasRequiredCrossSpawn = 1;
	const cp = require$$0$5;
	const parse = requireParse$1();
	const enoent = requireEnoent();
	function spawn(command, args, options) {
	    const parsed = parse(command, args, options);
	    const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
	    enoent.hookChildProcess(spawned, parsed);
	    return spawned;
	}
	function spawnSync(command, args, options) {
	    const parsed = parse(command, args, options);
	    const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
	    result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
	    return result;
	}
	crossSpawn.exports = spawn;
	crossSpawn.exports.spawn = spawn;
	crossSpawn.exports.sync = spawnSync;
	crossSpawn.exports._parse = parse;
	crossSpawn.exports._enoent = enoent;
	return crossSpawn.exports;
}

var crossSpawnExports = requireCrossSpawn();
var spawn = /*@__PURE__*/getDefaultExportFromCjs(crossSpawnExports);

const DEFAULT_INHERITED_ENV_VARS = process$2.platform === 'win32'
    ? [
        'APPDATA',
        'HOMEDRIVE',
        'HOMEPATH',
        'LOCALAPPDATA',
        'PATH',
        'PROCESSOR_ARCHITECTURE',
        'SYSTEMDRIVE',
        'SYSTEMROOT',
        'TEMP',
        'USERNAME',
        'USERPROFILE',
        'PROGRAMFILES'
    ]
    :
        ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER'];
function getDefaultEnvironment() {
    const env = {};
    for (const key of DEFAULT_INHERITED_ENV_VARS) {
        const value = process$2.env[key];
        if (value === undefined) {
            continue;
        }
        if (value.startsWith('()')) {
            continue;
        }
        env[key] = value;
    }
    return env;
}
class StdioClientTransport {
    constructor(server) {
        this._readBuffer = new ReadBuffer();
        this._stderrStream = null;
        this._serverParams = server;
        if (server.stderr === 'pipe' || server.stderr === 'overlapped') {
            this._stderrStream = new PassThrough();
        }
    }
    async start() {
        if (this._process) {
            throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.');
        }
        return new Promise((resolve, reject) => {
            this._process = spawn(this._serverParams.command, this._serverParams.args ?? [], {
                env: {
                    ...getDefaultEnvironment(),
                    ...this._serverParams.env
                },
                stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'],
                shell: false,
                windowsHide: process$2.platform === 'win32' && isElectron(),
                cwd: this._serverParams.cwd
            });
            this._process.on('error', error => {
                reject(error);
                this.onerror?.(error);
            });
            this._process.on('spawn', () => {
                resolve();
            });
            this._process.on('close', _code => {
                this._process = undefined;
                this.onclose?.();
            });
            this._process.stdin?.on('error', error => {
                this.onerror?.(error);
            });
            this._process.stdout?.on('data', chunk => {
                this._readBuffer.append(chunk);
                this.processReadBuffer();
            });
            this._process.stdout?.on('error', error => {
                this.onerror?.(error);
            });
            if (this._stderrStream && this._process.stderr) {
                this._process.stderr.pipe(this._stderrStream);
            }
        });
    }
    get stderr() {
        if (this._stderrStream) {
            return this._stderrStream;
        }
        return this._process?.stderr ?? null;
    }
    get pid() {
        return this._process?.pid ?? null;
    }
    processReadBuffer() {
        while (true) {
            try {
                const message = this._readBuffer.readMessage();
                if (message === null) {
                    break;
                }
                this.onmessage?.(message);
            }
            catch (error) {
                this.onerror?.(error);
            }
        }
    }
    async close() {
        if (this._process) {
            const processToClose = this._process;
            this._process = undefined;
            const closePromise = new Promise(resolve => {
                processToClose.once('close', () => {
                    resolve();
                });
            });
            try {
                processToClose.stdin?.end();
            }
            catch {
            }
            await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);
            if (processToClose.exitCode === null) {
                try {
                    processToClose.kill('SIGTERM');
                }
                catch {
                }
                await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);
            }
            if (processToClose.exitCode === null) {
                try {
                    processToClose.kill('SIGKILL');
                }
                catch {
                }
            }
        }
        this._readBuffer.clear();
    }
    send(message) {
        return new Promise(resolve => {
            if (!this._process?.stdin) {
                throw new Error('Not connected');
            }
            const json = serializeMessage(message);
            if (this._process.stdin.write(json)) {
                resolve();
            }
            else {
                this._process.stdin.once('drain', resolve);
            }
        });
    }
}
function isElectron() {
    return 'type' in process$2;
}

class ExperimentalClientTasks {
    constructor(_client) {
        this._client = _client;
    }
    async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
        const clientInternal = this._client;
        const optionsWithTask = {
            ...options,
            task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined)
        };
        const stream = clientInternal.requestStream({ method: 'tools/call', params }, resultSchema, optionsWithTask);
        const validator = clientInternal.getToolOutputValidator(params.name);
        for await (const message of stream) {
            if (message.type === 'result' && validator) {
                const result = message.result;
                if (!result.structuredContent && !result.isError) {
                    yield {
                        type: 'error',
                        error: new McpError(ErrorCode$1.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
                    };
                    return;
                }
                if (result.structuredContent) {
                    try {
                        const validationResult = validator(result.structuredContent);
                        if (!validationResult.valid) {
                            yield {
                                type: 'error',
                                error: new McpError(ErrorCode$1.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
                            };
                            return;
                        }
                    }
                    catch (error) {
                        if (error instanceof McpError) {
                            yield { type: 'error', error };
                            return;
                        }
                        yield {
                            type: 'error',
                            error: new McpError(ErrorCode$1.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)
                        };
                        return;
                    }
                }
            }
            yield message;
        }
    }
    async getTask(taskId, options) {
        return this._client.getTask({ taskId }, options);
    }
    async getTaskResult(taskId, resultSchema, options) {
        return this._client.getTaskResult({ taskId }, resultSchema, options);
    }
    async listTasks(cursor, options) {
        return this._client.listTasks(cursor ? { cursor } : undefined, options);
    }
    async cancelTask(taskId, options) {
        return this._client.cancelTask({ taskId }, options);
    }
    requestStream(request, resultSchema, options) {
        return this._client.requestStream(request, resultSchema, options);
    }
}

function applyElicitationDefaults(schema, data) {
    if (!schema || data === null || typeof data !== 'object')
        return;
    if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') {
        const obj = data;
        const props = schema.properties;
        for (const key of Object.keys(props)) {
            const propSchema = props[key];
            if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) {
                obj[key] = propSchema.default;
            }
            if (obj[key] !== undefined) {
                applyElicitationDefaults(propSchema, obj[key]);
            }
        }
    }
    if (Array.isArray(schema.anyOf)) {
        for (const sub of schema.anyOf) {
            if (typeof sub !== 'boolean') {
                applyElicitationDefaults(sub, data);
            }
        }
    }
    if (Array.isArray(schema.oneOf)) {
        for (const sub of schema.oneOf) {
            if (typeof sub !== 'boolean') {
                applyElicitationDefaults(sub, data);
            }
        }
    }
}
function getSupportedElicitationModes(capabilities) {
    if (!capabilities) {
        return { supportsFormMode: false, supportsUrlMode: false };
    }
    const hasFormCapability = capabilities.form !== undefined;
    const hasUrlCapability = capabilities.url !== undefined;
    const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability);
    const supportsUrlMode = hasUrlCapability;
    return { supportsFormMode, supportsUrlMode };
}
let Client$1 = class Client extends Protocol {
    constructor(_clientInfo, options) {
        super(options);
        this._clientInfo = _clientInfo;
        this._cachedToolOutputValidators = new Map();
        this._cachedKnownTaskTools = new Set();
        this._cachedRequiredTaskTools = new Set();
        this._listChangedDebounceTimers = new Map();
        this._capabilities = options?.capabilities ?? {};
        this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
        if (options?.listChanged) {
            this._pendingListChangedConfig = options.listChanged;
        }
    }
    _setupListChangedHandlers(config) {
        if (config.tools && this._serverCapabilities?.tools?.listChanged) {
            this._setupListChangedHandler('tools', ToolListChangedNotificationSchema, config.tools, async () => {
                const result = await this.listTools();
                return result.tools;
            });
        }
        if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {
            this._setupListChangedHandler('prompts', PromptListChangedNotificationSchema, config.prompts, async () => {
                const result = await this.listPrompts();
                return result.prompts;
            });
        }
        if (config.resources && this._serverCapabilities?.resources?.listChanged) {
            this._setupListChangedHandler('resources', ResourceListChangedNotificationSchema, config.resources, async () => {
                const result = await this.listResources();
                return result.resources;
            });
        }
    }
    get experimental() {
        if (!this._experimental) {
            this._experimental = {
                tasks: new ExperimentalClientTasks(this)
            };
        }
        return this._experimental;
    }
    registerCapabilities(capabilities) {
        if (this.transport) {
            throw new Error('Cannot register capabilities after connecting to transport');
        }
        this._capabilities = mergeCapabilities(this._capabilities, capabilities);
    }
    setRequestHandler(requestSchema, handler) {
        const shape = getObjectShape(requestSchema);
        const methodSchema = shape?.method;
        if (!methodSchema) {
            throw new Error('Schema is missing a method literal');
        }
        let methodValue;
        if (isZ4Schema(methodSchema)) {
            const v4Schema = methodSchema;
            const v4Def = v4Schema._zod?.def;
            methodValue = v4Def?.value ?? v4Schema.value;
        }
        else {
            const v3Schema = methodSchema;
            const legacyDef = v3Schema._def;
            methodValue = legacyDef?.value ?? v3Schema.value;
        }
        if (typeof methodValue !== 'string') {
            throw new Error('Schema method literal must be a string');
        }
        const method = methodValue;
        if (method === 'elicitation/create') {
            const wrappedHandler = async (request, extra) => {
                const validatedRequest = safeParse$1(ElicitRequestSchema, request);
                if (!validatedRequest.success) {
                    const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
                    throw new McpError(ErrorCode$1.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
                }
                const { params } = validatedRequest.data;
                params.mode = params.mode ?? 'form';
                const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
                if (params.mode === 'form' && !supportsFormMode) {
                    throw new McpError(ErrorCode$1.InvalidParams, 'Client does not support form-mode elicitation requests');
                }
                if (params.mode === 'url' && !supportsUrlMode) {
                    throw new McpError(ErrorCode$1.InvalidParams, 'Client does not support URL-mode elicitation requests');
                }
                const result = await Promise.resolve(handler(request, extra));
                if (params.task) {
                    const taskValidationResult = safeParse$1(CreateTaskResultSchema, result);
                    if (!taskValidationResult.success) {
                        const errorMessage = taskValidationResult.error instanceof Error
                            ? taskValidationResult.error.message
                            : String(taskValidationResult.error);
                        throw new McpError(ErrorCode$1.InvalidParams, `Invalid task creation result: ${errorMessage}`);
                    }
                    return taskValidationResult.data;
                }
                const validationResult = safeParse$1(ElicitResultSchema, result);
                if (!validationResult.success) {
                    const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
                    throw new McpError(ErrorCode$1.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
                }
                const validatedResult = validationResult.data;
                const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined;
                if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) {
                    if (this._capabilities.elicitation?.form?.applyDefaults) {
                        try {
                            applyElicitationDefaults(requestedSchema, validatedResult.content);
                        }
                        catch {
                        }
                    }
                }
                return validatedResult;
            };
            return super.setRequestHandler(requestSchema, wrappedHandler);
        }
        if (method === 'sampling/createMessage') {
            const wrappedHandler = async (request, extra) => {
                const validatedRequest = safeParse$1(CreateMessageRequestSchema, request);
                if (!validatedRequest.success) {
                    const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
                    throw new McpError(ErrorCode$1.InvalidParams, `Invalid sampling request: ${errorMessage}`);
                }
                const { params } = validatedRequest.data;
                const result = await Promise.resolve(handler(request, extra));
                if (params.task) {
                    const taskValidationResult = safeParse$1(CreateTaskResultSchema, result);
                    if (!taskValidationResult.success) {
                        const errorMessage = taskValidationResult.error instanceof Error
                            ? taskValidationResult.error.message
                            : String(taskValidationResult.error);
                        throw new McpError(ErrorCode$1.InvalidParams, `Invalid task creation result: ${errorMessage}`);
                    }
                    return taskValidationResult.data;
                }
                const hasTools = params.tools || params.toolChoice;
                const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
                const validationResult = safeParse$1(resultSchema, result);
                if (!validationResult.success) {
                    const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
                    throw new McpError(ErrorCode$1.InvalidParams, `Invalid sampling result: ${errorMessage}`);
                }
                return validationResult.data;
            };
            return super.setRequestHandler(requestSchema, wrappedHandler);
        }
        return super.setRequestHandler(requestSchema, handler);
    }
    assertCapability(capability, method) {
        if (!this._serverCapabilities?.[capability]) {
            throw new Error(`Server does not support ${capability} (required for ${method})`);
        }
    }
    async connect(transport, options) {
        await super.connect(transport);
        if (transport.sessionId !== undefined) {
            return;
        }
        try {
            const result = await this.request({
                method: 'initialize',
                params: {
                    protocolVersion: LATEST_PROTOCOL_VERSION,
                    capabilities: this._capabilities,
                    clientInfo: this._clientInfo
                }
            }, InitializeResultSchema, options);
            if (result === undefined) {
                throw new Error(`Server sent invalid initialize result: ${result}`);
            }
            if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
                throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
            }
            this._serverCapabilities = result.capabilities;
            this._serverVersion = result.serverInfo;
            if (transport.setProtocolVersion) {
                transport.setProtocolVersion(result.protocolVersion);
            }
            this._instructions = result.instructions;
            await this.notification({
                method: 'notifications/initialized'
            });
            if (this._pendingListChangedConfig) {
                this._setupListChangedHandlers(this._pendingListChangedConfig);
                this._pendingListChangedConfig = undefined;
            }
        }
        catch (error) {
            void this.close();
            throw error;
        }
    }
    getServerCapabilities() {
        return this._serverCapabilities;
    }
    getServerVersion() {
        return this._serverVersion;
    }
    getInstructions() {
        return this._instructions;
    }
    assertCapabilityForMethod(method) {
        switch (method) {
            case 'logging/setLevel':
                if (!this._serverCapabilities?.logging) {
                    throw new Error(`Server does not support logging (required for ${method})`);
                }
                break;
            case 'prompts/get':
            case 'prompts/list':
                if (!this._serverCapabilities?.prompts) {
                    throw new Error(`Server does not support prompts (required for ${method})`);
                }
                break;
            case 'resources/list':
            case 'resources/templates/list':
            case 'resources/read':
            case 'resources/subscribe':
            case 'resources/unsubscribe':
                if (!this._serverCapabilities?.resources) {
                    throw new Error(`Server does not support resources (required for ${method})`);
                }
                if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) {
                    throw new Error(`Server does not support resource subscriptions (required for ${method})`);
                }
                break;
            case 'tools/call':
            case 'tools/list':
                if (!this._serverCapabilities?.tools) {
                    throw new Error(`Server does not support tools (required for ${method})`);
                }
                break;
            case 'completion/complete':
                if (!this._serverCapabilities?.completions) {
                    throw new Error(`Server does not support completions (required for ${method})`);
                }
                break;
        }
    }
    assertNotificationCapability(method) {
        switch (method) {
            case 'notifications/roots/list_changed':
                if (!this._capabilities.roots?.listChanged) {
                    throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
                }
                break;
        }
    }
    assertRequestHandlerCapability(method) {
        if (!this._capabilities) {
            return;
        }
        switch (method) {
            case 'sampling/createMessage':
                if (!this._capabilities.sampling) {
                    throw new Error(`Client does not support sampling capability (required for ${method})`);
                }
                break;
            case 'elicitation/create':
                if (!this._capabilities.elicitation) {
                    throw new Error(`Client does not support elicitation capability (required for ${method})`);
                }
                break;
            case 'roots/list':
                if (!this._capabilities.roots) {
                    throw new Error(`Client does not support roots capability (required for ${method})`);
                }
                break;
            case 'tasks/get':
            case 'tasks/list':
            case 'tasks/result':
            case 'tasks/cancel':
                if (!this._capabilities.tasks) {
                    throw new Error(`Client does not support tasks capability (required for ${method})`);
                }
                break;
        }
    }
    assertTaskCapability(method) {
        assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, 'Server');
    }
    assertTaskHandlerCapability(method) {
        if (!this._capabilities) {
            return;
        }
        assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, 'Client');
    }
    async ping(options) {
        return this.request({ method: 'ping' }, EmptyResultSchema, options);
    }
    async complete(params, options) {
        return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options);
    }
    async setLoggingLevel(level, options) {
        return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options);
    }
    async getPrompt(params, options) {
        return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options);
    }
    async listPrompts(params, options) {
        return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options);
    }
    async listResources(params, options) {
        return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options);
    }
    async listResourceTemplates(params, options) {
        return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options);
    }
    async readResource(params, options) {
        return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options);
    }
    async subscribeResource(params, options) {
        return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options);
    }
    async unsubscribeResource(params, options) {
        return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options);
    }
    async callTool(params, resultSchema = CallToolResultSchema, options) {
        if (this.isToolTaskRequired(params.name)) {
            throw new McpError(ErrorCode$1.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
        }
        const result = await this.request({ method: 'tools/call', params }, resultSchema, options);
        const validator = this.getToolOutputValidator(params.name);
        if (validator) {
            if (!result.structuredContent && !result.isError) {
                throw new McpError(ErrorCode$1.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
            }
            if (result.structuredContent) {
                try {
                    const validationResult = validator(result.structuredContent);
                    if (!validationResult.valid) {
                        throw new McpError(ErrorCode$1.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
                    }
                }
                catch (error) {
                    if (error instanceof McpError) {
                        throw error;
                    }
                    throw new McpError(ErrorCode$1.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
                }
            }
        }
        return result;
    }
    isToolTask(toolName) {
        if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
            return false;
        }
        return this._cachedKnownTaskTools.has(toolName);
    }
    isToolTaskRequired(toolName) {
        return this._cachedRequiredTaskTools.has(toolName);
    }
    cacheToolMetadata(tools) {
        this._cachedToolOutputValidators.clear();
        this._cachedKnownTaskTools.clear();
        this._cachedRequiredTaskTools.clear();
        for (const tool of tools) {
            if (tool.outputSchema) {
                const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
                this._cachedToolOutputValidators.set(tool.name, toolValidator);
            }
            const taskSupport = tool.execution?.taskSupport;
            if (taskSupport === 'required' || taskSupport === 'optional') {
                this._cachedKnownTaskTools.add(tool.name);
            }
            if (taskSupport === 'required') {
                this._cachedRequiredTaskTools.add(tool.name);
            }
        }
    }
    getToolOutputValidator(toolName) {
        return this._cachedToolOutputValidators.get(toolName);
    }
    async listTools(params, options) {
        const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options);
        this.cacheToolMetadata(result.tools);
        return result;
    }
    _setupListChangedHandler(listType, notificationSchema, options, fetcher) {
        const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
        if (!parseResult.success) {
            throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
        }
        if (typeof options.onChanged !== 'function') {
            throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
        }
        const { autoRefresh, debounceMs } = parseResult.data;
        const { onChanged } = options;
        const refresh = async () => {
            if (!autoRefresh) {
                onChanged(null, null);
                return;
            }
            try {
                const items = await fetcher();
                onChanged(null, items);
            }
            catch (e) {
                const error = e instanceof Error ? e : new Error(String(e));
                onChanged(error, null);
            }
        };
        const handler = () => {
            if (debounceMs) {
                const existingTimer = this._listChangedDebounceTimers.get(listType);
                if (existingTimer) {
                    clearTimeout(existingTimer);
                }
                const timer = setTimeout(refresh, debounceMs);
                this._listChangedDebounceTimers.set(listType, timer);
            }
            else {
                refresh();
            }
        };
        this.setNotificationHandler(notificationSchema, handler);
    }
    async sendRootsListChanged() {
        return this.notification({ method: 'notifications/roots/list_changed' });
    }
};

/**
                               Apache License
                         Version 2.0, January 2004
                      http://www.apache.org/licenses/
 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
 1. Definitions.
    "License" shall mean the terms and conditions for use, reproduction,
    and distribution as defined by Sections 1 through 9 of this document.
    "Licensor" shall mean the copyright owner or entity authorized by
    the copyright owner that is granting the License.
    "Legal Entity" shall mean the union of the acting entity and all
    other entities that control, are controlled by, or are under common
    control with that entity. For the purposes of this definition,
    "control" means (i) the power, direct or indirect, to cause the
    direction or management of such entity, whether by contract or
    otherwise, or (ii) ownership of fifty percent (50%) or more of the
    outstanding shares, or (iii) beneficial ownership of such entity.
    "You" (or "Your") shall mean an individual or Legal Entity
    exercising permissions granted by this License.
    "Source" form shall mean the preferred form for making modifications,
    including but not limited to software source code, documentation
    source, and configuration files.
    "Object" form shall mean any form resulting from mechanical
    transformation or translation of a Source form, including but
    not limited to compiled object code, generated documentation,
    and conversions to other media types.
    "Work" shall mean the work of authorship, whether in Source or
    Object form, made available under the License, as indicated by a
    copyright notice that is included in or attached to the work
    (an example is provided in the Appendix below).
    "Derivative Works" shall mean any work, whether in Source or Object
    form, that is based on (or derived from) the Work and for which the
    editorial revisions, annotations, elaborations, or other modifications
    represent, as a whole, an original work of authorship. For the purposes
    of this License, Derivative Works shall not include works that remain
    separable from, or merely link (or bind by name) to the interfaces of,
    the Work and Derivative Works thereof.
    "Contribution" shall mean any work of authorship, including
    the original version of the Work and any modifications or additions
    to that Work or Derivative Works thereof, that is intentionally
    submitted to Licensor for inclusion in the Work by the copyright owner
    or by an individual or Legal Entity authorized to submit on behalf of
    the copyright owner. For the purposes of this definition, "submitted"
    means any form of electronic, verbal, or written communication sent
    to the Licensor or its representatives, including but not limited to
    communication on electronic mailing lists, source code control systems,
    and issue tracking systems that are managed by, or on behalf of, the
    Licensor for the purpose of discussing and improving the Work, but
    excluding communication that is conspicuously marked or otherwise
    designated in writing by the copyright owner as "Not a Contribution."
    "Contributor" shall mean Licensor and any individual or Legal Entity
    on behalf of whom a Contribution has been received by Licensor and
    subsequently incorporated within the Work.
 2. Grant of Copyright License. Subject to the terms and conditions of
    this License, each Contributor hereby grants to You a perpetual,
    worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    copyright license to reproduce, prepare Derivative Works of,
    publicly display, publicly perform, sublicense, and distribute the
    Work and such Derivative Works in Source or Object form.
 3. Grant of Patent License. Subject to the terms and conditions of
    this License, each Contributor hereby grants to You a perpetual,
    worldwide, non-exclusive, no-charge, royalty-free, irrevocable
    (except as stated in this section) patent license to make, have made,
    use, offer to sell, sell, import, and otherwise transfer the Work,
    where such license applies only to those patent claims licensable
    by such Contributor that are necessarily infringed by their
    Contribution(s) alone or by combination of their Contribution(s)
    with the Work to which such Contribution(s) was submitted. If You
    institute patent litigation against any entity (including a
    cross-claim or counterclaim in a lawsuit) alleging that the Work
    or a Contribution incorporated within the Work constitutes direct
    or contributory patent infringement, then any patent licenses
    granted to You under this License for that Work shall terminate
    as of the date such litigation is filed.
 4. Redistribution. You may reproduce and distribute copies of the
    Work or Derivative Works thereof in any medium, with or without
    modifications, and in Source or Object form, provided that You
    meet the following conditions:
    (a) You must give any other recipients of the Work or
        Derivative Works a copy of this License; and
    (b) You must cause any modified files to carry prominent notices
        stating that You changed the files; and
    (c) You must retain, in the Source form of any Derivative Works
        that You distribute, all copyright, patent, trademark, and
        attribution notices from the Source form of the Work,
        excluding those notices that do not pertain to any part of
        the Derivative Works; and
    (d) If the Work includes a "NOTICE" text file as part of its
        distribution, then any Derivative Works that You distribute must
        include a readable copy of the attribution notices contained
        within such NOTICE file, excluding those notices that do not
        pertain to any part of the Derivative Works, in at least one
        of the following places: within a NOTICE text file distributed
        as part of the Derivative Works; within the Source form or
        documentation, if provided along with the Derivative Works; or,
        within a display generated by the Derivative Works, if and
        wherever such third-party notices normally appear. The contents
        of the NOTICE file are for informational purposes only and
        do not modify the License. You may add Your own attribution
        notices within Derivative Works that You distribute, alongside
        or as an addendum to the NOTICE text from the Work, provided
        that such additional attribution notices cannot be construed
        as modifying the License.
    You may add Your own copyright statement to Your modifications and
    may provide additional or different license terms and conditions
    for use, reproduction, or distribution of Your modifications, or
    for any such Derivative Works as a whole, provided Your use,
    reproduction, and distribution of the Work otherwise complies with
    the conditions stated in this License.
 5. Submission of Contributions. Unless You explicitly state otherwise,
    any Contribution intentionally submitted for inclusion in the Work
    by You to the Licensor shall be under the terms and conditions of
    this License, without any additional terms or conditions.
    Notwithstanding the above, nothing herein shall supersede or modify
    the terms of any separate license agreement you may have executed
    with Licensor regarding such Contributions.
 6. Trademarks. This License does not grant permission to use the trade
    names, trademarks, service marks, or product names of the Licensor,
    except as required for reasonable and customary use in describing the
    origin of the Work and reproducing the content of the NOTICE file.
 7. Disclaimer of Warranty. Unless required by applicable law or
    agreed to in writing, Licensor provides the Work (and each
    Contributor provides its Contributions) on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    implied, including, without limitation, any warranties or conditions
    of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
    PARTICULAR PURPOSE. You are solely responsible for determining the
    appropriateness of using or redistributing the Work and assume any
    risks associated with Your exercise of permissions under this License.
 8. Limitation of Liability. In no event and under no legal theory,
    whether in tort (including negligence), contract, or otherwise,
    unless required by applicable law (such as deliberate and grossly
    negligent acts) or agreed to in writing, shall any Contributor be
    liable to You for damages, including any direct, indirect, special,
    incidental, or consequential damages of any character arising as a
    result of this License or out of the use or inability to use the
    Work (including but not limited to damages for loss of goodwill,
    work stoppage, computer failure or malfunction, or any and all
    other commercial damages or losses), even if such Contributor
    has been advised of the possibility of such damages.
 9. Accepting Warranty or Additional Liability. While redistributing
    the Work or Derivative Works thereof, You may choose to offer,
    and charge a fee for, acceptance of support, warranty, indemnity,
    or other liability obligations and/or rights consistent with this
    License. However, in accepting such obligations, You may act only
    on Your own behalf and on Your sole responsibility, not on behalf
    of any other Contributor, and only if You agree to indemnify,
    defend, and hold each Contributor harmless for any liability
    incurred by, or claims asserted against, such Contributor by reason
    of your accepting any such warranty or additional liability.
 END OF TERMS AND CONDITIONS
 APPENDIX: How to apply the Apache License to your work.
    To apply the Apache License to your work, attach the following
    boilerplate notice, with the fields enclosed by brackets "[]"
    replaced with your own identifying information. (Don't include
    the brackets!)  The text should be enclosed in the appropriate
    comment syntax for the file format. We also recommend that a
    file or class name and description of purpose be included on the
    same "printed page" as the copyright notice for easier
    identification within third-party archives.
 Copyright (c) 2015-2018 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/
var extendStatics$1 = function(d, b) {
  extendStatics$1 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
    d2.__proto__ = b2;
  } || function(d2, b2) {
    for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
  };
  return extendStatics$1(d, b);
};
function __extends$1(d, b) {
  if (typeof b !== "function" && b !== null)
    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics$1(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __awaiter$1(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, [])).next());
  });
}
function __generator$1(thisArg, body) {
  var _ = { label: 0, sent: function() {
    if (t[0] & 1) throw t[1];
    return t[1];
  }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  function step(op) {
    if (f) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_ = 0)), _) try {
      if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
      if (y = 0, t) op = [op[0] & 2, t.value];
      switch (op[0]) {
        case 0:
        case 1:
          t = op;
          break;
        case 4:
          _.label++;
          return { value: op[1], done: false };
        case 5:
          _.label++;
          y = op[1];
          op = [0];
          continue;
        case 7:
          op = _.ops.pop();
          _.trys.pop();
          continue;
        default:
          if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _ = 0;
            continue;
          }
          if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
            _.label = op[1];
            break;
          }
          if (op[0] === 6 && _.label < t[1]) {
            _.label = t[1];
            t = op;
            break;
          }
          if (t && _.label < t[2]) {
            _.label = t[2];
            _.ops.push(op);
            break;
          }
          if (t[2]) _.ops.pop();
          _.trys.pop();
          continue;
      }
      op = body.call(thisArg, _);
    } catch (e) {
      op = [6, e];
      y = 0;
    } finally {
      f = t = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __values$1(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  if (m) return m.call(o);
  if (o && typeof o.length === "number") return {
    next: function() {
      if (o && i >= o.length) o = void 0;
      return { value: o && o[i++], done: !o };
    }
  };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read$1(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m) return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  } catch (error) {
    e = { error };
  } finally {
    try {
      if (r && !r.done && (m = i["return"])) m.call(i);
    } finally {
      if (e) throw e.error;
    }
  }
  return ar;
}
function __spreadArray$1(to, from2, pack) {
  if (arguments.length === 2) for (var i = 0, l = from2.length, ar; i < l; i++) {
    if (ar || !(i in from2)) {
      if (!ar) ar = Array.prototype.slice.call(from2, 0, i);
      ar[i] = from2[i];
    }
  }
  return to.concat(ar || Array.prototype.slice.call(from2));
}
function __await$1(v) {
  return this instanceof __await$1 ? (this.v = v, this) : new __await$1(v);
}
function __asyncGenerator$1(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
  return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
    return this;
  }, i;
  function awaitReturn(f) {
    return function(v) {
      return Promise.resolve(v).then(f, reject);
    };
  }
  function verb(n, f) {
    if (g[n]) {
      i[n] = function(v) {
        return new Promise(function(a, b) {
          q.push([n, v, a, b]) > 1 || resume(n, v);
        });
      };
      if (f) i[n] = f(i[n]);
    }
  }
  function resume(n, v) {
    try {
      step(g[n](v));
    } catch (e) {
      settle(q[0][3], e);
    }
  }
  function step(r) {
    r.value instanceof __await$1 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f, v) {
    if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
  }
}
function __asyncValues$1(o) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values$1 === "function" ? __values$1(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function verb(n) {
    i[n] = o[n] && function(v) {
      return new Promise(function(resolve, reject) {
        v = o[n](v), settle(resolve, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve({ value: v2, done: d });
    }, reject);
  }
}
function isFunction(value) {
  return typeof value === "function";
}
function createErrorClass(createImpl) {
  var _super = function(instance) {
    Error.call(instance);
    instance.stack = new Error().stack;
  };
  var ctorFunc = createImpl(_super);
  ctorFunc.prototype = Object.create(Error.prototype);
  ctorFunc.prototype.constructor = ctorFunc;
  return ctorFunc;
}
var UnsubscriptionError = createErrorClass(function(_super) {
  return function UnsubscriptionErrorImpl(errors) {
    _super(this);
    this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
      return i + 1 + ") " + err.toString();
    }).join("\n  ") : "";
    this.name = "UnsubscriptionError";
    this.errors = errors;
  };
});
function arrRemove(arr, item) {
  if (arr) {
    var index = arr.indexOf(item);
    0 <= index && arr.splice(index, 1);
  }
}
var Subscription = (function() {
  function Subscription2(initialTeardown) {
    this.initialTeardown = initialTeardown;
    this.closed = false;
    this._parentage = null;
    this._finalizers = null;
  }
  Subscription2.prototype.unsubscribe = function() {
    var e_1, _a, e_2, _b;
    var errors;
    if (!this.closed) {
      this.closed = true;
      var _parentage = this._parentage;
      if (_parentage) {
        this._parentage = null;
        if (Array.isArray(_parentage)) {
          try {
            for (var _parentage_1 = __values$1(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
              var parent_1 = _parentage_1_1.value;
              parent_1.remove(this);
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
            } finally {
              if (e_1) throw e_1.error;
            }
          }
        } else {
          _parentage.remove(this);
        }
      }
      var initialFinalizer = this.initialTeardown;
      if (isFunction(initialFinalizer)) {
        try {
          initialFinalizer();
        } catch (e) {
          errors = e instanceof UnsubscriptionError ? e.errors : [e];
        }
      }
      var _finalizers = this._finalizers;
      if (_finalizers) {
        this._finalizers = null;
        try {
          for (var _finalizers_1 = __values$1(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
            var finalizer = _finalizers_1_1.value;
            try {
              execFinalizer(finalizer);
            } catch (err) {
              errors = errors !== null && errors !== void 0 ? errors : [];
              if (err instanceof UnsubscriptionError) {
                errors = __spreadArray$1(__spreadArray$1([], __read$1(errors)), __read$1(err.errors));
              } else {
                errors.push(err);
              }
            }
          }
        } catch (e_2_1) {
          e_2 = { error: e_2_1 };
        } finally {
          try {
            if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
          } finally {
            if (e_2) throw e_2.error;
          }
        }
      }
      if (errors) {
        throw new UnsubscriptionError(errors);
      }
    }
  };
  Subscription2.prototype.add = function(teardown) {
    var _a;
    if (teardown && teardown !== this) {
      if (this.closed) {
        execFinalizer(teardown);
      } else {
        if (teardown instanceof Subscription2) {
          if (teardown.closed || teardown._hasParent(this)) {
            return;
          }
          teardown._addParent(this);
        }
        (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
      }
    }
  };
  Subscription2.prototype._hasParent = function(parent) {
    var _parentage = this._parentage;
    return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
  };
  Subscription2.prototype._addParent = function(parent) {
    var _parentage = this._parentage;
    this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
  };
  Subscription2.prototype._removeParent = function(parent) {
    var _parentage = this._parentage;
    if (_parentage === parent) {
      this._parentage = null;
    } else if (Array.isArray(_parentage)) {
      arrRemove(_parentage, parent);
    }
  };
  Subscription2.prototype.remove = function(teardown) {
    var _finalizers = this._finalizers;
    _finalizers && arrRemove(_finalizers, teardown);
    if (teardown instanceof Subscription2) {
      teardown._removeParent(this);
    }
  };
  Subscription2.EMPTY = (function() {
    var empty = new Subscription2();
    empty.closed = true;
    return empty;
  })();
  return Subscription2;
})();
var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
function isSubscription(value) {
  return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
}
function execFinalizer(finalizer) {
  if (isFunction(finalizer)) {
    finalizer();
  } else {
    finalizer.unsubscribe();
  }
}
var config$2 = {
  Promise: void 0};
var timeoutProvider = {
  setTimeout: function(handler, timeout) {
    var args = [];
    for (var _i = 2; _i < arguments.length; _i++) {
      args[_i - 2] = arguments[_i];
    }
    return setTimeout.apply(void 0, __spreadArray$1([handler, timeout], __read$1(args)));
  },
  clearTimeout: function(handle) {
    return (clearTimeout)(handle);
  },
  delegate: void 0
};
function reportUnhandledError(err) {
  timeoutProvider.setTimeout(function() {
    {
      throw err;
    }
  });
}
function noop() {
}
function errorContext(cb) {
  {
    cb();
  }
}
var Subscriber = (function(_super) {
  __extends$1(Subscriber2, _super);
  function Subscriber2(destination) {
    var _this = _super.call(this) || this;
    _this.isStopped = false;
    if (destination) {
      _this.destination = destination;
      if (isSubscription(destination)) {
        destination.add(_this);
      }
    } else {
      _this.destination = EMPTY_OBSERVER;
    }
    return _this;
  }
  Subscriber2.create = function(next, error, complete) {
    return new SafeSubscriber(next, error, complete);
  };
  Subscriber2.prototype.next = function(value) {
    if (this.isStopped) ; else {
      this._next(value);
    }
  };
  Subscriber2.prototype.error = function(err) {
    if (this.isStopped) ; else {
      this.isStopped = true;
      this._error(err);
    }
  };
  Subscriber2.prototype.complete = function() {
    if (this.isStopped) ; else {
      this.isStopped = true;
      this._complete();
    }
  };
  Subscriber2.prototype.unsubscribe = function() {
    if (!this.closed) {
      this.isStopped = true;
      _super.prototype.unsubscribe.call(this);
      this.destination = null;
    }
  };
  Subscriber2.prototype._next = function(value) {
    this.destination.next(value);
  };
  Subscriber2.prototype._error = function(err) {
    try {
      this.destination.error(err);
    } finally {
      this.unsubscribe();
    }
  };
  Subscriber2.prototype._complete = function() {
    try {
      this.destination.complete();
    } finally {
      this.unsubscribe();
    }
  };
  return Subscriber2;
})(Subscription);
var ConsumerObserver = (function() {
  function ConsumerObserver2(partialObserver) {
    this.partialObserver = partialObserver;
  }
  ConsumerObserver2.prototype.next = function(value) {
    var partialObserver = this.partialObserver;
    if (partialObserver.next) {
      try {
        partialObserver.next(value);
      } catch (error) {
        handleUnhandledError(error);
      }
    }
  };
  ConsumerObserver2.prototype.error = function(err) {
    var partialObserver = this.partialObserver;
    if (partialObserver.error) {
      try {
        partialObserver.error(err);
      } catch (error) {
        handleUnhandledError(error);
      }
    } else {
      handleUnhandledError(err);
    }
  };
  ConsumerObserver2.prototype.complete = function() {
    var partialObserver = this.partialObserver;
    if (partialObserver.complete) {
      try {
        partialObserver.complete();
      } catch (error) {
        handleUnhandledError(error);
      }
    }
  };
  return ConsumerObserver2;
})();
var SafeSubscriber = (function(_super) {
  __extends$1(SafeSubscriber2, _super);
  function SafeSubscriber2(observerOrNext, error, complete) {
    var _this = _super.call(this) || this;
    var partialObserver;
    if (isFunction(observerOrNext) || !observerOrNext) {
      partialObserver = {
        next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0,
        error: error !== null && error !== void 0 ? error : void 0,
        complete: complete !== null && complete !== void 0 ? complete : void 0
      };
    } else {
      {
        partialObserver = observerOrNext;
      }
    }
    _this.destination = new ConsumerObserver(partialObserver);
    return _this;
  }
  return SafeSubscriber2;
})(Subscriber);
function handleUnhandledError(error) {
  {
    reportUnhandledError(error);
  }
}
function defaultErrorHandler(err) {
  throw err;
}
var EMPTY_OBSERVER = {
  closed: true,
  next: noop,
  error: defaultErrorHandler,
  complete: noop
};
var observable = (function() {
  return typeof Symbol === "function" && Symbol.observable || "@@observable";
})();
function identity(x) {
  return x;
}
function pipe() {
  var fns = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    fns[_i] = arguments[_i];
  }
  return pipeFromArray(fns);
}
function pipeFromArray(fns) {
  if (fns.length === 0) {
    return identity;
  }
  if (fns.length === 1) {
    return fns[0];
  }
  return function piped(input) {
    return fns.reduce(function(prev, fn) {
      return fn(prev);
    }, input);
  };
}
var Observable = (function() {
  function Observable2(subscribe) {
    if (subscribe) {
      this._subscribe = subscribe;
    }
  }
  Observable2.prototype.lift = function(operator) {
    var observable2 = new Observable2();
    observable2.source = this;
    observable2.operator = operator;
    return observable2;
  };
  Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
    var _this = this;
    var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
    errorContext(function() {
      var _a = _this, operator = _a.operator, source = _a.source;
      subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
    });
    return subscriber;
  };
  Observable2.prototype._trySubscribe = function(sink) {
    try {
      return this._subscribe(sink);
    } catch (err) {
      sink.error(err);
    }
  };
  Observable2.prototype.forEach = function(next, promiseCtor) {
    var _this = this;
    promiseCtor = getPromiseCtor(promiseCtor);
    return new promiseCtor(function(resolve, reject) {
      var subscriber = new SafeSubscriber({
        next: function(value) {
          try {
            next(value);
          } catch (err) {
            reject(err);
            subscriber.unsubscribe();
          }
        },
        error: reject,
        complete: resolve
      });
      _this.subscribe(subscriber);
    });
  };
  Observable2.prototype._subscribe = function(subscriber) {
    var _a;
    return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
  };
  Observable2.prototype[observable] = function() {
    return this;
  };
  Observable2.prototype.pipe = function() {
    var operations = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      operations[_i] = arguments[_i];
    }
    return pipeFromArray(operations)(this);
  };
  Observable2.prototype.toPromise = function(promiseCtor) {
    var _this = this;
    promiseCtor = getPromiseCtor(promiseCtor);
    return new promiseCtor(function(resolve, reject) {
      var value;
      _this.subscribe(function(x) {
        return value = x;
      }, function(err) {
        return reject(err);
      }, function() {
        return resolve(value);
      });
    });
  };
  Observable2.create = function(subscribe) {
    return new Observable2(subscribe);
  };
  return Observable2;
})();
function getPromiseCtor(promiseCtor) {
  var _a;
  return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config$2.Promise) !== null && _a !== void 0 ? _a : Promise;
}
function isObserver(value) {
  return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
}
function isSubscriber(value) {
  return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
}
function hasLift(source) {
  return isFunction(source === null || source === void 0 ? void 0 : source.lift);
}
function operate(init) {
  return function(source) {
    if (hasLift(source)) {
      return source.lift(function(liftedSource) {
        try {
          return init(liftedSource, this);
        } catch (err) {
          this.error(err);
        }
      });
    }
    throw new TypeError("Unable to lift unknown Observable type");
  };
}
function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
  return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
}
var OperatorSubscriber = (function(_super) {
  __extends$1(OperatorSubscriber2, _super);
  function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
    var _this = _super.call(this, destination) || this;
    _this.onFinalize = onFinalize;
    _this.shouldUnsubscribe = shouldUnsubscribe;
    _this._next = onNext ? function(value) {
      try {
        onNext(value);
      } catch (err) {
        destination.error(err);
      }
    } : _super.prototype._next;
    _this._error = onError ? function(err) {
      try {
        onError(err);
      } catch (err2) {
        destination.error(err2);
      } finally {
        this.unsubscribe();
      }
    } : _super.prototype._error;
    _this._complete = onComplete ? function() {
      try {
        onComplete();
      } catch (err) {
        destination.error(err);
      } finally {
        this.unsubscribe();
      }
    } : _super.prototype._complete;
    return _this;
  }
  OperatorSubscriber2.prototype.unsubscribe = function() {
    var _a;
    if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
      var closed_1 = this.closed;
      _super.prototype.unsubscribe.call(this);
      !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
    }
  };
  return OperatorSubscriber2;
})(Subscriber);
var ObjectUnsubscribedError = createErrorClass(function(_super) {
  return function ObjectUnsubscribedErrorImpl() {
    _super(this);
    this.name = "ObjectUnsubscribedError";
    this.message = "object unsubscribed";
  };
});
var Subject = (function(_super) {
  __extends$1(Subject2, _super);
  function Subject2() {
    var _this = _super.call(this) || this;
    _this.closed = false;
    _this.currentObservers = null;
    _this.observers = [];
    _this.isStopped = false;
    _this.hasError = false;
    _this.thrownError = null;
    return _this;
  }
  Subject2.prototype.lift = function(operator) {
    var subject = new AnonymousSubject(this, this);
    subject.operator = operator;
    return subject;
  };
  Subject2.prototype._throwIfClosed = function() {
    if (this.closed) {
      throw new ObjectUnsubscribedError();
    }
  };
  Subject2.prototype.next = function(value) {
    var _this = this;
    errorContext(function() {
      var e_1, _a;
      _this._throwIfClosed();
      if (!_this.isStopped) {
        if (!_this.currentObservers) {
          _this.currentObservers = Array.from(_this.observers);
        }
        try {
          for (var _b = __values$1(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
            var observer = _c.value;
            observer.next(value);
          }
        } catch (e_1_1) {
          e_1 = { error: e_1_1 };
        } finally {
          try {
            if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
          } finally {
            if (e_1) throw e_1.error;
          }
        }
      }
    });
  };
  Subject2.prototype.error = function(err) {
    var _this = this;
    errorContext(function() {
      _this._throwIfClosed();
      if (!_this.isStopped) {
        _this.hasError = _this.isStopped = true;
        _this.thrownError = err;
        var observers = _this.observers;
        while (observers.length) {
          observers.shift().error(err);
        }
      }
    });
  };
  Subject2.prototype.complete = function() {
    var _this = this;
    errorContext(function() {
      _this._throwIfClosed();
      if (!_this.isStopped) {
        _this.isStopped = true;
        var observers = _this.observers;
        while (observers.length) {
          observers.shift().complete();
        }
      }
    });
  };
  Subject2.prototype.unsubscribe = function() {
    this.isStopped = this.closed = true;
    this.observers = this.currentObservers = null;
  };
  Object.defineProperty(Subject2.prototype, "observed", {
    get: function() {
      var _a;
      return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
    },
    enumerable: false,
    configurable: true
  });
  Subject2.prototype._trySubscribe = function(subscriber) {
    this._throwIfClosed();
    return _super.prototype._trySubscribe.call(this, subscriber);
  };
  Subject2.prototype._subscribe = function(subscriber) {
    this._throwIfClosed();
    this._checkFinalizedStatuses(subscriber);
    return this._innerSubscribe(subscriber);
  };
  Subject2.prototype._innerSubscribe = function(subscriber) {
    var _this = this;
    var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
    if (hasError || isStopped) {
      return EMPTY_SUBSCRIPTION;
    }
    this.currentObservers = null;
    observers.push(subscriber);
    return new Subscription(function() {
      _this.currentObservers = null;
      arrRemove(observers, subscriber);
    });
  };
  Subject2.prototype._checkFinalizedStatuses = function(subscriber) {
    var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
    if (hasError) {
      subscriber.error(thrownError);
    } else if (isStopped) {
      subscriber.complete();
    }
  };
  Subject2.prototype.asObservable = function() {
    var observable2 = new Observable();
    observable2.source = this;
    return observable2;
  };
  Subject2.create = function(destination, source) {
    return new AnonymousSubject(destination, source);
  };
  return Subject2;
})(Observable);
var AnonymousSubject = (function(_super) {
  __extends$1(AnonymousSubject2, _super);
  function AnonymousSubject2(destination, source) {
    var _this = _super.call(this) || this;
    _this.destination = destination;
    _this.source = source;
    return _this;
  }
  AnonymousSubject2.prototype.next = function(value) {
    var _a, _b;
    (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
  };
  AnonymousSubject2.prototype.error = function(err) {
    var _a, _b;
    (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
  };
  AnonymousSubject2.prototype.complete = function() {
    var _a, _b;
    (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
  };
  AnonymousSubject2.prototype._subscribe = function(subscriber) {
    var _a, _b;
    return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
  };
  return AnonymousSubject2;
})(Subject);
var dateTimestampProvider = {
  now: function() {
    return (dateTimestampProvider.delegate || Date).now();
  },
  delegate: void 0
};
var ReplaySubject = (function(_super) {
  __extends$1(ReplaySubject2, _super);
  function ReplaySubject2(_bufferSize, _windowTime, _timestampProvider) {
    if (_bufferSize === void 0) {
      _bufferSize = Infinity;
    }
    if (_windowTime === void 0) {
      _windowTime = Infinity;
    }
    if (_timestampProvider === void 0) {
      _timestampProvider = dateTimestampProvider;
    }
    var _this = _super.call(this) || this;
    _this._bufferSize = _bufferSize;
    _this._windowTime = _windowTime;
    _this._timestampProvider = _timestampProvider;
    _this._buffer = [];
    _this._infiniteTimeWindow = true;
    _this._infiniteTimeWindow = _windowTime === Infinity;
    _this._bufferSize = Math.max(1, _bufferSize);
    _this._windowTime = Math.max(1, _windowTime);
    return _this;
  }
  ReplaySubject2.prototype.next = function(value) {
    var _a = this, isStopped = _a.isStopped, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow, _timestampProvider = _a._timestampProvider, _windowTime = _a._windowTime;
    if (!isStopped) {
      _buffer.push(value);
      !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
    }
    this._trimBuffer();
    _super.prototype.next.call(this, value);
  };
  ReplaySubject2.prototype._subscribe = function(subscriber) {
    this._throwIfClosed();
    this._trimBuffer();
    var subscription = this._innerSubscribe(subscriber);
    var _a = this, _infiniteTimeWindow = _a._infiniteTimeWindow, _buffer = _a._buffer;
    var copy = _buffer.slice();
    for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
      subscriber.next(copy[i]);
    }
    this._checkFinalizedStatuses(subscriber);
    return subscription;
  };
  ReplaySubject2.prototype._trimBuffer = function() {
    var _a = this, _bufferSize = _a._bufferSize, _timestampProvider = _a._timestampProvider, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow;
    var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
    _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
    if (!_infiniteTimeWindow) {
      var now = _timestampProvider.now();
      var last2 = 0;
      for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {
        last2 = i;
      }
      last2 && _buffer.splice(0, last2 + 1);
    }
  };
  return ReplaySubject2;
})(Subject);
var Action$1 = (function(_super) {
  __extends$1(Action2, _super);
  function Action2(scheduler, work) {
    return _super.call(this) || this;
  }
  Action2.prototype.schedule = function(state, delay2) {
    return this;
  };
  return Action2;
})(Subscription);
var intervalProvider = {
  setInterval: function(handler, timeout) {
    var args = [];
    for (var _i = 2; _i < arguments.length; _i++) {
      args[_i - 2] = arguments[_i];
    }
    return setInterval.apply(void 0, __spreadArray$1([handler, timeout], __read$1(args)));
  },
  clearInterval: function(handle) {
    return (clearInterval)(handle);
  },
  delegate: void 0
};
var AsyncAction = (function(_super) {
  __extends$1(AsyncAction2, _super);
  function AsyncAction2(scheduler, work) {
    var _this = _super.call(this, scheduler, work) || this;
    _this.scheduler = scheduler;
    _this.work = work;
    _this.pending = false;
    return _this;
  }
  AsyncAction2.prototype.schedule = function(state, delay2) {
    var _a;
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (this.closed) {
      return this;
    }
    this.state = state;
    var id = this.id;
    var scheduler = this.scheduler;
    if (id != null) {
      this.id = this.recycleAsyncId(scheduler, id, delay2);
    }
    this.pending = true;
    this.delay = delay2;
    this.id = (_a = this.id) !== null && _a !== void 0 ? _a : this.requestAsyncId(scheduler, this.id, delay2);
    return this;
  };
  AsyncAction2.prototype.requestAsyncId = function(scheduler, _id, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay2);
  };
  AsyncAction2.prototype.recycleAsyncId = function(_scheduler, id, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (delay2 != null && this.delay === delay2 && this.pending === false) {
      return id;
    }
    if (id != null) {
      intervalProvider.clearInterval(id);
    }
    return void 0;
  };
  AsyncAction2.prototype.execute = function(state, delay2) {
    if (this.closed) {
      return new Error("executing a cancelled action");
    }
    this.pending = false;
    var error = this._execute(state, delay2);
    if (error) {
      return error;
    } else if (this.pending === false && this.id != null) {
      this.id = this.recycleAsyncId(this.scheduler, this.id, null);
    }
  };
  AsyncAction2.prototype._execute = function(state, _delay) {
    var errored = false;
    var errorValue;
    try {
      this.work(state);
    } catch (e) {
      errored = true;
      errorValue = e ? e : new Error("Scheduled action threw falsy error");
    }
    if (errored) {
      this.unsubscribe();
      return errorValue;
    }
  };
  AsyncAction2.prototype.unsubscribe = function() {
    if (!this.closed) {
      var _a = this, id = _a.id, scheduler = _a.scheduler;
      var actions = scheduler.actions;
      this.work = this.state = this.scheduler = null;
      this.pending = false;
      arrRemove(actions, this);
      if (id != null) {
        this.id = this.recycleAsyncId(scheduler, id, null);
      }
      this.delay = null;
      _super.prototype.unsubscribe.call(this);
    }
  };
  return AsyncAction2;
})(Action$1);
var Scheduler = (function() {
  function Scheduler2(schedulerActionCtor, now) {
    if (now === void 0) {
      now = Scheduler2.now;
    }
    this.schedulerActionCtor = schedulerActionCtor;
    this.now = now;
  }
  Scheduler2.prototype.schedule = function(work, delay2, state) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    return new this.schedulerActionCtor(this, work).schedule(state, delay2);
  };
  Scheduler2.now = dateTimestampProvider.now;
  return Scheduler2;
})();
var AsyncScheduler = (function(_super) {
  __extends$1(AsyncScheduler2, _super);
  function AsyncScheduler2(SchedulerAction, now) {
    if (now === void 0) {
      now = Scheduler.now;
    }
    var _this = _super.call(this, SchedulerAction, now) || this;
    _this.actions = [];
    _this._active = false;
    return _this;
  }
  AsyncScheduler2.prototype.flush = function(action) {
    var actions = this.actions;
    if (this._active) {
      actions.push(action);
      return;
    }
    var error;
    this._active = true;
    do {
      if (error = action.execute(action.state, action.delay)) {
        break;
      }
    } while (action = actions.shift());
    this._active = false;
    if (error) {
      while (action = actions.shift()) {
        action.unsubscribe();
      }
      throw error;
    }
  };
  return AsyncScheduler2;
})(Scheduler);
var asyncScheduler = new AsyncScheduler(AsyncAction);
var async = asyncScheduler;
var EMPTY = new Observable(function(subscriber) {
  return subscriber.complete();
});
function isScheduler(value) {
  return value && isFunction(value.schedule);
}
function last(arr) {
  return arr[arr.length - 1];
}
function popScheduler(args) {
  return isScheduler(last(args)) ? args.pop() : void 0;
}
function popNumber(args, defaultValue) {
  return typeof last(args) === "number" ? args.pop() : defaultValue;
}
var isArrayLike = (function(x) {
  return x && typeof x.length === "number" && typeof x !== "function";
});
function isPromise(value) {
  return isFunction(value === null || value === void 0 ? void 0 : value.then);
}
function isInteropObservable(input) {
  return isFunction(input[observable]);
}
function isAsyncIterable(obj) {
  return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
}
function createInvalidObservableTypeError(input) {
  return new TypeError("You provided " + (input !== null && typeof input === "object" ? "an invalid object" : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
}
function getSymbolIterator() {
  if (typeof Symbol !== "function" || !Symbol.iterator) {
    return "@@iterator";
  }
  return Symbol.iterator;
}
var iterator = getSymbolIterator();
function isIterable(input) {
  return isFunction(input === null || input === void 0 ? void 0 : input[iterator]);
}
function readableStreamLikeToAsyncGenerator(readableStream) {
  return __asyncGenerator$1(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
    var reader, _a, value, done;
    return __generator$1(this, function(_b) {
      switch (_b.label) {
        case 0:
          reader = readableStream.getReader();
          _b.label = 1;
        case 1:
          _b.trys.push([1, , 9, 10]);
          _b.label = 2;
        case 2:
          return [4, __await$1(reader.read())];
        case 3:
          _a = _b.sent(), value = _a.value, done = _a.done;
          if (!done) return [3, 5];
          return [4, __await$1(void 0)];
        case 4:
          return [2, _b.sent()];
        case 5:
          return [4, __await$1(value)];
        case 6:
          return [4, _b.sent()];
        case 7:
          _b.sent();
          return [3, 2];
        case 8:
          return [3, 10];
        case 9:
          reader.releaseLock();
          return [7];
        case 10:
          return [2];
      }
    });
  });
}
function isReadableStreamLike(obj) {
  return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);
}
function innerFrom(input) {
  if (input instanceof Observable) {
    return input;
  }
  if (input != null) {
    if (isInteropObservable(input)) {
      return fromInteropObservable(input);
    }
    if (isArrayLike(input)) {
      return fromArrayLike(input);
    }
    if (isPromise(input)) {
      return fromPromise(input);
    }
    if (isAsyncIterable(input)) {
      return fromAsyncIterable(input);
    }
    if (isIterable(input)) {
      return fromIterable(input);
    }
    if (isReadableStreamLike(input)) {
      return fromReadableStreamLike(input);
    }
  }
  throw createInvalidObservableTypeError(input);
}
function fromInteropObservable(obj) {
  return new Observable(function(subscriber) {
    var obs = obj[observable]();
    if (isFunction(obs.subscribe)) {
      return obs.subscribe(subscriber);
    }
    throw new TypeError("Provided object does not correctly implement Symbol.observable");
  });
}
function fromArrayLike(array) {
  return new Observable(function(subscriber) {
    for (var i = 0; i < array.length && !subscriber.closed; i++) {
      subscriber.next(array[i]);
    }
    subscriber.complete();
  });
}
function fromPromise(promise) {
  return new Observable(function(subscriber) {
    promise.then(function(value) {
      if (!subscriber.closed) {
        subscriber.next(value);
        subscriber.complete();
      }
    }, function(err) {
      return subscriber.error(err);
    }).then(null, reportUnhandledError);
  });
}
function fromIterable(iterable) {
  return new Observable(function(subscriber) {
    var e_1, _a;
    try {
      for (var iterable_1 = __values$1(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
        var value = iterable_1_1.value;
        subscriber.next(value);
        if (subscriber.closed) {
          return;
        }
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);
      } finally {
        if (e_1) throw e_1.error;
      }
    }
    subscriber.complete();
  });
}
function fromAsyncIterable(asyncIterable) {
  return new Observable(function(subscriber) {
    process$1(asyncIterable, subscriber).catch(function(err) {
      return subscriber.error(err);
    });
  });
}
function fromReadableStreamLike(readableStream) {
  return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
}
function process$1(asyncIterable, subscriber) {
  var asyncIterable_1, asyncIterable_1_1;
  var e_2, _a;
  return __awaiter$1(this, void 0, void 0, function() {
    var value, e_2_1;
    return __generator$1(this, function(_b) {
      switch (_b.label) {
        case 0:
          _b.trys.push([0, 5, 6, 11]);
          asyncIterable_1 = __asyncValues$1(asyncIterable);
          _b.label = 1;
        case 1:
          return [4, asyncIterable_1.next()];
        case 2:
          if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];
          value = asyncIterable_1_1.value;
          subscriber.next(value);
          if (subscriber.closed) {
            return [2];
          }
          _b.label = 3;
        case 3:
          return [3, 1];
        case 4:
          return [3, 11];
        case 5:
          e_2_1 = _b.sent();
          e_2 = { error: e_2_1 };
          return [3, 11];
        case 6:
          _b.trys.push([6, , 9, 10]);
          if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];
          return [4, _a.call(asyncIterable_1)];
        case 7:
          _b.sent();
          _b.label = 8;
        case 8:
          return [3, 10];
        case 9:
          if (e_2) throw e_2.error;
          return [7];
        case 10:
          return [7];
        case 11:
          subscriber.complete();
          return [2];
      }
    });
  });
}
function executeSchedule(parentSubscription, scheduler, work, delay2, repeat) {
  if (delay2 === void 0) {
    delay2 = 0;
  }
  if (repeat === void 0) {
    repeat = false;
  }
  var scheduleSubscription = scheduler.schedule(function() {
    work();
    if (repeat) {
      parentSubscription.add(this.schedule(null, delay2));
    } else {
      this.unsubscribe();
    }
  }, delay2);
  parentSubscription.add(scheduleSubscription);
  if (!repeat) {
    return scheduleSubscription;
  }
}
function observeOn(scheduler, delay2) {
  if (delay2 === void 0) {
    delay2 = 0;
  }
  return operate(function(source, subscriber) {
    source.subscribe(createOperatorSubscriber(subscriber, function(value) {
      return executeSchedule(subscriber, scheduler, function() {
        return subscriber.next(value);
      }, delay2);
    }, function() {
      return executeSchedule(subscriber, scheduler, function() {
        return subscriber.complete();
      }, delay2);
    }, function(err) {
      return executeSchedule(subscriber, scheduler, function() {
        return subscriber.error(err);
      }, delay2);
    }));
  });
}
function subscribeOn(scheduler, delay2) {
  if (delay2 === void 0) {
    delay2 = 0;
  }
  return operate(function(source, subscriber) {
    subscriber.add(scheduler.schedule(function() {
      return source.subscribe(subscriber);
    }, delay2));
  });
}
function scheduleObservable(input, scheduler) {
  return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
}
function schedulePromise(input, scheduler) {
  return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
}
function scheduleArray(input, scheduler) {
  return new Observable(function(subscriber) {
    var i = 0;
    return scheduler.schedule(function() {
      if (i === input.length) {
        subscriber.complete();
      } else {
        subscriber.next(input[i++]);
        if (!subscriber.closed) {
          this.schedule();
        }
      }
    });
  });
}
function scheduleIterable(input, scheduler) {
  return new Observable(function(subscriber) {
    var iterator2;
    executeSchedule(subscriber, scheduler, function() {
      iterator2 = input[iterator]();
      executeSchedule(subscriber, scheduler, function() {
        var _a;
        var value;
        var done;
        try {
          _a = iterator2.next(), value = _a.value, done = _a.done;
        } catch (err) {
          subscriber.error(err);
          return;
        }
        if (done) {
          subscriber.complete();
        } else {
          subscriber.next(value);
        }
      }, 0, true);
    });
    return function() {
      return isFunction(iterator2 === null || iterator2 === void 0 ? void 0 : iterator2.return) && iterator2.return();
    };
  });
}
function scheduleAsyncIterable(input, scheduler) {
  if (!input) {
    throw new Error("Iterable cannot be null");
  }
  return new Observable(function(subscriber) {
    executeSchedule(subscriber, scheduler, function() {
      var iterator2 = input[Symbol.asyncIterator]();
      executeSchedule(subscriber, scheduler, function() {
        iterator2.next().then(function(result) {
          if (result.done) {
            subscriber.complete();
          } else {
            subscriber.next(result.value);
          }
        });
      }, 0, true);
    });
  });
}
function scheduleReadableStreamLike(input, scheduler) {
  return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);
}
function scheduled(input, scheduler) {
  if (input != null) {
    if (isInteropObservable(input)) {
      return scheduleObservable(input, scheduler);
    }
    if (isArrayLike(input)) {
      return scheduleArray(input, scheduler);
    }
    if (isPromise(input)) {
      return schedulePromise(input, scheduler);
    }
    if (isAsyncIterable(input)) {
      return scheduleAsyncIterable(input, scheduler);
    }
    if (isIterable(input)) {
      return scheduleIterable(input, scheduler);
    }
    if (isReadableStreamLike(input)) {
      return scheduleReadableStreamLike(input, scheduler);
    }
  }
  throw createInvalidObservableTypeError(input);
}
function from(input, scheduler) {
  return scheduler ? scheduled(input, scheduler) : innerFrom(input);
}
function of() {
  var args = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    args[_i] = arguments[_i];
  }
  var scheduler = popScheduler(args);
  return from(args, scheduler);
}
var EmptyError = createErrorClass(function(_super) {
  return function EmptyErrorImpl() {
    _super(this);
    this.name = "EmptyError";
    this.message = "no elements in sequence";
  };
});
function lastValueFrom(source, config2) {
  var hasConfig = typeof config2 === "object";
  return new Promise(function(resolve, reject) {
    var _hasValue = false;
    var _value;
    source.subscribe({
      next: function(value) {
        _value = value;
        _hasValue = true;
      },
      error: reject,
      complete: function() {
        if (_hasValue) {
          resolve(_value);
        } else if (hasConfig) {
          resolve(config2.defaultValue);
        } else {
          reject(new EmptyError());
        }
      }
    });
  });
}
function firstValueFrom(source, config2) {
  return new Promise(function(resolve, reject) {
    var subscriber = new SafeSubscriber({
      next: function(value) {
        resolve(value);
        subscriber.unsubscribe();
      },
      error: reject,
      complete: function() {
        {
          reject(new EmptyError());
        }
      }
    });
    source.subscribe(subscriber);
  });
}
function isValidDate(value) {
  return value instanceof Date && !isNaN(value);
}
function map(project, thisArg) {
  return operate(function(source, subscriber) {
    var index = 0;
    source.subscribe(createOperatorSubscriber(subscriber, function(value) {
      subscriber.next(project.call(thisArg, value, index++));
    }));
  });
}
var isArray = Array.isArray;
function callOrApply(fn, args) {
  return isArray(args) ? fn.apply(void 0, __spreadArray$1([], __read$1(args))) : fn(args);
}
function mapOneOrManyArgs(fn) {
  return map(function(args) {
    return callOrApply(fn, args);
  });
}
function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
  var buffer = [];
  var active = 0;
  var index = 0;
  var isComplete = false;
  var checkComplete = function() {
    if (isComplete && !buffer.length && !active) {
      subscriber.complete();
    }
  };
  var outerNext = function(value) {
    return active < concurrent ? doInnerSub(value) : buffer.push(value);
  };
  var doInnerSub = function(value) {
    expand && subscriber.next(value);
    active++;
    var innerComplete = false;
    innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, function(innerValue) {
      onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);
      if (expand) {
        outerNext(innerValue);
      } else {
        subscriber.next(innerValue);
      }
    }, function() {
      innerComplete = true;
    }, void 0, function() {
      if (innerComplete) {
        try {
          active--;
          var _loop_1 = function() {
            var bufferedValue = buffer.shift();
            if (innerSubScheduler) ; else {
              doInnerSub(bufferedValue);
            }
          };
          while (buffer.length && active < concurrent) {
            _loop_1();
          }
          checkComplete();
        } catch (err) {
          subscriber.error(err);
        }
      }
    }));
  };
  source.subscribe(createOperatorSubscriber(subscriber, outerNext, function() {
    isComplete = true;
    checkComplete();
  }));
  return function() {
    additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();
  };
}
function mergeMap(project, resultSelector, concurrent) {
  if (concurrent === void 0) {
    concurrent = Infinity;
  }
  if (isFunction(resultSelector)) {
    return mergeMap(function(a, i) {
      return map(function(b, ii) {
        return resultSelector(a, b, i, ii);
      })(innerFrom(project(a, i)));
    }, concurrent);
  } else if (typeof resultSelector === "number") {
    concurrent = resultSelector;
  }
  return operate(function(source, subscriber) {
    return mergeInternals(source, subscriber, project, concurrent);
  });
}
function mergeAll(concurrent) {
  if (concurrent === void 0) {
    concurrent = Infinity;
  }
  return mergeMap(identity, concurrent);
}
function concatAll() {
  return mergeAll(1);
}
function concat() {
  var args = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    args[_i] = arguments[_i];
  }
  return concatAll()(from(args, popScheduler(args)));
}
function defer(observableFactory) {
  return new Observable(function(subscriber) {
    innerFrom(observableFactory()).subscribe(subscriber);
  });
}
var nodeEventEmitterMethods = ["addListener", "removeListener"];
var eventTargetMethods = ["addEventListener", "removeEventListener"];
var jqueryMethods = ["on", "off"];
function fromEvent(target, eventName, options, resultSelector) {
  if (isFunction(options)) {
    resultSelector = options;
    options = void 0;
  }
  if (resultSelector) {
    return fromEvent(target, eventName, options).pipe(mapOneOrManyArgs(resultSelector));
  }
  var _a = __read$1(isEventTarget(target) ? eventTargetMethods.map(function(methodName) {
    return function(handler) {
      return target[methodName](eventName, handler, options);
    };
  }) : isNodeStyleEventEmitter(target) ? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName)) : isJQueryStyleEventEmitter(target) ? jqueryMethods.map(toCommonHandlerRegistry(target, eventName)) : [], 2), add = _a[0], remove = _a[1];
  if (!add) {
    if (isArrayLike(target)) {
      return mergeMap(function(subTarget) {
        return fromEvent(subTarget, eventName, options);
      })(innerFrom(target));
    }
  }
  if (!add) {
    throw new TypeError("Invalid event target");
  }
  return new Observable(function(subscriber) {
    var handler = function() {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return subscriber.next(1 < args.length ? args : args[0]);
    };
    add(handler);
    return function() {
      return remove(handler);
    };
  });
}
function toCommonHandlerRegistry(target, eventName) {
  return function(methodName) {
    return function(handler) {
      return target[methodName](eventName, handler);
    };
  };
}
function isNodeStyleEventEmitter(target) {
  return isFunction(target.addListener) && isFunction(target.removeListener);
}
function isJQueryStyleEventEmitter(target) {
  return isFunction(target.on) && isFunction(target.off);
}
function isEventTarget(target) {
  return isFunction(target.addEventListener) && isFunction(target.removeEventListener);
}
function timer(dueTime, intervalOrScheduler, scheduler) {
  if (dueTime === void 0) {
    dueTime = 0;
  }
  if (scheduler === void 0) {
    scheduler = async;
  }
  return new Observable(function(subscriber) {
    var due = isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime;
    if (due < 0) {
      due = 0;
    }
    var n = 0;
    return scheduler.schedule(function() {
      if (!subscriber.closed) {
        subscriber.next(n++);
        {
          subscriber.complete();
        }
      }
    }, due);
  });
}
function merge() {
  var args = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    args[_i] = arguments[_i];
  }
  var scheduler = popScheduler(args);
  var concurrent = popNumber(args, Infinity);
  var sources = args;
  return !sources.length ? EMPTY : sources.length === 1 ? innerFrom(sources[0]) : mergeAll(concurrent)(from(sources, scheduler));
}
var NEVER = new Observable(noop);
var isArray3 = Array.isArray;
function argsOrArgArray(args) {
  return args.length === 1 && isArray3(args[0]) ? args[0] : args;
}
function filter(predicate, thisArg) {
  return operate(function(source, subscriber) {
    var index = 0;
    source.subscribe(createOperatorSubscriber(subscriber, function(value) {
      return predicate.call(thisArg, value, index++) && subscriber.next(value);
    }));
  });
}
function race() {
  var sources = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    sources[_i] = arguments[_i];
  }
  sources = argsOrArgArray(sources);
  return sources.length === 1 ? innerFrom(sources[0]) : new Observable(raceInit(sources));
}
function raceInit(sources) {
  return function(subscriber) {
    var subscriptions = [];
    var _loop_1 = function(i2) {
      subscriptions.push(innerFrom(sources[i2]).subscribe(createOperatorSubscriber(subscriber, function(value) {
        if (subscriptions) {
          for (var s = 0; s < subscriptions.length; s++) {
            s !== i2 && subscriptions[s].unsubscribe();
          }
          subscriptions = null;
        }
        subscriber.next(value);
      })));
    };
    for (var i = 0; subscriptions && !subscriber.closed && i < sources.length; i++) {
      _loop_1(i);
    }
  };
}
function bufferCount(bufferSize, startBufferEvery) {
  if (startBufferEvery === void 0) {
    startBufferEvery = null;
  }
  startBufferEvery = startBufferEvery !== null && startBufferEvery !== void 0 ? startBufferEvery : bufferSize;
  return operate(function(source, subscriber) {
    var buffers = [];
    var count = 0;
    source.subscribe(createOperatorSubscriber(subscriber, function(value) {
      var e_1, _a, e_2, _b;
      var toEmit = null;
      if (count++ % startBufferEvery === 0) {
        buffers.push([]);
      }
      try {
        for (var buffers_1 = __values$1(buffers), buffers_1_1 = buffers_1.next(); !buffers_1_1.done; buffers_1_1 = buffers_1.next()) {
          var buffer = buffers_1_1.value;
          buffer.push(value);
          if (bufferSize <= buffer.length) {
            toEmit = toEmit !== null && toEmit !== void 0 ? toEmit : [];
            toEmit.push(buffer);
          }
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (buffers_1_1 && !buffers_1_1.done && (_a = buffers_1.return)) _a.call(buffers_1);
        } finally {
          if (e_1) throw e_1.error;
        }
      }
      if (toEmit) {
        try {
          for (var toEmit_1 = __values$1(toEmit), toEmit_1_1 = toEmit_1.next(); !toEmit_1_1.done; toEmit_1_1 = toEmit_1.next()) {
            var buffer = toEmit_1_1.value;
            arrRemove(buffers, buffer);
            subscriber.next(buffer);
          }
        } catch (e_2_1) {
          e_2 = { error: e_2_1 };
        } finally {
          try {
            if (toEmit_1_1 && !toEmit_1_1.done && (_b = toEmit_1.return)) _b.call(toEmit_1);
          } finally {
            if (e_2) throw e_2.error;
          }
        }
      }
    }, function() {
      var e_3, _a;
      try {
        for (var buffers_2 = __values$1(buffers), buffers_2_1 = buffers_2.next(); !buffers_2_1.done; buffers_2_1 = buffers_2.next()) {
          var buffer = buffers_2_1.value;
          subscriber.next(buffer);
        }
      } catch (e_3_1) {
        e_3 = { error: e_3_1 };
      } finally {
        try {
          if (buffers_2_1 && !buffers_2_1.done && (_a = buffers_2.return)) _a.call(buffers_2);
        } finally {
          if (e_3) throw e_3.error;
        }
      }
      subscriber.complete();
    }, void 0, function() {
      buffers = null;
    }));
  });
}
function catchError(selector) {
  return operate(function(source, subscriber) {
    var innerSub = null;
    var syncUnsub = false;
    var handledResult;
    innerSub = source.subscribe(createOperatorSubscriber(subscriber, void 0, void 0, function(err) {
      handledResult = innerFrom(selector(err, catchError(selector)(source)));
      if (innerSub) {
        innerSub.unsubscribe();
        innerSub = null;
        handledResult.subscribe(subscriber);
      } else {
        syncUnsub = true;
      }
    }));
    if (syncUnsub) {
      innerSub.unsubscribe();
      innerSub = null;
      handledResult.subscribe(subscriber);
    }
  });
}
function concatMap(project, resultSelector) {
  return isFunction(resultSelector) ? mergeMap(project, resultSelector, 1) : mergeMap(project, 1);
}
function defaultIfEmpty(defaultValue) {
  return operate(function(source, subscriber) {
    var hasValue = false;
    source.subscribe(createOperatorSubscriber(subscriber, function(value) {
      hasValue = true;
      subscriber.next(value);
    }, function() {
      if (!hasValue) {
        subscriber.next(defaultValue);
      }
      subscriber.complete();
    }));
  });
}
function take(count) {
  return count <= 0 ? function() {
    return EMPTY;
  } : operate(function(source, subscriber) {
    var seen = 0;
    source.subscribe(createOperatorSubscriber(subscriber, function(value) {
      if (++seen <= count) {
        subscriber.next(value);
        if (count <= seen) {
          subscriber.complete();
        }
      }
    }));
  });
}
function ignoreElements() {
  return operate(function(source, subscriber) {
    source.subscribe(createOperatorSubscriber(subscriber, noop));
  });
}
function distinctUntilChanged(comparator, keySelector) {
  if (keySelector === void 0) {
    keySelector = identity;
  }
  comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare;
  return operate(function(source, subscriber) {
    var previousKey;
    var first2 = true;
    source.subscribe(createOperatorSubscriber(subscriber, function(value) {
      var currentKey = keySelector(value);
      if (first2 || !comparator(previousKey, currentKey)) {
        first2 = false;
        previousKey = currentKey;
        subscriber.next(value);
      }
    }));
  });
}
function defaultCompare(a, b) {
  return a === b;
}
function throwIfEmpty(errorFactory) {
  if (errorFactory === void 0) {
    errorFactory = defaultErrorFactory;
  }
  return operate(function(source, subscriber) {
    var hasValue = false;
    source.subscribe(createOperatorSubscriber(subscriber, function(value) {
      hasValue = true;
      subscriber.next(value);
    }, function() {
      return hasValue ? subscriber.complete() : subscriber.error(errorFactory());
    }));
  });
}
function defaultErrorFactory() {
  return new EmptyError();
}
function first(predicate, defaultValue) {
  var hasDefaultValue = arguments.length >= 2;
  return function(source) {
    return source.pipe(predicate ? filter(function(v, i) {
      return predicate(v, i, source);
    }) : identity, take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function() {
      return new EmptyError();
    }));
  };
}
function mergeScan(accumulator, seed, concurrent) {
  if (concurrent === void 0) {
    concurrent = Infinity;
  }
  return operate(function(source, subscriber) {
    var state = seed;
    return mergeInternals(source, subscriber, function(value, index) {
      return accumulator(state, value, index);
    }, concurrent, function(value) {
      state = value;
    }, false, void 0, function() {
      return state = null;
    });
  });
}
function raceWith() {
  var otherSources = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    otherSources[_i] = arguments[_i];
  }
  return !otherSources.length ? identity : operate(function(source, subscriber) {
    raceInit(__spreadArray$1([source], __read$1(otherSources)))(subscriber);
  });
}
function retry(configOrCount) {
  if (configOrCount === void 0) {
    configOrCount = Infinity;
  }
  var config2;
  if (configOrCount && typeof configOrCount === "object") {
    config2 = configOrCount;
  } else {
    config2 = {
      count: configOrCount
    };
  }
  var _a = config2.count, count = _a === void 0 ? Infinity : _a, delay2 = config2.delay, _b = config2.resetOnSuccess, resetOnSuccess = _b === void 0 ? false : _b;
  return count <= 0 ? identity : operate(function(source, subscriber) {
    var soFar = 0;
    var innerSub;
    var subscribeForRetry = function() {
      var syncUnsub = false;
      innerSub = source.subscribe(createOperatorSubscriber(subscriber, function(value) {
        if (resetOnSuccess) {
          soFar = 0;
        }
        subscriber.next(value);
      }, void 0, function(err) {
        if (soFar++ < count) {
          var resub_1 = function() {
            if (innerSub) {
              innerSub.unsubscribe();
              innerSub = null;
              subscribeForRetry();
            } else {
              syncUnsub = true;
            }
          };
          if (delay2 != null) {
            var notifier = typeof delay2 === "number" ? timer(delay2) : innerFrom(delay2(err, soFar));
            var notifierSubscriber_1 = createOperatorSubscriber(subscriber, function() {
              notifierSubscriber_1.unsubscribe();
              resub_1();
            }, function() {
              subscriber.complete();
            });
            notifier.subscribe(notifierSubscriber_1);
          } else {
            resub_1();
          }
        } else {
          subscriber.error(err);
        }
      }));
      if (syncUnsub) {
        innerSub.unsubscribe();
        innerSub = null;
        subscribeForRetry();
      }
    };
    subscribeForRetry();
  });
}
function startWith() {
  var values = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    values[_i] = arguments[_i];
  }
  var scheduler = popScheduler(values);
  return operate(function(source, subscriber) {
    (scheduler ? concat(values, source, scheduler) : concat(values, source)).subscribe(subscriber);
  });
}
function switchMap(project, resultSelector) {
  return operate(function(source, subscriber) {
    var innerSubscriber = null;
    var index = 0;
    var isComplete = false;
    var checkComplete = function() {
      return isComplete && !innerSubscriber && subscriber.complete();
    };
    source.subscribe(createOperatorSubscriber(subscriber, function(value) {
      innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();
      var innerIndex = 0;
      var outerIndex = index++;
      innerFrom(project(value, outerIndex)).subscribe(innerSubscriber = createOperatorSubscriber(subscriber, function(innerValue) {
        return subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue);
      }, function() {
        innerSubscriber = null;
        checkComplete();
      }));
    }, function() {
      isComplete = true;
      checkComplete();
    }));
  });
}
function takeUntil(notifier) {
  return operate(function(source, subscriber) {
    innerFrom(notifier).subscribe(createOperatorSubscriber(subscriber, function() {
      return subscriber.complete();
    }, noop));
    !subscriber.closed && source.subscribe(subscriber);
  });
}
function tap(observerOrNext, error, complete) {
  var tapObserver = isFunction(observerOrNext) || error || complete ? { next: observerOrNext, error, complete } : observerOrNext;
  return tapObserver ? operate(function(source, subscriber) {
    var _a;
    (_a = tapObserver.subscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
    var isUnsub = true;
    source.subscribe(createOperatorSubscriber(subscriber, function(value) {
      var _a2;
      (_a2 = tapObserver.next) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver, value);
      subscriber.next(value);
    }, function() {
      var _a2;
      isUnsub = false;
      (_a2 = tapObserver.complete) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver);
      subscriber.complete();
    }, function(err) {
      var _a2;
      isUnsub = false;
      (_a2 = tapObserver.error) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver, err);
      subscriber.error(err);
    }, function() {
      var _a2, _b;
      if (isUnsub) {
        (_a2 = tapObserver.unsubscribe) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver);
      }
      (_b = tapObserver.finalize) === null || _b === void 0 ? void 0 : _b.call(tapObserver);
    }));
  }) : identity;
}

/**
MIT License
Copyright (c) 2021 Jason Miller
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
function mitt_default(n) {
  return { all: n = n ||  new Map(), on: function(t, e) {
    var i = n.get(t);
    i ? i.push(e) : n.set(t, [e]);
  }, off: function(t, e) {
    var i = n.get(t);
    i && (e ? i.splice(i.indexOf(e) >>> 0, 1) : n.set(t, []));
  }, emit: function(t, e) {
    var i = n.get(t);
    i && i.slice().map(function(n2) {
      n2(e);
    }), (i = n.get("*")) && i.slice().map(function(n2) {
      n2(t, e);
    });
  } };
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
Symbol.dispose ??= Symbol('dispose');
Symbol.asyncDispose ??= Symbol('asyncDispose');
const disposeSymbol = Symbol.dispose;
const asyncDisposeSymbol = Symbol.asyncDispose;
class DisposableStackPolyfill {
    #disposed = false;
    #stack = [];
    get disposed() {
        return this.#disposed;
    }
    dispose() {
        this[disposeSymbol]();
    }
    use(value) {
        if (value && typeof value[disposeSymbol] === 'function') {
            this.#stack.push(value);
        }
        return value;
    }
    adopt(value, onDispose) {
        this.#stack.push({
            [disposeSymbol]() {
                onDispose(value);
            },
        });
        return value;
    }
    defer(onDispose) {
        this.#stack.push({
            [disposeSymbol]() {
                onDispose();
            },
        });
    }
    move() {
        if (this.#disposed) {
            throw new ReferenceError('A disposed stack can not use anything new');
        }
        const stack = new DisposableStackPolyfill();
        stack.#stack = this.#stack;
        this.#stack = [];
        this.#disposed = true;
        return stack;
    }
    [disposeSymbol]() {
        if (this.#disposed) {
            return;
        }
        this.#disposed = true;
        const errors = [];
        for (const resource of this.#stack.reverse()) {
            try {
                resource[disposeSymbol]();
            }
            catch (e) {
                errors.push(e);
            }
        }
        if (errors.length === 1) {
            throw errors[0];
        }
        else if (errors.length > 1) {
            let suppressed = null;
            for (const error of errors) {
                if (suppressed === null) {
                    suppressed = error;
                }
                else {
                    suppressed = new SuppressedErrorPolyfill(error, suppressed);
                }
            }
            throw suppressed;
        }
    }
    [Symbol.toStringTag] = 'DisposableStack';
}
const DisposableStack = globalThis.DisposableStack ?? DisposableStackPolyfill;
class AsyncDisposableStackPolyfill {
    #disposed = false;
    #stack = [];
    get disposed() {
        return this.#disposed;
    }
    async disposeAsync() {
        await this[asyncDisposeSymbol]();
    }
    use(value) {
        if (value) {
            const asyncDispose = value[asyncDisposeSymbol];
            const dispose = value[disposeSymbol];
            if (typeof asyncDispose === 'function') {
                this.#stack.push(value);
            }
            else if (typeof dispose === 'function') {
                this.#stack.push({
                    [asyncDisposeSymbol]: async () => {
                        value[disposeSymbol]();
                    },
                });
            }
        }
        return value;
    }
    adopt(value, onDispose) {
        this.#stack.push({
            [asyncDisposeSymbol]() {
                return onDispose(value);
            },
        });
        return value;
    }
    defer(onDispose) {
        this.#stack.push({
            [asyncDisposeSymbol]() {
                return onDispose();
            },
        });
    }
    move() {
        if (this.#disposed) {
            throw new ReferenceError('A disposed stack can not use anything new');
        }
        const stack = new AsyncDisposableStackPolyfill();
        stack.#stack = this.#stack;
        this.#stack = [];
        this.#disposed = true;
        return stack;
    }
    async [asyncDisposeSymbol]() {
        if (this.#disposed) {
            return;
        }
        this.#disposed = true;
        const errors = [];
        for (const resource of this.#stack.reverse()) {
            try {
                await resource[asyncDisposeSymbol]();
            }
            catch (e) {
                errors.push(e);
            }
        }
        if (errors.length === 1) {
            throw errors[0];
        }
        else if (errors.length > 1) {
            let suppressed = null;
            for (const error of errors) {
                if (suppressed === null) {
                    suppressed = error;
                }
                else {
                    suppressed = new SuppressedErrorPolyfill(error, suppressed);
                }
            }
            throw suppressed;
        }
    }
    [Symbol.toStringTag] = 'AsyncDisposableStack';
}
const AsyncDisposableStack = globalThis.AsyncDisposableStack ?? AsyncDisposableStackPolyfill;
class SuppressedErrorPolyfill extends Error {
    #error;
    #suppressed;
    constructor(error, suppressed, message = 'An error was suppressed during disposal') {
        super(message);
        this.name = 'SuppressedError';
        this.#error = error;
        this.#suppressed = suppressed;
    }
    get error() {
        return this.#error;
    }
    get suppressed() {
        return this.#suppressed;
    }
}

/**
 * @license
 * Copyright 2022 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class EventEmitter {
    #emitter;
    #handlers = new Map();
    constructor(emitter = mitt_default(new Map())) {
        this.#emitter = emitter;
    }
    on(type, handler) {
        const handlers = this.#handlers.get(type);
        if (handlers === undefined) {
            this.#handlers.set(type, [handler]);
        }
        else {
            handlers.push(handler);
        }
        this.#emitter.on(type, handler);
        return this;
    }
    off(type, handler) {
        const handlers = this.#handlers.get(type) ?? [];
        if (handler === undefined) {
            for (const handler of handlers) {
                this.#emitter.off(type, handler);
            }
            this.#handlers.delete(type);
            return this;
        }
        const index = handlers.lastIndexOf(handler);
        if (index > -1) {
            this.#emitter.off(type, ...handlers.splice(index, 1));
        }
        return this;
    }
    emit(type, event) {
        this.#emitter.emit(type, event);
        return this.listenerCount(type) > 0;
    }
    once(type, handler) {
        const onceHandler = eventData => {
            handler(eventData);
            this.off(type, onceHandler);
        };
        return this.on(type, onceHandler);
    }
    listenerCount(type) {
        return this.#handlers.get(type)?.length || 0;
    }
    removeAllListeners(type) {
        if (type !== undefined) {
            return this.off(type);
        }
        this[disposeSymbol]();
        return this;
    }
    [disposeSymbol]() {
        for (const [type, handlers] of this.#handlers) {
            for (const handler of handlers) {
                this.#emitter.off(type, handler);
            }
        }
        this.#handlers.clear();
    }
}

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const isNode = !!(typeof process !== 'undefined' && process.version);
const environment = {
    value: {
        get fs() {
            throw new Error('fs is not available in this environment');
        },
        get ScreenRecorder() {
            throw new Error('ScreenRecorder is not available in this environment');
        },
    },
};

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const assert = (value, message) => {
    if (!value) {
        throw new Error(message);
    }
};

/**
 * @license
 * Copyright 2024 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function stringToTypedArray(string, base64Encoded = false) {
    if (base64Encoded) {
        if ('fromBase64' in Uint8Array) {
            return Uint8Array.fromBase64(string);
        }
        if (typeof Buffer === 'function') {
            return Buffer.from(string, 'base64');
        }
        return Uint8Array.from(atob(string), m => {
            return m.codePointAt(0);
        });
    }
    return new TextEncoder().encode(string);
}
function stringToBase64(str) {
    return typedArrayToBase64(new TextEncoder().encode(str));
}
function typedArrayToBase64(typedArray) {
    const chunkSize = 65534;
    const chunks = [];
    for (let i = 0; i < typedArray.length; i += chunkSize) {
        const chunk = typedArray.subarray(i, i + chunkSize);
        chunks.push(String.fromCodePoint.apply(null, chunk));
    }
    const binaryString = chunks.join('');
    return btoa(binaryString);
}
function mergeUint8Arrays(items) {
    let length = 0;
    for (const item of items) {
        length += item.length;
    }
    const result = new Uint8Array(length);
    let offset = 0;
    for (const item of items) {
        result.set(item, offset);
        offset += item.length;
    }
    return result;
}

/**
 * @license
 * Copyright 2025 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const packageVersion = '24.38.0';

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
let debugModule = null;
async function importDebug() {
    if (!debugModule) {
        debugModule = (await Promise.resolve().then(function () { return index; })).default;
    }
    return debugModule;
}
const debug$1 = (prefix) => {
    if (isNode) {
        return async (...logArgs) => {
            (await importDebug())(prefix)(logArgs);
        };
    }
    return (...logArgs) => {
        const debugLevel = globalThis.__PUPPETEER_DEBUG;
        if (!debugLevel) {
            return;
        }
        const everythingShouldBeLogged = debugLevel === '*';
        const prefixMatchesDebugLevel = everythingShouldBeLogged ||
            (debugLevel.endsWith('*')
                ? prefix.startsWith(debugLevel)
                : prefix === debugLevel);
        if (!prefixMatchesDebugLevel) {
            return;
        }
        console.log(`${prefix}:`, ...logArgs);
    };
};

/**
 * @license
 * Copyright 2018 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class PuppeteerError extends Error {
    constructor(message, options) {
        super(message, options);
        this.name = this.constructor.name;
    }
    get [Symbol.toStringTag]() {
        return this.constructor.name;
    }
}
let TimeoutError$1 = class TimeoutError extends PuppeteerError {
};
class TouchError extends PuppeteerError {
}
class ProtocolError extends PuppeteerError {
    #code;
    #originalMessage = '';
    set code(code) {
        this.#code = code;
    }
    get code() {
        return this.#code;
    }
    set originalMessage(originalMessage) {
        this.#originalMessage = originalMessage;
    }
    get originalMessage() {
        return this.#originalMessage;
    }
}
class UnsupportedOperation extends PuppeteerError {
}
class TargetCloseError extends ProtocolError {
}
class ConnectionClosedError extends ProtocolError {
}

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const paperFormats = {
    letter: {
        cm: { width: 21.59, height: 27.94 },
        in: { width: 8.5, height: 11 },
    },
    legal: {
        cm: { width: 21.59, height: 35.56 },
        in: { width: 8.5, height: 14 },
    },
    tabloid: {
        cm: { width: 27.94, height: 43.18 },
        in: { width: 11, height: 17 },
    },
    ledger: {
        cm: { width: 43.18, height: 27.94 },
        in: { width: 17, height: 11 },
    },
    a0: {
        cm: { width: 84.1, height: 118.9 },
        in: { width: 33.1102, height: 46.811 },
    },
    a1: {
        cm: { width: 59.4, height: 84.1 },
        in: { width: 23.3858, height: 33.1102 },
    },
    a2: {
        cm: { width: 42, height: 59.4 },
        in: { width: 16.5354, height: 23.3858 },
    },
    a3: {
        cm: { width: 29.7, height: 42 },
        in: { width: 11.6929, height: 16.5354 },
    },
    a4: {
        cm: { width: 21, height: 29.7 },
        in: { width: 8.2677, height: 11.6929 },
    },
    a5: {
        cm: { width: 14.8, height: 21 },
        in: { width: 5.8268, height: 8.2677 },
    },
    a6: {
        cm: { width: 10.5, height: 14.8 },
        in: { width: 4.1339, height: 5.8268 },
    },
};

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const debugError = debug$1('puppeteer:error');
const DEFAULT_VIEWPORT = Object.freeze({ width: 800, height: 600 });
const SOURCE_URL = Symbol('Source URL for Puppeteer evaluation scripts');
class PuppeteerURL {
    static INTERNAL_URL = 'pptr:internal';
    static fromCallSite(functionName, site) {
        const url = new PuppeteerURL();
        url.#functionName = functionName;
        url.#siteString = site.toString();
        return url;
    }
    static parse = (url) => {
        url = url.slice('pptr:'.length);
        const [functionName = '', siteString = ''] = url.split(';');
        const puppeteerUrl = new PuppeteerURL();
        puppeteerUrl.#functionName = functionName;
        puppeteerUrl.#siteString = decodeURIComponent(siteString);
        return puppeteerUrl;
    };
    static isPuppeteerURL = (url) => {
        return url.startsWith('pptr:');
    };
    #functionName;
    #siteString;
    get functionName() {
        return this.#functionName;
    }
    get siteString() {
        return this.#siteString;
    }
    toString() {
        return `pptr:${[
            this.#functionName,
            encodeURIComponent(this.#siteString),
        ].join(';')}`;
    }
}
const withSourcePuppeteerURLIfNone = (functionName, object) => {
    if (Object.prototype.hasOwnProperty.call(object, SOURCE_URL)) {
        return object;
    }
    const original = Error.prepareStackTrace;
    Error.prepareStackTrace = (_, stack) => {
        return stack[2];
    };
    const site = new Error().stack;
    Error.prepareStackTrace = original;
    return Object.assign(object, {
        [SOURCE_URL]: PuppeteerURL.fromCallSite(functionName, site),
    });
};
const getSourcePuppeteerURLIfAvailable = (object) => {
    if (Object.prototype.hasOwnProperty.call(object, SOURCE_URL)) {
        return object[SOURCE_URL];
    }
    return undefined;
};
const isString = (obj) => {
    return typeof obj === 'string' || obj instanceof String;
};
const isNumber = (obj) => {
    return typeof obj === 'number' || obj instanceof Number;
};
function evaluationString(
fun, ...args) {
    if (isString(fun)) {
        assert(args.length === 0, 'Cannot evaluate a string with arguments');
        return fun;
    }
    function serializeArgument(arg) {
        if (Object.is(arg, undefined)) {
            return 'undefined';
        }
        return JSON.stringify(arg);
    }
    return `(${fun})(${args.map(serializeArgument).join(',')})`;
}
async function getReadableAsTypedArray(readable, path) {
    const buffers = [];
    const reader = readable.getReader();
    if (path) {
        const fileHandle = await environment.value.fs.promises.open(path, 'w+');
        try {
            while (true) {
                const { done, value } = await reader.read();
                if (done) {
                    break;
                }
                buffers.push(value);
                await fileHandle.writeFile(value);
            }
        }
        finally {
            await fileHandle.close();
        }
    }
    else {
        while (true) {
            const { done, value } = await reader.read();
            if (done) {
                break;
            }
            buffers.push(value);
        }
    }
    try {
        const concat = mergeUint8Arrays(buffers);
        if (concat.length === 0) {
            return null;
        }
        return concat;
    }
    catch (error) {
        debugError(error);
        return null;
    }
}
async function getReadableFromProtocolStream(client, handle) {
    return new ReadableStream({
        async pull(controller) {
            const { data, base64Encoded, eof } = await client.send('IO.read', {
                handle,
            });
            controller.enqueue(stringToTypedArray(data, base64Encoded ?? false));
            if (eof) {
                await client.send('IO.close', { handle });
                controller.close();
            }
        },
    });
}
const VALID_DIALOG_TYPES = new Set([
    'alert',
    'confirm',
    'prompt',
    'beforeunload',
]);
function validateDialogType(type) {
    let dialogType = null;
    if (VALID_DIALOG_TYPES.has(type)) {
        dialogType = type;
    }
    assert(dialogType, `Unknown javascript dialog type: ${type}`);
    return dialogType;
}
function timeout(ms, cause) {
    return ms === 0
        ? NEVER
        : timer(ms).pipe(map(() => {
            throw new TimeoutError$1(`Timed out after waiting ${ms}ms`, { cause });
        }));
}
const UTILITY_WORLD_NAME = '__puppeteer_utility_world__' + packageVersion;
const SOURCE_URL_REGEX = /^[\x20\t]*\/\/[@#] sourceURL=\s{0,10}(\S*?)\s{0,10}$/m;
function getSourceUrlComment(url) {
    return `//# sourceURL=${url}`;
}
const NETWORK_IDLE_TIME = 500;
function parsePDFOptions(options = {}, lengthUnit = 'in') {
    const defaults = {
        scale: 1,
        displayHeaderFooter: false,
        headerTemplate: '',
        footerTemplate: '',
        printBackground: false,
        landscape: false,
        pageRanges: '',
        preferCSSPageSize: false,
        omitBackground: false,
        outline: false,
        tagged: true,
        waitForFonts: true,
    };
    let width = 8.5;
    let height = 11;
    if (options.format) {
        const format = paperFormats[options.format.toLowerCase()][lengthUnit];
        assert(format, 'Unknown paper format: ' + options.format);
        width = format.width;
        height = format.height;
    }
    else {
        width = convertPrintParameterToInches(options.width, lengthUnit) ?? width;
        height =
            convertPrintParameterToInches(options.height, lengthUnit) ?? height;
    }
    const margin = {
        top: convertPrintParameterToInches(options.margin?.top, lengthUnit) || 0,
        left: convertPrintParameterToInches(options.margin?.left, lengthUnit) || 0,
        bottom: convertPrintParameterToInches(options.margin?.bottom, lengthUnit) || 0,
        right: convertPrintParameterToInches(options.margin?.right, lengthUnit) || 0,
    };
    if (options.outline) {
        options.tagged = true;
    }
    return {
        ...defaults,
        ...options,
        width,
        height,
        margin,
    };
}
const unitToPixels = {
    px: 1,
    in: 96,
    cm: 37.8,
    mm: 3.78,
};
function convertPrintParameterToInches(parameter, lengthUnit = 'in') {
    if (typeof parameter === 'undefined') {
        return undefined;
    }
    let pixels;
    if (isNumber(parameter)) {
        pixels = parameter;
    }
    else if (isString(parameter)) {
        const text = parameter;
        let unit = text.substring(text.length - 2).toLowerCase();
        let valueText = '';
        if (unit in unitToPixels) {
            valueText = text.substring(0, text.length - 2);
        }
        else {
            unit = 'px';
            valueText = text;
        }
        const value = Number(valueText);
        assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
        pixels = value * unitToPixels[unit];
    }
    else {
        throw new Error('page.pdf() Cannot handle parameter type: ' + typeof parameter);
    }
    return pixels / unitToPixels[lengthUnit];
}
function fromEmitterEvent(emitter, eventName) {
    return new Observable(subscriber => {
        const listener = (event) => {
            subscriber.next(event);
        };
        emitter.on(eventName, listener);
        return () => {
            emitter.off(eventName, listener);
        };
    });
}
function fromAbortSignal(signal, cause) {
    return signal
        ? fromEvent(signal, 'abort').pipe(map(() => {
            if (signal.reason instanceof Error) {
                signal.reason.cause = cause;
                throw signal.reason;
            }
            throw new Error(signal.reason, { cause });
        }))
        : NEVER;
}
function filterAsync(predicate) {
    return mergeMap((value) => {
        return from(Promise.resolve(predicate(value))).pipe(filter(isMatch => {
            return isMatch;
        }), map(() => {
            return value;
        }));
    });
}

const WEB_PERMISSION_TO_PROTOCOL_PERMISSION = new Map([
    ['accelerometer', 'sensors'],
    ['ambient-light-sensor', 'sensors'],
    ['background-sync', 'backgroundSync'],
    ['camera', 'videoCapture'],
    ['clipboard-read', 'clipboardReadWrite'],
    ['clipboard-sanitized-write', 'clipboardSanitizedWrite'],
    ['clipboard-write', 'clipboardReadWrite'],
    ['geolocation', 'geolocation'],
    ['gyroscope', 'sensors'],
    ['idle-detection', 'idleDetection'],
    ['keyboard-lock', 'keyboardLock'],
    ['magnetometer', 'sensors'],
    ['microphone', 'audioCapture'],
    ['midi', 'midi'],
    ['notifications', 'notifications'],
    ['payment-handler', 'paymentHandler'],
    ['persistent-storage', 'durableStorage'],
    ['pointer-lock', 'pointerLock'],
    ['midi-sysex', 'midiSysex'],
]);
let Browser$1 = class Browser extends EventEmitter {
    constructor() {
        super();
    }
    async waitForTarget(predicate, options = {}) {
        const { timeout: ms = 30000, signal } = options;
        return await firstValueFrom(merge(fromEmitterEvent(this, "targetcreated" ), fromEmitterEvent(this, "targetchanged" ), from(this.targets())).pipe(filterAsync(predicate), raceWith(fromAbortSignal(signal), timeout(ms))));
    }
    async pages(includeAll = false) {
        const contextPages = await Promise.all(this.browserContexts().map(context => {
            return context.pages(includeAll);
        }));
        return contextPages.reduce((acc, x) => {
            return acc.concat(x);
        }, []);
    }
    async cookies() {
        return await this.defaultBrowserContext().cookies();
    }
    async setCookie(...cookies) {
        return await this.defaultBrowserContext().setCookie(...cookies);
    }
    async deleteCookie(...cookies) {
        return await this.defaultBrowserContext().deleteCookie(...cookies);
    }
    async deleteMatchingCookies(...filters) {
        return await this.defaultBrowserContext().deleteMatchingCookies(...filters);
    }
    async setPermission(origin, ...permissions) {
        return await this.defaultBrowserContext().setPermission(origin, ...permissions);
    }
    isConnected() {
        return this.connected;
    }
    [disposeSymbol]() {
        if (this.process()) {
            return void this.close().catch(debugError);
        }
        return void this.disconnect().catch(debugError);
    }
    [asyncDisposeSymbol]() {
        if (this.process()) {
            return this.close();
        }
        return this.disconnect();
    }
};

/**
 * @license
 * Copyright 2024 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class Deferred {
    static create(opts) {
        return new Deferred(opts);
    }
    static async race(awaitables) {
        const deferredWithTimeout = new Set();
        try {
            const promises = awaitables.map(value => {
                if (value instanceof Deferred) {
                    if (value.#timeoutId) {
                        deferredWithTimeout.add(value);
                    }
                    return value.valueOrThrow();
                }
                return value;
            });
            return await Promise.race(promises);
        }
        finally {
            for (const deferred of deferredWithTimeout) {
                deferred.reject(new Error('Timeout cleared'));
            }
        }
    }
    #isResolved = false;
    #isRejected = false;
    #value;
    #resolve;
    #taskPromise = new Promise(resolve => {
        this.#resolve = resolve;
    });
    #timeoutId;
    #timeoutError;
    constructor(opts) {
        if (opts && opts.timeout > 0) {
            this.#timeoutError = new TimeoutError$1(opts.message);
            this.#timeoutId = setTimeout(() => {
                this.reject(this.#timeoutError);
            }, opts.timeout);
        }
    }
    #finish(value) {
        clearTimeout(this.#timeoutId);
        this.#value = value;
        this.#resolve();
    }
    resolve(value) {
        if (this.#isRejected || this.#isResolved) {
            return;
        }
        this.#isResolved = true;
        this.#finish(value);
    }
    reject(error) {
        if (this.#isRejected || this.#isResolved) {
            return;
        }
        this.#isRejected = true;
        this.#finish(error);
    }
    resolved() {
        return this.#isResolved;
    }
    finished() {
        return this.#isResolved || this.#isRejected;
    }
    value() {
        return this.#value;
    }
    #promise;
    valueOrThrow() {
        if (!this.#promise) {
            this.#promise = (async () => {
                await this.#taskPromise;
                if (this.#isRejected) {
                    throw this.#value;
                }
                return this.#value;
            })();
        }
        return this.#promise;
    }
}

/**
 * @license
 * Copyright 2024 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
let Mutex$2 = class Mutex {
    static Guard = class Guard {
        #mutex;
        #onRelease;
        constructor(mutex, onRelease) {
            this.#mutex = mutex;
            this.#onRelease = onRelease;
        }
        [disposeSymbol]() {
            this.#onRelease?.();
            return this.#mutex.release();
        }
    };
    #locked = false;
    #acquirers = [];
    async acquire(onRelease) {
        if (!this.#locked) {
            this.#locked = true;
            return new Mutex.Guard(this);
        }
        const deferred = Deferred.create();
        this.#acquirers.push(deferred.resolve.bind(deferred));
        await deferred.valueOrThrow();
        return new Mutex.Guard(this, onRelease);
    }
    release() {
        const resolve = this.#acquirers.shift();
        if (!resolve) {
            this.#locked = false;
            return;
        }
        resolve();
    }
};

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class BrowserContext extends EventEmitter {
    constructor() {
        super();
    }
    #pageScreenshotMutex;
    #screenshotOperationsCount = 0;
    startScreenshot() {
        const mutex = this.#pageScreenshotMutex || new Mutex$2();
        this.#pageScreenshotMutex = mutex;
        this.#screenshotOperationsCount++;
        return mutex.acquire(() => {
            this.#screenshotOperationsCount--;
            if (this.#screenshotOperationsCount === 0) {
                this.#pageScreenshotMutex = undefined;
            }
        });
    }
    waitForScreenshotOperations() {
        return this.#pageScreenshotMutex?.acquire();
    }
    async waitForTarget(predicate, options = {}) {
        const { timeout: ms = 30000 } = options;
        return await firstValueFrom(merge(fromEmitterEvent(this, "targetcreated" ), fromEmitterEvent(this, "targetchanged" ), from(this.targets())).pipe(filterAsync(predicate), raceWith(timeout(ms))));
    }
    async deleteCookie(...cookies) {
        return await this.setCookie(...cookies.map(cookie => {
            return {
                ...cookie,
                expires: 1,
            };
        }));
    }
    async deleteMatchingCookies(...filters) {
        const cookies = await this.cookies();
        const cookiesToDelete = cookies.filter(cookie => {
            return filters.some(filter => {
                if (filter.name === cookie.name) {
                    if (filter.domain !== undefined && filter.domain === cookie.domain) {
                        return true;
                    }
                    if (filter.path !== undefined && filter.path === cookie.path) {
                        return true;
                    }
                    if (filter.partitionKey !== undefined &&
                        cookie.partitionKey !== undefined) {
                        if (typeof cookie.partitionKey !== 'object') {
                            throw new Error('Unexpected string partition key');
                        }
                        if (typeof filter.partitionKey === 'string') {
                            if (filter.partitionKey === cookie.partitionKey?.sourceOrigin) {
                                return true;
                            }
                        }
                        else {
                            if (filter.partitionKey.sourceOrigin ===
                                cookie.partitionKey?.sourceOrigin) {
                                return true;
                            }
                        }
                    }
                    if (filter.url !== undefined) {
                        const url = new URL(filter.url);
                        if (url.hostname === cookie.domain &&
                            url.pathname === cookie.path) {
                            return true;
                        }
                    }
                    return true;
                }
                return false;
            });
        });
        await this.deleteCookie(...cookiesToDelete);
    }
    get closed() {
        return !this.browser().browserContexts().includes(this);
    }
    get id() {
        return undefined;
    }
    [disposeSymbol]() {
        return void this.close().catch(debugError);
    }
    [asyncDisposeSymbol]() {
        return this.close();
    }
}

var CDPSessionEvent;
(function (CDPSessionEvent) {
    CDPSessionEvent.Disconnected = Symbol('CDPSession.Disconnected');
    CDPSessionEvent.Swapped = Symbol('CDPSession.Swapped');
    CDPSessionEvent.Ready = Symbol('CDPSession.Ready');
    CDPSessionEvent.SessionAttached = 'sessionattached';
    CDPSessionEvent.SessionDetached = 'sessiondetached';
})(CDPSessionEvent || (CDPSessionEvent = {}));
class CDPSession extends EventEmitter {
    constructor() {
        super();
    }
    parentSession() {
        return undefined;
    }
}

/**
 * @license
 * Copyright 2025 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class DeviceRequestPrompt {
    devices = [];
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class Dialog {
    #type;
    #message;
    #defaultValue;
    handled = false;
    constructor(type, message, defaultValue = '') {
        this.#type = type;
        this.#message = message;
        this.#defaultValue = defaultValue;
    }
    type() {
        return this.#type;
    }
    message() {
        return this.#message;
    }
    defaultValue() {
        return this.#defaultValue;
    }
    async accept(promptText) {
        assert(!this.handled, 'Cannot accept dialog which is already handled!');
        this.handled = true;
        await this.handle({
            accept: true,
            text: promptText,
        });
    }
    async dismiss() {
        assert(!this.handled, 'Cannot dismiss dialog which is already handled!');
        this.handled = true;
        await this.handle({
            accept: false,
        });
    }
}

class AsyncIterableUtil {
    static async *map(iterable, map) {
        for await (const value of iterable) {
            yield await map(value);
        }
    }
    static async *flatMap(iterable, map) {
        for await (const value of iterable) {
            yield* map(value);
        }
    }
    static async collect(iterable) {
        const result = [];
        for await (const value of iterable) {
            result.push(value);
        }
        return result;
    }
    static async first(iterable) {
        for await (const value of iterable) {
            return value;
        }
        return;
    }
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const _isElementHandle = Symbol('_isElementHandle');

/**
 * @license
 * Copyright 2022 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function isErrorLike$1(obj) {
    return (typeof obj === 'object' && obj !== null && 'name' in obj && 'message' in obj);
}
function rewriteError$1(error, message, originalMessage) {
    error.message = message;
    error.originalMessage = originalMessage ?? error.originalMessage;
    return error;
}
function createProtocolErrorMessage(object) {
    let message = object.error.message;
    if (object.error &&
        typeof object.error === 'object' &&
        'data' in object.error) {
        message += ` ${object.error.data}`;
    }
    return message;
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const createdFunctions = new Map();
const createFunction = (functionValue) => {
    let fn = createdFunctions.get(functionValue);
    if (fn) {
        return fn;
    }
    fn = new Function(`return ${functionValue}`)();
    createdFunctions.set(functionValue, fn);
    return fn;
};
function stringifyFunction(fn) {
    let value = fn.toString();
    if (value.match(/^(async )*function(\(|\s)/) ||
        value.match(/^(async )*function\s*\*\s*/)) {
        return value;
    }
    const isArrow = value.startsWith('(') ||
        value.match(/^async\s*\(/) ||
        value.match(/^(async)*\s*(?:[$_\p{ID_Start}])(?:[$\u200C\u200D\p{ID_Continue}])*\s*=>/u);
    if (isArrow) {
        return value;
    }
    let prefix = 'function ';
    if (value.startsWith('async ')) {
        prefix = `async ${prefix}`;
        value = value.substring('async '.length);
    }
    return `${prefix}${value}`;
}
const interpolateFunction = (fn, replacements) => {
    let value = stringifyFunction(fn);
    for (const [name, jsValue] of Object.entries(replacements)) {
        value = value.replace(new RegExp(`PLACEHOLDER\\(\\s*(?:'${name}'|"${name}")\\s*\\)`, 'g'),
        `(${jsValue})`);
    }
    return createFunction(value);
};

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __addDisposableResource$d = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$d = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
const DEFAULT_BATCH_SIZE = 20;
async function* fastTransposeIteratorHandle(iterator, size) {
    const env_1 = { stack: [], error: void 0, hasError: false };
    try {
        const array = __addDisposableResource$d(env_1, await iterator.evaluateHandle(async (iterator, size) => {
            const results = [];
            while (results.length < size) {
                const result = await iterator.next();
                if (result.done) {
                    break;
                }
                results.push(result.value);
            }
            return results;
        }, size), false);
        const properties = (await array.getProperties());
        const handles = properties.values();
        const stack = __addDisposableResource$d(env_1, new DisposableStack(), false);
        stack.defer(() => {
            for (const handle_1 of handles) {
                const env_2 = { stack: [], error: void 0, hasError: false };
                try {
                    const handle = __addDisposableResource$d(env_2, handle_1, false);
                    handle[disposeSymbol]();
                }
                catch (e_2) {
                    env_2.error = e_2;
                    env_2.hasError = true;
                }
                finally {
                    __disposeResources$d(env_2);
                }
            }
        });
        yield* handles;
        return properties.size === 0;
    }
    catch (e_1) {
        env_1.error = e_1;
        env_1.hasError = true;
    }
    finally {
        __disposeResources$d(env_1);
    }
}
async function* transposeIteratorHandle(iterator) {
    let size = DEFAULT_BATCH_SIZE;
    while (!(yield* fastTransposeIteratorHandle(iterator, size))) {
        size <<= 1;
    }
}
async function* transposeIterableHandle(handle) {
    const env_3 = { stack: [], error: void 0, hasError: false };
    try {
        const generatorHandle = __addDisposableResource$d(env_3, await handle.evaluateHandle(iterable => {
            return (async function* () {
                yield* iterable;
            })();
        }), false);
        yield* transposeIteratorHandle(generatorHandle);
    }
    catch (e_3) {
        env_3.error = e_3;
        env_3.hasError = true;
    }
    finally {
        __disposeResources$d(env_3);
    }
}

/**
 * @license
 * Copyright 2022 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class LazyArg {
    static create = (get) => {
        return new LazyArg(get);
    };
    #get;
    constructor(get) {
        this.#get = get;
    }
    async get(context) {
        return await this.#get(context);
    }
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __addDisposableResource$c = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$c = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
class QueryHandler {
    static querySelectorAll;
    static querySelector;
    static get _querySelector() {
        if (this.querySelector) {
            return this.querySelector;
        }
        if (!this.querySelectorAll) {
            throw new Error('Cannot create default `querySelector`.');
        }
        return (this.querySelector = interpolateFunction(async (node, selector, PuppeteerUtil) => {
            const querySelectorAll = PLACEHOLDER('querySelectorAll');
            const results = querySelectorAll(node, selector, PuppeteerUtil);
            for await (const result of results) {
                return result;
            }
            return null;
        }, {
            querySelectorAll: stringifyFunction(this.querySelectorAll),
        }));
    }
    static get _querySelectorAll() {
        if (this.querySelectorAll) {
            return this.querySelectorAll;
        }
        if (!this.querySelector) {
            throw new Error('Cannot create default `querySelectorAll`.');
        }
        return (this.querySelectorAll = interpolateFunction(async function* (node, selector, PuppeteerUtil) {
            const querySelector = PLACEHOLDER('querySelector');
            const result = await querySelector(node, selector, PuppeteerUtil);
            if (result) {
                yield result;
            }
        }, {
            querySelector: stringifyFunction(this.querySelector),
        }));
    }
    static async *queryAll(element, selector) {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
            const handle = __addDisposableResource$c(env_1, await element.evaluateHandle(this._querySelectorAll, selector, LazyArg.create(context => {
                return context.puppeteerUtil;
            })), false);
            yield* transposeIterableHandle(handle);
        }
        catch (e_1) {
            env_1.error = e_1;
            env_1.hasError = true;
        }
        finally {
            __disposeResources$c(env_1);
        }
    }
    static async queryOne(element, selector) {
        const env_2 = { stack: [], error: void 0, hasError: false };
        try {
            const result = __addDisposableResource$c(env_2, await element.evaluateHandle(this._querySelector, selector, LazyArg.create(context => {
                return context.puppeteerUtil;
            })), false);
            if (!(_isElementHandle in result)) {
                return null;
            }
            return result.move();
        }
        catch (e_2) {
            env_2.error = e_2;
            env_2.hasError = true;
        }
        finally {
            __disposeResources$c(env_2);
        }
    }
    static async waitFor(elementOrFrame, selector, options) {
        const env_3 = { stack: [], error: void 0, hasError: false };
        try {
            let frame;
            const element = __addDisposableResource$c(env_3, await (async () => {
                if (!(_isElementHandle in elementOrFrame)) {
                    frame = elementOrFrame;
                    return;
                }
                frame = elementOrFrame.frame;
                return await frame.isolatedRealm().adoptHandle(elementOrFrame);
            })(), false);
            const { visible = false, hidden = false, timeout, signal } = options;
            const polling = visible || hidden ? "raf"  : options.polling;
            try {
                const env_4 = { stack: [], error: void 0, hasError: false };
                try {
                    signal?.throwIfAborted();
                    const handle = __addDisposableResource$c(env_4, await frame.isolatedRealm().waitForFunction(async (PuppeteerUtil, query, selector, root, visible) => {
                        const querySelector = PuppeteerUtil.createFunction(query);
                        const node = await querySelector(root ?? document, selector, PuppeteerUtil);
                        return PuppeteerUtil.checkVisibility(node, visible);
                    }, {
                        polling,
                        root: element,
                        timeout,
                        signal,
                    }, LazyArg.create(context => {
                        return context.puppeteerUtil;
                    }), stringifyFunction(this._querySelector), selector, element, visible ? true : hidden ? false : undefined), false);
                    if (signal?.aborted) {
                        throw signal.reason;
                    }
                    if (!(_isElementHandle in handle)) {
                        return null;
                    }
                    return await frame.mainRealm().transferHandle(handle);
                }
                catch (e_3) {
                    env_4.error = e_3;
                    env_4.hasError = true;
                }
                finally {
                    __disposeResources$c(env_4);
                }
            }
            catch (error) {
                if (!isErrorLike$1(error)) {
                    throw error;
                }
                if (error.name === 'AbortError') {
                    throw error;
                }
                const waitForSelectorError = new (error instanceof TimeoutError$1 ? TimeoutError$1 : Error)(`Waiting for selector \`${selector}\` failed`);
                waitForSelectorError.cause = error;
                throw waitForSelectorError;
            }
        }
        catch (e_4) {
            env_3.error = e_4;
            env_3.hasError = true;
        }
        finally {
            __disposeResources$c(env_3);
        }
    }
}

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const isKnownAttribute = (attribute) => {
    return ['name', 'role'].includes(attribute);
};
const ATTRIBUTE_REGEXP = /\[\s*(?<attribute>\w+)\s*=\s*(?<quote>"|')(?<value>\\.|.*?(?=\k<quote>))\k<quote>\s*\]/g;
const parseARIASelector = (selector) => {
    if (selector.length > 10_000) {
        throw new Error(`Selector ${selector} is too long`);
    }
    const queryOptions = {};
    const defaultName = selector.replace(ATTRIBUTE_REGEXP, (_, attribute, __, value) => {
        assert(isKnownAttribute(attribute), `Unknown aria attribute "${attribute}" in selector`);
        queryOptions[attribute] = value;
        return '';
    });
    if (defaultName && !queryOptions.name) {
        queryOptions.name = defaultName;
    }
    return queryOptions;
};
class ARIAQueryHandler extends QueryHandler {
    static querySelector = async (node, selector, { ariaQuerySelector }) => {
        return await ariaQuerySelector(node, selector);
    };
    static async *queryAll(element, selector) {
        const { name, role } = parseARIASelector(selector);
        yield* element.queryAXTree(name, role);
    }
    static queryOne = async (element, selector) => {
        return ((await AsyncIterableUtil.first(this.queryAll(element, selector))) ?? null);
    };
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class CSSQueryHandler extends QueryHandler {
    static querySelector = (element, selector, { cssQuerySelector }) => {
        return cssQuerySelector(element, selector);
    };
    static querySelectorAll = (element, selector, { cssQuerySelectorAll }) => {
        return cssQuerySelectorAll(element, selector);
    };
}

const source = "\"use strict\";var g=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var l=(t,e)=>{for(var r in e)g(t,r,{get:e[r],enumerable:!0})},G=(t,e,r,o)=>{if(e&&typeof e==\"object\"||typeof e==\"function\")for(let s of B(e))!Y.call(t,s)&&s!==r&&g(t,s,{get:()=>e[s],enumerable:!(o=X(e,s))||o.enumerable});return t};var J=t=>G(g({},\"__esModule\",{value:!0}),t);var pe={};l(pe,{default:()=>he});module.exports=J(pe);var N=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},p=class extends N{};var c=class t{static create(e){return new t(e)}static async race(e){let r=new Set;try{let o=e.map(s=>s instanceof t?(s.#s&&r.add(s),s.valueOrThrow()):s);return await Promise.race(o)}finally{for(let o of r)o.reject(new Error(\"Timeout cleared\"))}}#e=!1;#r=!1;#o;#t;#a=new Promise(e=>{this.#t=e});#s;#i;constructor(e){e&&e.timeout>0&&(this.#i=new p(e.message),this.#s=setTimeout(()=>{this.reject(this.#i)},e.timeout))}#l(e){clearTimeout(this.#s),this.#o=e,this.#t()}resolve(e){this.#r||this.#e||(this.#e=!0,this.#l(e))}reject(e){this.#r||this.#e||(this.#r=!0,this.#l(e))}resolved(){return this.#e}finished(){return this.#e||this.#r}value(){return this.#o}#n;valueOrThrow(){return this.#n||(this.#n=(async()=>{if(await this.#a,this.#r)throw this.#o;return this.#o})()),this.#n}};var L=new Map,W=t=>{let e=L.get(t);return e||(e=new Function(`return ${t}`)(),L.set(t,e),e)};var b={};l(b,{ariaQuerySelector:()=>z,ariaQuerySelectorAll:()=>x});var z=(t,e)=>globalThis.__ariaQuerySelector(t,e),x=async function*(t,e){yield*await globalThis.__ariaQuerySelectorAll(t,e)};var E={};l(E,{cssQuerySelector:()=>K,cssQuerySelectorAll:()=>Z});var K=(t,e)=>t.querySelector(e),Z=function(t,e){return t.querySelectorAll(e)};var A={};l(A,{customQuerySelectors:()=>P});var v=class{#e=new Map;register(e,r){if(!r.queryOne&&r.queryAll){let o=r.queryAll;r.queryOne=(s,i)=>{for(let n of o(s,i))return n;return null}}else if(r.queryOne&&!r.queryAll){let o=r.queryOne;r.queryAll=(s,i)=>{let n=o(s,i);return n?[n]:[]}}else if(!r.queryOne||!r.queryAll)throw new Error(\"At least one query method must be defined.\");this.#e.set(e,{querySelector:r.queryOne,querySelectorAll:r.queryAll})}unregister(e){this.#e.delete(e)}get(e){return this.#e.get(e)}clear(){this.#e.clear()}},P=new v;var R={};l(R,{pierceQuerySelector:()=>ee,pierceQuerySelectorAll:()=>te});var ee=(t,e)=>{let r=null,o=s=>{let i=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT);do{let n=i.currentNode;n.shadowRoot&&o(n.shadowRoot),!(n instanceof ShadowRoot)&&n!==s&&!r&&n.matches(e)&&(r=n)}while(!r&&i.nextNode())};return t instanceof Document&&(t=t.documentElement),o(t),r},te=(t,e)=>{let r=[],o=s=>{let i=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT);do{let n=i.currentNode;n.shadowRoot&&o(n.shadowRoot),!(n instanceof ShadowRoot)&&n!==s&&n.matches(e)&&r.push(n)}while(i.nextNode())};return t instanceof Document&&(t=t.documentElement),o(t),r};var u=(t,e)=>{if(!t)throw new Error(e)};var y=class{#e;#r;#o;#t;constructor(e,r){this.#e=e,this.#r=r}async start(){let e=this.#t=c.create(),r=await this.#e();if(r){e.resolve(r);return}this.#o=new MutationObserver(async()=>{let o=await this.#e();o&&(e.resolve(o),await this.stop())}),this.#o.observe(this.#r,{childList:!0,subtree:!0,attributes:!0})}async stop(){u(this.#t,\"Polling never started.\"),this.#t.finished()||this.#t.reject(new Error(\"Polling stopped\")),this.#o&&(this.#o.disconnect(),this.#o=void 0)}result(){return u(this.#t,\"Polling never started.\"),this.#t.valueOrThrow()}},w=class{#e;#r;constructor(e){this.#e=e}async start(){let e=this.#r=c.create(),r=await this.#e();if(r){e.resolve(r);return}let o=async()=>{if(e.finished())return;let s=await this.#e();if(!s){window.requestAnimationFrame(o);return}e.resolve(s),await this.stop()};window.requestAnimationFrame(o)}async stop(){u(this.#r,\"Polling never started.\"),this.#r.finished()||this.#r.reject(new Error(\"Polling stopped\"))}result(){return u(this.#r,\"Polling never started.\"),this.#r.valueOrThrow()}},T=class{#e;#r;#o;#t;constructor(e,r){this.#e=e,this.#r=r}async start(){let e=this.#t=c.create(),r=await this.#e();if(r){e.resolve(r);return}this.#o=setInterval(async()=>{let o=await this.#e();o&&(e.resolve(o),await this.stop())},this.#r)}async stop(){u(this.#t,\"Polling never started.\"),this.#t.finished()||this.#t.reject(new Error(\"Polling stopped\")),this.#o&&(clearInterval(this.#o),this.#o=void 0)}result(){return u(this.#t,\"Polling never started.\"),this.#t.valueOrThrow()}};var _={};l(_,{PCombinator:()=>H,pQuerySelector:()=>fe,pQuerySelectorAll:()=>$});var a=class{static async*map(e,r){for await(let o of e)yield await r(o)}static async*flatMap(e,r){for await(let o of e)yield*r(o)}static async collect(e){let r=[];for await(let o of e)r.push(o);return r}static async first(e){for await(let r of e)return r}};var C={};l(C,{textQuerySelectorAll:()=>m});var re=new Set([\"checkbox\",\"image\",\"radio\"]),oe=t=>t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement&&!re.has(t.type),se=new Set([\"SCRIPT\",\"STYLE\"]),f=t=>!se.has(t.nodeName)&&!document.head?.contains(t),I=new WeakMap,F=t=>{for(;t;)I.delete(t),t instanceof ShadowRoot?t=t.host:t=t.parentNode},j=new WeakSet,ne=new MutationObserver(t=>{for(let e of t)F(e.target)}),d=t=>{let e=I.get(t);if(e||(e={full:\"\",immediate:[]},!f(t)))return e;let r=\"\";if(oe(t))e.full=t.value,e.immediate.push(t.value),t.addEventListener(\"input\",o=>{F(o.target)},{once:!0,capture:!0});else{for(let o=t.firstChild;o;o=o.nextSibling){if(o.nodeType===Node.TEXT_NODE){e.full+=o.nodeValue??\"\",r+=o.nodeValue??\"\";continue}r&&e.immediate.push(r),r=\"\",o.nodeType===Node.ELEMENT_NODE&&(e.full+=d(o).full)}r&&e.immediate.push(r),t instanceof Element&&t.shadowRoot&&(e.full+=d(t.shadowRoot).full),j.has(t)||(ne.observe(t,{childList:!0,characterData:!0,subtree:!0}),j.add(t))}return I.set(t,e),e};var m=function*(t,e){let r=!1;for(let o of t.childNodes)if(o instanceof Element&&f(o)){let s;o.shadowRoot?s=m(o.shadowRoot,e):s=m(o,e);for(let i of s)yield i,r=!0}r||t instanceof Element&&f(t)&&d(t).full.includes(e)&&(yield t)};var k={};l(k,{checkVisibility:()=>le,pierce:()=>S,pierceAll:()=>O});var ie=[\"hidden\",\"collapse\"],le=(t,e)=>{if(!t)return e===!1;if(e===void 0)return t;let r=t.nodeType===Node.TEXT_NODE?t.parentElement:t,o=window.getComputedStyle(r),s=o&&!ie.includes(o.visibility)&&!ae(r);return e===s?t:!1};function ae(t){let e=t.getBoundingClientRect();return e.width===0||e.height===0}var ce=t=>\"shadowRoot\"in t&&t.shadowRoot instanceof ShadowRoot;function*S(t){ce(t)?yield t.shadowRoot:yield t}function*O(t){t=S(t).next().value,yield t;let e=[document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT)];for(let r of e){let o;for(;o=r.nextNode();)o.shadowRoot&&(yield o.shadowRoot,e.push(document.createTreeWalker(o.shadowRoot,NodeFilter.SHOW_ELEMENT)))}}var D={};l(D,{xpathQuerySelectorAll:()=>q});var q=function*(t,e,r=-1){let s=(t.ownerDocument||document).evaluate(e,t,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE),i=[],n;for(;(n=s.iterateNext())&&(i.push(n),!(r&&i.length===r)););for(let h=0;h<i.length;h++)n=i[h],yield n,i[h]=null};var ue=/[-\\w\\P{ASCII}*]/u,H=(r=>(r.Descendent=\">>>\",r.Child=\">>>>\",r))(H||{}),V=t=>\"querySelectorAll\"in t,Q=class{#e;#r=[];#o=void 0;elements;constructor(e,r){this.elements=[e],this.#e=r,this.#t()}async run(){for(typeof this.#o==\"string\"&&this.#o.trimStart()===\":scope\"&&this.#t();this.#o!==void 0;this.#t()){let e=this.#o;typeof e==\"string\"?e[0]&&ue.test(e[0])?this.elements=a.flatMap(this.elements,async function*(r){V(r)&&(yield*r.querySelectorAll(e))}):this.elements=a.flatMap(this.elements,async function*(r){if(!r.parentElement){if(!V(r))return;yield*r.querySelectorAll(e);return}let o=0;for(let s of r.parentElement.children)if(++o,s===r)break;yield*r.parentElement.querySelectorAll(`:scope>:nth-child(${o})${e}`)}):this.elements=a.flatMap(this.elements,async function*(r){switch(e.name){case\"text\":yield*m(r,e.value);break;case\"xpath\":yield*q(r,e.value);break;case\"aria\":yield*x(r,e.value);break;default:let o=P.get(e.name);if(!o)throw new Error(`Unknown selector type: ${e.name}`);yield*o.querySelectorAll(r,e.value)}})}}#t(){if(this.#r.length!==0){this.#o=this.#r.shift();return}if(this.#e.length===0){this.#o=void 0;return}let e=this.#e.shift();switch(e){case\">>>>\":{this.elements=a.flatMap(this.elements,S),this.#t();break}case\">>>\":{this.elements=a.flatMap(this.elements,O),this.#t();break}default:this.#r=e,this.#t();break}}},M=class{#e=new WeakMap;calculate(e,r=[]){if(e===null)return r;e instanceof ShadowRoot&&(e=e.host);let o=this.#e.get(e);if(o)return[...o,...r];let s=0;for(let n=e.previousSibling;n;n=n.previousSibling)++s;let i=this.calculate(e.parentNode,[s]);return this.#e.set(e,i),[...i,...r]}},U=(t,e)=>{if(t.length+e.length===0)return 0;let[r=-1,...o]=t,[s=-1,...i]=e;return r===s?U(o,i):r<s?-1:1},de=async function*(t){let e=new Set;for await(let o of t)e.add(o);let r=new M;yield*[...e.values()].map(o=>[o,r.calculate(o)]).sort(([,o],[,s])=>U(o,s)).map(([o])=>o)},$=function(t,e){let r=JSON.parse(e);if(r.some(o=>{let s=0;return o.some(i=>(typeof i==\"string\"?++s:s=0,s>1))}))throw new Error(\"Multiple deep combinators found in sequence.\");return de(a.flatMap(r,o=>{let s=new Q(t,o);return s.run(),s.elements}))},fe=async function(t,e){for await(let r of $(t,e))return r;return null};var me=Object.freeze({...b,...A,...R,..._,...C,...k,...D,...E,Deferred:c,createFunction:W,createTextContent:d,IntervalPoller:T,isSuitableNodeForTextMatching:f,MutationPoller:y,RAFPoller:w}),he=me;\n";

/**
 * @license
 * Copyright 2024 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class ScriptInjector {
    #updated = false;
    #amendments = new Set();
    append(statement) {
        this.#update(() => {
            this.#amendments.add(statement);
        });
    }
    pop(statement) {
        this.#update(() => {
            this.#amendments.delete(statement);
        });
    }
    inject(inject, force = false) {
        if (this.#updated || force) {
            inject(this.#get());
        }
        this.#updated = false;
    }
    #update(callback) {
        callback();
        this.#updated = true;
    }
    #get() {
        return `(() => {
      const module = {};
      ${source}
      ${[...this.#amendments]
            .map(statement => {
            return `(${statement})(module.exports.default);`;
        })
            .join('')}
      return module.exports.default;
    })()`;
    }
}
const scriptInjector = new ScriptInjector();

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class CustomQueryHandlerRegistry {
    #handlers = new Map();
    get(name) {
        const handler = this.#handlers.get(name);
        return handler ? handler[1] : undefined;
    }
    register(name, handler) {
        assert(!this.#handlers.has(name), `Cannot register over existing handler: ${name}`);
        assert(/^[a-zA-Z]+$/.test(name), `Custom query handler names may only contain [a-zA-Z]`);
        assert(handler.queryAll || handler.queryOne, `At least one query method must be implemented.`);
        const Handler = class extends QueryHandler {
            static querySelectorAll = interpolateFunction((node, selector, PuppeteerUtil) => {
                return PuppeteerUtil.customQuerySelectors
                    .get(PLACEHOLDER('name'))
                    .querySelectorAll(node, selector);
            }, { name: JSON.stringify(name) });
            static querySelector = interpolateFunction((node, selector, PuppeteerUtil) => {
                return PuppeteerUtil.customQuerySelectors
                    .get(PLACEHOLDER('name'))
                    .querySelector(node, selector);
            }, { name: JSON.stringify(name) });
        };
        const registerScript = interpolateFunction((PuppeteerUtil) => {
            PuppeteerUtil.customQuerySelectors.register(PLACEHOLDER('name'), {
                queryAll: PLACEHOLDER('queryAll'),
                queryOne: PLACEHOLDER('queryOne'),
            });
        }, {
            name: JSON.stringify(name),
            queryAll: handler.queryAll
                ? stringifyFunction(handler.queryAll)
                : String(undefined),
            queryOne: handler.queryOne
                ? stringifyFunction(handler.queryOne)
                : String(undefined),
        }).toString();
        this.#handlers.set(name, [registerScript, Handler]);
        scriptInjector.append(registerScript);
    }
    unregister(name) {
        const handler = this.#handlers.get(name);
        if (!handler) {
            throw new Error(`Cannot unregister unknown handler: ${name}`);
        }
        scriptInjector.pop(handler[0]);
        this.#handlers.delete(name);
    }
    names() {
        return [...this.#handlers.keys()];
    }
    clear() {
        for (const [registerScript] of this.#handlers) {
            scriptInjector.pop(registerScript);
        }
        this.#handlers.clear();
    }
}
const customQueryHandlers = new CustomQueryHandlerRegistry();

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class PierceQueryHandler extends QueryHandler {
    static querySelector = (element, selector, { pierceQuerySelector }) => {
        return pierceQuerySelector(element, selector);
    };
    static querySelectorAll = (element, selector, { pierceQuerySelectorAll }) => {
        return pierceQuerySelectorAll(element, selector);
    };
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class PQueryHandler extends QueryHandler {
    static querySelectorAll = (element, selector, { pQuerySelectorAll }) => {
        return pQuerySelectorAll(element, selector);
    };
    static querySelector = (element, selector, { pQuerySelector }) => {
        return pQuerySelector(element, selector);
    };
}

/**
MIT License
Copyright (c) 2020 Lea Verou
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var TOKENS = {
  attribute: /\[\s*(?:(?<namespace>\*|[-\w\P{ASCII}]*)\|)?(?<name>[-\w\P{ASCII}]+)\s*(?:(?<operator>\W?=)\s*(?<value>.+?)\s*(\s(?<caseSensitive>[iIsS]))?\s*)?\]/gu,
  id: /#(?<name>[-\w\P{ASCII}]+)/gu,
  class: /\.(?<name>[-\w\P{ASCII}]+)/gu,
  comma: /\s*,\s*/g,
  combinator: /\s*[\s>+~]\s*/g,
  "pseudo-element": /::(?<name>[-\w\P{ASCII}]+)(?:\((?<argument>¶*)\))?/gu,
  "pseudo-class": /:(?<name>[-\w\P{ASCII}]+)(?:\((?<argument>¶*)\))?/gu,
  universal: /(?:(?<namespace>\*|[-\w\P{ASCII}]*)\|)?\*/gu,
  type: /(?:(?<namespace>\*|[-\w\P{ASCII}]*)\|)?(?<name>[-\w\P{ASCII}]+)/gu
};
var TRIM_TOKENS =  new Set(["combinator", "comma"]);
var getArgumentPatternByType = (type) => {
  switch (type) {
    case "pseudo-element":
    case "pseudo-class":
      return new RegExp(TOKENS[type].source.replace("(?<argument>\xB6*)", "(?<argument>.*)"), "gu");
    default:
      return TOKENS[type];
  }
};
function gobbleParens(text, offset) {
  let nesting = 0;
  let result = "";
  for (; offset < text.length; offset++) {
    const char = text[offset];
    switch (char) {
      case "(":
        ++nesting;
        break;
      case ")":
        --nesting;
        break;
    }
    result += char;
    if (nesting === 0) {
      return result;
    }
  }
  return result;
}
function tokenizeBy(text, grammar = TOKENS) {
  if (!text) {
    return [];
  }
  const tokens = [text];
  for (const [type, pattern] of Object.entries(grammar)) {
    for (let i = 0; i < tokens.length; i++) {
      const token = tokens[i];
      if (typeof token !== "string") {
        continue;
      }
      pattern.lastIndex = 0;
      const match = pattern.exec(token);
      if (!match) {
        continue;
      }
      const from = match.index - 1;
      const args = [];
      const content = match[0];
      const before = token.slice(0, from + 1);
      if (before) {
        args.push(before);
      }
      args.push({
        ...match.groups,
        type,
        content
      });
      const after = token.slice(from + content.length + 1);
      if (after) {
        args.push(after);
      }
      tokens.splice(i, 1, ...args);
    }
  }
  let offset = 0;
  for (const token of tokens) {
    switch (typeof token) {
      case "string":
        throw new Error(`Unexpected sequence ${token} found at index ${offset}`);
      case "object":
        offset += token.content.length;
        token.pos = [offset - token.content.length, offset];
        if (TRIM_TOKENS.has(token.type)) {
          token.content = token.content.trim() || " ";
        }
        break;
    }
  }
  return tokens;
}
var STRING_PATTERN = /(['"])([^\\\n]*?)\1/g;
var ESCAPE_PATTERN = /\\./g;
function tokenize(selector, grammar = TOKENS) {
  selector = selector.trim();
  if (selector === "") {
    return [];
  }
  const replacements = [];
  selector = selector.replace(ESCAPE_PATTERN, (value, offset) => {
    replacements.push({ value, offset });
    return "\uE000".repeat(value.length);
  });
  selector = selector.replace(STRING_PATTERN, (value, quote, content, offset) => {
    replacements.push({ value, offset });
    return `${quote}${"\uE001".repeat(content.length)}${quote}`;
  });
  {
    let pos = 0;
    let offset;
    while ((offset = selector.indexOf("(", pos)) > -1) {
      const value = gobbleParens(selector, offset);
      replacements.push({ value, offset });
      selector = `${selector.substring(0, offset)}(${"\xB6".repeat(value.length - 2)})${selector.substring(offset + value.length)}`;
      pos = offset + value.length;
    }
  }
  const tokens = tokenizeBy(selector, grammar);
  const changedTokens =  new Set();
  for (const replacement of replacements.reverse()) {
    for (const token of tokens) {
      const { offset, value } = replacement;
      if (!(token.pos[0] <= offset && offset + value.length <= token.pos[1])) {
        continue;
      }
      const { content } = token;
      const tokenOffset = offset - token.pos[0];
      token.content = content.slice(0, tokenOffset) + value + content.slice(tokenOffset + value.length);
      if (token.content !== content) {
        changedTokens.add(token);
      }
    }
  }
  for (const token of changedTokens) {
    const pattern = getArgumentPatternByType(token.type);
    if (!pattern) {
      throw new Error(`Unknown token type: ${token.type}`);
    }
    pattern.lastIndex = 0;
    const match = pattern.exec(token.content);
    if (!match) {
      throw new Error(`Unable to parse content for ${token.type}: ${token.content}`);
    }
    Object.assign(token, match.groups);
  }
  return tokens;
}
function stringify(listOrNode) {
  if (Array.isArray(listOrNode)) {
    return listOrNode.map((token) => token.content).join("");
  }
  switch (listOrNode.type) {
    case "list":
      return listOrNode.list.map(stringify).join(",");
    case "relative":
      return listOrNode.combinator + stringify(listOrNode.right);
    case "complex":
      return stringify(listOrNode.left) + listOrNode.combinator + stringify(listOrNode.right);
    case "compound":
      return listOrNode.list.map(stringify).join("");
    default:
      return listOrNode.content;
  }
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
TOKENS['nesting'] = /&/g;
TOKENS['combinator'] = /\s*(>>>>?|[\s>+~])\s*/g;
const ESCAPE_REGEXP = /\\[\s\S]/g;
const unquote = (text) => {
    if (text.length <= 1) {
        return text;
    }
    if ((text[0] === '"' || text[0] === "'") && text.endsWith(text[0])) {
        text = text.slice(1, -1);
    }
    return text.replace(ESCAPE_REGEXP, match => {
        return match[1];
    });
};
function parsePSelectors(selector) {
    let isPureCSS = true;
    let hasAria = false;
    let hasPseudoClasses = false;
    const tokens = tokenize(selector);
    if (tokens.length === 0) {
        return [[], isPureCSS, hasPseudoClasses, false];
    }
    let compoundSelector = [];
    let complexSelector = [compoundSelector];
    const selectors = [complexSelector];
    const storage = [];
    for (const token of tokens) {
        switch (token.type) {
            case 'combinator':
                switch (token.content) {
                    case ">>>" :
                        isPureCSS = false;
                        if (storage.length) {
                            compoundSelector.push(stringify(storage));
                            storage.splice(0);
                        }
                        compoundSelector = [];
                        complexSelector.push(">>>" );
                        complexSelector.push(compoundSelector);
                        continue;
                    case ">>>>" :
                        isPureCSS = false;
                        if (storage.length) {
                            compoundSelector.push(stringify(storage));
                            storage.splice(0);
                        }
                        compoundSelector = [];
                        complexSelector.push(">>>>" );
                        complexSelector.push(compoundSelector);
                        continue;
                }
                break;
            case 'pseudo-element':
                if (!token.name.startsWith('-p-')) {
                    break;
                }
                isPureCSS = false;
                if (storage.length) {
                    compoundSelector.push(stringify(storage));
                    storage.splice(0);
                }
                const name = token.name.slice(3);
                if (name === 'aria') {
                    hasAria = true;
                }
                compoundSelector.push({
                    name,
                    value: unquote(token.argument ?? ''),
                });
                continue;
            case 'pseudo-class':
                hasPseudoClasses = true;
                break;
            case 'comma':
                if (storage.length) {
                    compoundSelector.push(stringify(storage));
                    storage.splice(0);
                }
                compoundSelector = [];
                complexSelector = [compoundSelector];
                selectors.push(complexSelector);
                continue;
        }
        storage.push(token);
    }
    if (storage.length) {
        compoundSelector.push(stringify(storage));
    }
    return [selectors, isPureCSS, hasPseudoClasses, hasAria];
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class TextQueryHandler extends QueryHandler {
    static querySelectorAll = (element, selector, { textQuerySelectorAll }) => {
        return textQuerySelectorAll(element, selector);
    };
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class XPathQueryHandler extends QueryHandler {
    static querySelectorAll = (element, selector, { xpathQuerySelectorAll }) => {
        return xpathQuerySelectorAll(element, selector);
    };
    static querySelector = (element, selector, { xpathQuerySelectorAll }) => {
        for (const result of xpathQuerySelectorAll(element, selector, 1)) {
            return result;
        }
        return null;
    };
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const BUILTIN_QUERY_HANDLERS = {
    aria: ARIAQueryHandler,
    pierce: PierceQueryHandler,
    xpath: XPathQueryHandler,
    text: TextQueryHandler,
};
const QUERY_SEPARATORS = ['=', '/'];
function getQueryHandlerAndSelector(selector) {
    for (const handlerMap of [
        customQueryHandlers.names().map(name => {
            return [name, customQueryHandlers.get(name)];
        }),
        Object.entries(BUILTIN_QUERY_HANDLERS),
    ]) {
        for (const [name, QueryHandler] of handlerMap) {
            for (const separator of QUERY_SEPARATORS) {
                const prefix = `${name}${separator}`;
                if (selector.startsWith(prefix)) {
                    selector = selector.slice(prefix.length);
                    return {
                        updatedSelector: selector,
                        polling: name === 'aria' ? "raf"  : "mutation" ,
                        QueryHandler,
                    };
                }
            }
        }
    }
    try {
        const [pSelector, isPureCSS, hasPseudoClasses, hasAria] = parsePSelectors(selector);
        if (isPureCSS) {
            return {
                updatedSelector: selector,
                polling: hasPseudoClasses
                    ? "raf"
                    : "mutation" ,
                QueryHandler: CSSQueryHandler,
            };
        }
        return {
            updatedSelector: JSON.stringify(pSelector),
            polling: hasAria ? "raf"  : "mutation" ,
            QueryHandler: PQueryHandler,
        };
    }
    catch {
        return {
            updatedSelector: selector,
            polling: "mutation" ,
            QueryHandler: CSSQueryHandler,
        };
    }
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __addDisposableResource$b = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$b = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
const instances = new WeakSet();
function moveable(Class, _) {
    let hasDispose = false;
    if (Class.prototype[disposeSymbol]) {
        const dispose = Class.prototype[disposeSymbol];
        Class.prototype[disposeSymbol] = function () {
            if (instances.has(this)) {
                instances.delete(this);
                return;
            }
            return dispose.call(this);
        };
        hasDispose = true;
    }
    if (Class.prototype[asyncDisposeSymbol]) {
        const asyncDispose = Class.prototype[asyncDisposeSymbol];
        Class.prototype[asyncDisposeSymbol] = function () {
            if (instances.has(this)) {
                instances.delete(this);
                return;
            }
            return asyncDispose.call(this);
        };
        hasDispose = true;
    }
    if (hasDispose) {
        Class.prototype.move = function () {
            instances.add(this);
            return this;
        };
    }
    return Class;
}
function throwIfDisposed(message = value => {
    return `Attempted to use disposed ${value.constructor.name}.`;
}) {
    return (target, _) => {
        return function (...args) {
            if (this.disposed) {
                throw new Error(message(this));
            }
            return target.call(this, ...args);
        };
    };
}
function invokeAtMostOnceForArguments(target, _) {
    const cache = new WeakMap();
    let cacheDepth = -1;
    return function (...args) {
        if (cacheDepth === -1) {
            cacheDepth = args.length;
        }
        if (cacheDepth !== args.length) {
            throw new Error('Memoized method was called with the wrong number of arguments');
        }
        let freshArguments = false;
        let cacheIterator = cache;
        for (const arg of args) {
            if (cacheIterator.has(arg)) {
                cacheIterator = cacheIterator.get(arg);
            }
            else {
                freshArguments = true;
                cacheIterator.set(arg, new WeakMap());
                cacheIterator = cacheIterator.get(arg);
            }
        }
        if (!freshArguments) {
            return;
        }
        return target.call(this, ...args);
    };
}
function guarded(getKey = function () {
    return this;
}) {
    return (target, _) => {
        const mutexes = new WeakMap();
        return async function (...args) {
            const env_1 = { stack: [], error: void 0, hasError: false };
            try {
                const key = getKey.call(this);
                let mutex = mutexes.get(key);
                if (!mutex) {
                    mutex = new Mutex$2();
                    mutexes.set(key, mutex);
                }
                const _ = __addDisposableResource$b(env_1, await mutex.acquire(), true);
                return await target.call(this, ...args);
            }
            catch (e_1) {
                env_1.error = e_1;
                env_1.hasError = true;
            }
            finally {
                const result_1 = __disposeResources$b(env_1);
                if (result_1)
                    await result_1;
            }
        };
    };
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __runInitializers$8 = (undefined && undefined.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
var __esDecorate$8 = (undefined && undefined.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __addDisposableResource$a = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$a = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
let JSHandle = (() => {
    let _classDecorators = [moveable];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _instanceExtraInitializers = [];
    let _getProperty_decorators;
    let _getProperties_decorators;
    (class {
        static { _classThis = this; }
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
            __esDecorate$8(this, null, _getProperty_decorators, { kind: "method", name: "getProperty", static: false, private: false, access: { has: obj => "getProperty" in obj, get: obj => obj.getProperty }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$8(this, null, _getProperties_decorators, { kind: "method", name: "getProperties", static: false, private: false, access: { has: obj => "getProperties" in obj, get: obj => obj.getProperties }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$8(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            _classThis = _classDescriptor.value;
            if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
            __runInitializers$8(_classThis, _classExtraInitializers);
        }
        constructor() {
            __runInitializers$8(this, _instanceExtraInitializers);
        }
        async evaluate(pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.evaluate.name, pageFunction);
            return await this.realm.evaluate(pageFunction, this, ...args);
        }
        async evaluateHandle(pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.evaluateHandle.name, pageFunction);
            return await this.realm.evaluateHandle(pageFunction, this, ...args);
        }
        async getProperty(propertyName) {
            return await this.evaluateHandle((object, propertyName) => {
                return object[propertyName];
            }, propertyName);
        }
        async getProperties() {
            const propertyNames = await this.evaluate(object => {
                const enumerableProperties = [];
                const descriptors = Object.getOwnPropertyDescriptors(object);
                for (const propertyName in descriptors) {
                    if (descriptors[propertyName]?.enumerable) {
                        enumerableProperties.push(propertyName);
                    }
                }
                return enumerableProperties;
            });
            const map = new Map();
            const results = await Promise.all(propertyNames.map(key => {
                return this.getProperty(key);
            }));
            for (const [key, value] of Object.entries(propertyNames)) {
                const env_1 = { stack: [], error: void 0, hasError: false };
                try {
                    const handle = __addDisposableResource$a(env_1, results[key], false);
                    if (handle) {
                        map.set(value, handle.move());
                    }
                }
                catch (e_1) {
                    env_1.error = e_1;
                    env_1.hasError = true;
                }
                finally {
                    __disposeResources$a(env_1);
                }
            }
            return map;
        }
        [(_getProperty_decorators = [throwIfDisposed()], _getProperties_decorators = [throwIfDisposed()], disposeSymbol)]() {
            return void this.dispose().catch(debugError);
        }
        [asyncDisposeSymbol]() {
            return this.dispose();
        }
    });
    return _classThis;
})();

var __addDisposableResource$9 = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$9 = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
var LocatorEvent;
(function (LocatorEvent) {
    LocatorEvent["Action"] = "action";
})(LocatorEvent || (LocatorEvent = {}));
class Locator extends EventEmitter {
    static race(locators) {
        return RaceLocator.create(locators);
    }
    visibility = null;
    _timeout = 30000;
    #ensureElementIsInTheViewport = true;
    #waitForEnabled = true;
    #waitForStableBoundingBox = true;
    operators = {
        conditions: (conditions, signal) => {
            return mergeMap((handle) => {
                return merge(...conditions.map(condition => {
                    return condition(handle, signal);
                })).pipe(defaultIfEmpty(handle));
            });
        },
        retryAndRaceWithSignalAndTimer: (signal, cause) => {
            const candidates = [];
            if (signal) {
                candidates.push(fromAbortSignal(signal, cause));
            }
            candidates.push(timeout(this._timeout, cause));
            return pipe(retry({ delay: RETRY_DELAY }), raceWith(...candidates));
        },
    };
    get timeout() {
        return this._timeout;
    }
    setTimeout(timeout) {
        const locator = this._clone();
        locator._timeout = timeout;
        return locator;
    }
    setVisibility(visibility) {
        const locator = this._clone();
        locator.visibility = visibility;
        return locator;
    }
    setWaitForEnabled(value) {
        const locator = this._clone();
        locator.#waitForEnabled = value;
        return locator;
    }
    setEnsureElementIsInTheViewport(value) {
        const locator = this._clone();
        locator.#ensureElementIsInTheViewport = value;
        return locator;
    }
    setWaitForStableBoundingBox(value) {
        const locator = this._clone();
        locator.#waitForStableBoundingBox = value;
        return locator;
    }
    copyOptions(locator) {
        this._timeout = locator._timeout;
        this.visibility = locator.visibility;
        this.#waitForEnabled = locator.#waitForEnabled;
        this.#ensureElementIsInTheViewport = locator.#ensureElementIsInTheViewport;
        this.#waitForStableBoundingBox = locator.#waitForStableBoundingBox;
        return this;
    }
    #waitForEnabledIfNeeded = (handle, signal) => {
        if (!this.#waitForEnabled) {
            return EMPTY;
        }
        return from(handle.frame.waitForFunction(element => {
            if (!(element instanceof HTMLElement)) {
                return true;
            }
            const isNativeFormControl = [
                'BUTTON',
                'INPUT',
                'SELECT',
                'TEXTAREA',
                'OPTION',
                'OPTGROUP',
            ].includes(element.nodeName);
            return !isNativeFormControl || !element.hasAttribute('disabled');
        }, {
            timeout: this._timeout,
            signal,
        }, handle)).pipe(ignoreElements());
    };
    #waitForStableBoundingBoxIfNeeded = (handle) => {
        if (!this.#waitForStableBoundingBox) {
            return EMPTY;
        }
        return defer(() => {
            return from(handle.evaluate(element => {
                return new Promise(resolve => {
                    window.requestAnimationFrame(() => {
                        const rect1 = element.getBoundingClientRect();
                        window.requestAnimationFrame(() => {
                            const rect2 = element.getBoundingClientRect();
                            resolve([
                                {
                                    x: rect1.x,
                                    y: rect1.y,
                                    width: rect1.width,
                                    height: rect1.height,
                                },
                                {
                                    x: rect2.x,
                                    y: rect2.y,
                                    width: rect2.width,
                                    height: rect2.height,
                                },
                            ]);
                        });
                    });
                });
            }));
        }).pipe(first(([rect1, rect2]) => {
            return (rect1.x === rect2.x &&
                rect1.y === rect2.y &&
                rect1.width === rect2.width &&
                rect1.height === rect2.height);
        }), retry({ delay: RETRY_DELAY }), ignoreElements());
    };
    #ensureElementIsInTheViewportIfNeeded = (handle) => {
        if (!this.#ensureElementIsInTheViewport) {
            return EMPTY;
        }
        return from(handle.isIntersectingViewport({ threshold: 0 })).pipe(filter(isIntersectingViewport => {
            return !isIntersectingViewport;
        }), mergeMap(() => {
            return from(handle.scrollIntoView());
        }), mergeMap(() => {
            return defer(() => {
                return from(handle.isIntersectingViewport({ threshold: 0 }));
            }).pipe(first(identity), retry({ delay: RETRY_DELAY }), ignoreElements());
        }));
    };
    #click(options) {
        const signal = options?.signal;
        const cause = new Error('Locator.click');
        return this._wait(options).pipe(this.operators.conditions([
            this.#ensureElementIsInTheViewportIfNeeded,
            this.#waitForStableBoundingBoxIfNeeded,
            this.#waitForEnabledIfNeeded,
        ], signal), tap(() => {
            return this.emit(LocatorEvent.Action, undefined);
        }), mergeMap(handle => {
            return from(handle.click(options)).pipe(catchError(err => {
                void handle.dispose().catch(debugError);
                throw err;
            }));
        }), this.operators.retryAndRaceWithSignalAndTimer(signal, cause));
    }
    #fill(value, options) {
        const signal = options?.signal;
        const typingThreshold = options?.typingThreshold ?? 100;
        const cause = new Error('Locator.fill');
        return this._wait(options).pipe(this.operators.conditions([
            this.#ensureElementIsInTheViewportIfNeeded,
            this.#waitForStableBoundingBoxIfNeeded,
            this.#waitForEnabledIfNeeded,
        ], signal), tap(() => {
            return this.emit(LocatorEvent.Action, undefined);
        }), mergeMap(handle => {
            return from(handle.evaluate(el => {
                if (el instanceof HTMLSelectElement) {
                    return 'select';
                }
                if (el instanceof HTMLTextAreaElement) {
                    return 'typeable-input';
                }
                if (el instanceof HTMLInputElement) {
                    if (new Set([
                        'textarea',
                        'text',
                        'url',
                        'tel',
                        'search',
                        'password',
                        'number',
                        'email',
                    ]).has(el.type)) {
                        return 'typeable-input';
                    }
                    else {
                        return 'other-input';
                    }
                }
                if (el.isContentEditable) {
                    return 'contenteditable';
                }
                return 'unknown';
            }))
                .pipe(mergeMap(inputType => {
                const fillDirectly = () => {
                    return from(handle.focus()).pipe(mergeMap(() => {
                        return from(handle.evaluate((input, newValue) => {
                            const element = input;
                            const currentValue = element.isContentEditable
                                ? element.innerText
                                : element.value;
                            if (currentValue === newValue) {
                                return;
                            }
                            if (element.isContentEditable) {
                                element.innerText = newValue;
                            }
                            else {
                                element.value = newValue;
                            }
                            element.dispatchEvent(new Event('input', { bubbles: true }));
                            element.dispatchEvent(new Event('change', { bubbles: true }));
                        }, value));
                    }));
                };
                switch (inputType) {
                    case 'select':
                        return from(handle.select(value).then(noop));
                    case 'contenteditable':
                    case 'typeable-input':
                        if (value.length < typingThreshold) {
                            return from(handle.evaluate((input, newValue) => {
                                const element = input;
                                const currentValue = element.isContentEditable
                                    ? element.innerText
                                    : input.value;
                                if (newValue.length <= currentValue.length ||
                                    !newValue.startsWith(currentValue)) {
                                    if (element.isContentEditable) {
                                        element.innerText = '';
                                    }
                                    else {
                                        input.value = '';
                                    }
                                    return newValue;
                                }
                                if (element.isContentEditable) {
                                    element.innerText = '';
                                    element.innerText = currentValue;
                                }
                                else {
                                    input.value = '';
                                    input.value = currentValue;
                                }
                                return newValue.substring(currentValue.length);
                            }, value)).pipe(mergeMap(textToType => {
                                if (!textToType) {
                                    return of(undefined);
                                }
                                return from(handle.type(textToType));
                            }));
                        }
                        return fillDirectly();
                    case 'other-input':
                        return fillDirectly();
                    case 'unknown':
                        throw new Error(`Element cannot be filled out.`);
                }
            }))
                .pipe(catchError(err => {
                void handle.dispose().catch(debugError);
                throw err;
            }));
        }), this.operators.retryAndRaceWithSignalAndTimer(signal, cause));
    }
    #hover(options) {
        const signal = options?.signal;
        const cause = new Error('Locator.hover');
        return this._wait(options).pipe(this.operators.conditions([
            this.#ensureElementIsInTheViewportIfNeeded,
            this.#waitForStableBoundingBoxIfNeeded,
        ], signal), tap(() => {
            return this.emit(LocatorEvent.Action, undefined);
        }), mergeMap(handle => {
            return from(handle.hover()).pipe(catchError(err => {
                void handle.dispose().catch(debugError);
                throw err;
            }));
        }), this.operators.retryAndRaceWithSignalAndTimer(signal, cause));
    }
    #scroll(options) {
        const signal = options?.signal;
        const cause = new Error('Locator.scroll');
        return this._wait(options).pipe(this.operators.conditions([
            this.#ensureElementIsInTheViewportIfNeeded,
            this.#waitForStableBoundingBoxIfNeeded,
        ], signal), tap(() => {
            return this.emit(LocatorEvent.Action, undefined);
        }), mergeMap(handle => {
            return from(handle.evaluate((el, scrollTop, scrollLeft) => {
                if (scrollTop !== undefined) {
                    el.scrollTop = scrollTop;
                }
                if (scrollLeft !== undefined) {
                    el.scrollLeft = scrollLeft;
                }
            }, options?.scrollTop, options?.scrollLeft)).pipe(catchError(err => {
                void handle.dispose().catch(debugError);
                throw err;
            }));
        }), this.operators.retryAndRaceWithSignalAndTimer(signal, cause));
    }
    clone() {
        return this._clone();
    }
    async waitHandle(options) {
        const cause = new Error('Locator.waitHandle');
        return await firstValueFrom(this._wait(options).pipe(this.operators.retryAndRaceWithSignalAndTimer(options?.signal, cause)));
    }
    async wait(options) {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
            const handle = __addDisposableResource$9(env_1, await this.waitHandle(options), false);
            return await handle.jsonValue();
        }
        catch (e_1) {
            env_1.error = e_1;
            env_1.hasError = true;
        }
        finally {
            __disposeResources$9(env_1);
        }
    }
    map(mapper) {
        return new MappedLocator(this._clone(), handle => {
            return handle.evaluateHandle(mapper);
        });
    }
    filter(predicate) {
        return new FilteredLocator(this._clone(), async (handle, signal) => {
            await handle.frame.waitForFunction(predicate, { signal, timeout: this._timeout }, handle);
            return true;
        });
    }
    filterHandle(predicate) {
        return new FilteredLocator(this._clone(), predicate);
    }
    mapHandle(mapper) {
        return new MappedLocator(this._clone(), mapper);
    }
    click(options) {
        return firstValueFrom(this.#click(options));
    }
    fill(value, options) {
        return firstValueFrom(this.#fill(value, options));
    }
    hover(options) {
        return firstValueFrom(this.#hover(options));
    }
    scroll(options) {
        return firstValueFrom(this.#scroll(options));
    }
}
class FunctionLocator extends Locator {
    static create(pageOrFrame, func) {
        return new FunctionLocator(pageOrFrame, func).setTimeout('getDefaultTimeout' in pageOrFrame
            ? pageOrFrame.getDefaultTimeout()
            : pageOrFrame.page().getDefaultTimeout());
    }
    #pageOrFrame;
    #func;
    constructor(pageOrFrame, func) {
        super();
        this.#pageOrFrame = pageOrFrame;
        this.#func = func;
    }
    _clone() {
        return new FunctionLocator(this.#pageOrFrame, this.#func);
    }
    _wait(options) {
        const signal = options?.signal;
        return defer(() => {
            return from(this.#pageOrFrame.waitForFunction(this.#func, {
                timeout: this.timeout,
                signal,
            }));
        }).pipe(throwIfEmpty());
    }
}
class DelegatedLocator extends Locator {
    #delegate;
    constructor(delegate) {
        super();
        this.#delegate = delegate;
        this.copyOptions(this.#delegate);
    }
    get delegate() {
        return this.#delegate;
    }
    setTimeout(timeout) {
        const locator = super.setTimeout(timeout);
        locator.#delegate = this.#delegate.setTimeout(timeout);
        return locator;
    }
    setVisibility(visibility) {
        const locator = super.setVisibility(visibility);
        locator.#delegate = locator.#delegate.setVisibility(visibility);
        return locator;
    }
    setWaitForEnabled(value) {
        const locator = super.setWaitForEnabled(value);
        locator.#delegate = this.#delegate.setWaitForEnabled(value);
        return locator;
    }
    setEnsureElementIsInTheViewport(value) {
        const locator = super.setEnsureElementIsInTheViewport(value);
        locator.#delegate = this.#delegate.setEnsureElementIsInTheViewport(value);
        return locator;
    }
    setWaitForStableBoundingBox(value) {
        const locator = super.setWaitForStableBoundingBox(value);
        locator.#delegate = this.#delegate.setWaitForStableBoundingBox(value);
        return locator;
    }
}
class FilteredLocator extends DelegatedLocator {
    #predicate;
    constructor(base, predicate) {
        super(base);
        this.#predicate = predicate;
    }
    _clone() {
        return new FilteredLocator(this.delegate.clone(), this.#predicate).copyOptions(this);
    }
    _wait(options) {
        return this.delegate._wait(options).pipe(mergeMap(handle => {
            return from(Promise.resolve(this.#predicate(handle, options?.signal))).pipe(filter(value => {
                return value;
            }), map(() => {
                return handle;
            }));
        }), throwIfEmpty());
    }
}
class MappedLocator extends DelegatedLocator {
    #mapper;
    constructor(base, mapper) {
        super(base);
        this.#mapper = mapper;
    }
    _clone() {
        return new MappedLocator(this.delegate.clone(), this.#mapper).copyOptions(this);
    }
    _wait(options) {
        return this.delegate._wait(options).pipe(mergeMap(handle => {
            return from(Promise.resolve(this.#mapper(handle, options?.signal)));
        }));
    }
}
class NodeLocator extends Locator {
    static create(pageOrFrame, selector) {
        return new NodeLocator(pageOrFrame, selector).setTimeout('getDefaultTimeout' in pageOrFrame
            ? pageOrFrame.getDefaultTimeout()
            : pageOrFrame.page().getDefaultTimeout());
    }
    static createFromHandle(pageOrFrame, handle) {
        return new NodeLocator(pageOrFrame, handle).setTimeout('getDefaultTimeout' in pageOrFrame
            ? pageOrFrame.getDefaultTimeout()
            : pageOrFrame.page().getDefaultTimeout());
    }
    #pageOrFrame;
    #selectorOrHandle;
    constructor(pageOrFrame, selectorOrHandle) {
        super();
        this.#pageOrFrame = pageOrFrame;
        this.#selectorOrHandle = selectorOrHandle;
    }
    #waitForVisibilityIfNeeded = (handle) => {
        if (!this.visibility) {
            return EMPTY;
        }
        return (() => {
            switch (this.visibility) {
                case 'hidden':
                    return defer(() => {
                        return from(handle.isHidden());
                    });
                case 'visible':
                    return defer(() => {
                        return from(handle.isVisible());
                    });
            }
        })().pipe(first(identity), retry({ delay: RETRY_DELAY }), ignoreElements());
    };
    _clone() {
        return new NodeLocator(this.#pageOrFrame,
        this.#selectorOrHandle).copyOptions(this);
    }
    _wait(options) {
        const signal = options?.signal;
        return defer(() => {
            if (typeof this.#selectorOrHandle === 'string') {
                return from(this.#pageOrFrame.waitForSelector(this.#selectorOrHandle, {
                    visible: false,
                    timeout: this._timeout,
                    signal,
                }));
            }
            else {
                return of(this.#selectorOrHandle);
            }
        }).pipe(filter((value) => {
            return value !== null;
        }), throwIfEmpty(), this.operators.conditions([this.#waitForVisibilityIfNeeded], signal));
    }
}
function checkLocatorArray(locators) {
    for (const locator of locators) {
        if (!(locator instanceof Locator)) {
            throw new Error('Unknown locator for race candidate');
        }
    }
    return locators;
}
class RaceLocator extends Locator {
    static create(locators) {
        const array = checkLocatorArray(locators);
        return new RaceLocator(array);
    }
    #locators;
    constructor(locators) {
        super();
        this.#locators = locators;
    }
    _clone() {
        return new RaceLocator(this.#locators.map(locator => {
            return locator.clone();
        })).copyOptions(this);
    }
    _wait(options) {
        return race(...this.#locators.map(locator => {
            return locator._wait(options);
        }));
    }
}
const RETRY_DELAY = 100;

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __runInitializers$7 = (undefined && undefined.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
var __esDecorate$7 = (undefined && undefined.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __addDisposableResource$8 = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$8 = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
var __setFunctionName$3 = (undefined && undefined.__setFunctionName) || function (f, name, prefix) {
    if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
    return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
function bindIsolatedHandle(target, _) {
    return async function (...args) {
        if (this.realm === this.frame.isolatedRealm()) {
            return await target.call(this, ...args);
        }
        let adoptedThis;
        if (this['isolatedHandle']) {
            adoptedThis = this['isolatedHandle'];
        }
        else {
            this['isolatedHandle'] = adoptedThis = await this.frame
                .isolatedRealm()
                .adoptHandle(this);
        }
        const result = await target.call(adoptedThis, ...args);
        if (result === adoptedThis) {
            return this;
        }
        if (result instanceof JSHandle) {
            return await this.realm.transferHandle(result);
        }
        if (Array.isArray(result)) {
            await Promise.all(result.map(async (item, index, result) => {
                if (item instanceof JSHandle) {
                    result[index] = await this.realm.transferHandle(item);
                }
            }));
        }
        if (result instanceof Map) {
            await Promise.all([...result.entries()].map(async ([key, value]) => {
                if (value instanceof JSHandle) {
                    result.set(key, await this.realm.transferHandle(value));
                }
            }));
        }
        return result;
    };
}
let ElementHandle = (() => {
    let _classSuper = JSHandle;
    let _instanceExtraInitializers = [];
    let _getProperty_decorators;
    let _getProperties_decorators;
    let _jsonValue_decorators;
    let _$_decorators;
    let _$$_decorators;
    let _private_$$_decorators;
    let _private_$$_descriptor;
    let _waitForSelector_decorators;
    let _isVisible_decorators;
    let _isHidden_decorators;
    let _toElement_decorators;
    let _clickablePoint_decorators;
    let _hover_decorators;
    let _click_decorators;
    let _drag_decorators;
    let _dragEnter_decorators;
    let _dragOver_decorators;
    let _drop_decorators;
    let _dragAndDrop_decorators;
    let _select_decorators;
    let _tap_decorators;
    let _touchStart_decorators;
    let _touchMove_decorators;
    let _touchEnd_decorators;
    let _focus_decorators;
    let _type_decorators;
    let _press_decorators;
    let _boundingBox_decorators;
    let _boxModel_decorators;
    let _screenshot_decorators;
    let _isIntersectingViewport_decorators;
    let _scrollIntoView_decorators;
    let _asLocator_decorators;
    return class ElementHandle extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _getProperty_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _getProperties_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _jsonValue_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _$_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _$$_decorators = [throwIfDisposed()];
            _private_$$_decorators = [bindIsolatedHandle];
            _waitForSelector_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _isVisible_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _isHidden_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _toElement_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _clickablePoint_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _hover_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _click_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _drag_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _dragEnter_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _dragOver_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _drop_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _dragAndDrop_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _select_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _tap_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _touchStart_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _touchMove_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _touchEnd_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _focus_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _type_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _press_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _boundingBox_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _boxModel_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _screenshot_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _isIntersectingViewport_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _scrollIntoView_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _asLocator_decorators = [throwIfDisposed()];
            __esDecorate$7(this, null, _getProperty_decorators, { kind: "method", name: "getProperty", static: false, private: false, access: { has: obj => "getProperty" in obj, get: obj => obj.getProperty }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _getProperties_decorators, { kind: "method", name: "getProperties", static: false, private: false, access: { has: obj => "getProperties" in obj, get: obj => obj.getProperties }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _jsonValue_decorators, { kind: "method", name: "jsonValue", static: false, private: false, access: { has: obj => "jsonValue" in obj, get: obj => obj.jsonValue }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _$_decorators, { kind: "method", name: "$", static: false, private: false, access: { has: obj => "$" in obj, get: obj => obj.$ }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _$$_decorators, { kind: "method", name: "$$", static: false, private: false, access: { has: obj => "$$" in obj, get: obj => obj.$$ }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, _private_$$_descriptor = { value: __setFunctionName$3(async function (selector) {
                    return await this.#$$impl(selector);
                }, "#$$") }, _private_$$_decorators, { kind: "method", name: "#$$", static: false, private: true, access: { has: obj => #$$ in obj, get: obj => obj.#$$ }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _waitForSelector_decorators, { kind: "method", name: "waitForSelector", static: false, private: false, access: { has: obj => "waitForSelector" in obj, get: obj => obj.waitForSelector }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _isVisible_decorators, { kind: "method", name: "isVisible", static: false, private: false, access: { has: obj => "isVisible" in obj, get: obj => obj.isVisible }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _isHidden_decorators, { kind: "method", name: "isHidden", static: false, private: false, access: { has: obj => "isHidden" in obj, get: obj => obj.isHidden }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _toElement_decorators, { kind: "method", name: "toElement", static: false, private: false, access: { has: obj => "toElement" in obj, get: obj => obj.toElement }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _clickablePoint_decorators, { kind: "method", name: "clickablePoint", static: false, private: false, access: { has: obj => "clickablePoint" in obj, get: obj => obj.clickablePoint }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _hover_decorators, { kind: "method", name: "hover", static: false, private: false, access: { has: obj => "hover" in obj, get: obj => obj.hover }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _click_decorators, { kind: "method", name: "click", static: false, private: false, access: { has: obj => "click" in obj, get: obj => obj.click }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _drag_decorators, { kind: "method", name: "drag", static: false, private: false, access: { has: obj => "drag" in obj, get: obj => obj.drag }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _dragEnter_decorators, { kind: "method", name: "dragEnter", static: false, private: false, access: { has: obj => "dragEnter" in obj, get: obj => obj.dragEnter }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _dragOver_decorators, { kind: "method", name: "dragOver", static: false, private: false, access: { has: obj => "dragOver" in obj, get: obj => obj.dragOver }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _drop_decorators, { kind: "method", name: "drop", static: false, private: false, access: { has: obj => "drop" in obj, get: obj => obj.drop }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _dragAndDrop_decorators, { kind: "method", name: "dragAndDrop", static: false, private: false, access: { has: obj => "dragAndDrop" in obj, get: obj => obj.dragAndDrop }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _select_decorators, { kind: "method", name: "select", static: false, private: false, access: { has: obj => "select" in obj, get: obj => obj.select }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _tap_decorators, { kind: "method", name: "tap", static: false, private: false, access: { has: obj => "tap" in obj, get: obj => obj.tap }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _touchStart_decorators, { kind: "method", name: "touchStart", static: false, private: false, access: { has: obj => "touchStart" in obj, get: obj => obj.touchStart }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _touchMove_decorators, { kind: "method", name: "touchMove", static: false, private: false, access: { has: obj => "touchMove" in obj, get: obj => obj.touchMove }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _touchEnd_decorators, { kind: "method", name: "touchEnd", static: false, private: false, access: { has: obj => "touchEnd" in obj, get: obj => obj.touchEnd }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _focus_decorators, { kind: "method", name: "focus", static: false, private: false, access: { has: obj => "focus" in obj, get: obj => obj.focus }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _type_decorators, { kind: "method", name: "type", static: false, private: false, access: { has: obj => "type" in obj, get: obj => obj.type }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _press_decorators, { kind: "method", name: "press", static: false, private: false, access: { has: obj => "press" in obj, get: obj => obj.press }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _boundingBox_decorators, { kind: "method", name: "boundingBox", static: false, private: false, access: { has: obj => "boundingBox" in obj, get: obj => obj.boundingBox }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _boxModel_decorators, { kind: "method", name: "boxModel", static: false, private: false, access: { has: obj => "boxModel" in obj, get: obj => obj.boxModel }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _screenshot_decorators, { kind: "method", name: "screenshot", static: false, private: false, access: { has: obj => "screenshot" in obj, get: obj => obj.screenshot }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _isIntersectingViewport_decorators, { kind: "method", name: "isIntersectingViewport", static: false, private: false, access: { has: obj => "isIntersectingViewport" in obj, get: obj => obj.isIntersectingViewport }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _scrollIntoView_decorators, { kind: "method", name: "scrollIntoView", static: false, private: false, access: { has: obj => "scrollIntoView" in obj, get: obj => obj.scrollIntoView }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$7(this, null, _asLocator_decorators, { kind: "method", name: "asLocator", static: false, private: false, access: { has: obj => "asLocator" in obj, get: obj => obj.asLocator }, metadata: _metadata }, null, _instanceExtraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        isolatedHandle = __runInitializers$7(this, _instanceExtraInitializers);
        handle;
        constructor(handle) {
            super();
            this.handle = handle;
            this[_isElementHandle] = true;
        }
        get id() {
            return this.handle.id;
        }
        get disposed() {
            return this.handle.disposed;
        }
        async getProperty(propertyName) {
            return await this.handle.getProperty(propertyName);
        }
        async getProperties() {
            return await this.handle.getProperties();
        }
        async evaluate(pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.evaluate.name, pageFunction);
            return await this.handle.evaluate(pageFunction, ...args);
        }
        async evaluateHandle(pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.evaluateHandle.name, pageFunction);
            return await this.handle.evaluateHandle(pageFunction, ...args);
        }
        async jsonValue() {
            return await this.handle.jsonValue();
        }
        toString() {
            return this.handle.toString();
        }
        remoteObject() {
            return this.handle.remoteObject();
        }
        async dispose() {
            await Promise.all([this.handle.dispose(), this.isolatedHandle?.dispose()]);
        }
        asElement() {
            return this;
        }
        async $(selector) {
            const { updatedSelector, QueryHandler } = getQueryHandlerAndSelector(selector);
            return (await QueryHandler.queryOne(this, updatedSelector));
        }
        async $$(selector, options) {
            if (options?.isolate === false) {
                return await this.#$$impl(selector);
            }
            return await this.#$$(selector);
        }
        get #$$() { return _private_$$_descriptor.value; }
        async #$$impl(selector) {
            const { updatedSelector, QueryHandler } = getQueryHandlerAndSelector(selector);
            return await AsyncIterableUtil.collect(QueryHandler.queryAll(this, updatedSelector));
        }
        async $eval(selector, pageFunction, ...args) {
            const env_1 = { stack: [], error: void 0, hasError: false };
            try {
                pageFunction = withSourcePuppeteerURLIfNone(this.$eval.name, pageFunction);
                const elementHandle = __addDisposableResource$8(env_1, await this.$(selector), false);
                if (!elementHandle) {
                    throw new Error(`Error: failed to find element matching selector "${selector}"`);
                }
                return await elementHandle.evaluate(pageFunction, ...args);
            }
            catch (e_1) {
                env_1.error = e_1;
                env_1.hasError = true;
            }
            finally {
                __disposeResources$8(env_1);
            }
        }
        async $$eval(selector, pageFunction, ...args) {
            const env_2 = { stack: [], error: void 0, hasError: false };
            try {
                pageFunction = withSourcePuppeteerURLIfNone(this.$$eval.name, pageFunction);
                const results = await this.$$(selector);
                const elements = __addDisposableResource$8(env_2, await this.evaluateHandle((_, ...elements) => {
                    return elements;
                }, ...results), false);
                const [result] = await Promise.all([
                    elements.evaluate(pageFunction, ...args),
                    ...results.map(results => {
                        return results.dispose();
                    }),
                ]);
                return result;
            }
            catch (e_2) {
                env_2.error = e_2;
                env_2.hasError = true;
            }
            finally {
                __disposeResources$8(env_2);
            }
        }
        async waitForSelector(selector, options = {}) {
            const { updatedSelector, QueryHandler, polling } = getQueryHandlerAndSelector(selector);
            return (await QueryHandler.waitFor(this, updatedSelector, {
                polling,
                ...options,
            }));
        }
        async #checkVisibility(visibility) {
            return await this.evaluate(async (element, PuppeteerUtil, visibility) => {
                return Boolean(PuppeteerUtil.checkVisibility(element, visibility));
            }, LazyArg.create(context => {
                return context.puppeteerUtil;
            }), visibility);
        }
        async isVisible() {
            return await this.#checkVisibility(true);
        }
        async isHidden() {
            return await this.#checkVisibility(false);
        }
        async toElement(tagName) {
            const isMatchingTagName = await this.evaluate((node, tagName) => {
                return node.nodeName === tagName.toUpperCase();
            }, tagName);
            if (!isMatchingTagName) {
                throw new Error(`Element is not a(n) \`${tagName}\` element`);
            }
            return this;
        }
        async clickablePoint(offset) {
            const box = await this.#clickableBox();
            if (!box) {
                throw new Error('Node is either not clickable or not an Element');
            }
            if (offset !== undefined) {
                return {
                    x: box.x + offset.x,
                    y: box.y + offset.y,
                };
            }
            return {
                x: box.x + box.width / 2,
                y: box.y + box.height / 2,
            };
        }
        async hover() {
            await this.scrollIntoViewIfNeeded();
            const { x, y } = await this.clickablePoint();
            await this.frame.page().mouse.move(x, y);
        }
        async click(options = {}) {
            await this.scrollIntoViewIfNeeded();
            const { x, y } = await this.clickablePoint(options.offset);
            try {
                await this.frame.page().mouse.click(x, y, options);
            }
            finally {
                if (options.debugHighlight) {
                    await this.frame.page().evaluate((x, y) => {
                        const highlight = document.createElement('div');
                        highlight.innerHTML = `<style>
        @scope {
          :scope {
              position: fixed;
              left: ${x}px;
              top: ${y}px;
              width: 10px;
              height: 10px;
              border-radius: 50%;
              animation: colorChange 10s 1 normal;
              animation-fill-mode: forwards;
          }

          @keyframes colorChange {
              from {
                  background-color: red;
              }
              to {
                  background-color: #FADADD00;
              }
          }
        }
      </style>`;
                        highlight.addEventListener('animationend', () => {
                            highlight.remove();
                        }, { once: true });
                        document.body.append(highlight);
                    }, x, y);
                }
            }
        }
        async drag(target) {
            await this.scrollIntoViewIfNeeded();
            const page = this.frame.page();
            if (page.isDragInterceptionEnabled()) {
                const source = await this.clickablePoint();
                if (target instanceof ElementHandle) {
                    target = await target.clickablePoint();
                }
                return await page.mouse.drag(source, target);
            }
            try {
                if (!page._isDragging) {
                    page._isDragging = true;
                    await this.hover();
                    await page.mouse.down();
                }
                if (target instanceof ElementHandle) {
                    await target.hover();
                }
                else {
                    await page.mouse.move(target.x, target.y);
                }
            }
            catch (error) {
                page._isDragging = false;
                throw error;
            }
        }
        async dragEnter(data = { items: [], dragOperationsMask: 1 }) {
            const page = this.frame.page();
            await this.scrollIntoViewIfNeeded();
            const target = await this.clickablePoint();
            await page.mouse.dragEnter(target, data);
        }
        async dragOver(data = { items: [], dragOperationsMask: 1 }) {
            const page = this.frame.page();
            await this.scrollIntoViewIfNeeded();
            const target = await this.clickablePoint();
            await page.mouse.dragOver(target, data);
        }
        async drop(dataOrElement = {
            items: [],
            dragOperationsMask: 1,
        }) {
            const page = this.frame.page();
            if ('items' in dataOrElement) {
                await this.scrollIntoViewIfNeeded();
                const destination = await this.clickablePoint();
                await page.mouse.drop(destination, dataOrElement);
            }
            else {
                await dataOrElement.drag(this);
                page._isDragging = false;
                await page.mouse.up();
            }
        }
        async dragAndDrop(target, options) {
            const page = this.frame.page();
            assert(page.isDragInterceptionEnabled(), 'Drag Interception is not enabled!');
            await this.scrollIntoViewIfNeeded();
            const startPoint = await this.clickablePoint();
            const targetPoint = await target.clickablePoint();
            await page.mouse.dragAndDrop(startPoint, targetPoint, options);
        }
        async select(...values) {
            for (const value of values) {
                assert(isString(value), 'Values must be strings. Found value "' +
                    value +
                    '" of type "' +
                    typeof value +
                    '"');
            }
            return await this.evaluate((element, vals) => {
                const values = new Set(vals);
                if (!(element instanceof HTMLSelectElement)) {
                    throw new Error('Element is not a <select> element.');
                }
                const selectedValues = new Set();
                if (!element.multiple) {
                    for (const option of element.options) {
                        option.selected = false;
                    }
                    for (const option of element.options) {
                        if (values.has(option.value)) {
                            option.selected = true;
                            selectedValues.add(option.value);
                            break;
                        }
                    }
                }
                else {
                    for (const option of element.options) {
                        option.selected = values.has(option.value);
                        if (option.selected) {
                            selectedValues.add(option.value);
                        }
                    }
                }
                element.dispatchEvent(new Event('input', { bubbles: true }));
                element.dispatchEvent(new Event('change', { bubbles: true }));
                return [...selectedValues.values()];
            }, values);
        }
        async tap() {
            await this.scrollIntoViewIfNeeded();
            const { x, y } = await this.clickablePoint();
            await this.frame.page().touchscreen.tap(x, y);
        }
        async touchStart() {
            await this.scrollIntoViewIfNeeded();
            const { x, y } = await this.clickablePoint();
            return await this.frame.page().touchscreen.touchStart(x, y);
        }
        async touchMove(touch) {
            await this.scrollIntoViewIfNeeded();
            const { x, y } = await this.clickablePoint();
            if (touch) {
                return await touch.move(x, y);
            }
            await this.frame.page().touchscreen.touchMove(x, y);
        }
        async touchEnd() {
            await this.scrollIntoViewIfNeeded();
            await this.frame.page().touchscreen.touchEnd();
        }
        async focus() {
            await this.evaluate(element => {
                if (!(element instanceof HTMLElement)) {
                    throw new Error('Cannot focus non-HTMLElement');
                }
                return element.focus();
            });
        }
        async type(text, options) {
            await this.focus();
            await this.frame.page().keyboard.type(text, options);
        }
        async press(key, options) {
            await this.focus();
            await this.frame.page().keyboard.press(key, options);
        }
        async #clickableBox() {
            const boxes = await this.evaluate(element => {
                if (!(element instanceof Element)) {
                    return null;
                }
                return [...element.getClientRects()].map(rect => {
                    return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
                });
            });
            if (!boxes?.length) {
                return null;
            }
            await this.#intersectBoundingBoxesWithFrame(boxes);
            let frame = this.frame;
            let parentFrame;
            while ((parentFrame = frame?.parentFrame())) {
                const env_3 = { stack: [], error: void 0, hasError: false };
                try {
                    const handle = __addDisposableResource$8(env_3, await frame.frameElement(), false);
                    if (!handle) {
                        throw new Error('Unsupported frame type');
                    }
                    const parentBox = await handle.evaluate(element => {
                        if (element.getClientRects().length === 0) {
                            return null;
                        }
                        const rect = element.getBoundingClientRect();
                        const style = window.getComputedStyle(element);
                        return {
                            left: rect.left +
                                parseInt(style.paddingLeft, 10) +
                                parseInt(style.borderLeftWidth, 10),
                            top: rect.top +
                                parseInt(style.paddingTop, 10) +
                                parseInt(style.borderTopWidth, 10),
                        };
                    });
                    if (!parentBox) {
                        return null;
                    }
                    for (const box of boxes) {
                        box.x += parentBox.left;
                        box.y += parentBox.top;
                    }
                    await handle.#intersectBoundingBoxesWithFrame(boxes);
                    frame = parentFrame;
                }
                catch (e_3) {
                    env_3.error = e_3;
                    env_3.hasError = true;
                }
                finally {
                    __disposeResources$8(env_3);
                }
            }
            const box = boxes.find(box => {
                return box.width >= 1 && box.height >= 1;
            });
            if (!box) {
                return null;
            }
            return {
                x: box.x,
                y: box.y,
                height: box.height,
                width: box.width,
            };
        }
        async #intersectBoundingBoxesWithFrame(boxes) {
            const { documentWidth, documentHeight } = await this.frame
                .isolatedRealm()
                .evaluate(() => {
                return {
                    documentWidth: document.documentElement.clientWidth,
                    documentHeight: document.documentElement.clientHeight,
                };
            });
            for (const box of boxes) {
                intersectBoundingBox(box, documentWidth, documentHeight);
            }
        }
        async boundingBox() {
            const box = await this.evaluate(element => {
                if (!(element instanceof Element)) {
                    return null;
                }
                if (element.getClientRects().length === 0) {
                    return null;
                }
                const rect = element.getBoundingClientRect();
                return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
            });
            if (!box) {
                return null;
            }
            const offset = await this.#getTopLeftCornerOfFrame();
            if (!offset) {
                return null;
            }
            return {
                x: box.x + offset.x,
                y: box.y + offset.y,
                height: box.height,
                width: box.width,
            };
        }
        async boxModel() {
            const model = await this.evaluate(element => {
                if (!(element instanceof Element)) {
                    return null;
                }
                if (element.getClientRects().length === 0) {
                    return null;
                }
                const rect = element.getBoundingClientRect();
                const style = window.getComputedStyle(element);
                const offsets = {
                    padding: {
                        left: parseInt(style.paddingLeft, 10),
                        top: parseInt(style.paddingTop, 10),
                        right: parseInt(style.paddingRight, 10),
                        bottom: parseInt(style.paddingBottom, 10),
                    },
                    margin: {
                        left: -parseInt(style.marginLeft, 10),
                        top: -parseInt(style.marginTop, 10),
                        right: -parseInt(style.marginRight, 10),
                        bottom: -parseInt(style.marginBottom, 10),
                    },
                    border: {
                        left: parseInt(style.borderLeft, 10),
                        top: parseInt(style.borderTop, 10),
                        right: parseInt(style.borderRight, 10),
                        bottom: parseInt(style.borderBottom, 10),
                    },
                };
                const border = [
                    { x: rect.left, y: rect.top },
                    { x: rect.left + rect.width, y: rect.top },
                    { x: rect.left + rect.width, y: rect.top + rect.height },
                    { x: rect.left, y: rect.top + rect.height },
                ];
                const padding = transformQuadWithOffsets(border, offsets.border);
                const content = transformQuadWithOffsets(padding, offsets.padding);
                const margin = transformQuadWithOffsets(border, offsets.margin);
                return {
                    content,
                    padding,
                    border,
                    margin,
                    width: rect.width,
                    height: rect.height,
                };
                function transformQuadWithOffsets(quad, offsets) {
                    return [
                        {
                            x: quad[0].x + offsets.left,
                            y: quad[0].y + offsets.top,
                        },
                        {
                            x: quad[1].x - offsets.right,
                            y: quad[1].y + offsets.top,
                        },
                        {
                            x: quad[2].x - offsets.right,
                            y: quad[2].y - offsets.bottom,
                        },
                        {
                            x: quad[3].x + offsets.left,
                            y: quad[3].y - offsets.bottom,
                        },
                    ];
                }
            });
            if (!model) {
                return null;
            }
            const offset = await this.#getTopLeftCornerOfFrame();
            if (!offset) {
                return null;
            }
            for (const attribute of [
                'content',
                'padding',
                'border',
                'margin',
            ]) {
                for (const point of model[attribute]) {
                    point.x += offset.x;
                    point.y += offset.y;
                }
            }
            return model;
        }
        async #getTopLeftCornerOfFrame() {
            const point = { x: 0, y: 0 };
            let frame = this.frame;
            let parentFrame;
            while ((parentFrame = frame?.parentFrame())) {
                const env_4 = { stack: [], error: void 0, hasError: false };
                try {
                    const handle = __addDisposableResource$8(env_4, await frame.frameElement(), false);
                    if (!handle) {
                        throw new Error('Unsupported frame type');
                    }
                    const parentBox = await handle.evaluate(element => {
                        if (element.getClientRects().length === 0) {
                            return null;
                        }
                        const rect = element.getBoundingClientRect();
                        const style = window.getComputedStyle(element);
                        return {
                            left: rect.left +
                                parseInt(style.paddingLeft, 10) +
                                parseInt(style.borderLeftWidth, 10),
                            top: rect.top +
                                parseInt(style.paddingTop, 10) +
                                parseInt(style.borderTopWidth, 10),
                        };
                    });
                    if (!parentBox) {
                        return null;
                    }
                    point.x += parentBox.left;
                    point.y += parentBox.top;
                    frame = parentFrame;
                }
                catch (e_4) {
                    env_4.error = e_4;
                    env_4.hasError = true;
                }
                finally {
                    __disposeResources$8(env_4);
                }
            }
            return point;
        }
        async screenshot(options = {}) {
            const { scrollIntoView = true, clip } = options;
            const page = this.frame.page();
            if (scrollIntoView) {
                await this.scrollIntoViewIfNeeded();
            }
            const elementClip = await this.#nonEmptyVisibleBoundingBox();
            const [pageLeft, pageTop] = await this.evaluate(() => {
                if (!window.visualViewport) {
                    throw new Error('window.visualViewport is not supported.');
                }
                return [
                    window.visualViewport.pageLeft,
                    window.visualViewport.pageTop,
                ];
            });
            elementClip.x += pageLeft;
            elementClip.y += pageTop;
            if (clip) {
                elementClip.x += clip.x;
                elementClip.y += clip.y;
                elementClip.height = clip.height;
                elementClip.width = clip.width;
            }
            return await page.screenshot({ ...options, clip: elementClip });
        }
        async #nonEmptyVisibleBoundingBox() {
            const box = await this.boundingBox();
            assert(box, 'Node is either not visible or not an HTMLElement');
            assert(box.width !== 0, 'Node has 0 width.');
            assert(box.height !== 0, 'Node has 0 height.');
            return box;
        }
        async assertConnectedElement() {
            const error = await this.evaluate(async (element) => {
                if (!element.isConnected) {
                    return 'Node is detached from document';
                }
                if (element.nodeType !== Node.ELEMENT_NODE) {
                    return 'Node is not of type HTMLElement';
                }
                return;
            });
            if (error) {
                throw new Error(error);
            }
        }
        async scrollIntoViewIfNeeded() {
            if (await this.isIntersectingViewport({
                threshold: 1,
            })) {
                return;
            }
            await this.scrollIntoView();
        }
        async isIntersectingViewport(options = {}) {
            const env_5 = { stack: [], error: void 0, hasError: false };
            try {
                await this.assertConnectedElement();
                const handle = await this.#asSVGElementHandle();
                const target = __addDisposableResource$8(env_5, handle && (await handle.#getOwnerSVGElement()), false);
                return await (target ?? this).evaluate(async (element, threshold) => {
                    const visibleRatio = await new Promise(resolve => {
                        const observer = new IntersectionObserver(entries => {
                            resolve(entries[0].intersectionRatio);
                            observer.disconnect();
                        });
                        observer.observe(element);
                    });
                    return threshold === 1 ? visibleRatio === 1 : visibleRatio > threshold;
                }, options.threshold ?? 0);
            }
            catch (e_5) {
                env_5.error = e_5;
                env_5.hasError = true;
            }
            finally {
                __disposeResources$8(env_5);
            }
        }
        async scrollIntoView() {
            await this.assertConnectedElement();
            await this.evaluate(async (element) => {
                element.scrollIntoView({
                    block: 'center',
                    inline: 'center',
                    behavior: 'instant',
                });
            });
        }
        asLocator() {
            return NodeLocator.createFromHandle(this.frame, this);
        }
        async #asSVGElementHandle() {
            if (await this.evaluate(element => {
                return element instanceof SVGElement;
            })) {
                return this;
            }
            else {
                return null;
            }
        }
        async #getOwnerSVGElement() {
            return await this.evaluateHandle(element => {
                if (element instanceof SVGSVGElement) {
                    return element;
                }
                return element.ownerSVGElement;
            });
        }
    };
})();
function intersectBoundingBox(box, width, height) {
    box.width = Math.max(box.x >= 0
        ? Math.min(width - box.x, box.width)
        : Math.min(width, box.width + box.x), 0);
    box.height = Math.max(box.y >= 0
        ? Math.min(height - box.y, box.height)
        : Math.min(height, box.height + box.y), 0);
    box.x = Math.max(box.x, 0);
    box.y = Math.max(box.y, 0);
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __runInitializers$6 = (undefined && undefined.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
var __esDecorate$6 = (undefined && undefined.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __addDisposableResource$7 = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$7 = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
var FrameEvent;
(function (FrameEvent) {
    FrameEvent.FrameNavigated = Symbol('Frame.FrameNavigated');
    FrameEvent.FrameSwapped = Symbol('Frame.FrameSwapped');
    FrameEvent.LifecycleEvent = Symbol('Frame.LifecycleEvent');
    FrameEvent.FrameNavigatedWithinDocument = Symbol('Frame.FrameNavigatedWithinDocument');
    FrameEvent.FrameDetached = Symbol('Frame.FrameDetached');
    FrameEvent.FrameSwappedByActivation = Symbol('Frame.FrameSwappedByActivation');
})(FrameEvent || (FrameEvent = {}));
const throwIfDetached = throwIfDisposed(frame => {
    return `Attempted to use detached Frame '${frame._id}'.`;
});
let Frame = (() => {
    let _classSuper = EventEmitter;
    let _instanceExtraInitializers = [];
    let _frameElement_decorators;
    let _evaluateHandle_decorators;
    let _evaluate_decorators;
    let _locator_decorators;
    let _$_decorators;
    let _$$_decorators;
    let _$eval_decorators;
    let _$$eval_decorators;
    let _waitForSelector_decorators;
    let _waitForFunction_decorators;
    let _content_decorators;
    let _addScriptTag_decorators;
    let _addStyleTag_decorators;
    let _click_decorators;
    let _focus_decorators;
    let _hover_decorators;
    let _select_decorators;
    let _tap_decorators;
    let _type_decorators;
    let _title_decorators;
    return class Frame extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _frameElement_decorators = [throwIfDetached];
            _evaluateHandle_decorators = [throwIfDetached];
            _evaluate_decorators = [throwIfDetached];
            _locator_decorators = [throwIfDetached];
            _$_decorators = [throwIfDetached];
            _$$_decorators = [throwIfDetached];
            _$eval_decorators = [throwIfDetached];
            _$$eval_decorators = [throwIfDetached];
            _waitForSelector_decorators = [throwIfDetached];
            _waitForFunction_decorators = [throwIfDetached];
            _content_decorators = [throwIfDetached];
            _addScriptTag_decorators = [throwIfDetached];
            _addStyleTag_decorators = [throwIfDetached];
            _click_decorators = [throwIfDetached];
            _focus_decorators = [throwIfDetached];
            _hover_decorators = [throwIfDetached];
            _select_decorators = [throwIfDetached];
            _tap_decorators = [throwIfDetached];
            _type_decorators = [throwIfDetached];
            _title_decorators = [throwIfDetached];
            __esDecorate$6(this, null, _frameElement_decorators, { kind: "method", name: "frameElement", static: false, private: false, access: { has: obj => "frameElement" in obj, get: obj => obj.frameElement }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _evaluateHandle_decorators, { kind: "method", name: "evaluateHandle", static: false, private: false, access: { has: obj => "evaluateHandle" in obj, get: obj => obj.evaluateHandle }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _evaluate_decorators, { kind: "method", name: "evaluate", static: false, private: false, access: { has: obj => "evaluate" in obj, get: obj => obj.evaluate }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _locator_decorators, { kind: "method", name: "locator", static: false, private: false, access: { has: obj => "locator" in obj, get: obj => obj.locator }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _$_decorators, { kind: "method", name: "$", static: false, private: false, access: { has: obj => "$" in obj, get: obj => obj.$ }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _$$_decorators, { kind: "method", name: "$$", static: false, private: false, access: { has: obj => "$$" in obj, get: obj => obj.$$ }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _$eval_decorators, { kind: "method", name: "$eval", static: false, private: false, access: { has: obj => "$eval" in obj, get: obj => obj.$eval }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _$$eval_decorators, { kind: "method", name: "$$eval", static: false, private: false, access: { has: obj => "$$eval" in obj, get: obj => obj.$$eval }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _waitForSelector_decorators, { kind: "method", name: "waitForSelector", static: false, private: false, access: { has: obj => "waitForSelector" in obj, get: obj => obj.waitForSelector }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _waitForFunction_decorators, { kind: "method", name: "waitForFunction", static: false, private: false, access: { has: obj => "waitForFunction" in obj, get: obj => obj.waitForFunction }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _content_decorators, { kind: "method", name: "content", static: false, private: false, access: { has: obj => "content" in obj, get: obj => obj.content }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _addScriptTag_decorators, { kind: "method", name: "addScriptTag", static: false, private: false, access: { has: obj => "addScriptTag" in obj, get: obj => obj.addScriptTag }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _addStyleTag_decorators, { kind: "method", name: "addStyleTag", static: false, private: false, access: { has: obj => "addStyleTag" in obj, get: obj => obj.addStyleTag }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _click_decorators, { kind: "method", name: "click", static: false, private: false, access: { has: obj => "click" in obj, get: obj => obj.click }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _focus_decorators, { kind: "method", name: "focus", static: false, private: false, access: { has: obj => "focus" in obj, get: obj => obj.focus }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _hover_decorators, { kind: "method", name: "hover", static: false, private: false, access: { has: obj => "hover" in obj, get: obj => obj.hover }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _select_decorators, { kind: "method", name: "select", static: false, private: false, access: { has: obj => "select" in obj, get: obj => obj.select }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _tap_decorators, { kind: "method", name: "tap", static: false, private: false, access: { has: obj => "tap" in obj, get: obj => obj.tap }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _type_decorators, { kind: "method", name: "type", static: false, private: false, access: { has: obj => "type" in obj, get: obj => obj.type }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$6(this, null, _title_decorators, { kind: "method", name: "title", static: false, private: false, access: { has: obj => "title" in obj, get: obj => obj.title }, metadata: _metadata }, null, _instanceExtraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        _id = __runInitializers$6(this, _instanceExtraInitializers);
        _parentId;
        _name;
        _hasStartedLoading = false;
        constructor() {
            super();
        }
        #_document;
        #document() {
            if (!this.#_document) {
                this.#_document = this.mainRealm().evaluateHandle(() => {
                    return document;
                });
            }
            return this.#_document;
        }
        clearDocumentHandle() {
            this.#_document = undefined;
        }
        async frameElement() {
            const env_1 = { stack: [], error: void 0, hasError: false };
            try {
                const parentFrame = this.parentFrame();
                if (!parentFrame) {
                    return null;
                }
                const list = __addDisposableResource$7(env_1, await parentFrame.isolatedRealm().evaluateHandle(() => {
                    return document.querySelectorAll('iframe,frame');
                }), false);
                for await (const iframe_1 of transposeIterableHandle(list)) {
                    const env_2 = { stack: [], error: void 0, hasError: false };
                    try {
                        const iframe = __addDisposableResource$7(env_2, iframe_1, false);
                        const frame = await iframe.contentFrame();
                        if (frame?._id === this._id) {
                            return (await parentFrame
                                .mainRealm()
                                .adoptHandle(iframe));
                        }
                    }
                    catch (e_1) {
                        env_2.error = e_1;
                        env_2.hasError = true;
                    }
                    finally {
                        __disposeResources$7(env_2);
                    }
                }
                return null;
            }
            catch (e_2) {
                env_1.error = e_2;
                env_1.hasError = true;
            }
            finally {
                __disposeResources$7(env_1);
            }
        }
        async evaluateHandle(pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.evaluateHandle.name, pageFunction);
            return await this.mainRealm().evaluateHandle(pageFunction, ...args);
        }
        async evaluate(pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.evaluate.name, pageFunction);
            return await this.mainRealm().evaluate(pageFunction, ...args);
        }
        locator(input) {
            if (typeof input === 'string') {
                return NodeLocator.create(this, input);
            }
            else {
                return FunctionLocator.create(this, input);
            }
        }
        async $(selector) {
            const document = await this.#document();
            return await document.$(selector);
        }
        async $$(selector, options) {
            const document = await this.#document();
            return await document.$$(selector, options);
        }
        async $eval(selector, pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.$eval.name, pageFunction);
            const document = await this.#document();
            return await document.$eval(selector, pageFunction, ...args);
        }
        async $$eval(selector, pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.$$eval.name, pageFunction);
            const document = await this.#document();
            return await document.$$eval(selector, pageFunction, ...args);
        }
        async waitForSelector(selector, options = {}) {
            const { updatedSelector, QueryHandler, polling } = getQueryHandlerAndSelector(selector);
            return (await QueryHandler.waitFor(this, updatedSelector, {
                polling,
                ...options,
            }));
        }
        async waitForFunction(pageFunction, options = {}, ...args) {
            return await this.mainRealm().waitForFunction(pageFunction, options, ...args);
        }
        async content() {
            return await this.evaluate(() => {
                let content = '';
                for (const node of document.childNodes) {
                    switch (node) {
                        case document.documentElement:
                            content += document.documentElement.outerHTML;
                            break;
                        default:
                            content += new XMLSerializer().serializeToString(node);
                            break;
                    }
                }
                return content;
            });
        }
        async setFrameContent(content) {
            return await this.evaluate(html => {
                document.open();
                document.write(html);
                document.close();
            }, content);
        }
        name() {
            return this._name || '';
        }
        isDetached() {
            return this.detached;
        }
        get disposed() {
            return this.detached;
        }
        async addScriptTag(options) {
            let { content = '', type } = options;
            const { path } = options;
            if (+!!options.url + +!!path + +!!content !== 1) {
                throw new Error('Exactly one of `url`, `path`, or `content` must be specified.');
            }
            if (path) {
                content = await environment.value.fs.promises.readFile(path, 'utf8');
                content += `//# sourceURL=${path.replace(/\n/g, '')}`;
            }
            type = type ?? 'text/javascript';
            return await this.mainRealm().transferHandle(await this.isolatedRealm().evaluateHandle(async ({ url, id, type, content }) => {
                return await new Promise((resolve, reject) => {
                    const script = document.createElement('script');
                    script.type = type;
                    script.text = content;
                    script.addEventListener('error', event => {
                        reject(new Error(event.message ?? 'Could not load script'));
                    }, { once: true });
                    if (id) {
                        script.id = id;
                    }
                    if (url) {
                        script.src = url;
                        script.addEventListener('load', () => {
                            resolve(script);
                        }, { once: true });
                        document.head.appendChild(script);
                    }
                    else {
                        document.head.appendChild(script);
                        resolve(script);
                    }
                });
            }, { ...options, type, content }));
        }
        async addStyleTag(options) {
            let { content = '' } = options;
            const { path } = options;
            if (+!!options.url + +!!path + +!!content !== 1) {
                throw new Error('Exactly one of `url`, `path`, or `content` must be specified.');
            }
            if (path) {
                content = await environment.value.fs.promises.readFile(path, 'utf8');
                content += '/*# sourceURL=' + path.replace(/\n/g, '') + '*/';
                options.content = content;
            }
            return await this.mainRealm().transferHandle(await this.isolatedRealm().evaluateHandle(async ({ url, content }) => {
                return await new Promise((resolve, reject) => {
                    let element;
                    if (!url) {
                        element = document.createElement('style');
                        element.appendChild(document.createTextNode(content));
                    }
                    else {
                        const link = document.createElement('link');
                        link.rel = 'stylesheet';
                        link.href = url;
                        element = link;
                    }
                    element.addEventListener('load', () => {
                        resolve(element);
                    }, { once: true });
                    element.addEventListener('error', event => {
                        reject(new Error(event.message ?? 'Could not load style'));
                    }, { once: true });
                    document.head.appendChild(element);
                    return element;
                });
            }, options));
        }
        async click(selector, options = {}) {
            const env_3 = { stack: [], error: void 0, hasError: false };
            try {
                const handle = __addDisposableResource$7(env_3, await this.$(selector), false);
                assert(handle, `No element found for selector: ${selector}`);
                await handle.click(options);
                await handle.dispose();
            }
            catch (e_3) {
                env_3.error = e_3;
                env_3.hasError = true;
            }
            finally {
                __disposeResources$7(env_3);
            }
        }
        async focus(selector) {
            const env_4 = { stack: [], error: void 0, hasError: false };
            try {
                const handle = __addDisposableResource$7(env_4, await this.$(selector), false);
                assert(handle, `No element found for selector: ${selector}`);
                await handle.focus();
            }
            catch (e_4) {
                env_4.error = e_4;
                env_4.hasError = true;
            }
            finally {
                __disposeResources$7(env_4);
            }
        }
        async hover(selector) {
            const env_5 = { stack: [], error: void 0, hasError: false };
            try {
                const handle = __addDisposableResource$7(env_5, await this.$(selector), false);
                assert(handle, `No element found for selector: ${selector}`);
                await handle.hover();
            }
            catch (e_5) {
                env_5.error = e_5;
                env_5.hasError = true;
            }
            finally {
                __disposeResources$7(env_5);
            }
        }
        async select(selector, ...values) {
            const env_6 = { stack: [], error: void 0, hasError: false };
            try {
                const handle = __addDisposableResource$7(env_6, await this.$(selector), false);
                assert(handle, `No element found for selector: ${selector}`);
                return await handle.select(...values);
            }
            catch (e_6) {
                env_6.error = e_6;
                env_6.hasError = true;
            }
            finally {
                __disposeResources$7(env_6);
            }
        }
        async tap(selector) {
            const env_7 = { stack: [], error: void 0, hasError: false };
            try {
                const handle = __addDisposableResource$7(env_7, await this.$(selector), false);
                assert(handle, `No element found for selector: ${selector}`);
                await handle.tap();
            }
            catch (e_7) {
                env_7.error = e_7;
                env_7.hasError = true;
            }
            finally {
                __disposeResources$7(env_7);
            }
        }
        async type(selector, text, options) {
            const env_8 = { stack: [], error: void 0, hasError: false };
            try {
                const handle = __addDisposableResource$7(env_8, await this.$(selector), false);
                assert(handle, `No element found for selector: ${selector}`);
                await handle.type(text, options);
            }
            catch (e_8) {
                env_8.error = e_8;
                env_8.hasError = true;
            }
            finally {
                __disposeResources$7(env_8);
            }
        }
        async title() {
            return await this.isolatedRealm().evaluate(() => {
                return document.title;
            });
        }
    };
})();

class HTTPRequest {
    _interceptionId;
    _failureText = null;
    _response = null;
    _fromMemoryCache = false;
    _redirectChain = [];
    interception = {
        enabled: false,
        handled: false,
        handlers: [],
        resolutionState: {
            action: InterceptResolutionAction.None,
        },
        requestOverrides: {},
        response: null,
        abortReason: null,
    };
    constructor() { }
    continueRequestOverrides() {
        return this.interception.requestOverrides;
    }
    responseForRequest() {
        return this.interception.response;
    }
    abortErrorReason() {
        return this.interception.abortReason;
    }
    interceptResolutionState() {
        if (!this.interception.enabled) {
            return { action: InterceptResolutionAction.Disabled };
        }
        if (this.interception.handled) {
            return { action: InterceptResolutionAction.AlreadyHandled };
        }
        return { ...this.interception.resolutionState };
    }
    isInterceptResolutionHandled() {
        return this.interception.handled;
    }
    enqueueInterceptAction(pendingHandler) {
        this.interception.handlers.push(pendingHandler);
    }
    async finalizeInterceptions() {
        await this.interception.handlers.reduce((promiseChain, interceptAction) => {
            return promiseChain.then(interceptAction);
        }, Promise.resolve());
        this.interception.handlers = [];
        const { action } = this.interceptResolutionState();
        switch (action) {
            case 'abort':
                return await this._abort(this.interception.abortReason);
            case 'respond':
                if (this.interception.response === null) {
                    throw new Error('Response is missing for the interception');
                }
                return await this._respond(this.interception.response);
            case 'continue':
                return await this._continue(this.interception.requestOverrides);
        }
    }
    verifyInterception() {
        assert(this.interception.enabled, 'Request Interception is not enabled!');
        assert(!this.interception.handled, 'Request is already handled!');
    }
    async continue(overrides = {}, priority) {
        this.verifyInterception();
        if (!this.canBeIntercepted()) {
            return;
        }
        if (priority === undefined) {
            return await this._continue(overrides);
        }
        this.interception.requestOverrides = overrides;
        if (this.interception.resolutionState.priority === undefined ||
            priority > this.interception.resolutionState.priority) {
            this.interception.resolutionState = {
                action: InterceptResolutionAction.Continue,
                priority,
            };
            return;
        }
        if (priority === this.interception.resolutionState.priority) {
            if (this.interception.resolutionState.action === 'abort' ||
                this.interception.resolutionState.action === 'respond') {
                return;
            }
            this.interception.resolutionState.action =
                InterceptResolutionAction.Continue;
        }
        return;
    }
    async respond(response, priority) {
        this.verifyInterception();
        if (!this.canBeIntercepted()) {
            return;
        }
        if (priority === undefined) {
            return await this._respond(response);
        }
        this.interception.response = response;
        if (this.interception.resolutionState.priority === undefined ||
            priority > this.interception.resolutionState.priority) {
            this.interception.resolutionState = {
                action: InterceptResolutionAction.Respond,
                priority,
            };
            return;
        }
        if (priority === this.interception.resolutionState.priority) {
            if (this.interception.resolutionState.action === 'abort') {
                return;
            }
            this.interception.resolutionState.action =
                InterceptResolutionAction.Respond;
        }
    }
    async abort(errorCode = 'failed', priority) {
        this.verifyInterception();
        if (!this.canBeIntercepted()) {
            return;
        }
        const errorReason = errorReasons[errorCode];
        assert(errorReason, 'Unknown error code: ' + errorCode);
        if (priority === undefined) {
            return await this._abort(errorReason);
        }
        this.interception.abortReason = errorReason;
        if (this.interception.resolutionState.priority === undefined ||
            priority >= this.interception.resolutionState.priority) {
            this.interception.resolutionState = {
                action: InterceptResolutionAction.Abort,
                priority,
            };
            return;
        }
    }
    static getResponse(body) {
        const byteBody = isString(body)
            ? new TextEncoder().encode(body)
            : body;
        return {
            contentLength: byteBody.byteLength,
            base64: typedArrayToBase64(byteBody),
        };
    }
}
var InterceptResolutionAction;
(function (InterceptResolutionAction) {
    InterceptResolutionAction["Abort"] = "abort";
    InterceptResolutionAction["Respond"] = "respond";
    InterceptResolutionAction["Continue"] = "continue";
    InterceptResolutionAction["Disabled"] = "disabled";
    InterceptResolutionAction["None"] = "none";
    InterceptResolutionAction["AlreadyHandled"] = "already-handled";
})(InterceptResolutionAction || (InterceptResolutionAction = {}));
function headersArray(headers) {
    const result = [];
    for (const name in headers) {
        const value = headers[name];
        if (!Object.is(value, undefined)) {
            const values = Array.isArray(value) ? value : [value];
            result.push(...values.map(value => {
                return { name, value: value + '' };
            }));
        }
    }
    return result;
}
const STATUS_TEXTS = {
    '100': 'Continue',
    '101': 'Switching Protocols',
    '102': 'Processing',
    '103': 'Early Hints',
    '200': 'OK',
    '201': 'Created',
    '202': 'Accepted',
    '203': 'Non-Authoritative Information',
    '204': 'No Content',
    '205': 'Reset Content',
    '206': 'Partial Content',
    '207': 'Multi-Status',
    '208': 'Already Reported',
    '226': 'IM Used',
    '300': 'Multiple Choices',
    '301': 'Moved Permanently',
    '302': 'Found',
    '303': 'See Other',
    '304': 'Not Modified',
    '305': 'Use Proxy',
    '306': 'Switch Proxy',
    '307': 'Temporary Redirect',
    '308': 'Permanent Redirect',
    '400': 'Bad Request',
    '401': 'Unauthorized',
    '402': 'Payment Required',
    '403': 'Forbidden',
    '404': 'Not Found',
    '405': 'Method Not Allowed',
    '406': 'Not Acceptable',
    '407': 'Proxy Authentication Required',
    '408': 'Request Timeout',
    '409': 'Conflict',
    '410': 'Gone',
    '411': 'Length Required',
    '412': 'Precondition Failed',
    '413': 'Payload Too Large',
    '414': 'URI Too Long',
    '415': 'Unsupported Media Type',
    '416': 'Range Not Satisfiable',
    '417': 'Expectation Failed',
    '418': "I'm a teapot",
    '421': 'Misdirected Request',
    '422': 'Unprocessable Entity',
    '423': 'Locked',
    '424': 'Failed Dependency',
    '425': 'Too Early',
    '426': 'Upgrade Required',
    '428': 'Precondition Required',
    '429': 'Too Many Requests',
    '431': 'Request Header Fields Too Large',
    '451': 'Unavailable For Legal Reasons',
    '500': 'Internal Server Error',
    '501': 'Not Implemented',
    '502': 'Bad Gateway',
    '503': 'Service Unavailable',
    '504': 'Gateway Timeout',
    '505': 'HTTP Version Not Supported',
    '506': 'Variant Also Negotiates',
    '507': 'Insufficient Storage',
    '508': 'Loop Detected',
    '510': 'Not Extended',
    '511': 'Network Authentication Required',
};
const errorReasons = {
    aborted: 'Aborted',
    accessdenied: 'AccessDenied',
    addressunreachable: 'AddressUnreachable',
    blockedbyclient: 'BlockedByClient',
    blockedbyresponse: 'BlockedByResponse',
    connectionaborted: 'ConnectionAborted',
    connectionclosed: 'ConnectionClosed',
    connectionfailed: 'ConnectionFailed',
    connectionrefused: 'ConnectionRefused',
    connectionreset: 'ConnectionReset',
    internetdisconnected: 'InternetDisconnected',
    namenotresolved: 'NameNotResolved',
    timedout: 'TimedOut',
    failed: 'Failed',
};
function handleError(error) {
    if (error.originalMessage.includes('Invalid header') ||
        error.originalMessage.includes('Unsafe header') ||
        error.originalMessage.includes('Expected "header"') ||
        error.originalMessage.includes('invalid argument')) {
        throw error;
    }
    debugError(error);
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class HTTPResponse {
    constructor() { }
    ok() {
        const status = this.status();
        return status === 0 || (status >= 200 && status <= 299);
    }
    async buffer() {
        const content = await this.content();
        return Buffer.from(content);
    }
    async text() {
        const content = await this.content();
        return new TextDecoder('utf-8', { fatal: true }).decode(content);
    }
    async json() {
        const content = await this.text();
        return JSON.parse(content);
    }
}

/**
 * @license
 * Copyright 2024 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function createIncrementalIdGenerator() {
    let id = 0;
    return () => {
        if (id === Number.MAX_SAFE_INTEGER) {
            id = 0;
        }
        return ++id;
    };
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class Keyboard {
    constructor() { }
}
const MouseButton = Object.freeze({
    Left: 'left',
    Right: 'right',
    Middle: 'middle',
    Back: 'back',
    Forward: 'forward',
});
class Mouse {
    constructor() { }
}
class Touchscreen {
    idGenerator = createIncrementalIdGenerator();
    touches = [];
    constructor() { }
    removeHandle(handle) {
        const index = this.touches.indexOf(handle);
        if (index === -1) {
            return;
        }
        this.touches.splice(index, 1);
    }
    async tap(x, y) {
        const touch = await this.touchStart(x, y);
        await touch.end();
    }
    async touchMove(x, y) {
        const touch = this.touches[0];
        if (!touch) {
            throw new TouchError('Must start a new Touch first');
        }
        return await touch.move(x, y);
    }
    async touchEnd() {
        const touch = this.touches.shift();
        if (!touch) {
            throw new TouchError('Must start a new Touch first');
        }
        await touch.end();
    }
}

/**
 * @license
 * Copyright 2019 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const DEFAULT_TIMEOUT = 30000;
class TimeoutSettings {
    #defaultTimeout;
    #defaultNavigationTimeout;
    constructor() {
        this.#defaultTimeout = null;
        this.#defaultNavigationTimeout = null;
    }
    setDefaultTimeout(timeout) {
        this.#defaultTimeout = timeout;
    }
    setDefaultNavigationTimeout(timeout) {
        this.#defaultNavigationTimeout = timeout;
    }
    navigationTimeout() {
        if (this.#defaultNavigationTimeout !== null) {
            return this.#defaultNavigationTimeout;
        }
        if (this.#defaultTimeout !== null) {
            return this.#defaultTimeout;
        }
        return DEFAULT_TIMEOUT;
    }
    timeout() {
        if (this.#defaultTimeout !== null) {
            return this.#defaultTimeout;
        }
        return DEFAULT_TIMEOUT;
    }
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __runInitializers$5 = (undefined && undefined.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
var __esDecorate$5 = (undefined && undefined.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __addDisposableResource$6 = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$6 = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
function setDefaultScreenshotOptions(options) {
    options.optimizeForSpeed ??= false;
    options.type ??= 'png';
    options.fromSurface ??= true;
    options.fullPage ??= false;
    options.omitBackground ??= false;
    options.encoding ??= 'binary';
    options.captureBeyondViewport ??= true;
}
let Page = (() => {
    let _classSuper = EventEmitter;
    let _instanceExtraInitializers = [];
    let _screenshot_decorators;
    return class Page extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            __esDecorate$5(this, null, _screenshot_decorators, { kind: "method", name: "screenshot", static: false, private: false, access: { has: obj => "screenshot" in obj, get: obj => obj.screenshot }, metadata: _metadata }, null, _instanceExtraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        _isDragging = (__runInitializers$5(this, _instanceExtraInitializers), false);
        _timeoutSettings = new TimeoutSettings();
        _tabId = '';
        #requestHandlers = new WeakMap();
        #inflight$ = new ReplaySubject(1);
        constructor() {
            super();
            fromEmitterEvent(this, "request" )
                .pipe(mergeMap(originalRequest => {
                return concat(of(1), merge(fromEmitterEvent(this, "requestfailed" ), fromEmitterEvent(this, "requestfinished" ), fromEmitterEvent(this, "response" ).pipe(map(response => {
                    return response.request();
                }))).pipe(filter(request => {
                    return request.id === originalRequest.id;
                }), take(1), map(() => {
                    return -1;
                })));
            }), mergeScan((acc, addend) => {
                return of(acc + addend);
            }, 0), takeUntil(fromEmitterEvent(this, "close" )), startWith(0))
                .subscribe(this.#inflight$);
        }
        on(type, handler) {
            if (type !== "request" ) {
                return super.on(type, handler);
            }
            let wrapper = this.#requestHandlers.get(handler);
            if (wrapper === undefined) {
                wrapper = (event) => {
                    event.enqueueInterceptAction(() => {
                        return handler(event);
                    });
                };
                this.#requestHandlers.set(handler, wrapper);
            }
            return super.on(type, wrapper);
        }
        off(type, handler) {
            if (type === "request" ) {
                handler =
                    this.#requestHandlers.get(handler) || handler;
            }
            return super.off(type, handler);
        }
        get accessibility() {
            return this.mainFrame().accessibility;
        }
        locator(input) {
            if (typeof input === 'string') {
                return NodeLocator.create(this, input);
            }
            else {
                return FunctionLocator.create(this, input);
            }
        }
        locatorRace(locators) {
            return Locator.race(locators);
        }
        async $(selector) {
            return await this.mainFrame().$(selector);
        }
        async $$(selector, options) {
            return await this.mainFrame().$$(selector, options);
        }
        async evaluateHandle(pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.evaluateHandle.name, pageFunction);
            return await this.mainFrame().evaluateHandle(pageFunction, ...args);
        }
        async $eval(selector, pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.$eval.name, pageFunction);
            return await this.mainFrame().$eval(selector, pageFunction, ...args);
        }
        async $$eval(selector, pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.$$eval.name, pageFunction);
            return await this.mainFrame().$$eval(selector, pageFunction, ...args);
        }
        async addScriptTag(options) {
            return await this.mainFrame().addScriptTag(options);
        }
        async addStyleTag(options) {
            return await this.mainFrame().addStyleTag(options);
        }
        url() {
            return this.mainFrame().url();
        }
        async content() {
            return await this.mainFrame().content();
        }
        async setContent(html, options) {
            await this.mainFrame().setContent(html, options);
        }
        async goto(url, options) {
            return await this.mainFrame().goto(url, options);
        }
        async waitForNavigation(options = {}) {
            return await this.mainFrame().waitForNavigation(options);
        }
        waitForRequest(urlOrPredicate, options = {}) {
            const { timeout: ms = this._timeoutSettings.timeout(), signal } = options;
            if (typeof urlOrPredicate === 'string') {
                const url = urlOrPredicate;
                urlOrPredicate = (request) => {
                    return request.url() === url;
                };
            }
            const observable$ = fromEmitterEvent(this, "request" ).pipe(filterAsync(urlOrPredicate), raceWith(timeout(ms), fromAbortSignal(signal), fromEmitterEvent(this, "close" ).pipe(map(() => {
                throw new TargetCloseError('Page closed!');
            }))));
            return firstValueFrom(observable$);
        }
        waitForResponse(urlOrPredicate, options = {}) {
            const { timeout: ms = this._timeoutSettings.timeout(), signal } = options;
            if (typeof urlOrPredicate === 'string') {
                const url = urlOrPredicate;
                urlOrPredicate = (response) => {
                    return response.url() === url;
                };
            }
            const observable$ = fromEmitterEvent(this, "response" ).pipe(filterAsync(urlOrPredicate), raceWith(timeout(ms), fromAbortSignal(signal), fromEmitterEvent(this, "close" ).pipe(map(() => {
                throw new TargetCloseError('Page closed!');
            }))));
            return firstValueFrom(observable$);
        }
        waitForNetworkIdle(options = {}) {
            return firstValueFrom(this.waitForNetworkIdle$(options));
        }
        waitForNetworkIdle$(options = {}) {
            const { timeout: ms = this._timeoutSettings.timeout(), idleTime = NETWORK_IDLE_TIME, concurrency = 0, signal, } = options;
            return this.#inflight$.pipe(map(inflight => {
                return inflight > concurrency;
            }), distinctUntilChanged(), switchMap(isInflightOverConcurrency => {
                if (isInflightOverConcurrency) {
                    return EMPTY;
                }
                return timer(idleTime);
            }), map(() => { }), raceWith(timeout(ms), fromAbortSignal(signal), fromEmitterEvent(this, "close" ).pipe(map(() => {
                throw new TargetCloseError('Page closed!');
            }))));
        }
        async waitForFrame(urlOrPredicate, options = {}) {
            const { timeout: ms = this.getDefaultTimeout(), signal } = options;
            const predicate = isString(urlOrPredicate)
                ? (frame) => {
                    return urlOrPredicate === frame.url();
                }
                : urlOrPredicate;
            return await firstValueFrom(merge(fromEmitterEvent(this, "frameattached" ), fromEmitterEvent(this, "framenavigated" ), from(this.frames())).pipe(filterAsync(predicate), first(), raceWith(timeout(ms), fromAbortSignal(signal), fromEmitterEvent(this, "close" ).pipe(map(() => {
                throw new TargetCloseError('Page closed.');
            })))));
        }
        async emulate(device) {
            await Promise.all([
                this.setUserAgent({ userAgent: device.userAgent }),
                this.setViewport(device.viewport),
            ]);
        }
        async evaluate(pageFunction, ...args) {
            pageFunction = withSourcePuppeteerURLIfNone(this.evaluate.name, pageFunction);
            return await this.mainFrame().evaluate(pageFunction, ...args);
        }
        async _maybeWriteTypedArrayToFile(path, typedArray) {
            if (!path) {
                return;
            }
            await environment.value.fs.promises.writeFile(path, typedArray);
        }
        async screencast(options = {}) {
            const ScreenRecorder = environment.value.ScreenRecorder;
            const [width, height, devicePixelRatio] = await this.#getNativePixelDimensions();
            let crop;
            if (options.crop) {
                const { x, y, width: cropWidth, height: cropHeight, } = roundRectangle(normalizeRectangle(options.crop));
                if (x < 0 || y < 0) {
                    throw new Error(`\`crop.x\` and \`crop.y\` must be greater than or equal to 0.`);
                }
                if (cropWidth <= 0 || cropHeight <= 0) {
                    throw new Error(`\`crop.height\` and \`crop.width\` must be greater than or equal to 0.`);
                }
                const viewportWidth = width / devicePixelRatio;
                const viewportHeight = height / devicePixelRatio;
                if (x + cropWidth > viewportWidth) {
                    throw new Error(`\`crop.width\` cannot be larger than the viewport width (${viewportWidth}).`);
                }
                if (y + cropHeight > viewportHeight) {
                    throw new Error(`\`crop.height\` cannot be larger than the viewport height (${viewportHeight}).`);
                }
                crop = {
                    x: x * devicePixelRatio,
                    y: y * devicePixelRatio,
                    width: cropWidth * devicePixelRatio,
                    height: cropHeight * devicePixelRatio,
                };
            }
            if (options.speed !== undefined && options.speed <= 0) {
                throw new Error(`\`speed\` must be greater than 0.`);
            }
            if (options.scale !== undefined && options.scale <= 0) {
                throw new Error(`\`scale\` must be greater than 0.`);
            }
            const recorder = new ScreenRecorder(this, width, height, {
                ...options,
                crop,
            });
            try {
                await this._startScreencast();
            }
            catch (error) {
                void recorder.stop();
                throw error;
            }
            if (options.path) {
                const { createWriteStream } = environment.value.fs;
                const stream = createWriteStream(options.path, 'binary');
                recorder.pipe(stream);
            }
            return recorder;
        }
        #screencastSessionCount = 0;
        #startScreencastPromise;
        async _startScreencast() {
            ++this.#screencastSessionCount;
            if (!this.#startScreencastPromise) {
                this.#startScreencastPromise = this.mainFrame()
                    .client.send('Page.startScreencast', { format: 'png' })
                    .then(() => {
                    return new Promise(resolve => {
                        return this.mainFrame().client.once('Page.screencastFrame', () => {
                            return resolve();
                        });
                    });
                });
            }
            await this.#startScreencastPromise;
        }
        async _stopScreencast() {
            --this.#screencastSessionCount;
            if (!this.#startScreencastPromise) {
                return;
            }
            this.#startScreencastPromise = undefined;
            if (this.#screencastSessionCount === 0) {
                await this.mainFrame().client.send('Page.stopScreencast');
            }
        }
        async #getNativePixelDimensions() {
            const env_1 = { stack: [], error: void 0, hasError: false };
            try {
                const viewport = this.viewport();
                const stack = __addDisposableResource$6(env_1, new DisposableStack(), false);
                if (viewport && viewport.deviceScaleFactor !== 0) {
                    await this.setViewport({ ...viewport, deviceScaleFactor: 0 });
                    stack.defer(() => {
                        void this.setViewport(viewport).catch(debugError);
                    });
                }
                return await this.mainFrame()
                    .isolatedRealm()
                    .evaluate(() => {
                    return [
                        window.visualViewport.width * window.devicePixelRatio,
                        window.visualViewport.height * window.devicePixelRatio,
                        window.devicePixelRatio,
                    ];
                });
            }
            catch (e_1) {
                env_1.error = e_1;
                env_1.hasError = true;
            }
            finally {
                __disposeResources$6(env_1);
            }
        }
        async screenshot(userOptions = {}) {
            const env_2 = { stack: [], error: void 0, hasError: false };
            try {
                const _guard = __addDisposableResource$6(env_2, await this.browserContext().startScreenshot(), false);
                const options = {
                    ...userOptions,
                    clip: userOptions.clip
                        ? {
                            ...userOptions.clip,
                        }
                        : undefined,
                };
                if (options.type === undefined && options.path !== undefined) {
                    const filePath = options.path;
                    const extension = filePath
                        .slice(filePath.lastIndexOf('.') + 1)
                        .toLowerCase();
                    switch (extension) {
                        case 'png':
                            options.type = 'png';
                            break;
                        case 'jpeg':
                        case 'jpg':
                            options.type = 'jpeg';
                            break;
                        case 'webp':
                            options.type = 'webp';
                            break;
                    }
                }
                if (options.quality !== undefined) {
                    if (options.quality < 0 || options.quality > 100) {
                        throw new Error(`Expected 'quality' (${options.quality}) to be between 0 and 100, inclusive.`);
                    }
                    if (options.type === undefined ||
                        !['jpeg', 'webp'].includes(options.type)) {
                        throw new Error(`${options.type ?? 'png'} screenshots do not support 'quality'.`);
                    }
                }
                if (options.clip) {
                    if (options.clip.width <= 0) {
                        throw new Error("'width' in 'clip' must be positive.");
                    }
                    if (options.clip.height <= 0) {
                        throw new Error("'height' in 'clip' must be positive.");
                    }
                }
                setDefaultScreenshotOptions(options);
                const stack = __addDisposableResource$6(env_2, new AsyncDisposableStack(), true);
                if (options.clip) {
                    if (options.fullPage) {
                        throw new Error("'clip' and 'fullPage' are mutually exclusive");
                    }
                    options.clip = roundRectangle(normalizeRectangle(options.clip));
                }
                else {
                    if (options.fullPage) {
                        if (!options.captureBeyondViewport) {
                            const scrollDimensions = await this.mainFrame()
                                .isolatedRealm()
                                .evaluate(() => {
                                const element = document.documentElement;
                                return {
                                    width: element.scrollWidth,
                                    height: element.scrollHeight,
                                };
                            });
                            const viewport = this.viewport();
                            await this.setViewport({
                                ...viewport,
                                ...scrollDimensions,
                            });
                            stack.defer(async () => {
                                await this.setViewport(viewport).catch(debugError);
                            });
                        }
                    }
                    else {
                        options.captureBeyondViewport = false;
                    }
                }
                const data = await this._screenshot(options);
                if (options.encoding === 'base64') {
                    return data;
                }
                const typedArray = stringToTypedArray(data, true);
                await this._maybeWriteTypedArrayToFile(options.path, typedArray);
                return typedArray;
            }
            catch (e_2) {
                env_2.error = e_2;
                env_2.hasError = true;
            }
            finally {
                const result_1 = __disposeResources$6(env_2);
                if (result_1)
                    await result_1;
            }
        }
        async title() {
            return await this.mainFrame().title();
        }
        click(selector, options) {
            return this.mainFrame().click(selector, options);
        }
        focus(selector) {
            return this.mainFrame().focus(selector);
        }
        hover(selector) {
            return this.mainFrame().hover(selector);
        }
        select(selector, ...values) {
            return this.mainFrame().select(selector, ...values);
        }
        tap(selector) {
            return this.mainFrame().tap(selector);
        }
        type(selector, text, options) {
            return this.mainFrame().type(selector, text, options);
        }
        async waitForSelector(selector, options = {}) {
            return await this.mainFrame().waitForSelector(selector, options);
        }
        waitForFunction(pageFunction, options, ...args) {
            return this.mainFrame().waitForFunction(pageFunction, options, ...args);
        }
        [(_screenshot_decorators = [guarded(function () {
                return this.browser();
            })], disposeSymbol)]() {
            return void this.close().catch(debugError);
        }
        [asyncDisposeSymbol]() {
            return this.close();
        }
    };
})();
function normalizeRectangle(clip) {
    return {
        ...clip,
        ...(clip.width < 0
            ? {
                x: clip.x + clip.width,
                width: -clip.width,
            }
            : {
                x: clip.x,
                width: clip.width,
            }),
        ...(clip.height < 0
            ? {
                y: clip.y + clip.height,
                height: -clip.height,
            }
            : {
                y: clip.y,
                height: clip.height,
            }),
    };
}
function roundRectangle(clip) {
    const x = Math.round(clip.x);
    const y = Math.round(clip.y);
    const width = Math.round(clip.width + clip.x - x);
    const height = Math.round(clip.height + clip.y - y);
    return { ...clip, x, y, width, height };
}

/**
 * @license
 * Copyright 2022 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class WaitTask {
    #world;
    #polling;
    #root;
    #fn;
    #args;
    #timeout;
    #genericError = new Error('Waiting failed');
    #timeoutError;
    #result = Deferred.create();
    #poller;
    #signal;
    #reruns = [];
    constructor(world, options, fn, ...args) {
        this.#world = world;
        this.#polling = options.polling;
        this.#root = options.root;
        this.#signal = options.signal;
        this.#signal?.addEventListener('abort', this.#onAbortSignal, {
            once: true,
        });
        switch (typeof fn) {
            case 'string':
                this.#fn = `() => {return (${fn});}`;
                break;
            default:
                this.#fn = stringifyFunction(fn);
                break;
        }
        this.#args = args;
        this.#world.taskManager.add(this);
        if (options.timeout) {
            this.#timeoutError = new TimeoutError$1(`Waiting failed: ${options.timeout}ms exceeded`);
            this.#timeout = setTimeout(() => {
                void this.terminate(this.#timeoutError);
            }, options.timeout);
        }
        void this.rerun();
    }
    get result() {
        return this.#result.valueOrThrow();
    }
    async rerun() {
        for (const prev of this.#reruns) {
            prev.abort();
        }
        this.#reruns.length = 0;
        const controller = new AbortController();
        this.#reruns.push(controller);
        try {
            switch (this.#polling) {
                case 'raf':
                    this.#poller = await this.#world.evaluateHandle(({ RAFPoller, createFunction }, fn, ...args) => {
                        const fun = createFunction(fn);
                        return new RAFPoller(() => {
                            return fun(...args);
                        });
                    }, LazyArg.create(context => {
                        return context.puppeteerUtil;
                    }), this.#fn, ...this.#args);
                    break;
                case 'mutation':
                    this.#poller = await this.#world.evaluateHandle(({ MutationPoller, createFunction }, root, fn, ...args) => {
                        const fun = createFunction(fn);
                        return new MutationPoller(() => {
                            return fun(...args);
                        }, root || document);
                    }, LazyArg.create(context => {
                        return context.puppeteerUtil;
                    }), this.#root, this.#fn, ...this.#args);
                    break;
                default:
                    this.#poller = await this.#world.evaluateHandle(({ IntervalPoller, createFunction }, ms, fn, ...args) => {
                        const fun = createFunction(fn);
                        return new IntervalPoller(() => {
                            return fun(...args);
                        }, ms);
                    }, LazyArg.create(context => {
                        return context.puppeteerUtil;
                    }), this.#polling, this.#fn, ...this.#args);
                    break;
            }
            await this.#poller.evaluate(poller => {
                void poller.start();
            });
            const result = await this.#poller.evaluateHandle(poller => {
                return poller.result();
            });
            this.#result.resolve(result);
            await this.terminate();
        }
        catch (error) {
            if (controller.signal.aborted) {
                return;
            }
            const badError = this.getBadError(error);
            if (badError) {
                this.#genericError.cause = badError;
                await this.terminate(this.#genericError);
            }
        }
    }
    async terminate(error) {
        this.#world.taskManager.delete(this);
        this.#signal?.removeEventListener('abort', this.#onAbortSignal);
        clearTimeout(this.#timeout);
        if (error && !this.#result.finished()) {
            this.#result.reject(error);
        }
        if (this.#poller) {
            try {
                await this.#poller.evaluate(async (poller) => {
                    await poller.stop();
                });
                if (this.#poller) {
                    await this.#poller.dispose();
                    this.#poller = undefined;
                }
            }
            catch {
            }
        }
    }
    getBadError(error) {
        if (isErrorLike$1(error)) {
            if (error.message.includes('Execution context is not available in detached frame')) {
                return new Error('Waiting failed: Frame detached');
            }
            if (error.message.includes('Execution context was destroyed')) {
                return;
            }
            if (error.message.includes('Cannot find context with specified id')) {
                return;
            }
            if (error.message.includes('DiscardedBrowsingContextError')) {
                return;
            }
            return error;
        }
        return new Error('WaitTask failed with an error', {
            cause: error,
        });
    }
    #onAbortSignal = () => {
        void this.terminate(this.#signal?.reason);
    };
}
class TaskManager {
    #tasks = new Set();
    add(task) {
        this.#tasks.add(task);
    }
    delete(task) {
        this.#tasks.delete(task);
    }
    terminateAll(error) {
        for (const task of this.#tasks) {
            void task.terminate(error);
        }
        this.#tasks.clear();
    }
    async rerunAll() {
        await Promise.all([...this.#tasks].map(task => {
            return task.rerun();
        }));
    }
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class Realm {
    timeoutSettings;
    taskManager = new TaskManager();
    constructor(timeoutSettings) {
        this.timeoutSettings = timeoutSettings;
    }
    async waitForFunction(pageFunction, options = {}, ...args) {
        const { polling = 'raf', timeout = this.timeoutSettings.timeout(), root, signal, } = options;
        if (typeof polling === 'number' && polling < 0) {
            throw new Error('Cannot poll with non-positive interval');
        }
        const waitTask = new WaitTask(this, {
            polling,
            root,
            timeout,
            signal,
        }, pageFunction, ...args);
        return await waitTask.result;
    }
    get disposed() {
        return this.#disposed;
    }
    #disposed = false;
    dispose() {
        this.#disposed = true;
        this.taskManager.terminateAll(new Error('waitForFunction failed: frame got detached.'));
    }
    [disposeSymbol]() {
        this.dispose();
    }
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var TargetType;
(function (TargetType) {
    TargetType["PAGE"] = "page";
    TargetType["BACKGROUND_PAGE"] = "background_page";
    TargetType["SERVICE_WORKER"] = "service_worker";
    TargetType["SHARED_WORKER"] = "shared_worker";
    TargetType["BROWSER"] = "browser";
    TargetType["WEBVIEW"] = "webview";
    TargetType["OTHER"] = "other";
    TargetType["TAB"] = "tab";
})(TargetType || (TargetType = {}));
let Target$1 = class Target {
    constructor() { }
    async worker() {
        return null;
    }
    async page() {
        return null;
    }
};

/**
 * @license
 * Copyright 2018 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
let WebWorker$1 = class WebWorker extends EventEmitter {
    timeoutSettings = new TimeoutSettings();
    #url;
    constructor(url) {
        super();
        this.#url = url;
    }
    url() {
        return this.#url;
    }
    async evaluate(func, ...args) {
        func = withSourcePuppeteerURLIfNone(this.evaluate.name, func);
        return await this.mainRealm().evaluate(func, ...args);
    }
    async evaluateHandle(func, ...args) {
        func = withSourcePuppeteerURLIfNone(this.evaluateHandle.name, func);
        return await this.mainRealm().evaluateHandle(func, ...args);
    }
    async close() {
        throw new UnsupportedOperation('WebWorker.close() is not supported');
    }
};

/**
 * @license
 * Copyright 2018 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __addDisposableResource$5 = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$5 = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
class Accessibility {
    #realm;
    #frameId;
    constructor(realm, frameId = '') {
        this.#realm = realm;
        this.#frameId = frameId;
    }
    async snapshot(options = {}) {
        const { interestingOnly = true, root = null, includeIframes = false, } = options;
        const { nodes } = await this.#realm.environment.client.send('Accessibility.getFullAXTree', {
            frameId: this.#frameId,
        });
        let backendNodeId;
        if (root) {
            const { node } = await this.#realm.environment.client.send('DOM.describeNode', {
                objectId: root.id,
            });
            backendNodeId = node.backendNodeId;
        }
        const defaultRoot = AXNode.createTree(this.#realm, nodes);
        const populateIframes = async (root) => {
            if (root.payload.role?.value === 'Iframe') {
                const env_1 = { stack: [], error: void 0, hasError: false };
                try {
                    if (!root.payload.backendDOMNodeId) {
                        return;
                    }
                    const handle = __addDisposableResource$5(env_1, (await this.#realm.adoptBackendNode(root.payload.backendDOMNodeId)), false);
                    if (!handle || !('contentFrame' in handle)) {
                        return;
                    }
                    const frame = await handle.contentFrame();
                    if (!frame) {
                        return;
                    }
                    try {
                        const iframeSnapshot = await frame.accessibility.snapshot(options);
                        root.iframeSnapshot = iframeSnapshot ?? undefined;
                    }
                    catch (error) {
                        debugError(error);
                    }
                }
                catch (e_1) {
                    env_1.error = e_1;
                    env_1.hasError = true;
                }
                finally {
                    __disposeResources$5(env_1);
                }
            }
            for (const child of root.children) {
                await populateIframes(child);
            }
        };
        let needle = defaultRoot;
        if (!defaultRoot) {
            return null;
        }
        if (includeIframes) {
            await populateIframes(defaultRoot);
        }
        if (backendNodeId) {
            needle = defaultRoot.find(node => {
                return node.payload.backendDOMNodeId === backendNodeId;
            });
        }
        if (!needle) {
            return null;
        }
        if (!interestingOnly) {
            return this.serializeTree(needle)[0] ?? null;
        }
        const interestingNodes = new Set();
        this.collectInterestingNodes(interestingNodes, defaultRoot, false);
        return this.serializeTree(needle, interestingNodes)[0] ?? null;
    }
    serializeTree(node, interestingNodes) {
        const children = [];
        for (const child of node.children) {
            children.push(...this.serializeTree(child, interestingNodes));
        }
        if (interestingNodes && !interestingNodes.has(node)) {
            return children;
        }
        const serializedNode = node.serialize();
        if (children.length) {
            serializedNode.children = children;
        }
        if (node.iframeSnapshot) {
            if (!serializedNode.children) {
                serializedNode.children = [];
            }
            serializedNode.children.push(node.iframeSnapshot);
        }
        return [serializedNode];
    }
    collectInterestingNodes(collection, node, insideControl) {
        if (node.isInteresting(insideControl) || node.iframeSnapshot) {
            collection.add(node);
        }
        if (node.isLeafNode()) {
            return;
        }
        insideControl = insideControl || node.isControl();
        for (const child of node.children) {
            this.collectInterestingNodes(collection, child, insideControl);
        }
    }
}
class AXNode {
    payload;
    children = [];
    iframeSnapshot;
    #richlyEditable = false;
    #editable = false;
    #focusable = false;
    #hidden = false;
    #busy = false;
    #modal = false;
    #hasErrormessage = false;
    #hasDetails = false;
    #name;
    #role;
    #description;
    #roledescription;
    #live;
    #ignored;
    #cachedHasFocusableChild;
    #realm;
    constructor(realm, payload) {
        this.payload = payload;
        this.#role = this.payload.role ? this.payload.role.value : 'Unknown';
        this.#ignored = this.payload.ignored;
        this.#name = this.payload.name ? this.payload.name.value : '';
        this.#description = this.payload.description
            ? this.payload.description.value
            : undefined;
        this.#realm = realm;
        for (const property of this.payload.properties || []) {
            if (property.name === 'editable') {
                this.#richlyEditable = property.value.value === 'richtext';
                this.#editable = true;
            }
            if (property.name === 'focusable') {
                this.#focusable = property.value.value;
            }
            if (property.name === 'hidden') {
                this.#hidden = property.value.value;
            }
            if (property.name === 'busy') {
                this.#busy = property.value.value;
            }
            if (property.name === 'live') {
                this.#live = property.value.value;
            }
            if (property.name === 'modal') {
                this.#modal = property.value.value;
            }
            if (property.name === 'roledescription') {
                this.#roledescription = property.value.value;
            }
            if (property.name === 'errormessage') {
                this.#hasErrormessage = true;
            }
            if (property.name === 'details') {
                this.#hasDetails = true;
            }
        }
    }
    #isPlainTextField() {
        if (this.#richlyEditable) {
            return false;
        }
        if (this.#editable) {
            return true;
        }
        return this.#role === 'textbox' || this.#role === 'searchbox';
    }
    #isTextOnlyObject() {
        const role = this.#role;
        return (role === 'LineBreak' ||
            role === 'text' ||
            role === 'InlineTextBox' ||
            role === 'StaticText');
    }
    #hasFocusableChild() {
        if (this.#cachedHasFocusableChild === undefined) {
            this.#cachedHasFocusableChild = false;
            for (const child of this.children) {
                if (child.#focusable || child.#hasFocusableChild()) {
                    this.#cachedHasFocusableChild = true;
                    break;
                }
            }
        }
        return this.#cachedHasFocusableChild;
    }
    find(predicate) {
        if (predicate(this)) {
            return this;
        }
        for (const child of this.children) {
            const result = child.find(predicate);
            if (result) {
                return result;
            }
        }
        return null;
    }
    isLeafNode() {
        if (!this.children.length) {
            return true;
        }
        if (this.#isPlainTextField() || this.#isTextOnlyObject()) {
            return true;
        }
        switch (this.#role) {
            case 'doc-cover':
            case 'graphics-symbol':
            case 'img':
            case 'image':
            case 'Meter':
            case 'scrollbar':
            case 'slider':
            case 'separator':
            case 'progressbar':
                return true;
        }
        if (this.#hasFocusableChild()) {
            return false;
        }
        if (this.#role === 'heading' && this.#name) {
            return true;
        }
        return false;
    }
    isControl() {
        switch (this.#role) {
            case 'button':
            case 'checkbox':
            case 'ColorWell':
            case 'combobox':
            case 'DisclosureTriangle':
            case 'listbox':
            case 'menu':
            case 'menubar':
            case 'menuitem':
            case 'menuitemcheckbox':
            case 'menuitemradio':
            case 'radio':
            case 'scrollbar':
            case 'searchbox':
            case 'slider':
            case 'spinbutton':
            case 'switch':
            case 'tab':
            case 'textbox':
            case 'tree':
            case 'treeitem':
                return true;
            default:
                return false;
        }
    }
    isLandmark() {
        switch (this.#role) {
            case 'banner':
            case 'complementary':
            case 'contentinfo':
            case 'form':
            case 'main':
            case 'navigation':
            case 'region':
            case 'search':
                return true;
            default:
                return false;
        }
    }
    isInteresting(insideControl) {
        const role = this.#role;
        if (role === 'Ignored' || this.#hidden || this.#ignored) {
            return false;
        }
        if (this.isLandmark()) {
            return true;
        }
        if (this.#focusable ||
            this.#richlyEditable ||
            this.#busy ||
            (this.#live && this.#live !== 'off') ||
            this.#modal ||
            this.#hasErrormessage ||
            this.#hasDetails ||
            this.#roledescription) {
            return true;
        }
        if (this.isControl()) {
            return true;
        }
        if (insideControl) {
            return false;
        }
        return this.isLeafNode() && (!!this.#name || !!this.#description);
    }
    serialize() {
        const properties = new Map();
        for (const property of this.payload.properties || []) {
            properties.set(property.name.toLowerCase(), property.value.value);
        }
        if (this.payload.name) {
            properties.set('name', this.payload.name.value);
        }
        if (this.payload.value) {
            properties.set('value', this.payload.value.value);
        }
        if (this.payload.description) {
            properties.set('description', this.payload.description.value);
        }
        const node = {
            role: this.#role,
            elementHandle: async () => {
                const env_2 = { stack: [], error: void 0, hasError: false };
                try {
                    if (!this.payload.backendDOMNodeId) {
                        return null;
                    }
                    const handle = __addDisposableResource$5(env_2, await this.#realm.adoptBackendNode(this.payload.backendDOMNodeId), false);
                    return (await handle.evaluateHandle(node => {
                        return node.nodeType === Node.TEXT_NODE ? node.parentElement : node;
                    }));
                }
                catch (e_2) {
                    env_2.error = e_2;
                    env_2.hasError = true;
                }
                finally {
                    __disposeResources$5(env_2);
                }
            },
            backendNodeId: this.payload.backendDOMNodeId,
            loaderId: this.#realm.environment._loaderId,
        };
        const userStringProperties = [
            'name',
            'value',
            'description',
            'keyshortcuts',
            'roledescription',
            'valuetext',
            'url',
        ];
        const getUserStringPropertyValue = (key) => {
            return properties.get(key);
        };
        for (const userStringProperty of userStringProperties) {
            if (!properties.has(userStringProperty)) {
                continue;
            }
            node[userStringProperty] = getUserStringPropertyValue(userStringProperty);
        }
        const booleanProperties = [
            'disabled',
            'expanded',
            'focused',
            'modal',
            'multiline',
            'multiselectable',
            'readonly',
            'required',
            'selected',
            'busy',
            'atomic',
        ];
        const getBooleanPropertyValue = (key) => {
            return !!properties.get(key);
        };
        for (const booleanProperty of booleanProperties) {
            if (booleanProperty === 'focused' && this.#role === 'RootWebArea') {
                continue;
            }
            if (!properties.has(booleanProperty)) {
                continue;
            }
            node[booleanProperty] = getBooleanPropertyValue(booleanProperty);
        }
        const tristateProperties = ['checked', 'pressed'];
        for (const tristateProperty of tristateProperties) {
            if (!properties.has(tristateProperty)) {
                continue;
            }
            const value = properties.get(tristateProperty);
            node[tristateProperty] =
                value === 'mixed' ? 'mixed' : value === 'true' ? true : false;
        }
        const numericalProperties = [
            'level',
            'valuemax',
            'valuemin',
        ];
        const getNumericalPropertyValue = (key) => {
            return properties.get(key);
        };
        for (const numericalProperty of numericalProperties) {
            if (!properties.has(numericalProperty)) {
                continue;
            }
            node[numericalProperty] = getNumericalPropertyValue(numericalProperty);
        }
        const tokenProperties = [
            'autocomplete',
            'haspopup',
            'invalid',
            'orientation',
            'live',
            'relevant',
            'errormessage',
            'details',
        ];
        const getTokenPropertyValue = (key) => {
            return properties.get(key);
        };
        for (const tokenProperty of tokenProperties) {
            const value = getTokenPropertyValue(tokenProperty);
            if (!value || value === 'false') {
                continue;
            }
            node[tokenProperty] = getTokenPropertyValue(tokenProperty);
        }
        return node;
    }
    static createTree(realm, payloads) {
        const nodeById = new Map();
        for (const payload of payloads) {
            nodeById.set(payload.nodeId, new AXNode(realm, payload));
        }
        for (const node of nodeById.values()) {
            for (const childId of node.payload.childIds || []) {
                const child = nodeById.get(childId);
                if (child) {
                    node.children.push(child);
                }
            }
        }
        return nodeById.values().next().value ?? null;
    }
}

var __addDisposableResource$4 = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$4 = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
let Binding$2 = class Binding {
    #name;
    #fn;
    #initSource;
    constructor(name, fn, initSource) {
        this.#name = name;
        this.#fn = fn;
        this.#initSource = initSource;
    }
    get name() {
        return this.#name;
    }
    get initSource() {
        return this.#initSource;
    }
    async run(context, id, args, isTrivial) {
        const stack = new DisposableStack();
        try {
            if (!isTrivial) {
                const env_1 = { stack: [], error: void 0, hasError: false };
                try {
                    const handles = __addDisposableResource$4(env_1, await context.evaluateHandle((name, seq) => {
                        return globalThis[name].args.get(seq);
                    }, this.#name, id), false);
                    const properties = await handles.getProperties();
                    for (const [index, handle] of properties) {
                        if (index in args) {
                            switch (handle.remoteObject().subtype) {
                                case 'node':
                                    args[+index] = handle;
                                    break;
                                default:
                                    stack.use(handle);
                            }
                        }
                        else {
                            stack.use(handle);
                        }
                    }
                }
                catch (e_1) {
                    env_1.error = e_1;
                    env_1.hasError = true;
                }
                finally {
                    __disposeResources$4(env_1);
                }
            }
            await context.evaluate((name, seq, result) => {
                const callbacks = globalThis[name].callbacks;
                callbacks.get(seq).resolve(result);
                callbacks.delete(seq);
            }, this.#name, id, await this.#fn(...args));
            for (const arg of args) {
                if (arg instanceof JSHandle) {
                    stack.use(arg);
                }
            }
        }
        catch (error) {
            if (isErrorLike$1(error)) {
                await context
                    .evaluate((name, seq, message, stack) => {
                    const error = new Error(message);
                    error.stack = stack;
                    const callbacks = globalThis[name].callbacks;
                    callbacks.get(seq).reject(error);
                    callbacks.delete(seq);
                }, this.#name, id, error.message, error.stack)
                    .catch(debugError);
            }
            else {
                await context
                    .evaluate((name, seq, error) => {
                    const callbacks = globalThis[name].callbacks;
                    callbacks.get(seq).reject(error);
                    callbacks.delete(seq);
                }, this.#name, id, error)
                    .catch(debugError);
            }
        }
    }
};

class CdpBluetoothEmulation {
    #connection;
    constructor(connection) {
        this.#connection = connection;
    }
    async emulateAdapter(state, leSupported = true) {
        await this.#connection.send('BluetoothEmulation.disable');
        await this.#connection.send('BluetoothEmulation.enable', {
            state,
            leSupported,
        });
    }
    async disableEmulation() {
        await this.#connection.send('BluetoothEmulation.disable');
    }
    async simulatePreconnectedPeripheral(preconnectedPeripheral) {
        await this.#connection.send('BluetoothEmulation.simulatePreconnectedPeripheral', preconnectedPeripheral);
    }
}

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
let ConsoleMessage$1 = class ConsoleMessage {
    #type;
    #text;
    #args;
    #stackTraceLocations;
    #frame;
    #rawStackTrace;
    #targetId;
    constructor(type, text, args, stackTraceLocations, frame, rawStackTrace, targetId) {
        this.#type = type;
        this.#text = text;
        this.#args = args;
        this.#stackTraceLocations = stackTraceLocations;
        this.#frame = frame;
        this.#rawStackTrace = rawStackTrace;
        this.#targetId = targetId;
    }
    type() {
        return this.#type;
    }
    text() {
        return this.#text;
    }
    args() {
        return this.#args;
    }
    location() {
        return (this.#stackTraceLocations[0] ??
            (this.#frame ? { url: this.#frame.url() } : {}));
    }
    stackTrace() {
        return this.#stackTraceLocations;
    }
    _rawStackTrace() {
        return this.#rawStackTrace;
    }
    _targetId() {
        return this.#targetId;
    }
};

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class FileChooser {
    #element;
    #multiple;
    #handled = false;
    constructor(element, multiple) {
        this.#element = element;
        this.#multiple = multiple;
    }
    isMultiple() {
        return this.#multiple;
    }
    async accept(paths) {
        assert(!this.#handled, 'Cannot accept FileChooser which is already handled!');
        this.#handled = true;
        await this.#element.uploadFile(...paths);
    }
    async cancel() {
        assert(!this.#handled, 'Cannot cancel FileChooser which is already handled!');
        this.#handled = true;
        await this.#element.evaluate(element => {
            element.dispatchEvent(new Event('cancel', { bubbles: true }));
        });
    }
}

/**
 * @license
 * Copyright 2022 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var NetworkManagerEvent;
(function (NetworkManagerEvent) {
    NetworkManagerEvent.Request = Symbol('NetworkManager.Request');
    NetworkManagerEvent.RequestServedFromCache = Symbol('NetworkManager.RequestServedFromCache');
    NetworkManagerEvent.Response = Symbol('NetworkManager.Response');
    NetworkManagerEvent.RequestFailed = Symbol('NetworkManager.RequestFailed');
    NetworkManagerEvent.RequestFinished = Symbol('NetworkManager.RequestFinished');
})(NetworkManagerEvent || (NetworkManagerEvent = {}));

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class CallbackRegistry {
    #callbacks = new Map();
    #idGenerator;
    constructor(idGenerator) {
        this.#idGenerator = idGenerator;
    }
    create(label, timeout, request) {
        const callback = new Callback(this.#idGenerator(), label, timeout);
        this.#callbacks.set(callback.id, callback);
        try {
            request(callback.id);
        }
        catch (error) {
            callback.promise.catch(debugError).finally(() => {
                this.#callbacks.delete(callback.id);
            });
            callback.reject(error);
            throw error;
        }
        return callback.promise.finally(() => {
            this.#callbacks.delete(callback.id);
        });
    }
    reject(id, message, originalMessage) {
        const callback = this.#callbacks.get(id);
        if (!callback) {
            return;
        }
        this._reject(callback, message, originalMessage);
    }
    rejectRaw(id, error) {
        const callback = this.#callbacks.get(id);
        if (!callback) {
            return;
        }
        callback.reject(error);
    }
    _reject(callback, errorMessage, originalMessage) {
        let error;
        let message;
        if (errorMessage instanceof ProtocolError) {
            error = errorMessage;
            error.cause = callback.error;
            message = errorMessage.message;
        }
        else {
            error = callback.error;
            message = errorMessage;
        }
        callback.reject(rewriteError$1(error, `Protocol error (${callback.label}): ${message}`, originalMessage));
    }
    resolve(id, value) {
        const callback = this.#callbacks.get(id);
        if (!callback) {
            return;
        }
        callback.resolve(value);
    }
    clear() {
        for (const callback of this.#callbacks.values()) {
            this._reject(callback, new TargetCloseError('Target closed'));
        }
        this.#callbacks.clear();
    }
    getPendingProtocolErrors() {
        const result = [];
        for (const callback of this.#callbacks.values()) {
            result.push(new Error(`${callback.label} timed out. Trace: ${callback.error.stack}`));
        }
        return result;
    }
}
class Callback {
    #id;
    #error = new ProtocolError();
    #deferred = Deferred.create();
    #timer;
    #label;
    constructor(id, label, timeout) {
        this.#id = id;
        this.#label = label;
        if (timeout) {
            this.#timer = setTimeout(() => {
                this.#deferred.reject(rewriteError$1(this.#error, `${label} timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.`));
            }, timeout);
        }
    }
    resolve(value) {
        clearTimeout(this.#timer);
        this.#deferred.resolve(value);
    }
    reject(error) {
        clearTimeout(this.#timer);
        this.#deferred.reject(error);
    }
    get id() {
        return this.#id;
    }
    get promise() {
        return this.#deferred.valueOrThrow();
    }
    get error() {
        return this.#error;
    }
    get label() {
        return this.#label;
    }
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class CdpCDPSession extends CDPSession {
    #sessionId;
    #targetType;
    #callbacks;
    #connection;
    #parentSessionId;
    #target;
    #rawErrors = false;
    #detached = false;
    constructor(connection, targetType, sessionId, parentSessionId, rawErrors) {
        super();
        this.#connection = connection;
        this.#targetType = targetType;
        this.#callbacks = new CallbackRegistry(connection._idGenerator);
        this.#sessionId = sessionId;
        this.#parentSessionId = parentSessionId;
        this.#rawErrors = rawErrors;
    }
    setTarget(target) {
        this.#target = target;
    }
    target() {
        assert(this.#target, 'Target must exist');
        return this.#target;
    }
    connection() {
        return this.#connection;
    }
    get detached() {
        return this.#connection._closed || this.#detached;
    }
    parentSession() {
        if (!this.#parentSessionId) {
            return this;
        }
        const parent = this.#connection?.session(this.#parentSessionId);
        return parent ?? undefined;
    }
    send(method, params, options) {
        if (this.detached) {
            return Promise.reject(new TargetCloseError(`Protocol error (${method}): Session closed. Most likely the ${this.#targetType} has been closed.`));
        }
        return this.#connection._rawSend(this.#callbacks, method, params, this.#sessionId, options);
    }
    onMessage(object) {
        if (object.id) {
            if (object.error) {
                if (this.#rawErrors) {
                    this.#callbacks.rejectRaw(object.id, object.error);
                }
                else {
                    this.#callbacks.reject(object.id, createProtocolErrorMessage(object), object.error.message);
                }
            }
            else {
                this.#callbacks.resolve(object.id, object.result);
            }
        }
        else {
            assert(!object.id);
            this.emit(object.method, object.params);
        }
    }
    async detach() {
        if (this.detached) {
            throw new Error(`Session already detached. Most likely the ${this.#targetType} has been closed.`);
        }
        await this.#connection.send('Target.detachFromTarget', {
            sessionId: this.#sessionId,
        });
        this.#detached = true;
    }
    onClosed() {
        this.#callbacks.clear();
        this.#detached = true;
        this.emit(CDPSessionEvent.Disconnected, undefined);
    }
    id() {
        return this.#sessionId;
    }
    getPendingProtocolErrors() {
        return this.#callbacks.getPendingProtocolErrors();
    }
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const debugProtocolSend = debug$1('puppeteer:protocol:SEND ►');
const debugProtocolReceive = debug$1('puppeteer:protocol:RECV ◀');
class Connection extends EventEmitter {
    #url;
    #transport;
    #delay;
    #timeout;
    #sessions = new Map();
    #closed = false;
    #manuallyAttached = new Set();
    #callbacks;
    #rawErrors = false;
    #idGenerator;
    constructor(url, transport, delay = 0, timeout, rawErrors = false, idGenerator = createIncrementalIdGenerator()) {
        super();
        this.#rawErrors = rawErrors;
        this.#idGenerator = idGenerator;
        this.#callbacks = new CallbackRegistry(idGenerator);
        this.#url = url;
        this.#delay = delay;
        this.#timeout = timeout ?? 180_000;
        this.#transport = transport;
        this.#transport.onmessage = this.onMessage.bind(this);
        this.#transport.onclose = this.#onClose.bind(this);
    }
    static fromSession(session) {
        return session.connection();
    }
    get delay() {
        return this.#delay;
    }
    get timeout() {
        return this.#timeout;
    }
    get _closed() {
        return this.#closed;
    }
    get _idGenerator() {
        return this.#idGenerator;
    }
    get _sessions() {
        return this.#sessions;
    }
    _session(sessionId) {
        return this.#sessions.get(sessionId) || null;
    }
    session(sessionId) {
        return this._session(sessionId);
    }
    url() {
        return this.#url;
    }
    send(method, params, options) {
        return this._rawSend(this.#callbacks, method, params, undefined, options);
    }
    _rawSend(callbacks, method, params, sessionId, options) {
        if (this.#closed) {
            return Promise.reject(new ConnectionClosedError('Connection closed.'));
        }
        return callbacks.create(method, options?.timeout ?? this.#timeout, id => {
            const stringifiedMessage = JSON.stringify({
                method,
                params,
                id,
                sessionId,
            });
            debugProtocolSend(stringifiedMessage);
            this.#transport.send(stringifiedMessage);
        });
    }
    async closeBrowser() {
        await this.send('Browser.close');
    }
    async onMessage(message) {
        if (this.#delay) {
            await new Promise(r => {
                return setTimeout(r, this.#delay);
            });
        }
        debugProtocolReceive(message);
        const object = JSON.parse(message);
        if (object.method === 'Target.attachedToTarget') {
            const sessionId = object.params.sessionId;
            const session = new CdpCDPSession(this, object.params.targetInfo.type, sessionId, object.sessionId, this.#rawErrors);
            this.#sessions.set(sessionId, session);
            this.emit(CDPSessionEvent.SessionAttached, session);
            const parentSession = this.#sessions.get(object.sessionId);
            if (parentSession) {
                parentSession.emit(CDPSessionEvent.SessionAttached, session);
            }
        }
        else if (object.method === 'Target.detachedFromTarget') {
            const session = this.#sessions.get(object.params.sessionId);
            if (session) {
                session.onClosed();
                this.#sessions.delete(object.params.sessionId);
                this.emit(CDPSessionEvent.SessionDetached, session);
                const parentSession = this.#sessions.get(object.sessionId);
                if (parentSession) {
                    parentSession.emit(CDPSessionEvent.SessionDetached, session);
                }
            }
        }
        if (object.sessionId) {
            const session = this.#sessions.get(object.sessionId);
            if (session) {
                session.onMessage(object);
            }
        }
        else if (object.id) {
            if (object.error) {
                if (this.#rawErrors) {
                    this.#callbacks.rejectRaw(object.id, object.error);
                }
                else {
                    this.#callbacks.reject(object.id, createProtocolErrorMessage(object), object.error.message);
                }
            }
            else {
                this.#callbacks.resolve(object.id, object.result);
            }
        }
        else {
            this.emit(object.method, object.params);
        }
    }
    #onClose() {
        if (this.#closed) {
            return;
        }
        this.#closed = true;
        this.#transport.onmessage = undefined;
        this.#transport.onclose = undefined;
        this.#callbacks.clear();
        for (const session of this.#sessions.values()) {
            session.onClosed();
        }
        this.#sessions.clear();
        this.emit(CDPSessionEvent.Disconnected, undefined);
    }
    dispose() {
        this.#onClose();
        this.#transport.close();
    }
    isAutoAttached(targetId) {
        return !this.#manuallyAttached.has(targetId);
    }
    async _createSession(targetInfo, isAutoAttachEmulated = true) {
        if (!isAutoAttachEmulated) {
            this.#manuallyAttached.add(targetInfo.targetId);
        }
        const { sessionId } = await this.send('Target.attachToTarget', {
            targetId: targetInfo.targetId,
            flatten: true,
        });
        this.#manuallyAttached.delete(targetInfo.targetId);
        const session = this.#sessions.get(sessionId);
        if (!session) {
            throw new Error('CDPSession creation failed.');
        }
        return session;
    }
    async createSession(targetInfo) {
        return await this._createSession(targetInfo, false);
    }
    getPendingProtocolErrors() {
        const result = [];
        result.push(...this.#callbacks.getPendingProtocolErrors());
        for (const session of this.#sessions.values()) {
            result.push(...session.getPendingProtocolErrors());
        }
        return result;
    }
}
function isTargetClosedError(error) {
    return error instanceof TargetCloseError;
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class Coverage {
    #jsCoverage;
    #cssCoverage;
    constructor(client) {
        this.#jsCoverage = new JSCoverage(client);
        this.#cssCoverage = new CSSCoverage(client);
    }
    updateClient(client) {
        this.#jsCoverage.updateClient(client);
        this.#cssCoverage.updateClient(client);
    }
    async startJSCoverage(options = {}) {
        return await this.#jsCoverage.start(options);
    }
    async stopJSCoverage() {
        return await this.#jsCoverage.stop();
    }
    async startCSSCoverage(options = {}) {
        return await this.#cssCoverage.start(options);
    }
    async stopCSSCoverage() {
        return await this.#cssCoverage.stop();
    }
}
class JSCoverage {
    #client;
    #enabled = false;
    #scriptURLs = new Map();
    #scriptSources = new Map();
    #subscriptions;
    #resetOnNavigation = false;
    #reportAnonymousScripts = false;
    #includeRawScriptCoverage = false;
    constructor(client) {
        this.#client = client;
    }
    updateClient(client) {
        this.#client = client;
    }
    async start(options = {}) {
        assert(!this.#enabled, 'JSCoverage is already enabled');
        const { resetOnNavigation = true, reportAnonymousScripts = false, includeRawScriptCoverage = false, useBlockCoverage = true, } = options;
        this.#resetOnNavigation = resetOnNavigation;
        this.#reportAnonymousScripts = reportAnonymousScripts;
        this.#includeRawScriptCoverage = includeRawScriptCoverage;
        this.#enabled = true;
        this.#scriptURLs.clear();
        this.#scriptSources.clear();
        this.#subscriptions = new DisposableStack();
        const clientEmitter = this.#subscriptions.use(new EventEmitter(this.#client));
        clientEmitter.on('Debugger.scriptParsed', this.#onScriptParsed.bind(this));
        clientEmitter.on('Runtime.executionContextsCleared', this.#onExecutionContextsCleared.bind(this));
        await Promise.all([
            this.#client.send('Profiler.enable'),
            this.#client.send('Profiler.startPreciseCoverage', {
                callCount: this.#includeRawScriptCoverage,
                detailed: useBlockCoverage,
            }),
            this.#client.send('Debugger.enable'),
            this.#client.send('Debugger.setSkipAllPauses', { skip: true }),
        ]);
    }
    #onExecutionContextsCleared() {
        if (!this.#resetOnNavigation) {
            return;
        }
        this.#scriptURLs.clear();
        this.#scriptSources.clear();
    }
    async #onScriptParsed(event) {
        if (PuppeteerURL.isPuppeteerURL(event.url)) {
            return;
        }
        if (!event.url && !this.#reportAnonymousScripts) {
            return;
        }
        try {
            const response = await this.#client.send('Debugger.getScriptSource', {
                scriptId: event.scriptId,
            });
            this.#scriptURLs.set(event.scriptId, event.url);
            this.#scriptSources.set(event.scriptId, response.scriptSource);
        }
        catch (error) {
            debugError(error);
        }
    }
    async stop() {
        assert(this.#enabled, 'JSCoverage is not enabled');
        this.#enabled = false;
        const result = await Promise.all([
            this.#client.send('Profiler.takePreciseCoverage'),
            this.#client.send('Profiler.stopPreciseCoverage'),
            this.#client.send('Profiler.disable'),
            this.#client.send('Debugger.disable'),
        ]);
        this.#subscriptions?.dispose();
        const coverage = [];
        const profileResponse = result[0];
        for (const entry of profileResponse.result) {
            let url = this.#scriptURLs.get(entry.scriptId);
            if (!url && this.#reportAnonymousScripts) {
                url = 'debugger://VM' + entry.scriptId;
            }
            const text = this.#scriptSources.get(entry.scriptId);
            if (text === undefined || url === undefined) {
                continue;
            }
            const flattenRanges = [];
            for (const func of entry.functions) {
                flattenRanges.push(...func.ranges);
            }
            const ranges = convertToDisjointRanges(flattenRanges);
            if (!this.#includeRawScriptCoverage) {
                coverage.push({ url, ranges, text });
            }
            else {
                coverage.push({ url, ranges, text, rawScriptCoverage: entry });
            }
        }
        return coverage;
    }
}
class CSSCoverage {
    #client;
    #enabled = false;
    #stylesheetURLs = new Map();
    #stylesheetSources = new Map();
    #eventListeners;
    #resetOnNavigation = false;
    constructor(client) {
        this.#client = client;
    }
    updateClient(client) {
        this.#client = client;
    }
    async start(options = {}) {
        assert(!this.#enabled, 'CSSCoverage is already enabled');
        const { resetOnNavigation = true } = options;
        this.#resetOnNavigation = resetOnNavigation;
        this.#enabled = true;
        this.#stylesheetURLs.clear();
        this.#stylesheetSources.clear();
        this.#eventListeners = new DisposableStack();
        const clientEmitter = this.#eventListeners.use(new EventEmitter(this.#client));
        clientEmitter.on('CSS.styleSheetAdded', this.#onStyleSheet.bind(this));
        clientEmitter.on('Runtime.executionContextsCleared', this.#onExecutionContextsCleared.bind(this));
        await Promise.all([
            this.#client.send('DOM.enable'),
            this.#client.send('CSS.enable'),
            this.#client.send('CSS.startRuleUsageTracking'),
        ]);
    }
    #onExecutionContextsCleared() {
        if (!this.#resetOnNavigation) {
            return;
        }
        this.#stylesheetURLs.clear();
        this.#stylesheetSources.clear();
    }
    async #onStyleSheet(event) {
        const header = event.header;
        if (!header.sourceURL) {
            return;
        }
        try {
            const response = await this.#client.send('CSS.getStyleSheetText', {
                styleSheetId: header.styleSheetId,
            });
            this.#stylesheetURLs.set(header.styleSheetId, header.sourceURL);
            this.#stylesheetSources.set(header.styleSheetId, response.text);
        }
        catch (error) {
            debugError(error);
        }
    }
    async stop() {
        assert(this.#enabled, 'CSSCoverage is not enabled');
        this.#enabled = false;
        const ruleTrackingResponse = await this.#client.send('CSS.stopRuleUsageTracking');
        await Promise.all([
            this.#client.send('CSS.disable'),
            this.#client.send('DOM.disable'),
        ]);
        this.#eventListeners?.dispose();
        const styleSheetIdToCoverage = new Map();
        for (const entry of ruleTrackingResponse.ruleUsage) {
            let ranges = styleSheetIdToCoverage.get(entry.styleSheetId);
            if (!ranges) {
                ranges = [];
                styleSheetIdToCoverage.set(entry.styleSheetId, ranges);
            }
            ranges.push({
                startOffset: entry.startOffset,
                endOffset: entry.endOffset,
                count: entry.used ? 1 : 0,
            });
        }
        const coverage = [];
        for (const styleSheetId of this.#stylesheetURLs.keys()) {
            const url = this.#stylesheetURLs.get(styleSheetId);
            assert(typeof url !== 'undefined', `Stylesheet URL is undefined (styleSheetId=${styleSheetId})`);
            const text = this.#stylesheetSources.get(styleSheetId);
            assert(typeof text !== 'undefined', `Stylesheet text is undefined (styleSheetId=${styleSheetId})`);
            const ranges = convertToDisjointRanges(styleSheetIdToCoverage.get(styleSheetId) || []);
            coverage.push({ url, ranges, text });
        }
        return coverage;
    }
}
function convertToDisjointRanges(nestedRanges) {
    const points = [];
    for (const range of nestedRanges) {
        points.push({ offset: range.startOffset, type: 0, range });
        points.push({ offset: range.endOffset, type: 1, range });
    }
    points.sort((a, b) => {
        if (a.offset !== b.offset) {
            return a.offset - b.offset;
        }
        if (a.type !== b.type) {
            return b.type - a.type;
        }
        const aLength = a.range.endOffset - a.range.startOffset;
        const bLength = b.range.endOffset - b.range.startOffset;
        if (a.type === 0) {
            return bLength - aLength;
        }
        return aLength - bLength;
    });
    const hitCountStack = [];
    const results = [];
    let lastOffset = 0;
    for (const point of points) {
        if (hitCountStack.length &&
            lastOffset < point.offset &&
            hitCountStack[hitCountStack.length - 1] > 0) {
            const lastResult = results[results.length - 1];
            if (lastResult && lastResult.end === lastOffset) {
                lastResult.end = point.offset;
            }
            else {
                results.push({ start: lastOffset, end: point.offset });
            }
        }
        lastOffset = point.offset;
        if (point.type === 0) {
            hitCountStack.push(point.range.count);
        }
        else {
            hitCountStack.pop();
        }
    }
    return results.filter(range => {
        return range.end - range.start > 0;
    });
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class CdpDialog extends Dialog {
    #client;
    constructor(client, type, message, defaultValue = '') {
        super(type, message, defaultValue);
        this.#client = client;
    }
    async handle(options) {
        await this.#client.send('Page.handleJavaScriptDialog', {
            accept: options.accept,
            promptText: options.text,
        });
    }
}

var __runInitializers$4 = (undefined && undefined.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
var __esDecorate$4 = (undefined && undefined.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __setFunctionName$2 = (undefined && undefined.__setFunctionName) || function (f, name, prefix) {
    if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
    return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
class EmulatedState {
    #state;
    #clientProvider;
    #updater;
    constructor(initialState, clientProvider, updater) {
        this.#state = initialState;
        this.#clientProvider = clientProvider;
        this.#updater = updater;
        this.#clientProvider.registerState(this);
    }
    async setState(state) {
        this.#state = state;
        await this.sync();
    }
    get state() {
        return this.#state;
    }
    async sync() {
        await Promise.all(this.#clientProvider.clients().map(client => {
            return this.#updater(client, this.#state);
        }));
    }
}
let EmulationManager = (() => {
    let _instanceExtraInitializers = [];
    let _private_applyViewport_decorators;
    let _private_applyViewport_descriptor;
    let _private_emulateIdleState_decorators;
    let _private_emulateIdleState_descriptor;
    let _private_emulateTimezone_decorators;
    let _private_emulateTimezone_descriptor;
    let _private_emulateVisionDeficiency_decorators;
    let _private_emulateVisionDeficiency_descriptor;
    let _private_emulateCpuThrottling_decorators;
    let _private_emulateCpuThrottling_descriptor;
    let _private_emulateMediaFeatures_decorators;
    let _private_emulateMediaFeatures_descriptor;
    let _private_emulateMediaType_decorators;
    let _private_emulateMediaType_descriptor;
    let _private_setGeolocation_decorators;
    let _private_setGeolocation_descriptor;
    let _private_setDefaultBackgroundColor_decorators;
    let _private_setDefaultBackgroundColor_descriptor;
    let _private_setJavaScriptEnabled_decorators;
    let _private_setJavaScriptEnabled_descriptor;
    let _private_emulateFocus_decorators;
    let _private_emulateFocus_descriptor;
    return class EmulationManager {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
            _private_applyViewport_decorators = [invokeAtMostOnceForArguments];
            _private_emulateIdleState_decorators = [invokeAtMostOnceForArguments];
            _private_emulateTimezone_decorators = [invokeAtMostOnceForArguments];
            _private_emulateVisionDeficiency_decorators = [invokeAtMostOnceForArguments];
            _private_emulateCpuThrottling_decorators = [invokeAtMostOnceForArguments];
            _private_emulateMediaFeatures_decorators = [invokeAtMostOnceForArguments];
            _private_emulateMediaType_decorators = [invokeAtMostOnceForArguments];
            _private_setGeolocation_decorators = [invokeAtMostOnceForArguments];
            _private_setDefaultBackgroundColor_decorators = [invokeAtMostOnceForArguments];
            _private_setJavaScriptEnabled_decorators = [invokeAtMostOnceForArguments];
            _private_emulateFocus_decorators = [invokeAtMostOnceForArguments];
            __esDecorate$4(this, _private_applyViewport_descriptor = { value: __setFunctionName$2(async function (client, viewportState) {
                    if (!viewportState.viewport) {
                        await Promise.all([
                            client.send('Emulation.clearDeviceMetricsOverride'),
                            client.send('Emulation.setTouchEmulationEnabled', {
                                enabled: false,
                            }),
                        ]).catch(debugError);
                        return;
                    }
                    const { viewport } = viewportState;
                    const mobile = viewport.isMobile || false;
                    const width = viewport.width;
                    const height = viewport.height;
                    const deviceScaleFactor = viewport.deviceScaleFactor ?? 1;
                    const screenOrientation = viewport.isLandscape
                        ? { angle: 90, type: 'landscapePrimary' }
                        : { angle: 0, type: 'portraitPrimary' };
                    const hasTouch = viewport.hasTouch || false;
                    await Promise.all([
                        client
                            .send('Emulation.setDeviceMetricsOverride', {
                            mobile,
                            width,
                            height,
                            deviceScaleFactor,
                            screenOrientation,
                        })
                            .catch(err => {
                            if (err.message.includes('Target does not support metrics override')) {
                                debugError(err);
                                return;
                            }
                            throw err;
                        }),
                        client.send('Emulation.setTouchEmulationEnabled', {
                            enabled: hasTouch,
                        }),
                    ]);
                }, "#applyViewport") }, _private_applyViewport_decorators, { kind: "method", name: "#applyViewport", static: false, private: true, access: { has: obj => #applyViewport in obj, get: obj => obj.#applyViewport }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$4(this, _private_emulateIdleState_descriptor = { value: __setFunctionName$2(async function (client, idleStateState) {
                    if (!idleStateState.active) {
                        return;
                    }
                    if (idleStateState.overrides) {
                        await client.send('Emulation.setIdleOverride', {
                            isUserActive: idleStateState.overrides.isUserActive,
                            isScreenUnlocked: idleStateState.overrides.isScreenUnlocked,
                        });
                    }
                    else {
                        await client.send('Emulation.clearIdleOverride');
                    }
                }, "#emulateIdleState") }, _private_emulateIdleState_decorators, { kind: "method", name: "#emulateIdleState", static: false, private: true, access: { has: obj => #emulateIdleState in obj, get: obj => obj.#emulateIdleState }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$4(this, _private_emulateTimezone_descriptor = { value: __setFunctionName$2(async function (client, timezoneState) {
                    if (!timezoneState.active) {
                        return;
                    }
                    try {
                        await client.send('Emulation.setTimezoneOverride', {
                            timezoneId: timezoneState.timezoneId || '',
                        });
                    }
                    catch (error) {
                        if (isErrorLike$1(error) && error.message.includes('Invalid timezone')) {
                            throw new Error(`Invalid timezone ID: ${timezoneState.timezoneId}`);
                        }
                        throw error;
                    }
                }, "#emulateTimezone") }, _private_emulateTimezone_decorators, { kind: "method", name: "#emulateTimezone", static: false, private: true, access: { has: obj => #emulateTimezone in obj, get: obj => obj.#emulateTimezone }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$4(this, _private_emulateVisionDeficiency_descriptor = { value: __setFunctionName$2(async function (client, visionDeficiency) {
                    if (!visionDeficiency.active) {
                        return;
                    }
                    await client.send('Emulation.setEmulatedVisionDeficiency', {
                        type: visionDeficiency.visionDeficiency || 'none',
                    });
                }, "#emulateVisionDeficiency") }, _private_emulateVisionDeficiency_decorators, { kind: "method", name: "#emulateVisionDeficiency", static: false, private: true, access: { has: obj => #emulateVisionDeficiency in obj, get: obj => obj.#emulateVisionDeficiency }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$4(this, _private_emulateCpuThrottling_descriptor = { value: __setFunctionName$2(async function (client, state) {
                    if (!state.active) {
                        return;
                    }
                    await client.send('Emulation.setCPUThrottlingRate', {
                        rate: state.factor ?? 1,
                    });
                }, "#emulateCpuThrottling") }, _private_emulateCpuThrottling_decorators, { kind: "method", name: "#emulateCpuThrottling", static: false, private: true, access: { has: obj => #emulateCpuThrottling in obj, get: obj => obj.#emulateCpuThrottling }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$4(this, _private_emulateMediaFeatures_descriptor = { value: __setFunctionName$2(async function (client, state) {
                    if (!state.active) {
                        return;
                    }
                    await client.send('Emulation.setEmulatedMedia', {
                        features: state.mediaFeatures,
                    });
                }, "#emulateMediaFeatures") }, _private_emulateMediaFeatures_decorators, { kind: "method", name: "#emulateMediaFeatures", static: false, private: true, access: { has: obj => #emulateMediaFeatures in obj, get: obj => obj.#emulateMediaFeatures }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$4(this, _private_emulateMediaType_descriptor = { value: __setFunctionName$2(async function (client, state) {
                    if (!state.active) {
                        return;
                    }
                    await client.send('Emulation.setEmulatedMedia', {
                        media: state.type || '',
                    });
                }, "#emulateMediaType") }, _private_emulateMediaType_decorators, { kind: "method", name: "#emulateMediaType", static: false, private: true, access: { has: obj => #emulateMediaType in obj, get: obj => obj.#emulateMediaType }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$4(this, _private_setGeolocation_descriptor = { value: __setFunctionName$2(async function (client, state) {
                    if (!state.active) {
                        return;
                    }
                    await client.send('Emulation.setGeolocationOverride', state.geoLocation
                        ? {
                            longitude: state.geoLocation.longitude,
                            latitude: state.geoLocation.latitude,
                            accuracy: state.geoLocation.accuracy,
                        }
                        : undefined);
                }, "#setGeolocation") }, _private_setGeolocation_decorators, { kind: "method", name: "#setGeolocation", static: false, private: true, access: { has: obj => #setGeolocation in obj, get: obj => obj.#setGeolocation }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$4(this, _private_setDefaultBackgroundColor_descriptor = { value: __setFunctionName$2(async function (client, state) {
                    if (!state.active) {
                        return;
                    }
                    await client.send('Emulation.setDefaultBackgroundColorOverride', {
                        color: state.color,
                    });
                }, "#setDefaultBackgroundColor") }, _private_setDefaultBackgroundColor_decorators, { kind: "method", name: "#setDefaultBackgroundColor", static: false, private: true, access: { has: obj => #setDefaultBackgroundColor in obj, get: obj => obj.#setDefaultBackgroundColor }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$4(this, _private_setJavaScriptEnabled_descriptor = { value: __setFunctionName$2(async function (client, state) {
                    if (!state.active) {
                        return;
                    }
                    await client.send('Emulation.setScriptExecutionDisabled', {
                        value: !state.javaScriptEnabled,
                    });
                }, "#setJavaScriptEnabled") }, _private_setJavaScriptEnabled_decorators, { kind: "method", name: "#setJavaScriptEnabled", static: false, private: true, access: { has: obj => #setJavaScriptEnabled in obj, get: obj => obj.#setJavaScriptEnabled }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$4(this, _private_emulateFocus_descriptor = { value: __setFunctionName$2(async function (client, state) {
                    if (!state.active) {
                        return;
                    }
                    await client.send('Emulation.setFocusEmulationEnabled', {
                        enabled: state.enabled,
                    });
                }, "#emulateFocus") }, _private_emulateFocus_decorators, { kind: "method", name: "#emulateFocus", static: false, private: true, access: { has: obj => #emulateFocus in obj, get: obj => obj.#emulateFocus }, metadata: _metadata }, null, _instanceExtraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #client = __runInitializers$4(this, _instanceExtraInitializers);
        #emulatingMobile = false;
        #hasTouch = false;
        #states = [];
        #viewportState = new EmulatedState({
            active: false,
        }, this, this.#applyViewport);
        #idleOverridesState = new EmulatedState({
            active: false,
        }, this, this.#emulateIdleState);
        #timezoneState = new EmulatedState({
            active: false,
        }, this, this.#emulateTimezone);
        #visionDeficiencyState = new EmulatedState({
            active: false,
        }, this, this.#emulateVisionDeficiency);
        #cpuThrottlingState = new EmulatedState({
            active: false,
        }, this, this.#emulateCpuThrottling);
        #mediaFeaturesState = new EmulatedState({
            active: false,
        }, this, this.#emulateMediaFeatures);
        #mediaTypeState = new EmulatedState({
            active: false,
        }, this, this.#emulateMediaType);
        #geoLocationState = new EmulatedState({
            active: false,
        }, this, this.#setGeolocation);
        #defaultBackgroundColorState = new EmulatedState({
            active: false,
        }, this, this.#setDefaultBackgroundColor);
        #javascriptEnabledState = new EmulatedState({
            javaScriptEnabled: true,
            active: false,
        }, this, this.#setJavaScriptEnabled);
        #focusState = new EmulatedState({
            enabled: true,
            active: false,
        }, this, this.#emulateFocus);
        #secondaryClients = new Set();
        constructor(client) {
            this.#client = client;
        }
        updateClient(client) {
            this.#client = client;
            this.#secondaryClients.delete(client);
        }
        registerState(state) {
            this.#states.push(state);
        }
        clients() {
            return [this.#client, ...Array.from(this.#secondaryClients)];
        }
        async registerSpeculativeSession(client) {
            this.#secondaryClients.add(client);
            client.once(CDPSessionEvent.Disconnected, () => {
                this.#secondaryClients.delete(client);
            });
            void Promise.all(this.#states.map(s => {
                return s.sync().catch(debugError);
            }));
        }
        get javascriptEnabled() {
            return this.#javascriptEnabledState.state.javaScriptEnabled;
        }
        async emulateViewport(viewport) {
            const currentState = this.#viewportState.state;
            if (!viewport && !currentState.active) {
                return false;
            }
            await this.#viewportState.setState(viewport
                ? {
                    viewport,
                    active: true,
                }
                : {
                    active: false,
                });
            const mobile = viewport?.isMobile || false;
            const hasTouch = viewport?.hasTouch || false;
            const reloadNeeded = this.#emulatingMobile !== mobile || this.#hasTouch !== hasTouch;
            this.#emulatingMobile = mobile;
            this.#hasTouch = hasTouch;
            return reloadNeeded;
        }
        get #applyViewport() { return _private_applyViewport_descriptor.value; }
        async emulateIdleState(overrides) {
            await this.#idleOverridesState.setState({
                active: true,
                overrides,
            });
        }
        get #emulateIdleState() { return _private_emulateIdleState_descriptor.value; }
        get #emulateTimezone() { return _private_emulateTimezone_descriptor.value; }
        async emulateTimezone(timezoneId) {
            await this.#timezoneState.setState({
                timezoneId,
                active: true,
            });
        }
        get #emulateVisionDeficiency() { return _private_emulateVisionDeficiency_descriptor.value; }
        async emulateVisionDeficiency(type) {
            const visionDeficiencies = new Set([
                'none',
                'achromatopsia',
                'blurredVision',
                'deuteranopia',
                'protanopia',
                'reducedContrast',
                'tritanopia',
            ]);
            assert(!type || visionDeficiencies.has(type), `Unsupported vision deficiency: ${type}`);
            await this.#visionDeficiencyState.setState({
                active: true,
                visionDeficiency: type,
            });
        }
        get #emulateCpuThrottling() { return _private_emulateCpuThrottling_descriptor.value; }
        async emulateCPUThrottling(factor) {
            assert(factor === null || factor >= 1, 'Throttling rate should be greater or equal to 1');
            await this.#cpuThrottlingState.setState({
                active: true,
                factor: factor ?? undefined,
            });
        }
        get #emulateMediaFeatures() { return _private_emulateMediaFeatures_descriptor.value; }
        async emulateMediaFeatures(features) {
            if (Array.isArray(features)) {
                for (const mediaFeature of features) {
                    const name = mediaFeature.name;
                    assert(/^(?:prefers-(?:color-scheme|reduced-motion)|color-gamut)$/.test(name), 'Unsupported media feature: ' + name);
                }
            }
            await this.#mediaFeaturesState.setState({
                active: true,
                mediaFeatures: features,
            });
        }
        get #emulateMediaType() { return _private_emulateMediaType_descriptor.value; }
        async emulateMediaType(type) {
            assert(type === 'screen' ||
                type === 'print' ||
                (type ?? undefined) === undefined, 'Unsupported media type: ' + type);
            await this.#mediaTypeState.setState({
                type,
                active: true,
            });
        }
        get #setGeolocation() { return _private_setGeolocation_descriptor.value; }
        async setGeolocation(options) {
            const { longitude, latitude, accuracy = 0 } = options;
            if (longitude < -180 || longitude > 180) {
                throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`);
            }
            if (latitude < -90 || latitude > 90) {
                throw new Error(`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`);
            }
            if (accuracy < 0) {
                throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`);
            }
            await this.#geoLocationState.setState({
                active: true,
                geoLocation: {
                    longitude,
                    latitude,
                    accuracy,
                },
            });
        }
        get #setDefaultBackgroundColor() { return _private_setDefaultBackgroundColor_descriptor.value; }
        async resetDefaultBackgroundColor() {
            await this.#defaultBackgroundColorState.setState({
                active: true,
                color: undefined,
            });
        }
        async setTransparentBackgroundColor() {
            await this.#defaultBackgroundColorState.setState({
                active: true,
                color: { r: 0, g: 0, b: 0, a: 0 },
            });
        }
        get #setJavaScriptEnabled() { return _private_setJavaScriptEnabled_descriptor.value; }
        async setJavaScriptEnabled(enabled) {
            await this.#javascriptEnabledState.setState({
                active: true,
                javaScriptEnabled: enabled,
            });
        }
        get #emulateFocus() { return _private_emulateFocus_descriptor.value; }
        async emulateFocus(enabled) {
            await this.#focusState.setState({
                active: true,
                enabled,
            });
        }
    };
})();

/**
 * @license
 * Copyright 2024 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class CdpPreloadScript {
    #id;
    #source;
    #frameToId = new WeakMap();
    constructor(mainFrame, id, source) {
        this.#id = id;
        this.#source = source;
        this.#frameToId.set(mainFrame, id);
    }
    get id() {
        return this.#id;
    }
    get source() {
        return this.#source;
    }
    getIdForFrame(frame) {
        return this.#frameToId.get(frame);
    }
    setIdForFrame(frame, identifier) {
        this.#frameToId.set(frame, identifier);
    }
}

/**
 * @license
 * Copyright 2022 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class CdpDeviceRequestPrompt extends DeviceRequestPrompt {
    #client;
    #timeoutSettings;
    #id;
    #handled = false;
    #updateDevicesHandle = this.#updateDevices.bind(this);
    #waitForDevicePromises = new Set();
    constructor(client, timeoutSettings, firstEvent) {
        super();
        this.#client = client;
        this.#timeoutSettings = timeoutSettings;
        this.#id = firstEvent.id;
        this.#client.on('DeviceAccess.deviceRequestPrompted', this.#updateDevicesHandle);
        this.#client.on('Target.detachedFromTarget', () => {
            this.#client = null;
        });
        this.#updateDevices(firstEvent);
    }
    #updateDevices(event) {
        if (event.id !== this.#id) {
            return;
        }
        for (const rawDevice of event.devices) {
            if (this.devices.some(device => {
                return device.id === rawDevice.id;
            })) {
                continue;
            }
            const newDevice = { id: rawDevice.id, name: rawDevice.name };
            this.devices.push(newDevice);
            for (const waitForDevicePromise of this.#waitForDevicePromises) {
                if (waitForDevicePromise.filter(newDevice)) {
                    waitForDevicePromise.promise.resolve(newDevice);
                }
            }
        }
    }
    async waitForDevice(filter, options = {}) {
        for (const device of this.devices) {
            if (filter(device)) {
                return device;
            }
        }
        const { timeout = this.#timeoutSettings.timeout() } = options;
        const deferred = Deferred.create({
            message: `Waiting for \`DeviceRequestPromptDevice\` failed: ${timeout}ms exceeded`,
            timeout,
        });
        if (options.signal) {
            options.signal.addEventListener('abort', () => {
                deferred.reject(options.signal?.reason);
            }, { once: true });
        }
        const handle = { filter, promise: deferred };
        this.#waitForDevicePromises.add(handle);
        try {
            return await deferred.valueOrThrow();
        }
        finally {
            this.#waitForDevicePromises.delete(handle);
        }
    }
    async select(device) {
        assert(this.#client !== null, 'Cannot select device through detached session!');
        assert(this.devices.includes(device), 'Cannot select unknown device!');
        assert(!this.#handled, 'Cannot select DeviceRequestPrompt which is already handled!');
        this.#client.off('DeviceAccess.deviceRequestPrompted', this.#updateDevicesHandle);
        this.#handled = true;
        return await this.#client.send('DeviceAccess.selectPrompt', {
            id: this.#id,
            deviceId: device.id,
        });
    }
    async cancel() {
        assert(this.#client !== null, 'Cannot cancel prompt through detached session!');
        assert(!this.#handled, 'Cannot cancel DeviceRequestPrompt which is already handled!');
        this.#client.off('DeviceAccess.deviceRequestPrompted', this.#updateDevicesHandle);
        this.#handled = true;
        return await this.#client.send('DeviceAccess.cancelPrompt', { id: this.#id });
    }
}
class CdpDeviceRequestPromptManager {
    #client;
    #timeoutSettings;
    #deviceRequestPromptDeferreds = new Set();
    constructor(client, timeoutSettings) {
        this.#client = client;
        this.#timeoutSettings = timeoutSettings;
        this.#client.on('DeviceAccess.deviceRequestPrompted', event => {
            this.#onDeviceRequestPrompted(event);
        });
        this.#client.on('Target.detachedFromTarget', () => {
            this.#client = null;
        });
    }
    async waitForDevicePrompt(options = {}) {
        assert(this.#client !== null, 'Cannot wait for device prompt through detached session!');
        const needsEnable = this.#deviceRequestPromptDeferreds.size === 0;
        let enablePromise;
        if (needsEnable) {
            enablePromise = this.#client.send('DeviceAccess.enable');
        }
        const { timeout = this.#timeoutSettings.timeout() } = options;
        const deferred = Deferred.create({
            message: `Waiting for \`DeviceRequestPrompt\` failed: ${timeout}ms exceeded`,
            timeout,
        });
        if (options.signal) {
            options.signal.addEventListener('abort', () => {
                deferred.reject(options.signal?.reason);
            }, { once: true });
        }
        this.#deviceRequestPromptDeferreds.add(deferred);
        try {
            const [result] = await Promise.all([
                deferred.valueOrThrow(),
                enablePromise,
            ]);
            return result;
        }
        finally {
            this.#deviceRequestPromptDeferreds.delete(deferred);
        }
    }
    #onDeviceRequestPrompted(event) {
        if (!this.#deviceRequestPromptDeferreds.size) {
            return;
        }
        assert(this.#client !== null);
        const devicePrompt = new CdpDeviceRequestPrompt(this.#client, this.#timeoutSettings, event);
        for (const promise of this.#deviceRequestPromptDeferreds) {
            promise.resolve(devicePrompt);
        }
        this.#deviceRequestPromptDeferreds.clear();
    }
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function createEvaluationError(details) {
    let name;
    let message;
    if (!details.exception) {
        name = 'Error';
        message = details.text;
    }
    else if ((details.exception.type !== 'object' ||
        details.exception.subtype !== 'error') &&
        !details.exception.objectId) {
        return valueFromPrimitiveRemoteObject(details.exception);
    }
    else {
        const detail = getErrorDetails(details);
        name = detail.name;
        message = detail.message;
    }
    const messageHeight = message.split('\n').length;
    const error = new Error(message);
    error.name = name;
    const stackLines = error.stack.split('\n');
    const messageLines = stackLines.splice(0, messageHeight);
    stackLines.shift();
    if (details.stackTrace && stackLines.length < Error.stackTraceLimit) {
        for (const frame of details.stackTrace.callFrames.reverse()) {
            if (PuppeteerURL.isPuppeteerURL(frame.url) &&
                frame.url !== PuppeteerURL.INTERNAL_URL) {
                const url = PuppeteerURL.parse(frame.url);
                stackLines.unshift(`    at ${frame.functionName || url.functionName} (${url.functionName} at ${url.siteString}, <anonymous>:${frame.lineNumber}:${frame.columnNumber})`);
            }
            else {
                stackLines.push(`    at ${frame.functionName || '<anonymous>'} (${frame.url}:${frame.lineNumber}:${frame.columnNumber})`);
            }
            if (stackLines.length >= Error.stackTraceLimit) {
                break;
            }
        }
    }
    error.stack = [...messageLines, ...stackLines].join('\n');
    return error;
}
const getErrorDetails = (details) => {
    let name = '';
    let message;
    const lines = details.exception?.description?.split('\n    at ') ?? [];
    const size = Math.min(details.stackTrace?.callFrames.length ?? 0, lines.length - 1);
    lines.splice(-size, size);
    if (details.exception?.className) {
        name = details.exception.className;
    }
    message = lines.join('\n');
    if (name && message.startsWith(`${name}: `)) {
        message = message.slice(name.length + 2);
    }
    return { message, name };
};
function createClientError(details) {
    let name;
    let message;
    if (!details.exception) {
        name = 'Error';
        message = details.text;
    }
    else if ((details.exception.type !== 'object' ||
        details.exception.subtype !== 'error') &&
        !details.exception.objectId) {
        return valueFromPrimitiveRemoteObject(details.exception);
    }
    else {
        const detail = getErrorDetails(details);
        name = detail.name;
        message = detail.message;
    }
    const error = new Error(message);
    error.name = name;
    const messageHeight = error.message.split('\n').length;
    const messageLines = error.stack.split('\n').splice(0, messageHeight);
    const stackLines = [];
    if (details.stackTrace) {
        for (const frame of details.stackTrace.callFrames) {
            stackLines.push(`    at ${frame.functionName || '<anonymous>'} (${frame.url}:${frame.lineNumber + 1}:${frame.columnNumber + 1})`);
            if (stackLines.length >= Error.stackTraceLimit) {
                break;
            }
        }
    }
    error.stack = [...messageLines, ...stackLines].join('\n');
    return error;
}
function valueFromJSHandle(handle) {
    const remoteObject = handle.remoteObject();
    if (remoteObject.objectId) {
        return valueFromRemoteObjectReference(handle);
    }
    else {
        return valueFromPrimitiveRemoteObject(remoteObject);
    }
}
function valueFromRemoteObjectReference(handle) {
    const remoteObject = handle.remoteObject();
    assert(remoteObject.objectId, 'Cannot extract value when no objectId is given');
    const description = remoteObject.description ?? '';
    if (remoteObject.subtype === 'error' && description) {
        const newlineIdx = description.indexOf('\n');
        if (newlineIdx === -1) {
            return description;
        }
        return description.slice(0, newlineIdx);
    }
    return `[${remoteObject.subtype || remoteObject.type} ${remoteObject.className}]`;
}
function valueFromPrimitiveRemoteObject(remoteObject) {
    assert(!remoteObject.objectId, 'Cannot extract value when objectId is given');
    if (remoteObject.unserializableValue) {
        if (remoteObject.type === 'bigint') {
            return BigInt(remoteObject.unserializableValue.replace('n', ''));
        }
        switch (remoteObject.unserializableValue) {
            case '-0':
                return -0;
            case 'NaN':
                return NaN;
            case 'Infinity':
                return Infinity;
            case '-Infinity':
                return -Infinity;
            default:
                throw new Error('Unsupported unserializable value: ' +
                    remoteObject.unserializableValue);
        }
    }
    return remoteObject.value;
}
function addPageBinding(type, name, prefix) {
    if (globalThis[name]) {
        return;
    }
    Object.assign(globalThis, {
        [name](...args) {
            const callPuppeteer = globalThis[name];
            callPuppeteer.args ??= new Map();
            callPuppeteer.callbacks ??= new Map();
            const seq = (callPuppeteer.lastSeq ?? 0) + 1;
            callPuppeteer.lastSeq = seq;
            callPuppeteer.args.set(seq, args);
            globalThis[prefix + name](JSON.stringify({
                type,
                name,
                seq,
                args,
                isTrivial: !args.some(value => {
                    return value instanceof Node;
                }),
            }));
            return new Promise((resolve, reject) => {
                callPuppeteer.callbacks.set(seq, {
                    resolve(value) {
                        callPuppeteer.args.delete(seq);
                        resolve(value);
                    },
                    reject(value) {
                        callPuppeteer.args.delete(seq);
                        reject(value);
                    },
                });
            });
        },
    });
}
const CDP_BINDING_PREFIX = 'puppeteer_';
function pageBindingInitString(type, name) {
    return evaluationString(addPageBinding, type, name, CDP_BINDING_PREFIX);
}

/**
 * @license
 * Copyright 2019 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class CdpJSHandle extends JSHandle {
    #disposed = false;
    #remoteObject;
    #world;
    constructor(world, remoteObject) {
        super();
        this.#world = world;
        this.#remoteObject = remoteObject;
    }
    get disposed() {
        return this.#disposed;
    }
    get realm() {
        return this.#world;
    }
    get client() {
        return this.realm.environment.client;
    }
    async jsonValue() {
        if (!this.#remoteObject.objectId) {
            return valueFromPrimitiveRemoteObject(this.#remoteObject);
        }
        const value = await this.evaluate(object => {
            return object;
        });
        if (value === undefined) {
            throw new Error('Could not serialize referenced object');
        }
        return value;
    }
    asElement() {
        return null;
    }
    async dispose() {
        if (this.#disposed) {
            return;
        }
        this.#disposed = true;
        await releaseObject(this.client, this.#remoteObject);
    }
    toString() {
        if (!this.#remoteObject.objectId) {
            return 'JSHandle:' + valueFromPrimitiveRemoteObject(this.#remoteObject);
        }
        const type = this.#remoteObject.subtype || this.#remoteObject.type;
        return 'JSHandle@' + type;
    }
    get id() {
        return this.#remoteObject.objectId;
    }
    remoteObject() {
        return this.#remoteObject;
    }
    async getProperties() {
        const response = await this.client.send('Runtime.getProperties', {
            objectId: this.#remoteObject.objectId,
            ownProperties: true,
        });
        const result = new Map();
        for (const property of response.result) {
            if (!property.enumerable || !property.value) {
                continue;
            }
            result.set(property.name, this.#world.createCdpHandle(property.value));
        }
        return result;
    }
}
async function releaseObject(client, remoteObject) {
    if (!remoteObject.objectId) {
        return;
    }
    await client
        .send('Runtime.releaseObject', { objectId: remoteObject.objectId })
        .catch(error => {
        debugError(error);
    });
}

/**
 * @license
 * Copyright 2019 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __runInitializers$3 = (undefined && undefined.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
var __esDecorate$3 = (undefined && undefined.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
const NON_ELEMENT_NODE_ROLES = new Set(['StaticText', 'InlineTextBox']);
let CdpElementHandle = (() => {
    let _classSuper = ElementHandle;
    let _instanceExtraInitializers = [];
    let _contentFrame_decorators;
    let _scrollIntoView_decorators;
    let _uploadFile_decorators;
    let _autofill_decorators;
    return class CdpElementHandle extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _contentFrame_decorators = [throwIfDisposed()];
            _scrollIntoView_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _uploadFile_decorators = [throwIfDisposed(), bindIsolatedHandle];
            _autofill_decorators = [throwIfDisposed()];
            __esDecorate$3(this, null, _contentFrame_decorators, { kind: "method", name: "contentFrame", static: false, private: false, access: { has: obj => "contentFrame" in obj, get: obj => obj.contentFrame }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$3(this, null, _scrollIntoView_decorators, { kind: "method", name: "scrollIntoView", static: false, private: false, access: { has: obj => "scrollIntoView" in obj, get: obj => obj.scrollIntoView }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$3(this, null, _uploadFile_decorators, { kind: "method", name: "uploadFile", static: false, private: false, access: { has: obj => "uploadFile" in obj, get: obj => obj.uploadFile }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$3(this, null, _autofill_decorators, { kind: "method", name: "autofill", static: false, private: false, access: { has: obj => "autofill" in obj, get: obj => obj.autofill }, metadata: _metadata }, null, _instanceExtraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #backendNodeId = __runInitializers$3(this, _instanceExtraInitializers);
        constructor(world, remoteObject) {
            super(new CdpJSHandle(world, remoteObject));
        }
        get realm() {
            return this.handle.realm;
        }
        get client() {
            return this.handle.client;
        }
        remoteObject() {
            return this.handle.remoteObject();
        }
        get #frameManager() {
            return this.frame._frameManager;
        }
        get frame() {
            return this.realm.environment;
        }
        async contentFrame() {
            const nodeInfo = await this.client.send('DOM.describeNode', {
                objectId: this.id,
            });
            if (typeof nodeInfo.node.frameId !== 'string') {
                return null;
            }
            return this.#frameManager.frame(nodeInfo.node.frameId);
        }
        async scrollIntoView() {
            await this.assertConnectedElement();
            try {
                await this.client.send('DOM.scrollIntoViewIfNeeded', {
                    objectId: this.id,
                });
            }
            catch (error) {
                debugError(error);
                await super.scrollIntoView();
            }
        }
        async uploadFile(...files) {
            const isMultiple = await this.evaluate(element => {
                return element.multiple;
            });
            assert(files.length <= 1 || isMultiple, 'Multiple file uploads only work with <input type=file multiple>');
            const path = environment.value.path;
            if (path) {
                files = files.map(filePath => {
                    if (path.win32.isAbsolute(filePath) ||
                        path.posix.isAbsolute(filePath)) {
                        return filePath;
                    }
                    else {
                        return path.resolve(filePath);
                    }
                });
            }
            if (files.length === 0) {
                await this.evaluate(element => {
                    element.files = new DataTransfer().files;
                    element.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
                    element.dispatchEvent(new Event('change', { bubbles: true }));
                });
                return;
            }
            const { node: { backendNodeId }, } = await this.client.send('DOM.describeNode', {
                objectId: this.id,
            });
            await this.client.send('DOM.setFileInputFiles', {
                objectId: this.id,
                files,
                backendNodeId,
            });
        }
        async autofill(data) {
            const nodeInfo = await this.client.send('DOM.describeNode', {
                objectId: this.handle.id,
            });
            const fieldId = nodeInfo.node.backendNodeId;
            const frameId = this.frame._id;
            await this.client.send('Autofill.trigger', {
                fieldId,
                frameId,
                card: data.creditCard,
            });
        }
        async *queryAXTree(name, role) {
            const { nodes } = await this.client.send('Accessibility.queryAXTree', {
                objectId: this.id,
                accessibleName: name,
                role,
            });
            const results = nodes.filter(node => {
                if (node.ignored) {
                    return false;
                }
                if (!node.role) {
                    return false;
                }
                if (NON_ELEMENT_NODE_ROLES.has(node.role.value)) {
                    return false;
                }
                return true;
            });
            return yield* AsyncIterableUtil.map(results, node => {
                return this.realm.adoptBackendNode(node.backendDOMNodeId);
            });
        }
        async backendNodeId() {
            if (this.#backendNodeId) {
                return this.#backendNodeId;
            }
            const { node } = await this.client.send('DOM.describeNode', {
                objectId: this.handle.id,
            });
            this.#backendNodeId = node.backendNodeId;
            return this.#backendNodeId;
        }
    };
})();

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __addDisposableResource$3 = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$3 = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
const ariaQuerySelectorBinding = new Binding$2('__ariaQuerySelector', ARIAQueryHandler.queryOne, '');
const ariaQuerySelectorAllBinding = new Binding$2('__ariaQuerySelectorAll', (async (element, selector) => {
    const results = ARIAQueryHandler.queryAll(element, selector);
    return await element.realm.evaluateHandle((...elements) => {
        return elements;
    }, ...(await AsyncIterableUtil.collect(results)));
}), '');
let ExecutionContext$1 = class ExecutionContext extends EventEmitter {
    #client;
    #world;
    #id;
    #name;
    #disposables = new DisposableStack();
    constructor(client, contextPayload, world) {
        super();
        this.#client = client;
        this.#world = world;
        this.#id = contextPayload.id;
        if (contextPayload.name) {
            this.#name = contextPayload.name;
        }
        const clientEmitter = this.#disposables.use(new EventEmitter(this.#client));
        clientEmitter.on('Runtime.bindingCalled', this.#onBindingCalled.bind(this));
        clientEmitter.on('Runtime.executionContextDestroyed', async (event) => {
            if (event.executionContextId === this.#id) {
                this[disposeSymbol]();
            }
        });
        clientEmitter.on('Runtime.executionContextsCleared', async () => {
            this[disposeSymbol]();
        });
        clientEmitter.on('Runtime.consoleAPICalled', this.#onConsoleAPI.bind(this));
        clientEmitter.on(CDPSessionEvent.Disconnected, () => {
            this[disposeSymbol]();
        });
    }
    #bindings = new Map();
    #mutex = new Mutex$2();
    async #addBinding(binding) {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
            if (this.#bindings.has(binding.name)) {
                return;
            }
            const _ = __addDisposableResource$3(env_1, await this.#mutex.acquire(), false);
            try {
                await this.#client.send('Runtime.addBinding', this.#name
                    ? {
                        name: CDP_BINDING_PREFIX + binding.name,
                        executionContextName: this.#name,
                    }
                    : {
                        name: CDP_BINDING_PREFIX + binding.name,
                        executionContextId: this.#id,
                    });
                await this.evaluate(addPageBinding, 'internal', binding.name, CDP_BINDING_PREFIX);
                this.#bindings.set(binding.name, binding);
            }
            catch (error) {
                if (error instanceof Error) {
                    if (error.message.includes('Execution context was destroyed')) {
                        return;
                    }
                    if (error.message.includes('Cannot find context with specified id')) {
                        return;
                    }
                }
                debugError(error);
            }
        }
        catch (e_1) {
            env_1.error = e_1;
            env_1.hasError = true;
        }
        finally {
            __disposeResources$3(env_1);
        }
    }
    async #onBindingCalled(event) {
        if (event.executionContextId !== this.#id) {
            return;
        }
        let payload;
        try {
            payload = JSON.parse(event.payload);
        }
        catch {
            return;
        }
        const { type, name, seq, args, isTrivial } = payload;
        if (type !== 'internal') {
            this.emit('bindingcalled', event);
            return;
        }
        if (!this.#bindings.has(name)) {
            this.emit('bindingcalled', event);
            return;
        }
        try {
            const binding = this.#bindings.get(name);
            await binding?.run(this, seq, args, isTrivial);
        }
        catch (err) {
            debugError(err);
        }
    }
    get id() {
        return this.#id;
    }
    #onConsoleAPI(event) {
        if (event.executionContextId !== this.#id) {
            return;
        }
        this.emit('consoleapicalled', event);
    }
    #bindingsInstalled = false;
    #puppeteerUtil;
    get puppeteerUtil() {
        let promise = Promise.resolve();
        if (!this.#bindingsInstalled) {
            promise = Promise.all([
                this.#addBindingWithoutThrowing(ariaQuerySelectorBinding),
                this.#addBindingWithoutThrowing(ariaQuerySelectorAllBinding),
            ]);
            this.#bindingsInstalled = true;
        }
        scriptInjector.inject(script => {
            if (this.#puppeteerUtil) {
                void this.#puppeteerUtil.then(handle => {
                    void handle.dispose();
                });
            }
            this.#puppeteerUtil = promise.then(() => {
                return this.evaluateHandle(script);
            });
        }, !this.#puppeteerUtil);
        return this.#puppeteerUtil;
    }
    async #addBindingWithoutThrowing(binding) {
        try {
            await this.#addBinding(binding);
        }
        catch (err) {
            debugError(err);
        }
    }
    async evaluate(pageFunction, ...args) {
        return await this.#evaluate(true, pageFunction, ...args);
    }
    async evaluateHandle(pageFunction, ...args) {
        return await this.#evaluate(false, pageFunction, ...args);
    }
    async #evaluate(returnByValue, pageFunction, ...args) {
        const sourceUrlComment = getSourceUrlComment(getSourcePuppeteerURLIfAvailable(pageFunction)?.toString() ??
            PuppeteerURL.INTERNAL_URL);
        if (isString(pageFunction)) {
            const contextId = this.#id;
            const expression = pageFunction;
            const expressionWithSourceUrl = SOURCE_URL_REGEX.test(expression)
                ? expression
                : `${expression}\n${sourceUrlComment}\n`;
            const { exceptionDetails, result: remoteObject } = await this.#client
                .send('Runtime.evaluate', {
                expression: expressionWithSourceUrl,
                contextId,
                returnByValue,
                awaitPromise: true,
                userGesture: true,
            })
                .catch(rewriteError);
            if (exceptionDetails) {
                throw createEvaluationError(exceptionDetails);
            }
            if (returnByValue) {
                return valueFromPrimitiveRemoteObject(remoteObject);
            }
            return this.#world.createCdpHandle(remoteObject);
        }
        const functionDeclaration = stringifyFunction(pageFunction);
        const functionDeclarationWithSourceUrl = SOURCE_URL_REGEX.test(functionDeclaration)
            ? functionDeclaration
            : `${functionDeclaration}\n${sourceUrlComment}\n`;
        let callFunctionOnPromise;
        try {
            callFunctionOnPromise = this.#client.send('Runtime.callFunctionOn', {
                functionDeclaration: functionDeclarationWithSourceUrl,
                executionContextId: this.#id,
                arguments: args.some(arg => {
                    return arg instanceof LazyArg;
                })
                    ? await Promise.all(args.map(arg => {
                        return convertArgumentAsync(this, arg);
                    }))
                    : args.map(arg => {
                        return convertArgument(this, arg);
                    }),
                returnByValue,
                awaitPromise: true,
                userGesture: true,
            });
        }
        catch (error) {
            if (error instanceof TypeError &&
                error.message.startsWith('Converting circular structure to JSON')) {
                error.message += ' Recursive objects are not allowed.';
            }
            throw error;
        }
        const { exceptionDetails, result: remoteObject } = await callFunctionOnPromise.catch(rewriteError);
        if (exceptionDetails) {
            throw createEvaluationError(exceptionDetails);
        }
        if (returnByValue) {
            return valueFromPrimitiveRemoteObject(remoteObject);
        }
        return this.#world.createCdpHandle(remoteObject);
        async function convertArgumentAsync(context, arg) {
            if (arg instanceof LazyArg) {
                arg = await arg.get(context);
            }
            return convertArgument(context, arg);
        }
        function convertArgument(context, arg) {
            if (typeof arg === 'bigint') {
                return { unserializableValue: `${arg.toString()}n` };
            }
            if (Object.is(arg, -0)) {
                return { unserializableValue: '-0' };
            }
            if (Object.is(arg, Infinity)) {
                return { unserializableValue: 'Infinity' };
            }
            if (Object.is(arg, -Infinity)) {
                return { unserializableValue: '-Infinity' };
            }
            if (Object.is(arg, NaN)) {
                return { unserializableValue: 'NaN' };
            }
            const objectHandle = arg && (arg instanceof CdpJSHandle || arg instanceof CdpElementHandle)
                ? arg
                : null;
            if (objectHandle) {
                if (objectHandle.realm !== context.#world) {
                    throw new Error('JSHandles can be evaluated only in the context they were created!');
                }
                if (objectHandle.disposed) {
                    throw new Error('JSHandle is disposed!');
                }
                if (objectHandle.remoteObject().unserializableValue) {
                    return {
                        unserializableValue: objectHandle.remoteObject().unserializableValue,
                    };
                }
                if (!objectHandle.remoteObject().objectId) {
                    return { value: objectHandle.remoteObject().value };
                }
                return { objectId: objectHandle.remoteObject().objectId };
            }
            return { value: arg };
        }
    }
    [disposeSymbol]() {
        this.#disposables.dispose();
        this.emit('disposed', undefined);
    }
};
const rewriteError = (error) => {
    if (error.message.includes('Object reference chain is too long')) {
        return { result: { type: 'undefined' } };
    }
    if (error.message.includes("Object couldn't be returned by value")) {
        return { result: { type: 'undefined' } };
    }
    if (error.message.endsWith('Cannot find context with specified id') ||
        error.message.endsWith('Inspected target navigated or closed')) {
        throw new Error('Execution context was destroyed, most likely because of a navigation.');
    }
    throw error;
};

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var FrameManagerEvent;
(function (FrameManagerEvent) {
    FrameManagerEvent.FrameAttached = Symbol('FrameManager.FrameAttached');
    FrameManagerEvent.FrameNavigated = Symbol('FrameManager.FrameNavigated');
    FrameManagerEvent.FrameDetached = Symbol('FrameManager.FrameDetached');
    FrameManagerEvent.FrameSwapped = Symbol('FrameManager.FrameSwapped');
    FrameManagerEvent.LifecycleEvent = Symbol('FrameManager.LifecycleEvent');
    FrameManagerEvent.FrameNavigatedWithinDocument = Symbol('FrameManager.FrameNavigatedWithinDocument');
    FrameManagerEvent.ConsoleApiCalled = Symbol('FrameManager.ConsoleApiCalled');
    FrameManagerEvent.BindingCalled = Symbol('FrameManager.BindingCalled');
})(FrameManagerEvent || (FrameManagerEvent = {}));

/**
 * @license
 * Copyright 2019 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class IsolatedWorld extends Realm {
    #context;
    #emitter = new EventEmitter();
    #frameOrWorker;
    constructor(frameOrWorker, timeoutSettings) {
        super(timeoutSettings);
        this.#frameOrWorker = frameOrWorker;
    }
    get environment() {
        return this.#frameOrWorker;
    }
    get client() {
        return this.#frameOrWorker.client;
    }
    get emitter() {
        return this.#emitter;
    }
    setContext(context) {
        this.#context?.[disposeSymbol]();
        context.once('disposed', this.#onContextDisposed.bind(this));
        context.on('consoleapicalled', this.#onContextConsoleApiCalled.bind(this));
        context.on('bindingcalled', this.#onContextBindingCalled.bind(this));
        this.#context = context;
        this.#emitter.emit('context', context);
        void this.taskManager.rerunAll();
    }
    #onContextDisposed() {
        this.#context = undefined;
        if ('clearDocumentHandle' in this.#frameOrWorker) {
            this.#frameOrWorker.clearDocumentHandle();
        }
    }
    #onContextConsoleApiCalled(event) {
        this.#emitter.emit('consoleapicalled', event);
    }
    #onContextBindingCalled(event) {
        this.#emitter.emit('bindingcalled', event);
    }
    hasContext() {
        return !!this.#context;
    }
    get context() {
        return this.#context;
    }
    #executionContext() {
        if (this.disposed) {
            throw new Error(`Execution context is not available in detached frame or worker "${this.environment.url()}" (are you trying to evaluate?)`);
        }
        return this.#context;
    }
    async #waitForExecutionContext() {
        const error = new Error('Execution context was destroyed');
        const result = await firstValueFrom(fromEmitterEvent(this.#emitter, 'context').pipe(raceWith(fromEmitterEvent(this.#emitter, 'disposed').pipe(map(() => {
            throw error;
        })), timeout(this.timeoutSettings.timeout()))));
        return result;
    }
    async evaluateHandle(pageFunction, ...args) {
        pageFunction = withSourcePuppeteerURLIfNone(this.evaluateHandle.name, pageFunction);
        let context = this.#executionContext();
        if (!context) {
            context = await this.#waitForExecutionContext();
        }
        return await context.evaluateHandle(pageFunction, ...args);
    }
    async evaluate(pageFunction, ...args) {
        pageFunction = withSourcePuppeteerURLIfNone(this.evaluate.name, pageFunction);
        let context = this.#executionContext();
        if (!context) {
            context = await this.#waitForExecutionContext();
        }
        return await context.evaluate(pageFunction, ...args);
    }
    async adoptBackendNode(backendNodeId) {
        let context = this.#executionContext();
        if (!context) {
            context = await this.#waitForExecutionContext();
        }
        const { object } = await this.client.send('DOM.resolveNode', {
            backendNodeId: backendNodeId,
            executionContextId: context.id,
        });
        return this.createCdpHandle(object);
    }
    async adoptHandle(handle) {
        if (handle.realm === this) {
            return (await handle.evaluateHandle(value => {
                return value;
            }));
        }
        const nodeInfo = await this.client.send('DOM.describeNode', {
            objectId: handle.id,
        });
        return (await this.adoptBackendNode(nodeInfo.node.backendNodeId));
    }
    async transferHandle(handle) {
        if (handle.realm === this) {
            return handle;
        }
        if (handle.remoteObject().objectId === undefined) {
            return handle;
        }
        const info = await this.client.send('DOM.describeNode', {
            objectId: handle.remoteObject().objectId,
        });
        const newHandle = (await this.adoptBackendNode(info.node.backendNodeId));
        await handle.dispose();
        return newHandle;
    }
    createCdpHandle(remoteObject) {
        if (remoteObject.subtype === 'node') {
            return new CdpElementHandle(this, remoteObject);
        }
        return new CdpJSHandle(this, remoteObject);
    }
    [disposeSymbol]() {
        this.#context?.[disposeSymbol]();
        this.#emitter.emit('disposed', undefined);
        super[disposeSymbol]();
        this.#emitter.removeAllListeners();
    }
}

/**
 * @license
 * Copyright 2022 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const MAIN_WORLD = Symbol('mainWorld');
const PUPPETEER_WORLD = Symbol('puppeteerWorld');

/**
 * @license
 * Copyright 2019 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const puppeteerToProtocolLifecycle = new Map([
    ['load', 'load'],
    ['domcontentloaded', 'DOMContentLoaded'],
    ['networkidle0', 'networkIdle'],
    ['networkidle2', 'networkAlmostIdle'],
]);
class LifecycleWatcher {
    #expectedLifecycle;
    #frame;
    #timeout;
    #navigationRequest = null;
    #subscriptions = new DisposableStack();
    #initialLoaderId;
    #terminationDeferred;
    #sameDocumentNavigationDeferred = Deferred.create();
    #lifecycleDeferred = Deferred.create();
    #newDocumentNavigationDeferred = Deferred.create();
    #error = new Error('LifecycleWatcher terminated');
    #hasSameDocumentNavigation;
    #swapped;
    #navigationResponseReceived;
    constructor(networkManager, frame, waitUntil, timeout, signal) {
        if (Array.isArray(waitUntil)) {
            waitUntil = waitUntil.slice();
        }
        else if (typeof waitUntil === 'string') {
            waitUntil = [waitUntil];
        }
        this.#initialLoaderId = frame._loaderId;
        this.#expectedLifecycle = waitUntil.map(value => {
            const protocolEvent = puppeteerToProtocolLifecycle.get(value);
            assert(protocolEvent, 'Unknown value for options.waitUntil: ' + value);
            return protocolEvent;
        });
        signal?.addEventListener('abort', () => {
            if (signal.reason instanceof Error) {
                signal.reason.cause = this.#error;
            }
            this.#terminationDeferred.reject(signal.reason);
        });
        this.#frame = frame;
        this.#timeout = timeout;
        const frameManagerEmitter = this.#subscriptions.use(new EventEmitter(frame._frameManager));
        frameManagerEmitter.on(FrameManagerEvent.LifecycleEvent, this.#checkLifecycleComplete.bind(this));
        const frameEmitter = this.#subscriptions.use(new EventEmitter(frame));
        frameEmitter.on(FrameEvent.FrameNavigatedWithinDocument, this.#navigatedWithinDocument.bind(this));
        frameEmitter.on(FrameEvent.FrameNavigated, this.#navigated.bind(this));
        frameEmitter.on(FrameEvent.FrameSwapped, this.#frameSwapped.bind(this));
        frameEmitter.on(FrameEvent.FrameSwappedByActivation, this.#frameSwapped.bind(this));
        frameEmitter.on(FrameEvent.FrameDetached, this.#onFrameDetached.bind(this));
        const networkManagerEmitter = this.#subscriptions.use(new EventEmitter(networkManager));
        networkManagerEmitter.on(NetworkManagerEvent.Request, this.#onRequest.bind(this));
        networkManagerEmitter.on(NetworkManagerEvent.Response, this.#onResponse.bind(this));
        networkManagerEmitter.on(NetworkManagerEvent.RequestFailed, this.#onRequestFailed.bind(this));
        this.#terminationDeferred = Deferred.create({
            timeout: this.#timeout,
            message: `Navigation timeout of ${this.#timeout} ms exceeded`,
        });
        this.#checkLifecycleComplete();
    }
    #onRequest(request) {
        if (request.frame() !== this.#frame || !request.isNavigationRequest()) {
            return;
        }
        this.#navigationRequest = request;
        this.#navigationResponseReceived?.resolve();
        this.#navigationResponseReceived = Deferred.create();
        if (request.response() !== null) {
            this.#navigationResponseReceived?.resolve();
        }
    }
    #onRequestFailed(request) {
        if (this.#navigationRequest?.id !== request.id) {
            return;
        }
        this.#navigationResponseReceived?.resolve();
    }
    #onResponse(response) {
        if (this.#navigationRequest?.id !== response.request().id) {
            return;
        }
        this.#navigationResponseReceived?.resolve();
    }
    #onFrameDetached(frame) {
        if (this.#frame === frame) {
            this.#error.message = 'Navigating frame was detached';
            this.#terminationDeferred.resolve(this.#error);
            return;
        }
        this.#checkLifecycleComplete();
    }
    async navigationResponse() {
        await this.#navigationResponseReceived?.valueOrThrow();
        return this.#navigationRequest ? this.#navigationRequest.response() : null;
    }
    sameDocumentNavigationPromise() {
        return this.#sameDocumentNavigationDeferred.valueOrThrow();
    }
    newDocumentNavigationPromise() {
        return this.#newDocumentNavigationDeferred.valueOrThrow();
    }
    lifecyclePromise() {
        return this.#lifecycleDeferred.valueOrThrow();
    }
    terminationPromise() {
        return this.#terminationDeferred.valueOrThrow();
    }
    #navigatedWithinDocument() {
        this.#hasSameDocumentNavigation = true;
        this.#checkLifecycleComplete();
    }
    #navigated(navigationType) {
        if (navigationType === 'BackForwardCacheRestore') {
            return this.#frameSwapped();
        }
        this.#checkLifecycleComplete();
    }
    #frameSwapped() {
        this.#swapped = true;
        this.#checkLifecycleComplete();
    }
    #checkLifecycleComplete() {
        if (!checkLifecycle(this.#frame, this.#expectedLifecycle)) {
            return;
        }
        this.#lifecycleDeferred.resolve();
        if (this.#hasSameDocumentNavigation) {
            this.#sameDocumentNavigationDeferred.resolve(undefined);
        }
        if (this.#swapped || this.#frame._loaderId !== this.#initialLoaderId) {
            this.#newDocumentNavigationDeferred.resolve(undefined);
        }
        function checkLifecycle(frame, expectedLifecycle) {
            for (const event of expectedLifecycle) {
                if (!frame._lifecycleEvents.has(event)) {
                    return false;
                }
            }
            for (const child of frame.childFrames()) {
                if (child._hasStartedLoading &&
                    !checkLifecycle(child, expectedLifecycle)) {
                    return false;
                }
            }
            return true;
        }
    }
    dispose() {
        this.#subscriptions.dispose();
        this.#error.cause = new Error('LifecycleWatcher disposed');
        this.#terminationDeferred.resolve(this.#error);
    }
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __runInitializers$2 = (undefined && undefined.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
var __esDecorate$2 = (undefined && undefined.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
let CdpFrame = (() => {
    let _classSuper = Frame;
    let _instanceExtraInitializers = [];
    let _goto_decorators;
    let _waitForNavigation_decorators;
    let _setContent_decorators;
    let _addPreloadScript_decorators;
    let _addExposedFunctionBinding_decorators;
    let _removeExposedFunctionBinding_decorators;
    let _waitForDevicePrompt_decorators;
    return class CdpFrame extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            __esDecorate$2(this, null, _goto_decorators, { kind: "method", name: "goto", static: false, private: false, access: { has: obj => "goto" in obj, get: obj => obj.goto }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$2(this, null, _waitForNavigation_decorators, { kind: "method", name: "waitForNavigation", static: false, private: false, access: { has: obj => "waitForNavigation" in obj, get: obj => obj.waitForNavigation }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$2(this, null, _setContent_decorators, { kind: "method", name: "setContent", static: false, private: false, access: { has: obj => "setContent" in obj, get: obj => obj.setContent }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$2(this, null, _addPreloadScript_decorators, { kind: "method", name: "addPreloadScript", static: false, private: false, access: { has: obj => "addPreloadScript" in obj, get: obj => obj.addPreloadScript }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$2(this, null, _addExposedFunctionBinding_decorators, { kind: "method", name: "addExposedFunctionBinding", static: false, private: false, access: { has: obj => "addExposedFunctionBinding" in obj, get: obj => obj.addExposedFunctionBinding }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$2(this, null, _removeExposedFunctionBinding_decorators, { kind: "method", name: "removeExposedFunctionBinding", static: false, private: false, access: { has: obj => "removeExposedFunctionBinding" in obj, get: obj => obj.removeExposedFunctionBinding }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate$2(this, null, _waitForDevicePrompt_decorators, { kind: "method", name: "waitForDevicePrompt", static: false, private: false, access: { has: obj => "waitForDevicePrompt" in obj, get: obj => obj.waitForDevicePrompt }, metadata: _metadata }, null, _instanceExtraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #url = (__runInitializers$2(this, _instanceExtraInitializers), '');
        #detached = false;
        #client;
        _frameManager;
        _loaderId = '';
        _lifecycleEvents = new Set();
        _id;
        _parentId;
        accessibility;
        worlds;
        constructor(frameManager, frameId, parentFrameId, client) {
            super();
            this._frameManager = frameManager;
            this.#url = '';
            this._id = frameId;
            this._parentId = parentFrameId;
            this.#detached = false;
            this.#client = client;
            this._loaderId = '';
            this.worlds = {
                [MAIN_WORLD]: new IsolatedWorld(this, this._frameManager.timeoutSettings),
                [PUPPETEER_WORLD]: new IsolatedWorld(this, this._frameManager.timeoutSettings),
            };
            this.accessibility = new Accessibility(this.worlds[MAIN_WORLD], frameId);
            this.on(FrameEvent.FrameSwappedByActivation, () => {
                this._onLoadingStarted();
                this._onLoadingStopped();
            });
            this.worlds[MAIN_WORLD].emitter.on('consoleapicalled', this.#onMainWorldConsoleApiCalled.bind(this));
            this.worlds[MAIN_WORLD].emitter.on('bindingcalled', this.#onMainWorldBindingCalled.bind(this));
        }
        #onMainWorldConsoleApiCalled(event) {
            this._frameManager.emit(FrameManagerEvent.ConsoleApiCalled, [
                this.worlds[MAIN_WORLD],
                event,
            ]);
        }
        #onMainWorldBindingCalled(event) {
            this._frameManager.emit(FrameManagerEvent.BindingCalled, [
                this.worlds[MAIN_WORLD],
                event,
            ]);
        }
        _client() {
            return this.#client;
        }
        updateId(id) {
            this._id = id;
        }
        updateClient(client) {
            this.#client = client;
        }
        page() {
            return this._frameManager.page();
        }
        async goto(url, options = {}) {
            const { referer = this._frameManager.networkManager.extraHTTPHeaders()['referer'], referrerPolicy = this._frameManager.networkManager.extraHTTPHeaders()['referer-policy'], waitUntil = ['load'], timeout = this._frameManager.timeoutSettings.navigationTimeout(), } = options;
            let ensureNewDocumentNavigation = false;
            const watcher = new LifecycleWatcher(this._frameManager.networkManager, this, waitUntil, timeout);
            let error = await Deferred.race([
                navigate(this.#client, url, referer, referrerPolicy ? referrerPolicyToProtocol(referrerPolicy) : undefined, this._id),
                watcher.terminationPromise(),
            ]);
            if (!error) {
                error = await Deferred.race([
                    watcher.terminationPromise(),
                    ensureNewDocumentNavigation
                        ? watcher.newDocumentNavigationPromise()
                        : watcher.sameDocumentNavigationPromise(),
                ]);
            }
            try {
                if (error) {
                    throw error;
                }
                return await watcher.navigationResponse();
            }
            finally {
                watcher.dispose();
            }
            async function navigate(client, url, referrer, referrerPolicy, frameId) {
                try {
                    const response = await client.send('Page.navigate', {
                        url,
                        referrer,
                        frameId,
                        referrerPolicy,
                    });
                    ensureNewDocumentNavigation = !!response.loaderId;
                    if (response.errorText === 'net::ERR_HTTP_RESPONSE_CODE_FAILURE') {
                        return null;
                    }
                    return response.errorText
                        ? new Error(`${response.errorText} at ${url}`)
                        : null;
                }
                catch (error) {
                    if (isErrorLike$1(error)) {
                        return error;
                    }
                    throw error;
                }
            }
        }
        async waitForNavigation(options = {}) {
            const { waitUntil = ['load'], timeout = this._frameManager.timeoutSettings.navigationTimeout(), signal, } = options;
            const watcher = new LifecycleWatcher(this._frameManager.networkManager, this, waitUntil, timeout, signal);
            const error = await Deferred.race([
                watcher.terminationPromise(),
                ...(options.ignoreSameDocumentNavigation
                    ? []
                    : [watcher.sameDocumentNavigationPromise()]),
                watcher.newDocumentNavigationPromise(),
            ]);
            try {
                if (error) {
                    throw error;
                }
                const result = await Deferred.race([watcher.terminationPromise(), watcher.navigationResponse()]);
                if (result instanceof Error) {
                    throw error;
                }
                return result || null;
            }
            finally {
                watcher.dispose();
            }
        }
        get client() {
            return this.#client;
        }
        mainRealm() {
            return this.worlds[MAIN_WORLD];
        }
        isolatedRealm() {
            return this.worlds[PUPPETEER_WORLD];
        }
        async setContent(html, options = {}) {
            const { waitUntil = ['load'], timeout = this._frameManager.timeoutSettings.navigationTimeout(), } = options;
            await this.setFrameContent(html);
            const watcher = new LifecycleWatcher(this._frameManager.networkManager, this, waitUntil, timeout);
            const error = await Deferred.race([
                watcher.terminationPromise(),
                watcher.lifecyclePromise(),
            ]);
            watcher.dispose();
            if (error) {
                throw error;
            }
        }
        url() {
            return this.#url;
        }
        parentFrame() {
            return this._frameManager._frameTree.parentFrame(this._id) || null;
        }
        childFrames() {
            return this._frameManager._frameTree.childFrames(this._id);
        }
        #deviceRequestPromptManager() {
            return this._frameManager._deviceRequestPromptManager(this.#client);
        }
        async addPreloadScript(preloadScript) {
            const parentFrame = this.parentFrame();
            if (parentFrame && this.#client === parentFrame.client) {
                return;
            }
            if (preloadScript.getIdForFrame(this)) {
                return;
            }
            const { identifier } = await this.#client.send('Page.addScriptToEvaluateOnNewDocument', {
                source: preloadScript.source,
            });
            preloadScript.setIdForFrame(this, identifier);
        }
        async addExposedFunctionBinding(binding) {
            if (this !== this._frameManager.mainFrame() && !this._hasStartedLoading) {
                return;
            }
            await Promise.all([
                this.#client.send('Runtime.addBinding', {
                    name: CDP_BINDING_PREFIX + binding.name,
                }),
                this.evaluate(binding.initSource).catch(debugError),
            ]);
        }
        async removeExposedFunctionBinding(binding) {
            if (this !== this._frameManager.mainFrame() && !this._hasStartedLoading) {
                return;
            }
            await Promise.all([
                this.#client.send('Runtime.removeBinding', {
                    name: CDP_BINDING_PREFIX + binding.name,
                }),
                this.evaluate(name => {
                    globalThis[name] = undefined;
                }, binding.name).catch(debugError),
            ]);
        }
        async waitForDevicePrompt(options = {}) {
            return await this.#deviceRequestPromptManager().waitForDevicePrompt(options);
        }
        _navigated(framePayload) {
            this._name = framePayload.name;
            this.#url = `${framePayload.url}${framePayload.urlFragment || ''}`;
        }
        _navigatedWithinDocument(url) {
            this.#url = url;
        }
        _onLifecycleEvent(loaderId, name) {
            if (name === 'init') {
                this._loaderId = loaderId;
                this._lifecycleEvents.clear();
            }
            this._lifecycleEvents.add(name);
        }
        _onLoadingStopped() {
            this._lifecycleEvents.add('DOMContentLoaded');
            this._lifecycleEvents.add('load');
        }
        _onLoadingStarted() {
            this._hasStartedLoading = true;
        }
        get detached() {
            return this.#detached;
        }
        [(_goto_decorators = [throwIfDetached], _waitForNavigation_decorators = [throwIfDetached], _setContent_decorators = [throwIfDetached], _addPreloadScript_decorators = [throwIfDetached], _addExposedFunctionBinding_decorators = [throwIfDetached], _removeExposedFunctionBinding_decorators = [throwIfDetached], _waitForDevicePrompt_decorators = [throwIfDetached], disposeSymbol)]() {
            if (this.#detached) {
                return;
            }
            this.#detached = true;
            this.worlds[MAIN_WORLD][disposeSymbol]();
            this.worlds[PUPPETEER_WORLD][disposeSymbol]();
        }
        exposeFunction() {
            throw new UnsupportedOperation();
        }
        async frameElement() {
            const parent = this.parentFrame();
            if (!parent) {
                return null;
            }
            const { backendNodeId } = await parent.client.send('DOM.getFrameOwner', {
                frameId: this._id,
            });
            return (await parent
                .mainRealm()
                .adoptBackendNode(backendNodeId));
        }
    };
})();
function referrerPolicyToProtocol(referrerPolicy) {
    return referrerPolicy.replaceAll(/-./g, match => {
        return match[1].toUpperCase();
    });
}

/**
 * @license
 * Copyright 2022 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class FrameTree {
    #frames = new Map();
    #parentIds = new Map();
    #childIds = new Map();
    #mainFrame;
    #isMainFrameStale = false;
    #waitRequests = new Map();
    getMainFrame() {
        return this.#mainFrame;
    }
    getById(frameId) {
        return this.#frames.get(frameId);
    }
    waitForFrame(frameId) {
        const frame = this.getById(frameId);
        if (frame) {
            return Promise.resolve(frame);
        }
        const deferred = Deferred.create();
        const callbacks = this.#waitRequests.get(frameId) || new Set();
        callbacks.add(deferred);
        return deferred.valueOrThrow();
    }
    frames() {
        return Array.from(this.#frames.values());
    }
    addFrame(frame) {
        this.#frames.set(frame._id, frame);
        if (frame._parentId) {
            this.#parentIds.set(frame._id, frame._parentId);
            if (!this.#childIds.has(frame._parentId)) {
                this.#childIds.set(frame._parentId, new Set());
            }
            this.#childIds.get(frame._parentId).add(frame._id);
        }
        else if (!this.#mainFrame || this.#isMainFrameStale) {
            this.#mainFrame = frame;
            this.#isMainFrameStale = false;
        }
        this.#waitRequests.get(frame._id)?.forEach(request => {
            return request.resolve(frame);
        });
    }
    removeFrame(frame) {
        this.#frames.delete(frame._id);
        this.#parentIds.delete(frame._id);
        if (frame._parentId) {
            this.#childIds.get(frame._parentId)?.delete(frame._id);
        }
        else {
            this.#isMainFrameStale = true;
        }
    }
    childFrames(frameId) {
        const childIds = this.#childIds.get(frameId);
        if (!childIds) {
            return [];
        }
        return Array.from(childIds)
            .map(id => {
            return this.getById(id);
        })
            .filter((frame) => {
            return frame !== undefined;
        });
    }
    parentFrame(frameId) {
        const parentId = this.#parentIds.get(frameId);
        return parentId ? this.getById(parentId) : undefined;
    }
}

class CdpHTTPRequest extends HTTPRequest {
    id;
    #client;
    #isNavigationRequest;
    #url;
    #resourceType;
    #method;
    #hasPostData = false;
    #postData;
    #headers = {};
    #frame;
    #initiator;
    get client() {
        return this.#client;
    }
    set client(newClient) {
        this.#client = newClient;
    }
    constructor(client, frame, interceptionId, allowInterception, data, redirectChain) {
        super();
        this.#client = client;
        this.id = data.requestId;
        this.#isNavigationRequest =
            data.requestId === data.loaderId && data.type === 'Document';
        this._interceptionId = interceptionId;
        this.#url = data.request.url + (data.request.urlFragment ?? '');
        this.#resourceType = (data.type || 'other').toLowerCase();
        this.#method = data.request.method;
        if (data.request.postDataEntries &&
            data.request.postDataEntries.length > 0) {
            this.#postData = new TextDecoder().decode(mergeUint8Arrays(data.request.postDataEntries
                .map(entry => {
                return entry.bytes ? stringToTypedArray(entry.bytes, true) : null;
            })
                .filter((entry) => {
                return entry !== null;
            })));
        }
        else {
            this.#postData = data.request.postData;
        }
        this.#hasPostData = data.request.hasPostData ?? false;
        this.#frame = frame;
        this._redirectChain = redirectChain;
        this.#initiator = data.initiator;
        this.interception.enabled = allowInterception;
        this.updateHeaders(data.request.headers);
    }
    updateHeaders(headers) {
        for (const [key, value] of Object.entries(headers)) {
            this.#headers[key.toLowerCase()] = value;
        }
    }
    url() {
        return this.#url;
    }
    resourceType() {
        return this.#resourceType;
    }
    method() {
        return this.#method;
    }
    postData() {
        return this.#postData;
    }
    hasPostData() {
        return this.#hasPostData;
    }
    async fetchPostData() {
        try {
            const result = await this.#client.send('Network.getRequestPostData', {
                requestId: this.id,
            });
            return result.postData;
        }
        catch (err) {
            debugError(err);
            return;
        }
    }
    headers() {
        return structuredClone(this.#headers);
    }
    response() {
        return this._response;
    }
    frame() {
        return this.#frame;
    }
    isNavigationRequest() {
        return this.#isNavigationRequest;
    }
    initiator() {
        return this.#initiator;
    }
    redirectChain() {
        return this._redirectChain.slice();
    }
    failure() {
        if (!this._failureText) {
            return null;
        }
        return {
            errorText: this._failureText,
        };
    }
    canBeIntercepted() {
        return !this.url().startsWith('data:') && !this._fromMemoryCache;
    }
    async _continue(overrides = {}) {
        const { url, method, postData, headers } = overrides;
        this.interception.handled = true;
        const postDataBinaryBase64 = postData
            ? stringToBase64(postData)
            : undefined;
        if (this._interceptionId === undefined) {
            throw new Error('HTTPRequest is missing _interceptionId needed for Fetch.continueRequest');
        }
        await this.#client
            .send('Fetch.continueRequest', {
            requestId: this._interceptionId,
            url,
            method,
            postData: postDataBinaryBase64,
            headers: headers ? headersArray(headers) : undefined,
        })
            .catch(error => {
            this.interception.handled = false;
            return handleError(error);
        });
    }
    async _respond(response) {
        this.interception.handled = true;
        let parsedBody;
        if (response.body) {
            parsedBody = HTTPRequest.getResponse(response.body);
        }
        const responseHeaders = {};
        if (response.headers) {
            for (const header of Object.keys(response.headers)) {
                const value = response.headers[header];
                responseHeaders[header.toLowerCase()] = Array.isArray(value)
                    ? value.map(item => {
                        return String(item);
                    })
                    : String(value);
            }
        }
        if (response.contentType) {
            responseHeaders['content-type'] = response.contentType;
        }
        if (parsedBody?.contentLength && !('content-length' in responseHeaders)) {
            responseHeaders['content-length'] = String(parsedBody.contentLength);
        }
        const status = response.status || 200;
        if (this._interceptionId === undefined) {
            throw new Error('HTTPRequest is missing _interceptionId needed for Fetch.fulfillRequest');
        }
        await this.#client
            .send('Fetch.fulfillRequest', {
            requestId: this._interceptionId,
            responseCode: status,
            responsePhrase: STATUS_TEXTS[status],
            responseHeaders: headersArray(responseHeaders),
            body: parsedBody?.base64,
        })
            .catch(error => {
            this.interception.handled = false;
            return handleError(error);
        });
    }
    async _abort(errorReason) {
        this.interception.handled = true;
        if (this._interceptionId === undefined) {
            throw new Error('HTTPRequest is missing _interceptionId needed for Fetch.failRequest');
        }
        await this.#client
            .send('Fetch.failRequest', {
            requestId: this._interceptionId,
            errorReason: errorReason || 'Failed',
        })
            .catch(handleError);
    }
}

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class SecurityDetails {
    #subjectName;
    #issuer;
    #validFrom;
    #validTo;
    #protocol;
    #sanList;
    constructor(securityPayload) {
        this.#subjectName = securityPayload.subjectName;
        this.#issuer = securityPayload.issuer;
        this.#validFrom = securityPayload.validFrom;
        this.#validTo = securityPayload.validTo;
        this.#protocol = securityPayload.protocol;
        this.#sanList = securityPayload.sanList;
    }
    issuer() {
        return this.#issuer;
    }
    validFrom() {
        return this.#validFrom;
    }
    validTo() {
        return this.#validTo;
    }
    protocol() {
        return this.#protocol;
    }
    subjectName() {
        return this.#subjectName;
    }
    subjectAlternativeNames() {
        return this.#sanList;
    }
}

class CdpHTTPResponse extends HTTPResponse {
    #request;
    #contentPromise = null;
    #bodyLoadedDeferred = Deferred.create();
    #remoteAddress;
    #status;
    #statusText;
    #fromDiskCache;
    #fromServiceWorker;
    #headers = {};
    #securityDetails;
    #timing;
    constructor(request, responsePayload, extraInfo) {
        super();
        this.#request = request;
        this.#remoteAddress = {
            ip: responsePayload.remoteIPAddress,
            port: responsePayload.remotePort,
        };
        this.#statusText =
            this.#parseStatusTextFromExtraInfo(extraInfo) ||
                responsePayload.statusText;
        this.#fromDiskCache = !!responsePayload.fromDiskCache;
        this.#fromServiceWorker = !!responsePayload.fromServiceWorker;
        this.#status = extraInfo ? extraInfo.statusCode : responsePayload.status;
        const headers = extraInfo ? extraInfo.headers : responsePayload.headers;
        for (const [key, value] of Object.entries(headers)) {
            this.#headers[key.toLowerCase()] = value;
        }
        this.#securityDetails = responsePayload.securityDetails
            ? new SecurityDetails(responsePayload.securityDetails)
            : null;
        this.#timing = responsePayload.timing || null;
    }
    #parseStatusTextFromExtraInfo(extraInfo) {
        if (!extraInfo || !extraInfo.headersText) {
            return;
        }
        const firstLine = extraInfo.headersText.split('\r', 1)[0];
        if (!firstLine || firstLine.length > 1_000) {
            return;
        }
        const match = firstLine.match(/[^ ]* [^ ]* (.*)/);
        if (!match) {
            return;
        }
        const statusText = match[1];
        if (!statusText) {
            return;
        }
        return statusText;
    }
    _resolveBody(err) {
        if (err) {
            return this.#bodyLoadedDeferred.reject(err);
        }
        return this.#bodyLoadedDeferred.resolve();
    }
    remoteAddress() {
        return this.#remoteAddress;
    }
    url() {
        return this.#request.url();
    }
    status() {
        return this.#status;
    }
    statusText() {
        return this.#statusText;
    }
    headers() {
        return this.#headers;
    }
    securityDetails() {
        return this.#securityDetails;
    }
    timing() {
        return this.#timing;
    }
    content() {
        if (!this.#contentPromise) {
            this.#contentPromise = this.#bodyLoadedDeferred
                .valueOrThrow()
                .then(async () => {
                try {
                    const response = await this.#request.client.send('Network.getResponseBody', {
                        requestId: this.#request.id,
                    });
                    return stringToTypedArray(response.body, response.base64Encoded);
                }
                catch (error) {
                    if (error instanceof ProtocolError &&
                        error.originalMessage ===
                            'No resource with given identifier found') {
                        throw new ProtocolError('Could not load response body for this request. This might happen if the request is a preflight request.');
                    }
                    throw error;
                }
            });
        }
        return this.#contentPromise;
    }
    request() {
        return this.#request;
    }
    fromCache() {
        return this.#fromDiskCache || this.#request._fromMemoryCache;
    }
    fromServiceWorker() {
        return this.#fromServiceWorker;
    }
    frame() {
        return this.#request.frame();
    }
}

/**
 * @license
 * Copyright 2022 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class NetworkEventManager {
    #requestWillBeSentMap = new Map();
    #requestPausedMap = new Map();
    #httpRequestsMap = new Map();
    #requestWillBeSentExtraInfoMap = new Map();
    #responseReceivedExtraInfoMap = new Map();
    #queuedRedirectInfoMap = new Map();
    #queuedEventGroupMap = new Map();
    forget(networkRequestId) {
        this.#requestWillBeSentMap.delete(networkRequestId);
        this.#requestPausedMap.delete(networkRequestId);
        this.#requestWillBeSentExtraInfoMap.delete(networkRequestId);
        this.#queuedEventGroupMap.delete(networkRequestId);
        this.#queuedRedirectInfoMap.delete(networkRequestId);
        this.#responseReceivedExtraInfoMap.delete(networkRequestId);
    }
    requestExtraInfo(networkRequestId) {
        if (!this.#requestWillBeSentExtraInfoMap.has(networkRequestId)) {
            this.#requestWillBeSentExtraInfoMap.set(networkRequestId, []);
        }
        return this.#requestWillBeSentExtraInfoMap.get(networkRequestId);
    }
    responseExtraInfo(networkRequestId) {
        if (!this.#responseReceivedExtraInfoMap.has(networkRequestId)) {
            this.#responseReceivedExtraInfoMap.set(networkRequestId, []);
        }
        return this.#responseReceivedExtraInfoMap.get(networkRequestId);
    }
    queuedRedirectInfo(fetchRequestId) {
        if (!this.#queuedRedirectInfoMap.has(fetchRequestId)) {
            this.#queuedRedirectInfoMap.set(fetchRequestId, []);
        }
        return this.#queuedRedirectInfoMap.get(fetchRequestId);
    }
    queueRedirectInfo(fetchRequestId, redirectInfo) {
        this.queuedRedirectInfo(fetchRequestId).push(redirectInfo);
    }
    takeQueuedRedirectInfo(fetchRequestId) {
        return this.queuedRedirectInfo(fetchRequestId).shift();
    }
    inFlightRequestsCount() {
        let inFlightRequestCounter = 0;
        for (const request of this.#httpRequestsMap.values()) {
            if (!request.response()) {
                inFlightRequestCounter++;
            }
        }
        return inFlightRequestCounter;
    }
    storeRequestWillBeSent(networkRequestId, event) {
        this.#requestWillBeSentMap.set(networkRequestId, event);
    }
    getRequestWillBeSent(networkRequestId) {
        return this.#requestWillBeSentMap.get(networkRequestId);
    }
    forgetRequestWillBeSent(networkRequestId) {
        this.#requestWillBeSentMap.delete(networkRequestId);
    }
    getRequestPaused(networkRequestId) {
        return this.#requestPausedMap.get(networkRequestId);
    }
    forgetRequestPaused(networkRequestId) {
        this.#requestPausedMap.delete(networkRequestId);
    }
    storeRequestPaused(networkRequestId, event) {
        this.#requestPausedMap.set(networkRequestId, event);
    }
    getRequest(networkRequestId) {
        return this.#httpRequestsMap.get(networkRequestId);
    }
    storeRequest(networkRequestId, request) {
        this.#httpRequestsMap.set(networkRequestId, request);
    }
    forgetRequest(networkRequestId) {
        this.#httpRequestsMap.delete(networkRequestId);
    }
    getQueuedEventGroup(networkRequestId) {
        return this.#queuedEventGroupMap.get(networkRequestId);
    }
    queueEventGroup(networkRequestId, event) {
        this.#queuedEventGroupMap.set(networkRequestId, event);
    }
    forgetQueuedEventGroup(networkRequestId) {
        this.#queuedEventGroupMap.delete(networkRequestId);
    }
    printState() {
        function replacer(_key, value) {
            if (value instanceof Map) {
                return {
                    dataType: 'Map',
                    value: Array.from(value.entries()),
                };
            }
            else if (value instanceof CdpHTTPRequest) {
                return {
                    dataType: 'CdpHTTPRequest',
                    value: `${value.id}: ${value.url()}`,
                };
            }
            {
                return value;
            }
        }
        console.log('httpRequestsMap', JSON.stringify(this.#httpRequestsMap, replacer, 2));
        console.log('requestWillBeSentMap', JSON.stringify(this.#requestWillBeSentMap, replacer, 2));
        console.log('requestWillBeSentMap', JSON.stringify(this.#responseReceivedExtraInfoMap, replacer, 2));
        console.log('requestWillBeSentMap', JSON.stringify(this.#requestPausedMap, replacer, 2));
    }
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
let NetworkManager$1 = class NetworkManager extends EventEmitter {
    #frameManager;
    #networkEventManager = new NetworkEventManager();
    #extraHTTPHeaders;
    #credentials = null;
    #attemptedAuthentications = new Set();
    #userRequestInterceptionEnabled = false;
    #protocolRequestInterceptionEnabled;
    #userCacheDisabled;
    #emulatedNetworkConditions;
    #userAgent;
    #userAgentMetadata;
    #platform;
    #handlers = [
        ['Fetch.requestPaused', this.#onRequestPaused],
        ['Fetch.authRequired', this.#onAuthRequired],
        ['Network.requestWillBeSent', this.#onRequestWillBeSent],
        ['Network.requestWillBeSentExtraInfo', this.#onRequestWillBeSentExtraInfo],
        ['Network.requestServedFromCache', this.#onRequestServedFromCache],
        ['Network.responseReceived', this.#onResponseReceived],
        ['Network.loadingFinished', this.#onLoadingFinished],
        ['Network.loadingFailed', this.#onLoadingFailed],
        ['Network.responseReceivedExtraInfo', this.#onResponseReceivedExtraInfo],
        [CDPSessionEvent.Disconnected, this.#removeClient],
    ];
    #clients = new Map();
    #networkEnabled = true;
    constructor(frameManager, networkEnabled) {
        super();
        this.#frameManager = frameManager;
        this.#networkEnabled = networkEnabled ?? true;
    }
    #canIgnoreError(error) {
        return (isErrorLike$1(error) &&
            (isTargetClosedError(error) ||
                error.message.includes('Not supported') ||
                error.message.includes("wasn't found")));
    }
    async addClient(client) {
        if (!this.#networkEnabled || this.#clients.has(client)) {
            return;
        }
        const subscriptions = new DisposableStack();
        this.#clients.set(client, subscriptions);
        const clientEmitter = subscriptions.use(new EventEmitter(client));
        for (const [event, handler] of this.#handlers) {
            clientEmitter.on(event, (arg) => {
                return handler.bind(this)(client, arg);
            });
        }
        try {
            await Promise.all([
                client.send('Network.enable'),
                this.#applyExtraHTTPHeaders(client),
                this.#applyNetworkConditions(client),
                this.#applyProtocolCacheDisabled(client),
                this.#applyProtocolRequestInterception(client),
                this.#applyUserAgent(client),
            ]);
        }
        catch (error) {
            if (this.#canIgnoreError(error)) {
                return;
            }
            throw error;
        }
    }
    async #removeClient(client) {
        this.#clients.get(client)?.dispose();
        this.#clients.delete(client);
    }
    async authenticate(credentials) {
        this.#credentials = credentials;
        const enabled = this.#userRequestInterceptionEnabled || !!this.#credentials;
        if (enabled === this.#protocolRequestInterceptionEnabled) {
            return;
        }
        this.#protocolRequestInterceptionEnabled = enabled;
        await this.#applyToAllClients(this.#applyProtocolRequestInterception.bind(this));
    }
    async setExtraHTTPHeaders(headers) {
        const extraHTTPHeaders = {};
        for (const [key, value] of Object.entries(headers)) {
            assert(isString(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`);
            extraHTTPHeaders[key.toLowerCase()] = value;
        }
        this.#extraHTTPHeaders = extraHTTPHeaders;
        await this.#applyToAllClients(this.#applyExtraHTTPHeaders.bind(this));
    }
    async #applyExtraHTTPHeaders(client) {
        if (this.#extraHTTPHeaders === undefined) {
            return;
        }
        try {
            await client.send('Network.setExtraHTTPHeaders', {
                headers: this.#extraHTTPHeaders,
            });
        }
        catch (error) {
            if (this.#canIgnoreError(error)) {
                return;
            }
            throw error;
        }
    }
    extraHTTPHeaders() {
        return Object.assign({}, this.#extraHTTPHeaders);
    }
    inFlightRequestsCount() {
        return this.#networkEventManager.inFlightRequestsCount();
    }
    async setOfflineMode(value) {
        if (!this.#emulatedNetworkConditions) {
            this.#emulatedNetworkConditions = {
                offline: false,
                upload: -1,
                download: -1,
                latency: 0,
            };
        }
        this.#emulatedNetworkConditions.offline = value;
        await this.#applyToAllClients(this.#applyNetworkConditions.bind(this));
    }
    async emulateNetworkConditions(networkConditions) {
        if (!this.#emulatedNetworkConditions) {
            this.#emulatedNetworkConditions = {
                offline: networkConditions?.offline ?? false,
                upload: -1,
                download: -1,
                latency: 0,
            };
        }
        this.#emulatedNetworkConditions.upload = networkConditions
            ? networkConditions.upload
            : -1;
        this.#emulatedNetworkConditions.download = networkConditions
            ? networkConditions.download
            : -1;
        this.#emulatedNetworkConditions.latency = networkConditions
            ? networkConditions.latency
            : 0;
        this.#emulatedNetworkConditions.offline =
            networkConditions?.offline ?? false;
        await this.#applyToAllClients(this.#applyNetworkConditions.bind(this));
    }
    async #applyToAllClients(fn) {
        await Promise.all(Array.from(this.#clients.keys()).map(client => {
            return fn(client);
        }));
    }
    async #applyNetworkConditions(client) {
        if (this.#emulatedNetworkConditions === undefined) {
            return;
        }
        try {
            await client.send('Network.emulateNetworkConditions', {
                offline: this.#emulatedNetworkConditions.offline,
                latency: this.#emulatedNetworkConditions.latency,
                uploadThroughput: this.#emulatedNetworkConditions.upload,
                downloadThroughput: this.#emulatedNetworkConditions.download,
            });
        }
        catch (error) {
            if (this.#canIgnoreError(error)) {
                return;
            }
            throw error;
        }
    }
    async setUserAgent(userAgent, userAgentMetadata, platform) {
        this.#userAgent = userAgent;
        this.#userAgentMetadata = userAgentMetadata;
        this.#platform = platform;
        await this.#applyToAllClients(this.#applyUserAgent.bind(this));
    }
    async #applyUserAgent(client) {
        if (this.#userAgent === undefined) {
            return;
        }
        try {
            await client.send('Network.setUserAgentOverride', {
                userAgent: this.#userAgent,
                userAgentMetadata: this.#userAgentMetadata,
                platform: this.#platform,
            });
        }
        catch (error) {
            if (this.#canIgnoreError(error)) {
                return;
            }
            throw error;
        }
    }
    async setCacheEnabled(enabled) {
        this.#userCacheDisabled = !enabled;
        await this.#applyToAllClients(this.#applyProtocolCacheDisabled.bind(this));
    }
    async setRequestInterception(value) {
        this.#userRequestInterceptionEnabled = value;
        const enabled = this.#userRequestInterceptionEnabled || !!this.#credentials;
        if (enabled === this.#protocolRequestInterceptionEnabled) {
            return;
        }
        this.#protocolRequestInterceptionEnabled = enabled;
        await this.#applyToAllClients(this.#applyProtocolRequestInterception.bind(this));
    }
    async #applyProtocolRequestInterception(client) {
        if (this.#protocolRequestInterceptionEnabled === undefined) {
            return;
        }
        if (this.#userCacheDisabled === undefined) {
            this.#userCacheDisabled = false;
        }
        try {
            if (this.#protocolRequestInterceptionEnabled) {
                await Promise.all([
                    this.#applyProtocolCacheDisabled(client),
                    client.send('Fetch.enable', {
                        handleAuthRequests: true,
                        patterns: [{ urlPattern: '*' }],
                    }),
                ]);
            }
            else {
                await Promise.all([
                    this.#applyProtocolCacheDisabled(client),
                    client.send('Fetch.disable'),
                ]);
            }
        }
        catch (error) {
            if (this.#canIgnoreError(error)) {
                return;
            }
            throw error;
        }
    }
    async #applyProtocolCacheDisabled(client) {
        if (this.#userCacheDisabled === undefined) {
            return;
        }
        try {
            await client.send('Network.setCacheDisabled', {
                cacheDisabled: this.#userCacheDisabled,
            });
        }
        catch (error) {
            if (this.#canIgnoreError(error)) {
                return;
            }
            throw error;
        }
    }
    #onRequestWillBeSent(client, event) {
        if (this.#userRequestInterceptionEnabled &&
            !event.request.url.startsWith('data:')) {
            const { requestId: networkRequestId } = event;
            this.#networkEventManager.storeRequestWillBeSent(networkRequestId, event);
            const requestPausedEvent = this.#networkEventManager.getRequestPaused(networkRequestId);
            if (requestPausedEvent) {
                const { requestId: fetchRequestId } = requestPausedEvent;
                this.#patchRequestEventHeaders(event, requestPausedEvent);
                this.#onRequest(client, event, fetchRequestId);
                this.#networkEventManager.forgetRequestPaused(networkRequestId);
            }
            return;
        }
        this.#onRequest(client, event, undefined);
    }
    #onAuthRequired(client, event) {
        let response = 'Default';
        if (this.#attemptedAuthentications.has(event.requestId)) {
            response = 'CancelAuth';
        }
        else if (this.#credentials) {
            response = 'ProvideCredentials';
            this.#attemptedAuthentications.add(event.requestId);
        }
        const { username, password } = this.#credentials || {
            username: undefined,
            password: undefined,
        };
        client
            .send('Fetch.continueWithAuth', {
            requestId: event.requestId,
            authChallengeResponse: { response, username, password },
        })
            .catch(debugError);
    }
    #onRequestPaused(client, event) {
        if (!this.#userRequestInterceptionEnabled &&
            this.#protocolRequestInterceptionEnabled) {
            client
                .send('Fetch.continueRequest', {
                requestId: event.requestId,
            })
                .catch(debugError);
        }
        const { networkId: networkRequestId, requestId: fetchRequestId } = event;
        if (!networkRequestId) {
            this.#onRequestWithoutNetworkInstrumentation(client, event);
            return;
        }
        const requestWillBeSentEvent = (() => {
            const requestWillBeSentEvent = this.#networkEventManager.getRequestWillBeSent(networkRequestId);
            if (requestWillBeSentEvent &&
                (requestWillBeSentEvent.request.url !== event.request.url ||
                    requestWillBeSentEvent.request.method !== event.request.method)) {
                this.#networkEventManager.forgetRequestWillBeSent(networkRequestId);
                return;
            }
            return requestWillBeSentEvent;
        })();
        if (requestWillBeSentEvent) {
            this.#patchRequestEventHeaders(requestWillBeSentEvent, event);
            this.#onRequest(client, requestWillBeSentEvent, fetchRequestId);
        }
        else {
            this.#networkEventManager.storeRequestPaused(networkRequestId, event);
        }
    }
    #patchRequestEventHeaders(requestWillBeSentEvent, requestPausedEvent) {
        requestWillBeSentEvent.request.headers = {
            ...requestWillBeSentEvent.request.headers,
            ...requestPausedEvent.request.headers,
        };
    }
    #onRequestWithoutNetworkInstrumentation(client, event) {
        const frame = event.frameId
            ? this.#frameManager.frame(event.frameId)
            : null;
        const request = new CdpHTTPRequest(client, frame, event.requestId, this.#userRequestInterceptionEnabled, event, []);
        this.emit(NetworkManagerEvent.Request, request);
        void request.finalizeInterceptions();
    }
    #onRequest(client, event, fetchRequestId, fromMemoryCache = false) {
        let redirectChain = [];
        if (event.redirectResponse) {
            let redirectResponseExtraInfo = null;
            if (event.redirectHasExtraInfo) {
                redirectResponseExtraInfo = this.#networkEventManager
                    .responseExtraInfo(event.requestId)
                    .shift();
                if (!redirectResponseExtraInfo) {
                    this.#networkEventManager.queueRedirectInfo(event.requestId, {
                        event,
                        fetchRequestId,
                    });
                    return;
                }
            }
            const request = this.#networkEventManager.getRequest(event.requestId);
            if (request) {
                this.#handleRequestRedirect(client, request, event.redirectResponse, redirectResponseExtraInfo);
                redirectChain = request._redirectChain;
                const extraInfo = this.#networkEventManager
                    .requestExtraInfo(event.requestId)
                    .shift();
                if (extraInfo) {
                    request.updateHeaders(extraInfo.headers);
                }
            }
        }
        const frame = event.frameId
            ? this.#frameManager.frame(event.frameId)
            : null;
        const request = new CdpHTTPRequest(client, frame, fetchRequestId, this.#userRequestInterceptionEnabled, event, redirectChain);
        const extraInfo = this.#networkEventManager
            .requestExtraInfo(event.requestId)
            .shift();
        if (extraInfo) {
            request.updateHeaders(extraInfo.headers);
        }
        request._fromMemoryCache = fromMemoryCache;
        this.#networkEventManager.storeRequest(event.requestId, request);
        this.emit(NetworkManagerEvent.Request, request);
        void request.finalizeInterceptions();
    }
    #onRequestWillBeSentExtraInfo(_client, event) {
        const request = this.#networkEventManager.getRequest(event.requestId);
        if (request) {
            request.updateHeaders(event.headers);
        }
        else {
            this.#networkEventManager.requestExtraInfo(event.requestId).push(event);
        }
    }
    #onRequestServedFromCache(client, event) {
        const requestWillBeSentEvent = this.#networkEventManager.getRequestWillBeSent(event.requestId);
        let request = this.#networkEventManager.getRequest(event.requestId);
        if (request) {
            request._fromMemoryCache = true;
        }
        if (!request && requestWillBeSentEvent) {
            this.#onRequest(client, requestWillBeSentEvent, undefined, true);
            request = this.#networkEventManager.getRequest(event.requestId);
        }
        if (!request) {
            debugError(new Error(`Request ${event.requestId} was served from cache but we could not find the corresponding request object`));
            return;
        }
        this.emit(NetworkManagerEvent.RequestServedFromCache, request);
    }
    #handleRequestRedirect(_client, request, responsePayload, extraInfo) {
        const response = new CdpHTTPResponse(request, responsePayload, extraInfo);
        request._response = response;
        request._redirectChain.push(request);
        response._resolveBody(new Error('Response body is unavailable for redirect responses'));
        this.#forgetRequest(request, false);
        this.emit(NetworkManagerEvent.Response, response);
        this.emit(NetworkManagerEvent.RequestFinished, request);
    }
    #emitResponseEvent(_client, responseReceived, extraInfo) {
        const request = this.#networkEventManager.getRequest(responseReceived.requestId);
        if (!request) {
            return;
        }
        const extraInfos = this.#networkEventManager.responseExtraInfo(responseReceived.requestId);
        if (extraInfos.length) {
            debugError(new Error('Unexpected extraInfo events for request ' +
                responseReceived.requestId));
        }
        if (responseReceived.response.fromDiskCache) {
            extraInfo = null;
        }
        const response = new CdpHTTPResponse(request, responseReceived.response, extraInfo);
        request._response = response;
        this.emit(NetworkManagerEvent.Response, response);
    }
    #onResponseReceived(client, event) {
        const request = this.#networkEventManager.getRequest(event.requestId);
        let extraInfo = null;
        if (request && !request._fromMemoryCache && event.hasExtraInfo) {
            extraInfo = this.#networkEventManager
                .responseExtraInfo(event.requestId)
                .shift();
            if (!extraInfo) {
                this.#networkEventManager.queueEventGroup(event.requestId, {
                    responseReceivedEvent: event,
                });
                return;
            }
        }
        this.#emitResponseEvent(client, event, extraInfo);
    }
    #onResponseReceivedExtraInfo(client, event) {
        const redirectInfo = this.#networkEventManager.takeQueuedRedirectInfo(event.requestId);
        if (redirectInfo) {
            this.#networkEventManager.responseExtraInfo(event.requestId).push(event);
            this.#onRequest(client, redirectInfo.event, redirectInfo.fetchRequestId);
            return;
        }
        const queuedEvents = this.#networkEventManager.getQueuedEventGroup(event.requestId);
        if (queuedEvents) {
            this.#networkEventManager.forgetQueuedEventGroup(event.requestId);
            this.#emitResponseEvent(client, queuedEvents.responseReceivedEvent, event);
            if (queuedEvents.loadingFinishedEvent) {
                this.#emitLoadingFinished(client, queuedEvents.loadingFinishedEvent);
            }
            if (queuedEvents.loadingFailedEvent) {
                this.#emitLoadingFailed(client, queuedEvents.loadingFailedEvent);
            }
            return;
        }
        this.#networkEventManager.responseExtraInfo(event.requestId).push(event);
    }
    #forgetRequest(request, events) {
        const requestId = request.id;
        const interceptionId = request._interceptionId;
        this.#networkEventManager.forgetRequest(requestId);
        if (interceptionId !== undefined) {
            this.#attemptedAuthentications.delete(interceptionId);
        }
        if (events) {
            this.#networkEventManager.forget(requestId);
        }
    }
    #onLoadingFinished(client, event) {
        const queuedEvents = this.#networkEventManager.getQueuedEventGroup(event.requestId);
        if (queuedEvents) {
            queuedEvents.loadingFinishedEvent = event;
        }
        else {
            this.#emitLoadingFinished(client, event);
        }
    }
    #emitLoadingFinished(client, event) {
        const request = this.#networkEventManager.getRequest(event.requestId);
        if (!request) {
            return;
        }
        this.#adoptCdpSessionIfNeeded(client, request);
        if (request.response()) {
            request.response()?._resolveBody();
        }
        this.#forgetRequest(request, true);
        this.emit(NetworkManagerEvent.RequestFinished, request);
    }
    #onLoadingFailed(client, event) {
        const queuedEvents = this.#networkEventManager.getQueuedEventGroup(event.requestId);
        if (queuedEvents) {
            queuedEvents.loadingFailedEvent = event;
        }
        else {
            this.#emitLoadingFailed(client, event);
        }
    }
    #emitLoadingFailed(client, event) {
        const request = this.#networkEventManager.getRequest(event.requestId);
        if (!request) {
            return;
        }
        this.#adoptCdpSessionIfNeeded(client, request);
        request._failureText = event.errorText;
        const response = request.response();
        if (response) {
            response._resolveBody();
        }
        this.#forgetRequest(request, true);
        this.emit(NetworkManagerEvent.RequestFailed, request);
    }
    #adoptCdpSessionIfNeeded(client, request) {
        if (client !== request.client) {
            request.client = client;
        }
    }
};

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const TIME_FOR_WAITING_FOR_SWAP = 100;
let FrameManager$1 = class FrameManager extends EventEmitter {
    #page;
    #networkManager;
    #timeoutSettings;
    #isolatedWorlds = new Set();
    #client;
    #scriptsToEvaluateOnNewDocument = new Map();
    #bindings = new Set();
    _frameTree = new FrameTree();
    #frameNavigatedReceived = new Set();
    #deviceRequestPromptManagerMap = new WeakMap();
    #frameTreeHandled;
    get timeoutSettings() {
        return this.#timeoutSettings;
    }
    get networkManager() {
        return this.#networkManager;
    }
    get client() {
        return this.#client;
    }
    constructor(client, page, timeoutSettings) {
        super();
        this.#client = client;
        this.#page = page;
        this.#networkManager = new NetworkManager$1(this, page.browser().isNetworkEnabled());
        this.#timeoutSettings = timeoutSettings;
        this.setupEventListeners(this.#client);
        client.once(CDPSessionEvent.Disconnected, () => {
            this.#onClientDisconnect().catch(debugError);
        });
    }
    async #onClientDisconnect() {
        const mainFrame = this._frameTree.getMainFrame();
        if (!mainFrame) {
            return;
        }
        if (!this.#page.browser().connected) {
            this.#removeFramesRecursively(mainFrame);
            return;
        }
        for (const child of mainFrame.childFrames()) {
            this.#removeFramesRecursively(child);
        }
        const swapped = Deferred.create({
            timeout: TIME_FOR_WAITING_FOR_SWAP,
            message: 'Frame was not swapped',
        });
        mainFrame.once(FrameEvent.FrameSwappedByActivation, () => {
            swapped.resolve();
        });
        try {
            await swapped.valueOrThrow();
        }
        catch {
            this.#removeFramesRecursively(mainFrame);
        }
    }
    async swapFrameTree(client) {
        this.#client = client;
        const frame = this._frameTree.getMainFrame();
        if (frame) {
            this.#frameNavigatedReceived.add(this.#client.target()._targetId);
            this._frameTree.removeFrame(frame);
            frame.updateId(this.#client.target()._targetId);
            this._frameTree.addFrame(frame);
            frame.updateClient(client);
        }
        this.setupEventListeners(client);
        client.once(CDPSessionEvent.Disconnected, () => {
            this.#onClientDisconnect().catch(debugError);
        });
        await this.initialize(client, frame);
        await this.#networkManager.addClient(client);
        if (frame) {
            frame.emit(FrameEvent.FrameSwappedByActivation, undefined);
        }
    }
    async registerSpeculativeSession(client) {
        await this.#networkManager.addClient(client);
    }
    setupEventListeners(session) {
        session.on('Page.frameAttached', async (event) => {
            await this.#frameTreeHandled?.valueOrThrow();
            this.#onFrameAttached(session, event.frameId, event.parentFrameId);
        });
        session.on('Page.frameNavigated', async (event) => {
            this.#frameNavigatedReceived.add(event.frame.id);
            await this.#frameTreeHandled?.valueOrThrow();
            void this.#onFrameNavigated(event.frame, event.type);
        });
        session.on('Page.navigatedWithinDocument', async (event) => {
            await this.#frameTreeHandled?.valueOrThrow();
            this.#onFrameNavigatedWithinDocument(event.frameId, event.url);
        });
        session.on('Page.frameDetached', async (event) => {
            await this.#frameTreeHandled?.valueOrThrow();
            this.#onFrameDetached(event.frameId, event.reason);
        });
        session.on('Page.frameStartedLoading', async (event) => {
            await this.#frameTreeHandled?.valueOrThrow();
            this.#onFrameStartedLoading(event.frameId);
        });
        session.on('Page.frameStoppedLoading', async (event) => {
            await this.#frameTreeHandled?.valueOrThrow();
            this.#onFrameStoppedLoading(event.frameId);
        });
        session.on('Runtime.executionContextCreated', async (event) => {
            await this.#frameTreeHandled?.valueOrThrow();
            this.#onExecutionContextCreated(event.context, session);
        });
        session.on('Page.lifecycleEvent', async (event) => {
            await this.#frameTreeHandled?.valueOrThrow();
            this.#onLifecycleEvent(event);
        });
    }
    async initialize(client, frame) {
        try {
            this.#frameTreeHandled?.resolve();
            this.#frameTreeHandled = Deferred.create();
            await Promise.all([
                this.#networkManager.addClient(client),
                client.send('Page.enable'),
                client.send('Page.getFrameTree').then(({ frameTree }) => {
                    this.#handleFrameTree(client, frameTree);
                    this.#frameTreeHandled?.resolve();
                }),
                client.send('Page.setLifecycleEventsEnabled', { enabled: true }),
                client.send('Runtime.enable').then(() => {
                    return this.#createIsolatedWorld(client, UTILITY_WORLD_NAME);
                }),
                ...(frame
                    ? Array.from(this.#scriptsToEvaluateOnNewDocument.values())
                    : []).map(script => {
                    return frame?.addPreloadScript(script);
                }),
                ...(frame ? Array.from(this.#bindings.values()) : []).map(binding => {
                    return frame?.addExposedFunctionBinding(binding);
                }),
            ]);
        }
        catch (error) {
            this.#frameTreeHandled?.resolve();
            if (isErrorLike$1(error) && isTargetClosedError(error)) {
                return;
            }
            throw error;
        }
    }
    page() {
        return this.#page;
    }
    mainFrame() {
        const mainFrame = this._frameTree.getMainFrame();
        assert(mainFrame, 'Requesting main frame too early!');
        return mainFrame;
    }
    frames() {
        return Array.from(this._frameTree.frames());
    }
    frame(frameId) {
        return this._frameTree.getById(frameId) || null;
    }
    async addExposedFunctionBinding(binding) {
        this.#bindings.add(binding);
        await Promise.all(this.frames().map(async (frame) => {
            return await frame.addExposedFunctionBinding(binding);
        }));
    }
    async removeExposedFunctionBinding(binding) {
        this.#bindings.delete(binding);
        await Promise.all(this.frames().map(async (frame) => {
            return await frame.removeExposedFunctionBinding(binding);
        }));
    }
    async evaluateOnNewDocument(source) {
        const { identifier } = await this.mainFrame()
            ._client()
            .send('Page.addScriptToEvaluateOnNewDocument', {
            source,
        });
        const preloadScript = new CdpPreloadScript(this.mainFrame(), identifier, source);
        this.#scriptsToEvaluateOnNewDocument.set(identifier, preloadScript);
        await Promise.all(this.frames().map(async (frame) => {
            return await frame.addPreloadScript(preloadScript);
        }));
        return { identifier };
    }
    async removeScriptToEvaluateOnNewDocument(identifier) {
        const preloadScript = this.#scriptsToEvaluateOnNewDocument.get(identifier);
        if (!preloadScript) {
            throw new Error(`Script to evaluate on new document with id ${identifier} not found`);
        }
        this.#scriptsToEvaluateOnNewDocument.delete(identifier);
        await Promise.all(this.frames().map(frame => {
            const identifier = preloadScript.getIdForFrame(frame);
            if (!identifier) {
                return;
            }
            return frame
                ._client()
                .send('Page.removeScriptToEvaluateOnNewDocument', {
                identifier,
            })
                .catch(debugError);
        }));
    }
    onAttachedToTarget(target) {
        if (target._getTargetInfo().type !== 'iframe') {
            return;
        }
        const frame = this.frame(target._getTargetInfo().targetId);
        if (frame) {
            frame.updateClient(target._session());
        }
        this.setupEventListeners(target._session());
        void this.initialize(target._session(), frame).catch(debugError);
    }
    _deviceRequestPromptManager(client) {
        let manager = this.#deviceRequestPromptManagerMap.get(client);
        if (manager === undefined) {
            manager = new CdpDeviceRequestPromptManager(client, this.#timeoutSettings);
            this.#deviceRequestPromptManagerMap.set(client, manager);
        }
        return manager;
    }
    #onLifecycleEvent(event) {
        const frame = this.frame(event.frameId);
        if (!frame) {
            return;
        }
        frame._onLifecycleEvent(event.loaderId, event.name);
        this.emit(FrameManagerEvent.LifecycleEvent, frame);
        frame.emit(FrameEvent.LifecycleEvent, undefined);
    }
    #onFrameStartedLoading(frameId) {
        const frame = this.frame(frameId);
        if (!frame) {
            return;
        }
        frame._onLoadingStarted();
    }
    #onFrameStoppedLoading(frameId) {
        const frame = this.frame(frameId);
        if (!frame) {
            return;
        }
        frame._onLoadingStopped();
        this.emit(FrameManagerEvent.LifecycleEvent, frame);
        frame.emit(FrameEvent.LifecycleEvent, undefined);
    }
    #handleFrameTree(session, frameTree) {
        if (frameTree.frame.parentId) {
            this.#onFrameAttached(session, frameTree.frame.id, frameTree.frame.parentId);
        }
        if (!this.#frameNavigatedReceived.has(frameTree.frame.id)) {
            void this.#onFrameNavigated(frameTree.frame, 'Navigation');
        }
        else {
            this.#frameNavigatedReceived.delete(frameTree.frame.id);
        }
        if (!frameTree.childFrames) {
            return;
        }
        for (const child of frameTree.childFrames) {
            this.#handleFrameTree(session, child);
        }
    }
    #onFrameAttached(session, frameId, parentFrameId) {
        let frame = this.frame(frameId);
        if (frame) {
            const parentFrame = this.frame(parentFrameId);
            if (session && parentFrame && frame.client !== parentFrame?.client) {
                frame.updateClient(session);
            }
            return;
        }
        frame = new CdpFrame(this, frameId, parentFrameId, session);
        this._frameTree.addFrame(frame);
        this.emit(FrameManagerEvent.FrameAttached, frame);
    }
    async #onFrameNavigated(framePayload, navigationType) {
        const frameId = framePayload.id;
        const isMainFrame = !framePayload.parentId;
        let frame = this._frameTree.getById(frameId);
        if (frame) {
            for (const child of frame.childFrames()) {
                this.#removeFramesRecursively(child);
            }
        }
        if (isMainFrame) {
            if (frame) {
                this._frameTree.removeFrame(frame);
                frame._id = frameId;
            }
            else {
                frame = new CdpFrame(this, frameId, undefined, this.#client);
            }
            this._frameTree.addFrame(frame);
        }
        frame = await this._frameTree.waitForFrame(frameId);
        frame._navigated(framePayload);
        this.emit(FrameManagerEvent.FrameNavigated, frame);
        frame.emit(FrameEvent.FrameNavigated, navigationType);
    }
    async #createIsolatedWorld(session, name) {
        const key = `${session.id()}:${name}`;
        if (this.#isolatedWorlds.has(key)) {
            return;
        }
        await session.send('Page.addScriptToEvaluateOnNewDocument', {
            source: `//# sourceURL=${PuppeteerURL.INTERNAL_URL}`,
            worldName: name,
        });
        await Promise.all(this.frames()
            .filter(frame => {
            return frame.client === session;
        })
            .map(frame => {
            return session
                .send('Page.createIsolatedWorld', {
                frameId: frame._id,
                worldName: name,
                grantUniveralAccess: true,
            })
                .catch(debugError);
        }));
        this.#isolatedWorlds.add(key);
    }
    #onFrameNavigatedWithinDocument(frameId, url) {
        const frame = this.frame(frameId);
        if (!frame) {
            return;
        }
        frame._navigatedWithinDocument(url);
        this.emit(FrameManagerEvent.FrameNavigatedWithinDocument, frame);
        frame.emit(FrameEvent.FrameNavigatedWithinDocument, undefined);
        this.emit(FrameManagerEvent.FrameNavigated, frame);
        frame.emit(FrameEvent.FrameNavigated, 'Navigation');
    }
    #onFrameDetached(frameId, reason) {
        const frame = this.frame(frameId);
        if (!frame) {
            return;
        }
        switch (reason) {
            case 'remove':
                this.#removeFramesRecursively(frame);
                break;
            case 'swap':
                this.emit(FrameManagerEvent.FrameSwapped, frame);
                frame.emit(FrameEvent.FrameSwapped, undefined);
                break;
        }
    }
    #onExecutionContextCreated(contextPayload, session) {
        const auxData = contextPayload.auxData;
        const frameId = auxData && auxData.frameId;
        const frame = typeof frameId === 'string' ? this.frame(frameId) : undefined;
        let world;
        if (frame) {
            if (frame.client !== session) {
                return;
            }
            if (contextPayload.auxData && contextPayload.auxData['isDefault']) {
                world = frame.worlds[MAIN_WORLD];
            }
            else if (contextPayload.name === UTILITY_WORLD_NAME) {
                world = frame.worlds[PUPPETEER_WORLD];
            }
        }
        if (!world) {
            return;
        }
        const context = new ExecutionContext$1(frame?.client || this.#client, contextPayload, world);
        world.setContext(context);
    }
    #removeFramesRecursively(frame) {
        for (const child of frame.childFrames()) {
            this.#removeFramesRecursively(child);
        }
        frame[disposeSymbol]();
        this._frameTree.removeFrame(frame);
        this.emit(FrameManagerEvent.FrameDetached, frame);
        frame.emit(FrameEvent.FrameDetached, frame);
    }
};

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const _keyDefinitions = {
    '0': { keyCode: 48, key: '0', code: 'Digit0' },
    '1': { keyCode: 49, key: '1', code: 'Digit1' },
    '2': { keyCode: 50, key: '2', code: 'Digit2' },
    '3': { keyCode: 51, key: '3', code: 'Digit3' },
    '4': { keyCode: 52, key: '4', code: 'Digit4' },
    '5': { keyCode: 53, key: '5', code: 'Digit5' },
    '6': { keyCode: 54, key: '6', code: 'Digit6' },
    '7': { keyCode: 55, key: '7', code: 'Digit7' },
    '8': { keyCode: 56, key: '8', code: 'Digit8' },
    '9': { keyCode: 57, key: '9', code: 'Digit9' },
    Power: { key: 'Power', code: 'Power' },
    Eject: { key: 'Eject', code: 'Eject' },
    Abort: { keyCode: 3, code: 'Abort', key: 'Cancel' },
    Help: { keyCode: 6, code: 'Help', key: 'Help' },
    Backspace: { keyCode: 8, code: 'Backspace', key: 'Backspace' },
    Tab: { keyCode: 9, code: 'Tab', key: 'Tab' },
    Numpad5: {
        keyCode: 12,
        shiftKeyCode: 101,
        key: 'Clear',
        code: 'Numpad5',
        shiftKey: '5',
        location: 3,
    },
    NumpadEnter: {
        keyCode: 13,
        code: 'NumpadEnter',
        key: 'Enter',
        text: '\r',
        location: 3,
    },
    Enter: { keyCode: 13, code: 'Enter', key: 'Enter', text: '\r' },
    '\r': { keyCode: 13, code: 'Enter', key: 'Enter', text: '\r' },
    '\n': { keyCode: 13, code: 'Enter', key: 'Enter', text: '\r' },
    ShiftLeft: { keyCode: 16, code: 'ShiftLeft', key: 'Shift', location: 1 },
    ShiftRight: { keyCode: 16, code: 'ShiftRight', key: 'Shift', location: 2 },
    ControlLeft: {
        keyCode: 17,
        code: 'ControlLeft',
        key: 'Control',
        location: 1,
    },
    ControlRight: {
        keyCode: 17,
        code: 'ControlRight',
        key: 'Control',
        location: 2,
    },
    AltLeft: { keyCode: 18, code: 'AltLeft', key: 'Alt', location: 1 },
    AltRight: { keyCode: 18, code: 'AltRight', key: 'Alt', location: 2 },
    Pause: { keyCode: 19, code: 'Pause', key: 'Pause' },
    CapsLock: { keyCode: 20, code: 'CapsLock', key: 'CapsLock' },
    Escape: { keyCode: 27, code: 'Escape', key: 'Escape' },
    Convert: { keyCode: 28, code: 'Convert', key: 'Convert' },
    NonConvert: { keyCode: 29, code: 'NonConvert', key: 'NonConvert' },
    Space: { keyCode: 32, code: 'Space', key: ' ' },
    Numpad9: {
        keyCode: 33,
        shiftKeyCode: 105,
        key: 'PageUp',
        code: 'Numpad9',
        shiftKey: '9',
        location: 3,
    },
    PageUp: { keyCode: 33, code: 'PageUp', key: 'PageUp' },
    Numpad3: {
        keyCode: 34,
        shiftKeyCode: 99,
        key: 'PageDown',
        code: 'Numpad3',
        shiftKey: '3',
        location: 3,
    },
    PageDown: { keyCode: 34, code: 'PageDown', key: 'PageDown' },
    End: { keyCode: 35, code: 'End', key: 'End' },
    Numpad1: {
        keyCode: 35,
        shiftKeyCode: 97,
        key: 'End',
        code: 'Numpad1',
        shiftKey: '1',
        location: 3,
    },
    Home: { keyCode: 36, code: 'Home', key: 'Home' },
    Numpad7: {
        keyCode: 36,
        shiftKeyCode: 103,
        key: 'Home',
        code: 'Numpad7',
        shiftKey: '7',
        location: 3,
    },
    ArrowLeft: { keyCode: 37, code: 'ArrowLeft', key: 'ArrowLeft' },
    Numpad4: {
        keyCode: 37,
        shiftKeyCode: 100,
        key: 'ArrowLeft',
        code: 'Numpad4',
        shiftKey: '4',
        location: 3,
    },
    Numpad8: {
        keyCode: 38,
        shiftKeyCode: 104,
        key: 'ArrowUp',
        code: 'Numpad8',
        shiftKey: '8',
        location: 3,
    },
    ArrowUp: { keyCode: 38, code: 'ArrowUp', key: 'ArrowUp' },
    ArrowRight: { keyCode: 39, code: 'ArrowRight', key: 'ArrowRight' },
    Numpad6: {
        keyCode: 39,
        shiftKeyCode: 102,
        key: 'ArrowRight',
        code: 'Numpad6',
        shiftKey: '6',
        location: 3,
    },
    Numpad2: {
        keyCode: 40,
        shiftKeyCode: 98,
        key: 'ArrowDown',
        code: 'Numpad2',
        shiftKey: '2',
        location: 3,
    },
    ArrowDown: { keyCode: 40, code: 'ArrowDown', key: 'ArrowDown' },
    Select: { keyCode: 41, code: 'Select', key: 'Select' },
    Open: { keyCode: 43, code: 'Open', key: 'Execute' },
    PrintScreen: { keyCode: 44, code: 'PrintScreen', key: 'PrintScreen' },
    Insert: { keyCode: 45, code: 'Insert', key: 'Insert' },
    Numpad0: {
        keyCode: 45,
        shiftKeyCode: 96,
        key: 'Insert',
        code: 'Numpad0',
        shiftKey: '0',
        location: 3,
    },
    Delete: { keyCode: 46, code: 'Delete', key: 'Delete' },
    NumpadDecimal: {
        keyCode: 46,
        shiftKeyCode: 110,
        code: 'NumpadDecimal',
        key: '\u0000',
        shiftKey: '.',
        location: 3,
    },
    Digit0: { keyCode: 48, code: 'Digit0', shiftKey: ')', key: '0' },
    Digit1: { keyCode: 49, code: 'Digit1', shiftKey: '!', key: '1' },
    Digit2: { keyCode: 50, code: 'Digit2', shiftKey: '@', key: '2' },
    Digit3: { keyCode: 51, code: 'Digit3', shiftKey: '#', key: '3' },
    Digit4: { keyCode: 52, code: 'Digit4', shiftKey: '$', key: '4' },
    Digit5: { keyCode: 53, code: 'Digit5', shiftKey: '%', key: '5' },
    Digit6: { keyCode: 54, code: 'Digit6', shiftKey: '^', key: '6' },
    Digit7: { keyCode: 55, code: 'Digit7', shiftKey: '&', key: '7' },
    Digit8: { keyCode: 56, code: 'Digit8', shiftKey: '*', key: '8' },
    Digit9: { keyCode: 57, code: 'Digit9', shiftKey: '(', key: '9' },
    KeyA: { keyCode: 65, code: 'KeyA', shiftKey: 'A', key: 'a' },
    KeyB: { keyCode: 66, code: 'KeyB', shiftKey: 'B', key: 'b' },
    KeyC: { keyCode: 67, code: 'KeyC', shiftKey: 'C', key: 'c' },
    KeyD: { keyCode: 68, code: 'KeyD', shiftKey: 'D', key: 'd' },
    KeyE: { keyCode: 69, code: 'KeyE', shiftKey: 'E', key: 'e' },
    KeyF: { keyCode: 70, code: 'KeyF', shiftKey: 'F', key: 'f' },
    KeyG: { keyCode: 71, code: 'KeyG', shiftKey: 'G', key: 'g' },
    KeyH: { keyCode: 72, code: 'KeyH', shiftKey: 'H', key: 'h' },
    KeyI: { keyCode: 73, code: 'KeyI', shiftKey: 'I', key: 'i' },
    KeyJ: { keyCode: 74, code: 'KeyJ', shiftKey: 'J', key: 'j' },
    KeyK: { keyCode: 75, code: 'KeyK', shiftKey: 'K', key: 'k' },
    KeyL: { keyCode: 76, code: 'KeyL', shiftKey: 'L', key: 'l' },
    KeyM: { keyCode: 77, code: 'KeyM', shiftKey: 'M', key: 'm' },
    KeyN: { keyCode: 78, code: 'KeyN', shiftKey: 'N', key: 'n' },
    KeyO: { keyCode: 79, code: 'KeyO', shiftKey: 'O', key: 'o' },
    KeyP: { keyCode: 80, code: 'KeyP', shiftKey: 'P', key: 'p' },
    KeyQ: { keyCode: 81, code: 'KeyQ', shiftKey: 'Q', key: 'q' },
    KeyR: { keyCode: 82, code: 'KeyR', shiftKey: 'R', key: 'r' },
    KeyS: { keyCode: 83, code: 'KeyS', shiftKey: 'S', key: 's' },
    KeyT: { keyCode: 84, code: 'KeyT', shiftKey: 'T', key: 't' },
    KeyU: { keyCode: 85, code: 'KeyU', shiftKey: 'U', key: 'u' },
    KeyV: { keyCode: 86, code: 'KeyV', shiftKey: 'V', key: 'v' },
    KeyW: { keyCode: 87, code: 'KeyW', shiftKey: 'W', key: 'w' },
    KeyX: { keyCode: 88, code: 'KeyX', shiftKey: 'X', key: 'x' },
    KeyY: { keyCode: 89, code: 'KeyY', shiftKey: 'Y', key: 'y' },
    KeyZ: { keyCode: 90, code: 'KeyZ', shiftKey: 'Z', key: 'z' },
    MetaLeft: { keyCode: 91, code: 'MetaLeft', key: 'Meta', location: 1 },
    MetaRight: { keyCode: 92, code: 'MetaRight', key: 'Meta', location: 2 },
    ContextMenu: { keyCode: 93, code: 'ContextMenu', key: 'ContextMenu' },
    NumpadMultiply: {
        keyCode: 106,
        code: 'NumpadMultiply',
        key: '*',
        location: 3,
    },
    NumpadAdd: { keyCode: 107, code: 'NumpadAdd', key: '+', location: 3 },
    NumpadSubtract: {
        keyCode: 109,
        code: 'NumpadSubtract',
        key: '-',
        location: 3,
    },
    NumpadDivide: { keyCode: 111, code: 'NumpadDivide', key: '/', location: 3 },
    F1: { keyCode: 112, code: 'F1', key: 'F1' },
    F2: { keyCode: 113, code: 'F2', key: 'F2' },
    F3: { keyCode: 114, code: 'F3', key: 'F3' },
    F4: { keyCode: 115, code: 'F4', key: 'F4' },
    F5: { keyCode: 116, code: 'F5', key: 'F5' },
    F6: { keyCode: 117, code: 'F6', key: 'F6' },
    F7: { keyCode: 118, code: 'F7', key: 'F7' },
    F8: { keyCode: 119, code: 'F8', key: 'F8' },
    F9: { keyCode: 120, code: 'F9', key: 'F9' },
    F10: { keyCode: 121, code: 'F10', key: 'F10' },
    F11: { keyCode: 122, code: 'F11', key: 'F11' },
    F12: { keyCode: 123, code: 'F12', key: 'F12' },
    F13: { keyCode: 124, code: 'F13', key: 'F13' },
    F14: { keyCode: 125, code: 'F14', key: 'F14' },
    F15: { keyCode: 126, code: 'F15', key: 'F15' },
    F16: { keyCode: 127, code: 'F16', key: 'F16' },
    F17: { keyCode: 128, code: 'F17', key: 'F17' },
    F18: { keyCode: 129, code: 'F18', key: 'F18' },
    F19: { keyCode: 130, code: 'F19', key: 'F19' },
    F20: { keyCode: 131, code: 'F20', key: 'F20' },
    F21: { keyCode: 132, code: 'F21', key: 'F21' },
    F22: { keyCode: 133, code: 'F22', key: 'F22' },
    F23: { keyCode: 134, code: 'F23', key: 'F23' },
    F24: { keyCode: 135, code: 'F24', key: 'F24' },
    NumLock: { keyCode: 144, code: 'NumLock', key: 'NumLock' },
    ScrollLock: { keyCode: 145, code: 'ScrollLock', key: 'ScrollLock' },
    AudioVolumeMute: {
        keyCode: 173,
        code: 'AudioVolumeMute',
        key: 'AudioVolumeMute',
    },
    AudioVolumeDown: {
        keyCode: 174,
        code: 'AudioVolumeDown',
        key: 'AudioVolumeDown',
    },
    AudioVolumeUp: { keyCode: 175, code: 'AudioVolumeUp', key: 'AudioVolumeUp' },
    MediaTrackNext: {
        keyCode: 176,
        code: 'MediaTrackNext',
        key: 'MediaTrackNext',
    },
    MediaTrackPrevious: {
        keyCode: 177,
        code: 'MediaTrackPrevious',
        key: 'MediaTrackPrevious',
    },
    MediaStop: { keyCode: 178, code: 'MediaStop', key: 'MediaStop' },
    MediaPlayPause: {
        keyCode: 179,
        code: 'MediaPlayPause',
        key: 'MediaPlayPause',
    },
    Semicolon: { keyCode: 186, code: 'Semicolon', shiftKey: ':', key: ';' },
    Equal: { keyCode: 187, code: 'Equal', shiftKey: '+', key: '=' },
    NumpadEqual: { keyCode: 187, code: 'NumpadEqual', key: '=', location: 3 },
    Comma: { keyCode: 188, code: 'Comma', shiftKey: '<', key: ',' },
    Minus: { keyCode: 189, code: 'Minus', shiftKey: '_', key: '-' },
    Period: { keyCode: 190, code: 'Period', shiftKey: '>', key: '.' },
    Slash: { keyCode: 191, code: 'Slash', shiftKey: '?', key: '/' },
    Backquote: { keyCode: 192, code: 'Backquote', shiftKey: '~', key: '`' },
    BracketLeft: { keyCode: 219, code: 'BracketLeft', shiftKey: '{', key: '[' },
    Backslash: { keyCode: 220, code: 'Backslash', shiftKey: '|', key: '\\' },
    BracketRight: { keyCode: 221, code: 'BracketRight', shiftKey: '}', key: ']' },
    Quote: { keyCode: 222, code: 'Quote', shiftKey: '"', key: "'" },
    AltGraph: { keyCode: 225, code: 'AltGraph', key: 'AltGraph' },
    Props: { keyCode: 247, code: 'Props', key: 'CrSel' },
    Cancel: { keyCode: 3, key: 'Cancel', code: 'Abort' },
    Clear: { keyCode: 12, key: 'Clear', code: 'Numpad5', location: 3 },
    Shift: { keyCode: 16, key: 'Shift', code: 'ShiftLeft', location: 1 },
    Control: { keyCode: 17, key: 'Control', code: 'ControlLeft', location: 1 },
    Alt: { keyCode: 18, key: 'Alt', code: 'AltLeft', location: 1 },
    Accept: { keyCode: 30, key: 'Accept' },
    ModeChange: { keyCode: 31, key: 'ModeChange' },
    ' ': { keyCode: 32, key: ' ', code: 'Space' },
    Print: { keyCode: 42, key: 'Print' },
    Execute: { keyCode: 43, key: 'Execute', code: 'Open' },
    '\u0000': { keyCode: 46, key: '\u0000', code: 'NumpadDecimal', location: 3 },
    a: { keyCode: 65, key: 'a', code: 'KeyA' },
    b: { keyCode: 66, key: 'b', code: 'KeyB' },
    c: { keyCode: 67, key: 'c', code: 'KeyC' },
    d: { keyCode: 68, key: 'd', code: 'KeyD' },
    e: { keyCode: 69, key: 'e', code: 'KeyE' },
    f: { keyCode: 70, key: 'f', code: 'KeyF' },
    g: { keyCode: 71, key: 'g', code: 'KeyG' },
    h: { keyCode: 72, key: 'h', code: 'KeyH' },
    i: { keyCode: 73, key: 'i', code: 'KeyI' },
    j: { keyCode: 74, key: 'j', code: 'KeyJ' },
    k: { keyCode: 75, key: 'k', code: 'KeyK' },
    l: { keyCode: 76, key: 'l', code: 'KeyL' },
    m: { keyCode: 77, key: 'm', code: 'KeyM' },
    n: { keyCode: 78, key: 'n', code: 'KeyN' },
    o: { keyCode: 79, key: 'o', code: 'KeyO' },
    p: { keyCode: 80, key: 'p', code: 'KeyP' },
    q: { keyCode: 81, key: 'q', code: 'KeyQ' },
    r: { keyCode: 82, key: 'r', code: 'KeyR' },
    s: { keyCode: 83, key: 's', code: 'KeyS' },
    t: { keyCode: 84, key: 't', code: 'KeyT' },
    u: { keyCode: 85, key: 'u', code: 'KeyU' },
    v: { keyCode: 86, key: 'v', code: 'KeyV' },
    w: { keyCode: 87, key: 'w', code: 'KeyW' },
    x: { keyCode: 88, key: 'x', code: 'KeyX' },
    y: { keyCode: 89, key: 'y', code: 'KeyY' },
    z: { keyCode: 90, key: 'z', code: 'KeyZ' },
    Meta: { keyCode: 91, key: 'Meta', code: 'MetaLeft', location: 1 },
    '*': { keyCode: 106, key: '*', code: 'NumpadMultiply', location: 3 },
    '+': { keyCode: 107, key: '+', code: 'NumpadAdd', location: 3 },
    '-': { keyCode: 109, key: '-', code: 'NumpadSubtract', location: 3 },
    '/': { keyCode: 111, key: '/', code: 'NumpadDivide', location: 3 },
    ';': { keyCode: 186, key: ';', code: 'Semicolon' },
    '=': { keyCode: 187, key: '=', code: 'Equal' },
    ',': { keyCode: 188, key: ',', code: 'Comma' },
    '.': { keyCode: 190, key: '.', code: 'Period' },
    '`': { keyCode: 192, key: '`', code: 'Backquote' },
    '[': { keyCode: 219, key: '[', code: 'BracketLeft' },
    '\\': { keyCode: 220, key: '\\', code: 'Backslash' },
    ']': { keyCode: 221, key: ']', code: 'BracketRight' },
    "'": { keyCode: 222, key: "'", code: 'Quote' },
    Attn: { keyCode: 246, key: 'Attn' },
    CrSel: { keyCode: 247, key: 'CrSel', code: 'Props' },
    ExSel: { keyCode: 248, key: 'ExSel' },
    EraseEof: { keyCode: 249, key: 'EraseEof' },
    Play: { keyCode: 250, key: 'Play' },
    ZoomOut: { keyCode: 251, key: 'ZoomOut' },
    ')': { keyCode: 48, key: ')', code: 'Digit0' },
    '!': { keyCode: 49, key: '!', code: 'Digit1' },
    '@': { keyCode: 50, key: '@', code: 'Digit2' },
    '#': { keyCode: 51, key: '#', code: 'Digit3' },
    $: { keyCode: 52, key: '$', code: 'Digit4' },
    '%': { keyCode: 53, key: '%', code: 'Digit5' },
    '^': { keyCode: 54, key: '^', code: 'Digit6' },
    '&': { keyCode: 55, key: '&', code: 'Digit7' },
    '(': { keyCode: 57, key: '(', code: 'Digit9' },
    A: { keyCode: 65, key: 'A', code: 'KeyA' },
    B: { keyCode: 66, key: 'B', code: 'KeyB' },
    C: { keyCode: 67, key: 'C', code: 'KeyC' },
    D: { keyCode: 68, key: 'D', code: 'KeyD' },
    E: { keyCode: 69, key: 'E', code: 'KeyE' },
    F: { keyCode: 70, key: 'F', code: 'KeyF' },
    G: { keyCode: 71, key: 'G', code: 'KeyG' },
    H: { keyCode: 72, key: 'H', code: 'KeyH' },
    I: { keyCode: 73, key: 'I', code: 'KeyI' },
    J: { keyCode: 74, key: 'J', code: 'KeyJ' },
    K: { keyCode: 75, key: 'K', code: 'KeyK' },
    L: { keyCode: 76, key: 'L', code: 'KeyL' },
    M: { keyCode: 77, key: 'M', code: 'KeyM' },
    N: { keyCode: 78, key: 'N', code: 'KeyN' },
    O: { keyCode: 79, key: 'O', code: 'KeyO' },
    P: { keyCode: 80, key: 'P', code: 'KeyP' },
    Q: { keyCode: 81, key: 'Q', code: 'KeyQ' },
    R: { keyCode: 82, key: 'R', code: 'KeyR' },
    S: { keyCode: 83, key: 'S', code: 'KeyS' },
    T: { keyCode: 84, key: 'T', code: 'KeyT' },
    U: { keyCode: 85, key: 'U', code: 'KeyU' },
    V: { keyCode: 86, key: 'V', code: 'KeyV' },
    W: { keyCode: 87, key: 'W', code: 'KeyW' },
    X: { keyCode: 88, key: 'X', code: 'KeyX' },
    Y: { keyCode: 89, key: 'Y', code: 'KeyY' },
    Z: { keyCode: 90, key: 'Z', code: 'KeyZ' },
    ':': { keyCode: 186, key: ':', code: 'Semicolon' },
    '<': { keyCode: 188, key: '<', code: 'Comma' },
    _: { keyCode: 189, key: '_', code: 'Minus' },
    '>': { keyCode: 190, key: '>', code: 'Period' },
    '?': { keyCode: 191, key: '?', code: 'Slash' },
    '~': { keyCode: 192, key: '~', code: 'Backquote' },
    '{': { keyCode: 219, key: '{', code: 'BracketLeft' },
    '|': { keyCode: 220, key: '|', code: 'Backslash' },
    '}': { keyCode: 221, key: '}', code: 'BracketRight' },
    '"': { keyCode: 222, key: '"', code: 'Quote' },
    SoftLeft: { key: 'SoftLeft', code: 'SoftLeft', location: 4 },
    SoftRight: { key: 'SoftRight', code: 'SoftRight', location: 4 },
    Camera: { keyCode: 44, key: 'Camera', code: 'Camera', location: 4 },
    Call: { key: 'Call', code: 'Call', location: 4 },
    EndCall: { keyCode: 95, key: 'EndCall', code: 'EndCall', location: 4 },
    VolumeDown: {
        keyCode: 182,
        key: 'VolumeDown',
        code: 'VolumeDown',
        location: 4,
    },
    VolumeUp: { keyCode: 183, key: 'VolumeUp', code: 'VolumeUp', location: 4 },
};

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class CdpKeyboard extends Keyboard {
    #client;
    #pressedKeys = new Set();
    _modifiers = 0;
    constructor(client) {
        super();
        this.#client = client;
    }
    updateClient(client) {
        this.#client = client;
    }
    async down(key, options = {
        text: undefined,
        commands: [],
    }) {
        const description = this.#keyDescriptionForString(key);
        const autoRepeat = this.#pressedKeys.has(description.code);
        this.#pressedKeys.add(description.code);
        this._modifiers |= this.#modifierBit(description.key);
        const text = options.text === undefined ? description.text : options.text;
        await this.#client.send('Input.dispatchKeyEvent', {
            type: text ? 'keyDown' : 'rawKeyDown',
            modifiers: this._modifiers,
            windowsVirtualKeyCode: description.keyCode,
            code: description.code,
            key: description.key,
            text: text,
            unmodifiedText: text,
            autoRepeat,
            location: description.location,
            isKeypad: description.location === 3,
            commands: options.commands,
        });
    }
    #modifierBit(key) {
        if (key === 'Alt') {
            return 1;
        }
        if (key === 'Control') {
            return 2;
        }
        if (key === 'Meta') {
            return 4;
        }
        if (key === 'Shift') {
            return 8;
        }
        return 0;
    }
    #keyDescriptionForString(keyString) {
        const shift = this._modifiers & 8;
        const description = {
            key: '',
            keyCode: 0,
            code: '',
            text: '',
            location: 0,
        };
        const definition = _keyDefinitions[keyString];
        assert(definition, `Unknown key: "${keyString}"`);
        if (definition.key) {
            description.key = definition.key;
        }
        if (shift && definition.shiftKey) {
            description.key = definition.shiftKey;
        }
        if (definition.keyCode) {
            description.keyCode = definition.keyCode;
        }
        if (shift && definition.shiftKeyCode) {
            description.keyCode = definition.shiftKeyCode;
        }
        if (definition.code) {
            description.code = definition.code;
        }
        if (definition.location) {
            description.location = definition.location;
        }
        if (description.key.length === 1) {
            description.text = description.key;
        }
        if (definition.text) {
            description.text = definition.text;
        }
        if (shift && definition.shiftText) {
            description.text = definition.shiftText;
        }
        if (this._modifiers & -9) {
            description.text = '';
        }
        return description;
    }
    async up(key) {
        const description = this.#keyDescriptionForString(key);
        this._modifiers &= ~this.#modifierBit(description.key);
        this.#pressedKeys.delete(description.code);
        await this.#client.send('Input.dispatchKeyEvent', {
            type: 'keyUp',
            modifiers: this._modifiers,
            key: description.key,
            windowsVirtualKeyCode: description.keyCode,
            code: description.code,
            location: description.location,
        });
    }
    async sendCharacter(char) {
        await this.#client.send('Input.insertText', { text: char });
    }
    charIsKey(char) {
        return !!_keyDefinitions[char];
    }
    async type(text, options = {}) {
        const delay = options.delay || undefined;
        for (const char of text) {
            if (this.charIsKey(char)) {
                await this.press(char, { delay });
            }
            else {
                if (delay) {
                    await new Promise(f => {
                        return setTimeout(f, delay);
                    });
                }
                await this.sendCharacter(char);
            }
        }
    }
    async press(key, options = {}) {
        const { delay = null } = options;
        await this.down(key, options);
        if (delay) {
            await new Promise(f => {
                return setTimeout(f, options.delay);
            });
        }
        await this.up(key);
    }
}
const getFlag = (button) => {
    switch (button) {
        case MouseButton.Left:
            return 1 ;
        case MouseButton.Right:
            return 2 ;
        case MouseButton.Middle:
            return 4 ;
        case MouseButton.Back:
            return 8 ;
        case MouseButton.Forward:
            return 16 ;
    }
};
const getButtonFromPressedButtons = (buttons) => {
    if (buttons & 1 ) {
        return MouseButton.Left;
    }
    else if (buttons & 2 ) {
        return MouseButton.Right;
    }
    else if (buttons & 4 ) {
        return MouseButton.Middle;
    }
    else if (buttons & 8 ) {
        return MouseButton.Back;
    }
    else if (buttons & 16 ) {
        return MouseButton.Forward;
    }
    return 'none';
};
class CdpMouse extends Mouse {
    #client;
    #keyboard;
    constructor(client, keyboard) {
        super();
        this.#client = client;
        this.#keyboard = keyboard;
    }
    updateClient(client) {
        this.#client = client;
    }
    #_state = {
        position: { x: 0, y: 0 },
        buttons: 0 ,
    };
    get #state() {
        return Object.assign({ ...this.#_state }, ...this.#transactions);
    }
    #transactions = [];
    #createTransaction() {
        const transaction = {};
        this.#transactions.push(transaction);
        const popTransaction = () => {
            this.#transactions.splice(this.#transactions.indexOf(transaction), 1);
        };
        return {
            update: (updates) => {
                Object.assign(transaction, updates);
            },
            commit: () => {
                this.#_state = { ...this.#_state, ...transaction };
                popTransaction();
            },
            rollback: popTransaction,
        };
    }
    async #withTransaction(action) {
        const { update, commit, rollback } = this.#createTransaction();
        try {
            await action(update);
            commit();
        }
        catch (error) {
            rollback();
            throw error;
        }
    }
    async reset() {
        const actions = [];
        for (const [flag, button] of [
            [1 , MouseButton.Left],
            [4 , MouseButton.Middle],
            [2 , MouseButton.Right],
            [16 , MouseButton.Forward],
            [8 , MouseButton.Back],
        ]) {
            if (this.#state.buttons & flag) {
                actions.push(this.up({ button: button }));
            }
        }
        if (this.#state.position.x !== 0 || this.#state.position.y !== 0) {
            actions.push(this.move(0, 0));
        }
        await Promise.all(actions);
    }
    async move(x, y, options = {}) {
        const { steps = 1 } = options;
        const from = this.#state.position;
        const to = { x, y };
        for (let i = 1; i <= steps; i++) {
            await this.#withTransaction(updateState => {
                updateState({
                    position: {
                        x: from.x + (to.x - from.x) * (i / steps),
                        y: from.y + (to.y - from.y) * (i / steps),
                    },
                });
                const { buttons, position } = this.#state;
                return this.#client.send('Input.dispatchMouseEvent', {
                    type: 'mouseMoved',
                    modifiers: this.#keyboard._modifiers,
                    buttons,
                    button: getButtonFromPressedButtons(buttons),
                    ...position,
                });
            });
        }
    }
    async down(options = {}) {
        const { button = MouseButton.Left, clickCount = 1 } = options;
        const flag = getFlag(button);
        if (!flag) {
            throw new Error(`Unsupported mouse button: ${button}`);
        }
        if (this.#state.buttons & flag) {
            throw new Error(`'${button}' is already pressed.`);
        }
        await this.#withTransaction(updateState => {
            updateState({
                buttons: this.#state.buttons | flag,
            });
            const { buttons, position } = this.#state;
            return this.#client.send('Input.dispatchMouseEvent', {
                type: 'mousePressed',
                modifiers: this.#keyboard._modifiers,
                clickCount,
                buttons,
                button,
                ...position,
            });
        });
    }
    async up(options = {}) {
        const { button = MouseButton.Left, clickCount = 1 } = options;
        const flag = getFlag(button);
        if (!flag) {
            throw new Error(`Unsupported mouse button: ${button}`);
        }
        if (!(this.#state.buttons & flag)) {
            throw new Error(`'${button}' is not pressed.`);
        }
        await this.#withTransaction(updateState => {
            updateState({
                buttons: this.#state.buttons & ~flag,
            });
            const { buttons, position } = this.#state;
            return this.#client.send('Input.dispatchMouseEvent', {
                type: 'mouseReleased',
                modifiers: this.#keyboard._modifiers,
                clickCount,
                buttons,
                button,
                ...position,
            });
        });
    }
    async click(x, y, options = {}) {
        const { delay, count = 1, clickCount = count } = options;
        if (count < 1) {
            throw new Error('Click must occur a positive number of times.');
        }
        const actions = [this.move(x, y)];
        if (clickCount === count) {
            for (let i = 1; i < count; ++i) {
                actions.push(this.down({ ...options, clickCount: i }), this.up({ ...options, clickCount: i }));
            }
        }
        actions.push(this.down({ ...options, clickCount }));
        if (typeof delay === 'number') {
            await Promise.all(actions);
            actions.length = 0;
            await new Promise(resolve => {
                setTimeout(resolve, delay);
            });
        }
        actions.push(this.up({ ...options, clickCount }));
        await Promise.all(actions);
    }
    async wheel(options = {}) {
        const { deltaX = 0, deltaY = 0 } = options;
        const { position, buttons } = this.#state;
        await this.#client.send('Input.dispatchMouseEvent', {
            type: 'mouseWheel',
            pointerType: 'mouse',
            modifiers: this.#keyboard._modifiers,
            deltaY,
            deltaX,
            buttons,
            ...position,
        });
    }
    async drag(start, target) {
        const promise = new Promise(resolve => {
            this.#client.once('Input.dragIntercepted', event => {
                return resolve(event.data);
            });
        });
        await this.move(start.x, start.y);
        await this.down();
        await this.move(target.x, target.y);
        return await promise;
    }
    async dragEnter(target, data) {
        await this.#client.send('Input.dispatchDragEvent', {
            type: 'dragEnter',
            x: target.x,
            y: target.y,
            modifiers: this.#keyboard._modifiers,
            data,
        });
    }
    async dragOver(target, data) {
        await this.#client.send('Input.dispatchDragEvent', {
            type: 'dragOver',
            x: target.x,
            y: target.y,
            modifiers: this.#keyboard._modifiers,
            data,
        });
    }
    async drop(target, data) {
        await this.#client.send('Input.dispatchDragEvent', {
            type: 'drop',
            x: target.x,
            y: target.y,
            modifiers: this.#keyboard._modifiers,
            data,
        });
    }
    async dragAndDrop(start, target, options = {}) {
        const { delay = null } = options;
        const data = await this.drag(start, target);
        await this.dragEnter(target, data);
        await this.dragOver(target, data);
        if (delay) {
            await new Promise(resolve => {
                return setTimeout(resolve, delay);
            });
        }
        await this.drop(target, data);
        await this.up();
    }
}
class CdpTouchHandle {
    #started = false;
    #touchScreen;
    #touchPoint;
    #client;
    #keyboard;
    constructor(client, touchScreen, keyboard, touchPoint) {
        this.#client = client;
        this.#touchScreen = touchScreen;
        this.#keyboard = keyboard;
        this.#touchPoint = touchPoint;
    }
    updateClient(client) {
        this.#client = client;
    }
    async start() {
        if (this.#started) {
            throw new TouchError('Touch has already started');
        }
        await this.#client.send('Input.dispatchTouchEvent', {
            type: 'touchStart',
            touchPoints: [this.#touchPoint],
            modifiers: this.#keyboard._modifiers,
        });
        this.#started = true;
    }
    move(x, y) {
        this.#touchPoint.x = Math.round(x);
        this.#touchPoint.y = Math.round(y);
        return this.#client.send('Input.dispatchTouchEvent', {
            type: 'touchMove',
            touchPoints: [this.#touchPoint],
            modifiers: this.#keyboard._modifiers,
        });
    }
    async end() {
        await this.#client.send('Input.dispatchTouchEvent', {
            type: 'touchEnd',
            touchPoints: [this.#touchPoint],
            modifiers: this.#keyboard._modifiers,
        });
        this.#touchScreen.removeHandle(this);
    }
}
class CdpTouchscreen extends Touchscreen {
    #client;
    #keyboard;
    constructor(client, keyboard) {
        super();
        this.#client = client;
        this.#keyboard = keyboard;
    }
    updateClient(client) {
        this.#client = client;
        this.touches.forEach(t => {
            t.updateClient(client);
        });
    }
    async touchStart(x, y) {
        const id = this.idGenerator();
        const touchPoint = {
            x: Math.round(x),
            y: Math.round(y),
            radiusX: 0.5,
            radiusY: 0.5,
            force: 0.5,
            id,
        };
        const touch = new CdpTouchHandle(this.#client, this, this.#keyboard, touchPoint);
        await touch.start();
        this.touches.push(touch);
        return touch;
    }
}

class Tracing {
    #client;
    #recording = false;
    #path;
    constructor(client) {
        this.#client = client;
    }
    updateClient(client) {
        this.#client = client;
    }
    async start(options = {}) {
        assert(!this.#recording, 'Cannot start recording trace while already recording trace.');
        const defaultCategories = [
            '-*',
            'devtools.timeline',
            'v8.execute',
            'disabled-by-default-devtools.timeline',
            'disabled-by-default-devtools.timeline.frame',
            'toplevel',
            'blink.console',
            'blink.user_timing',
            'latencyInfo',
            'disabled-by-default-devtools.timeline.stack',
            'disabled-by-default-v8.cpu_profiler',
        ];
        const { path, screenshots = false, categories = defaultCategories } = options;
        if (screenshots) {
            categories.push('disabled-by-default-devtools.screenshot');
        }
        const excludedCategories = categories
            .filter(cat => {
            return cat.startsWith('-');
        })
            .map(cat => {
            return cat.slice(1);
        });
        const includedCategories = categories.filter(cat => {
            return !cat.startsWith('-');
        });
        this.#path = path;
        this.#recording = true;
        await this.#client.send('Tracing.start', {
            transferMode: 'ReturnAsStream',
            traceConfig: {
                excludedCategories,
                includedCategories,
            },
        });
    }
    async stop() {
        const contentDeferred = Deferred.create();
        this.#client.once('Tracing.tracingComplete', async (event) => {
            try {
                assert(event.stream, 'Missing "stream"');
                const readable = await getReadableFromProtocolStream(this.#client, event.stream);
                const typedArray = await getReadableAsTypedArray(readable, this.#path);
                contentDeferred.resolve(typedArray ?? undefined);
            }
            catch (error) {
                if (isErrorLike$1(error)) {
                    contentDeferred.reject(error);
                }
                else {
                    contentDeferred.reject(new Error(`Unknown error: ${error}`));
                }
            }
        });
        await this.#client.send('Tracing.end');
        this.#recording = false;
        return await contentDeferred.valueOrThrow();
    }
}

class CdpWebWorker extends WebWorker$1 {
    #world;
    #client;
    #id;
    #targetType;
    constructor(client, url, targetId, targetType, consoleAPICalled, exceptionThrown, networkManager) {
        super(url);
        this.#id = targetId;
        this.#client = client;
        this.#targetType = targetType;
        this.#world = new IsolatedWorld(this, new TimeoutSettings());
        this.#client.once('Runtime.executionContextCreated', async (event) => {
            this.#world.setContext(new ExecutionContext$1(client, event.context, this.#world));
        });
        this.#world.emitter.on('consoleapicalled', async (event) => {
            try {
                return consoleAPICalled(this.#world, event);
            }
            catch (err) {
                debugError(err);
            }
        });
        this.#client.on('Runtime.exceptionThrown', exceptionThrown);
        this.#client.once(CDPSessionEvent.Disconnected, () => {
            this.#world.dispose();
        });
        networkManager?.addClient(this.#client).catch(debugError);
        this.#client.send('Runtime.enable').catch(debugError);
    }
    mainRealm() {
        return this.#world;
    }
    get client() {
        return this.#client;
    }
    async close() {
        switch (this.#targetType) {
            case TargetType.SERVICE_WORKER: {
                await this.client.connection()?.send('Target.closeTarget', {
                    targetId: this.#id,
                });
                await this.client.connection()?.send('Target.detachFromTarget', {
                    sessionId: this.client.id(),
                });
                break;
            }
            case TargetType.SHARED_WORKER: {
                await this.client.connection()?.send('Target.closeTarget', {
                    targetId: this.#id,
                });
                break;
            }
            default:
                await this.evaluate(() => {
                    self.close();
                });
        }
    }
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __addDisposableResource$2 = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$2 = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
function convertConsoleMessageLevel(method) {
    switch (method) {
        case 'warning':
            return 'warn';
        default:
            return method;
    }
}
function convertSameSiteFromPuppeteerToCdp(sameSite) {
    switch (sameSite) {
        case 'Strict':
        case 'Lax':
        case 'None':
            return sameSite;
        default:
            return undefined;
    }
}
class CdpPage extends Page {
    static async _create(client, target, defaultViewport) {
        const page = new CdpPage(client, target);
        await page.#initialize();
        if (defaultViewport) {
            try {
                await page.setViewport(defaultViewport);
            }
            catch (err) {
                if (isErrorLike$1(err) && isTargetClosedError(err)) {
                    debugError(err);
                }
                else {
                    throw err;
                }
            }
        }
        return page;
    }
    #closed = false;
    #targetManager;
    #cdpBluetoothEmulation;
    #primaryTargetClient;
    #primaryTarget;
    #tabTargetClient;
    #tabTarget;
    #keyboard;
    #mouse;
    #touchscreen;
    #frameManager;
    #emulationManager;
    #tracing;
    #bindings = new Map();
    #exposedFunctions = new Map();
    #coverage;
    #viewport;
    #workers = new Map();
    #fileChooserDeferreds = new Set();
    #sessionCloseDeferred = Deferred.create();
    #serviceWorkerBypassed = false;
    #userDragInterceptionEnabled = false;
    constructor(client, target) {
        super();
        this.#primaryTargetClient = client;
        this.#tabTargetClient = client.parentSession();
        assert(this.#tabTargetClient, 'Tab target session is not defined.');
        this.#tabTarget = this.#tabTargetClient.target();
        assert(this.#tabTarget, 'Tab target is not defined.');
        this._tabId = this.#tabTarget._getTargetInfo().targetId;
        this.#primaryTarget = target;
        this.#targetManager = target._targetManager();
        this.#keyboard = new CdpKeyboard(client);
        this.#mouse = new CdpMouse(client, this.#keyboard);
        this.#touchscreen = new CdpTouchscreen(client, this.#keyboard);
        this.#frameManager = new FrameManager$1(client, this, this._timeoutSettings);
        this.#emulationManager = new EmulationManager(client);
        this.#tracing = new Tracing(client);
        this.#coverage = new Coverage(client);
        this.#viewport = null;
        this.#cdpBluetoothEmulation = new CdpBluetoothEmulation(this.#primaryTargetClient.connection());
        const frameManagerEmitter = new EventEmitter(this.#frameManager);
        frameManagerEmitter.on(FrameManagerEvent.FrameAttached, frame => {
            this.emit("frameattached" , frame);
        });
        frameManagerEmitter.on(FrameManagerEvent.FrameDetached, frame => {
            this.emit("framedetached" , frame);
        });
        frameManagerEmitter.on(FrameManagerEvent.FrameNavigated, frame => {
            this.emit("framenavigated" , frame);
        });
        frameManagerEmitter.on(FrameManagerEvent.ConsoleApiCalled, ([world, event]) => {
            this.#onConsoleAPI(world, event);
        });
        frameManagerEmitter.on(FrameManagerEvent.BindingCalled, ([world, event]) => {
            void this.#onBindingCalled(world, event);
        });
        const networkManagerEmitter = new EventEmitter(this.#frameManager.networkManager);
        networkManagerEmitter.on(NetworkManagerEvent.Request, request => {
            this.emit("request" , request);
        });
        networkManagerEmitter.on(NetworkManagerEvent.RequestServedFromCache, request => {
            this.emit("requestservedfromcache" , request);
        });
        networkManagerEmitter.on(NetworkManagerEvent.Response, response => {
            this.emit("response" , response);
        });
        networkManagerEmitter.on(NetworkManagerEvent.RequestFailed, request => {
            this.emit("requestfailed" , request);
        });
        networkManagerEmitter.on(NetworkManagerEvent.RequestFinished, request => {
            this.emit("requestfinished" , request);
        });
        this.#tabTargetClient.on(CDPSessionEvent.Swapped, this.#onActivation.bind(this));
        this.#tabTargetClient.on(CDPSessionEvent.Ready, this.#onSecondaryTarget.bind(this));
        this.#targetManager.on("targetGone" , this.#onDetachedFromTarget);
        this.#tabTarget._isClosedDeferred
            .valueOrThrow()
            .then(() => {
            this.#targetManager.off("targetGone" , this.#onDetachedFromTarget);
            this.emit("close" , undefined);
            this.#closed = true;
        })
            .catch(debugError);
        this.#setupPrimaryTargetListeners();
        this.#attachExistingTargets();
    }
    #attachExistingTargets() {
        const queue = [];
        for (const childTarget of this.#targetManager.getChildTargets(this.#primaryTarget)) {
            queue.push(childTarget);
        }
        let idx = 0;
        while (idx < queue.length) {
            const next = queue[idx];
            idx++;
            const session = next._session();
            if (session) {
                this.#onAttachedToTarget(session);
            }
            for (const childTarget of this.#targetManager.getChildTargets(next)) {
                queue.push(childTarget);
            }
        }
    }
    async #onActivation(newSession) {
        assert(newSession instanceof CdpCDPSession, 'CDPSession is not instance of CdpCDPSession');
        this.#primaryTargetClient = newSession;
        this.#primaryTarget = newSession.target();
        assert(this.#primaryTarget, 'Missing target on swap');
        this.#keyboard.updateClient(newSession);
        this.#mouse.updateClient(newSession);
        this.#touchscreen.updateClient(newSession);
        this.#emulationManager.updateClient(newSession);
        this.#tracing.updateClient(newSession);
        this.#coverage.updateClient(newSession);
        await this.#frameManager.swapFrameTree(newSession);
        this.#setupPrimaryTargetListeners();
    }
    async #onSecondaryTarget(session) {
        assert(session instanceof CdpCDPSession);
        if (session.target()._subtype() !== 'prerender') {
            return;
        }
        this.#frameManager.registerSpeculativeSession(session).catch(debugError);
        this.#emulationManager
            .registerSpeculativeSession(session)
            .catch(debugError);
    }
    #setupPrimaryTargetListeners() {
        const clientEmitter = new EventEmitter(this.#primaryTargetClient);
        clientEmitter.on(CDPSessionEvent.Ready, this.#onAttachedToTarget);
        clientEmitter.on(CDPSessionEvent.Disconnected, () => {
            this.#sessionCloseDeferred.reject(new TargetCloseError('Target closed'));
        });
        clientEmitter.on('Page.domContentEventFired', () => {
            this.emit("domcontentloaded" , undefined);
        });
        clientEmitter.on('Page.loadEventFired', () => {
            this.emit("load" , undefined);
        });
        clientEmitter.on('Page.javascriptDialogOpening', this.#onDialog.bind(this));
        clientEmitter.on('Runtime.exceptionThrown', this.#handleException.bind(this));
        clientEmitter.on('Inspector.targetCrashed', this.#onTargetCrashed.bind(this));
        clientEmitter.on('Performance.metrics', this.#emitMetrics.bind(this));
        clientEmitter.on('Log.entryAdded', this.#onLogEntryAdded.bind(this));
        clientEmitter.on('Page.fileChooserOpened', this.#onFileChooser.bind(this));
    }
    #onDetachedFromTarget = (target) => {
        const sessionId = target._session()?.id();
        const worker = this.#workers.get(sessionId);
        if (!worker) {
            return;
        }
        this.#workers.delete(sessionId);
        this.emit("workerdestroyed" , worker);
    };
    #onAttachedToTarget = (session) => {
        assert(session instanceof CdpCDPSession);
        this.#frameManager.onAttachedToTarget(session.target());
        if (session.target()._getTargetInfo().type === 'worker') {
            const worker = new CdpWebWorker(session, session.target().url(), session.target()._targetId, session.target().type(), this.#onConsoleAPI.bind(this), this.#handleException.bind(this), this.#frameManager.networkManager);
            this.#workers.set(session.id(), worker);
            this.emit("workercreated" , worker);
        }
        session.on(CDPSessionEvent.Ready, this.#onAttachedToTarget);
    };
    async #initialize() {
        try {
            await Promise.all([
                this.#frameManager.initialize(this.#primaryTargetClient),
                this.#primaryTargetClient.send('Performance.enable'),
                this.#primaryTargetClient.send('Log.enable'),
            ]);
        }
        catch (err) {
            if (isErrorLike$1(err) && isTargetClosedError(err)) {
                debugError(err);
            }
            else {
                throw err;
            }
        }
    }
    async resize(params) {
        const windowId = await this.windowId();
        await this.#primaryTargetClient.send('Browser.setContentsSize', {
            windowId: Number(windowId),
            width: params.contentWidth,
            height: params.contentHeight,
        });
    }
    async windowId() {
        const { windowId } = await this.#primaryTargetClient.send('Browser.getWindowForTarget');
        return windowId.toString();
    }
    async #onFileChooser(event) {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
            if (!this.#fileChooserDeferreds.size) {
                return;
            }
            const frame = this.#frameManager.frame(event.frameId);
            assert(frame, 'This should never happen.');
            const handle = __addDisposableResource$2(env_1, (await frame.worlds[MAIN_WORLD].adoptBackendNode(event.backendNodeId)), false);
            const fileChooser = new FileChooser(handle.move(), event.mode !== 'selectSingle');
            for (const promise of this.#fileChooserDeferreds) {
                promise.resolve(fileChooser);
            }
            this.#fileChooserDeferreds.clear();
        }
        catch (e_1) {
            env_1.error = e_1;
            env_1.hasError = true;
        }
        finally {
            __disposeResources$2(env_1);
        }
    }
    _client() {
        return this.#primaryTargetClient;
    }
    isServiceWorkerBypassed() {
        return this.#serviceWorkerBypassed;
    }
    isDragInterceptionEnabled() {
        return this.#userDragInterceptionEnabled;
    }
    isJavaScriptEnabled() {
        return this.#emulationManager.javascriptEnabled;
    }
    async openDevTools() {
        const pageTargetId = this.target()._targetId;
        const browser = this.browser();
        const devtoolsPage = await browser._createDevToolsPage(pageTargetId);
        return devtoolsPage;
    }
    async waitForFileChooser(options = {}) {
        const needsEnable = this.#fileChooserDeferreds.size === 0;
        const { timeout = this._timeoutSettings.timeout() } = options;
        const deferred = Deferred.create({
            message: `Waiting for \`FileChooser\` failed: ${timeout}ms exceeded`,
            timeout,
        });
        if (options.signal) {
            options.signal.addEventListener('abort', () => {
                deferred.reject(options.signal?.reason);
            }, { once: true });
        }
        this.#fileChooserDeferreds.add(deferred);
        let enablePromise;
        if (needsEnable) {
            enablePromise = this.#primaryTargetClient.send('Page.setInterceptFileChooserDialog', {
                enabled: true,
            });
        }
        try {
            const [result] = await Promise.all([
                deferred.valueOrThrow(),
                enablePromise,
            ]);
            return result;
        }
        catch (error) {
            this.#fileChooserDeferreds.delete(deferred);
            throw error;
        }
    }
    async setGeolocation(options) {
        return await this.#emulationManager.setGeolocation(options);
    }
    target() {
        return this.#primaryTarget;
    }
    browser() {
        return this.#primaryTarget.browser();
    }
    browserContext() {
        return this.#primaryTarget.browserContext();
    }
    #onTargetCrashed() {
        this.emit("error" , new Error('Page crashed!'));
    }
    #onLogEntryAdded(event) {
        const { level, text, args, source, url, lineNumber, stackTrace } = event.entry;
        if (args) {
            args.map(arg => {
                void releaseObject(this.#primaryTargetClient, arg);
            });
        }
        if (source !== 'worker') {
            this.emit("console" , new ConsoleMessage$1(convertConsoleMessageLevel(level), text, [], [{ url, lineNumber }], undefined, stackTrace, this.#primaryTarget._targetId));
        }
    }
    mainFrame() {
        return this.#frameManager.mainFrame();
    }
    get keyboard() {
        return this.#keyboard;
    }
    get touchscreen() {
        return this.#touchscreen;
    }
    get coverage() {
        return this.#coverage;
    }
    get tracing() {
        return this.#tracing;
    }
    frames() {
        return this.#frameManager.frames();
    }
    workers() {
        return Array.from(this.#workers.values());
    }
    async setRequestInterception(value) {
        return await this.#frameManager.networkManager.setRequestInterception(value);
    }
    async setBypassServiceWorker(bypass) {
        this.#serviceWorkerBypassed = bypass;
        return await this.#primaryTargetClient.send('Network.setBypassServiceWorker', { bypass });
    }
    async setDragInterception(enabled) {
        this.#userDragInterceptionEnabled = enabled;
        return await this.#primaryTargetClient.send('Input.setInterceptDrags', {
            enabled,
        });
    }
    async setOfflineMode(enabled) {
        return await this.#frameManager.networkManager.setOfflineMode(enabled);
    }
    async emulateNetworkConditions(networkConditions) {
        return await this.#frameManager.networkManager.emulateNetworkConditions(networkConditions);
    }
    async emulateFocusedPage(enabled) {
        return await this.#emulationManager.emulateFocus(enabled);
    }
    setDefaultNavigationTimeout(timeout) {
        this._timeoutSettings.setDefaultNavigationTimeout(timeout);
    }
    setDefaultTimeout(timeout) {
        this._timeoutSettings.setDefaultTimeout(timeout);
    }
    getDefaultTimeout() {
        return this._timeoutSettings.timeout();
    }
    getDefaultNavigationTimeout() {
        return this._timeoutSettings.navigationTimeout();
    }
    async queryObjects(prototypeHandle) {
        assert(!prototypeHandle.disposed, 'Prototype JSHandle is disposed!');
        assert(prototypeHandle.id, 'Prototype JSHandle must not be referencing primitive value');
        const response = await this.mainFrame().client.send('Runtime.queryObjects', {
            prototypeObjectId: prototypeHandle.id,
        });
        return this.mainFrame()
            .mainRealm()
            .createCdpHandle(response.objects);
    }
    async cookies(...urls) {
        const originalCookies = (await this.#primaryTargetClient.send('Network.getCookies', {
            urls: urls.length ? urls : [this.url()],
        })).cookies;
        const unsupportedCookieAttributes = ['sourcePort'];
        const filterUnsupportedAttributes = (cookie) => {
            for (const attr of unsupportedCookieAttributes) {
                delete cookie[attr];
            }
            return cookie;
        };
        return originalCookies.map(filterUnsupportedAttributes).map(cookie => {
            return {
                ...cookie,
                partitionKey: cookie.partitionKey
                    ? cookie.partitionKey.topLevelSite
                    : undefined,
                sameParty: false,
            };
        });
    }
    async deleteCookie(...cookies) {
        const pageURL = this.url();
        for (const cookie of cookies) {
            const item = {
                ...cookie,
                partitionKey: convertCookiesPartitionKeyFromPuppeteerToCdp(cookie.partitionKey),
            };
            if (!cookie.url && pageURL.startsWith('http')) {
                item.url = pageURL;
            }
            await this.#primaryTargetClient.send('Network.deleteCookies', item);
            if (pageURL.startsWith('http') && !item.partitionKey) {
                const url = new URL(pageURL);
                await this.#primaryTargetClient.send('Network.deleteCookies', {
                    ...item,
                    partitionKey: {
                        topLevelSite: url.origin.replace(`:${url.port}`, ''),
                        hasCrossSiteAncestor: false,
                    },
                });
            }
        }
    }
    async setCookie(...cookies) {
        const pageURL = this.url();
        const startsWithHTTP = pageURL.startsWith('http');
        const items = cookies.map(cookie => {
            const item = Object.assign({}, cookie);
            if (!item.url && startsWithHTTP) {
                item.url = pageURL;
            }
            assert(item.url !== 'about:blank', `Blank page can not have cookie "${item.name}"`);
            assert(!String.prototype.startsWith.call(item.url || '', 'data:'), `Data URL page can not have cookie "${item.name}"`);
            return item;
        });
        await this.deleteCookie(...items);
        if (items.length) {
            await this.#primaryTargetClient.send('Network.setCookies', {
                cookies: items.map(cookieParam => {
                    return {
                        ...cookieParam,
                        partitionKey: convertCookiesPartitionKeyFromPuppeteerToCdp(cookieParam.partitionKey),
                        sameSite: convertSameSiteFromPuppeteerToCdp(cookieParam.sameSite),
                    };
                }),
            });
        }
    }
    async exposeFunction(name,
    pptrFunction) {
        if (this.#bindings.has(name)) {
            throw new Error(`Failed to add page binding with name ${name}: window['${name}'] already exists!`);
        }
        const source = pageBindingInitString('exposedFun', name);
        let binding;
        switch (typeof pptrFunction) {
            case 'function':
                binding = new Binding$2(name, pptrFunction, source);
                break;
            default:
                binding = new Binding$2(name, pptrFunction.default, source);
                break;
        }
        this.#bindings.set(name, binding);
        const [{ identifier }] = await Promise.all([
            this.#frameManager.evaluateOnNewDocument(source),
            this.#frameManager.addExposedFunctionBinding(binding),
        ]);
        this.#exposedFunctions.set(name, identifier);
    }
    async removeExposedFunction(name) {
        const exposedFunctionId = this.#exposedFunctions.get(name);
        if (!exposedFunctionId) {
            throw new Error(`Function with name "${name}" does not exist`);
        }
        const binding = this.#bindings.get(name);
        this.#exposedFunctions.delete(name);
        this.#bindings.delete(name);
        await Promise.all([
            this.#frameManager.removeScriptToEvaluateOnNewDocument(exposedFunctionId),
            this.#frameManager.removeExposedFunctionBinding(binding),
        ]);
    }
    async authenticate(credentials) {
        return await this.#frameManager.networkManager.authenticate(credentials);
    }
    async setExtraHTTPHeaders(headers) {
        return await this.#frameManager.networkManager.setExtraHTTPHeaders(headers);
    }
    async setUserAgent(userAgentOrOptions, userAgentMetadata) {
        if (typeof userAgentOrOptions === 'string') {
            return await this.#frameManager.networkManager.setUserAgent(userAgentOrOptions, userAgentMetadata);
        }
        else {
            const userAgent = userAgentOrOptions.userAgent ?? (await this.browser().userAgent());
            return await this.#frameManager.networkManager.setUserAgent(userAgent, userAgentOrOptions.userAgentMetadata, userAgentOrOptions.platform);
        }
    }
    async metrics() {
        const response = await this.#primaryTargetClient.send('Performance.getMetrics');
        return this.#buildMetricsObject(response.metrics);
    }
    async captureHeapSnapshot(options) {
        const { createWriteStream } = environment.value.fs;
        const stream = createWriteStream(options.path);
        const streamPromise = new Promise((resolve, reject) => {
            stream.on('error', reject);
            stream.on('finish', resolve);
        });
        const client = this.#primaryTargetClient;
        await client.send('HeapProfiler.enable');
        await client.send('HeapProfiler.collectGarbage');
        const handler = (event) => {
            stream.write(event.chunk);
        };
        client.on('HeapProfiler.addHeapSnapshotChunk', handler);
        try {
            await client.send('HeapProfiler.takeHeapSnapshot', {
                reportProgress: false,
            });
        }
        finally {
            client.off('HeapProfiler.addHeapSnapshotChunk', handler);
            await client.send('HeapProfiler.disable');
        }
        stream.end();
        await streamPromise;
    }
    #emitMetrics(event) {
        this.emit("metrics" , {
            title: event.title,
            metrics: this.#buildMetricsObject(event.metrics),
        });
    }
    #buildMetricsObject(metrics) {
        const result = {};
        for (const metric of metrics || []) {
            if (supportedMetrics.has(metric.name)) {
                result[metric.name] = metric.value;
            }
        }
        return result;
    }
    #handleException(exception) {
        this.emit("pageerror" , createClientError(exception.exceptionDetails));
    }
    #onConsoleAPI(world, event) {
        const values = event.args.map(arg => {
            return world.createCdpHandle(arg);
        });
        if (!this.listenerCount("console" )) {
            values.forEach(arg => {
                return arg.dispose();
            });
            return;
        }
        const textTokens = [];
        for (const arg of values) {
            textTokens.push(valueFromJSHandle(arg));
        }
        const stackTraceLocations = [];
        if (event.stackTrace) {
            for (const callFrame of event.stackTrace.callFrames) {
                stackTraceLocations.push({
                    url: callFrame.url,
                    lineNumber: callFrame.lineNumber,
                    columnNumber: callFrame.columnNumber,
                });
            }
        }
        let targetId;
        if (world.environment.client instanceof CdpCDPSession) {
            targetId = world.environment.client.target()._targetId;
        }
        const message = new ConsoleMessage$1(convertConsoleMessageLevel(event.type), textTokens.join(' '), values, stackTraceLocations, undefined, event.stackTrace, targetId);
        this.emit("console" , message);
    }
    async #onBindingCalled(world, event) {
        let payload;
        try {
            payload = JSON.parse(event.payload);
        }
        catch {
            return;
        }
        const { type, name, seq, args, isTrivial } = payload;
        if (type !== 'exposedFun') {
            return;
        }
        const context = world.context;
        if (!context) {
            return;
        }
        const binding = this.#bindings.get(name);
        await binding?.run(context, seq, args, isTrivial);
    }
    #onDialog(event) {
        const type = validateDialogType(event.type);
        const dialog = new CdpDialog(this.#primaryTargetClient, type, event.message, event.defaultPrompt);
        this.emit("dialog" , dialog);
    }
    async reload(options) {
        const [result] = await Promise.all([
            this.waitForNavigation({
                ...options,
                ignoreSameDocumentNavigation: true,
            }),
            this.#primaryTargetClient.send('Page.reload', {
                ignoreCache: options?.ignoreCache ?? false,
            }),
        ]);
        return result;
    }
    async createCDPSession() {
        return await this.target().createCDPSession();
    }
    async goBack(options = {}) {
        return await this.#go(-1, options);
    }
    async goForward(options = {}) {
        return await this.#go(1, options);
    }
    async #go(delta, options) {
        const history = await this.#primaryTargetClient.send('Page.getNavigationHistory');
        const entry = history.entries[history.currentIndex + delta];
        if (!entry) {
            throw new Error('History entry to navigate to not found.');
        }
        const result = await Promise.all([
            this.waitForNavigation(options),
            this.#primaryTargetClient.send('Page.navigateToHistoryEntry', {
                entryId: entry.id,
            }),
        ]);
        return result[0];
    }
    async bringToFront() {
        await this.#primaryTargetClient.send('Page.bringToFront');
    }
    async setJavaScriptEnabled(enabled) {
        return await this.#emulationManager.setJavaScriptEnabled(enabled);
    }
    async setBypassCSP(enabled) {
        await this.#primaryTargetClient.send('Page.setBypassCSP', { enabled });
    }
    async emulateMediaType(type) {
        return await this.#emulationManager.emulateMediaType(type);
    }
    async emulateCPUThrottling(factor) {
        return await this.#emulationManager.emulateCPUThrottling(factor);
    }
    async emulateMediaFeatures(features) {
        return await this.#emulationManager.emulateMediaFeatures(features);
    }
    async emulateTimezone(timezoneId) {
        return await this.#emulationManager.emulateTimezone(timezoneId);
    }
    async emulateIdleState(overrides) {
        return await this.#emulationManager.emulateIdleState(overrides);
    }
    async emulateVisionDeficiency(type) {
        return await this.#emulationManager.emulateVisionDeficiency(type);
    }
    async setViewport(viewport) {
        const needsReload = await this.#emulationManager.emulateViewport(viewport);
        this.#viewport = viewport;
        if (needsReload) {
            await this.reload();
        }
    }
    viewport() {
        return this.#viewport;
    }
    async evaluateOnNewDocument(pageFunction, ...args) {
        const source = evaluationString(pageFunction, ...args);
        return await this.#frameManager.evaluateOnNewDocument(source);
    }
    async removeScriptToEvaluateOnNewDocument(identifier) {
        return await this.#frameManager.removeScriptToEvaluateOnNewDocument(identifier);
    }
    async setCacheEnabled(enabled = true) {
        await this.#frameManager.networkManager.setCacheEnabled(enabled);
    }
    async _screenshot(options) {
        const env_2 = { stack: [], error: void 0, hasError: false };
        try {
            const { fromSurface, omitBackground, optimizeForSpeed, quality, clip: userClip, type, captureBeyondViewport, } = options;
            const stack = __addDisposableResource$2(env_2, new AsyncDisposableStack(), true);
            if (omitBackground && (type === 'png' || type === 'webp')) {
                await this.#emulationManager.setTransparentBackgroundColor();
                stack.defer(async () => {
                    await this.#emulationManager
                        .resetDefaultBackgroundColor()
                        .catch(debugError);
                });
            }
            let clip = userClip;
            if (clip && !captureBeyondViewport) {
                const viewport = await this.mainFrame()
                    .isolatedRealm()
                    .evaluate(() => {
                    const { height, pageLeft: x, pageTop: y, width, } = window.visualViewport;
                    return { x, y, height, width };
                });
                clip = getIntersectionRect(clip, viewport);
            }
            const { data } = await this.#primaryTargetClient.send('Page.captureScreenshot', {
                format: type,
                optimizeForSpeed,
                fromSurface,
                ...(quality !== undefined ? { quality: Math.round(quality) } : {}),
                ...(clip ? { clip: { ...clip, scale: clip.scale ?? 1 } } : {}),
                captureBeyondViewport,
            });
            return data;
        }
        catch (e_2) {
            env_2.error = e_2;
            env_2.hasError = true;
        }
        finally {
            const result_1 = __disposeResources$2(env_2);
            if (result_1)
                await result_1;
        }
    }
    async createPDFStream(options = {}) {
        const { timeout: ms = this._timeoutSettings.timeout() } = options;
        const { landscape, displayHeaderFooter, headerTemplate, footerTemplate, printBackground, scale, width: paperWidth, height: paperHeight, margin, pageRanges, preferCSSPageSize, omitBackground, tagged: generateTaggedPDF, outline: generateDocumentOutline, waitForFonts, } = parsePDFOptions(options);
        if (omitBackground) {
            await this.#emulationManager.setTransparentBackgroundColor();
        }
        if (waitForFonts) {
            await firstValueFrom(from(this.mainFrame()
                .isolatedRealm()
                .evaluate(() => {
                return document.fonts.ready;
            })).pipe(raceWith(timeout(ms))));
        }
        const printCommandPromise = this.#primaryTargetClient.send('Page.printToPDF', {
            transferMode: 'ReturnAsStream',
            landscape,
            displayHeaderFooter,
            headerTemplate,
            footerTemplate,
            printBackground,
            scale,
            paperWidth,
            paperHeight,
            marginTop: margin.top,
            marginBottom: margin.bottom,
            marginLeft: margin.left,
            marginRight: margin.right,
            pageRanges,
            preferCSSPageSize,
            generateTaggedPDF,
            generateDocumentOutline,
        });
        const result = await firstValueFrom(from(printCommandPromise).pipe(raceWith(timeout(ms))));
        if (omitBackground) {
            await this.#emulationManager.resetDefaultBackgroundColor();
        }
        assert(result.stream, '`stream` is missing from `Page.printToPDF');
        return await getReadableFromProtocolStream(this.#primaryTargetClient, result.stream);
    }
    async pdf(options = {}) {
        const { path = undefined } = options;
        const readable = await this.createPDFStream(options);
        const typedArray = await getReadableAsTypedArray(readable, path);
        assert(typedArray, 'Could not create typed array');
        return typedArray;
    }
    async close(options = { runBeforeUnload: undefined }) {
        const env_3 = { stack: [], error: void 0, hasError: false };
        try {
            const _guard = __addDisposableResource$2(env_3, await this.browserContext().waitForScreenshotOperations(), false);
            const connection = this.#primaryTargetClient.connection();
            assert(connection, 'Connection closed. Most likely the page has been closed.');
            const runBeforeUnload = !!options.runBeforeUnload;
            if (runBeforeUnload) {
                await this.#primaryTargetClient.send('Page.close');
            }
            else {
                await connection.send('Target.closeTarget', {
                    targetId: this.#primaryTarget._targetId,
                });
                await this.#tabTarget._isClosedDeferred.valueOrThrow();
            }
        }
        catch (e_3) {
            env_3.error = e_3;
            env_3.hasError = true;
        }
        finally {
            __disposeResources$2(env_3);
        }
    }
    isClosed() {
        return this.#closed;
    }
    get mouse() {
        return this.#mouse;
    }
    async waitForDevicePrompt(options = {}) {
        return await this.mainFrame().waitForDevicePrompt(options);
    }
    get bluetooth() {
        return this.#cdpBluetoothEmulation;
    }
}
const supportedMetrics = new Set([
    'Timestamp',
    'Documents',
    'Frames',
    'JSEventListeners',
    'Nodes',
    'LayoutCount',
    'RecalcStyleCount',
    'LayoutDuration',
    'RecalcStyleDuration',
    'ScriptDuration',
    'TaskDuration',
    'JSHeapUsedSize',
    'JSHeapTotalSize',
]);
function getIntersectionRect(clip, viewport) {
    const x = Math.max(clip.x, viewport.x);
    const y = Math.max(clip.y, viewport.y);
    return {
        x,
        y,
        width: Math.max(Math.min(clip.x + clip.width, viewport.x + viewport.width) - x, 0),
        height: Math.max(Math.min(clip.y + clip.height, viewport.y + viewport.height) - y, 0),
    };
}
function convertCookiesPartitionKeyFromPuppeteerToCdp(partitionKey) {
    if (partitionKey === undefined) {
        return undefined;
    }
    if (typeof partitionKey === 'string') {
        return {
            topLevelSite: partitionKey,
            hasCrossSiteAncestor: false,
        };
    }
    return {
        topLevelSite: partitionKey.sourceOrigin,
        hasCrossSiteAncestor: partitionKey.hasCrossSiteAncestor ?? false,
    };
}

/**
 * @license
 * Copyright 2024 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __addDisposableResource$1 = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
    if (value !== null && value !== void 0) {
        if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
        var dispose, inner;
        if (async) {
            if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
            dispose = value[Symbol.asyncDispose];
        }
        if (dispose === void 0) {
            if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
            dispose = value[Symbol.dispose];
            if (async) inner = dispose;
        }
        if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
        if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
        env.stack.push({ value: value, dispose: dispose, async: async });
    }
    else if (async) {
        env.stack.push({ async: true });
    }
    return value;
};
var __disposeResources$1 = (undefined && undefined.__disposeResources) || (function (SuppressedError) {
    return function (env) {
        function fail(e) {
            env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
                    }
                    else s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError) throw env.error;
        }
        return next();
    };
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
class CdpBrowserContext extends BrowserContext {
    #connection;
    #browser;
    #id;
    constructor(connection, browser, contextId) {
        super();
        this.#connection = connection;
        this.#browser = browser;
        this.#id = contextId;
    }
    get id() {
        return this.#id;
    }
    targets() {
        return this.#browser.targets().filter(target => {
            return target.browserContext() === this;
        });
    }
    async pages(includeAll = false) {
        const pages = await Promise.all(this.targets()
            .filter(target => {
            return (target.type() === 'page' ||
                ((target.type() === 'other' || includeAll) &&
                    this.#browser._getIsPageTargetCallback()?.(target)));
        })
            .map(target => {
            return target.page();
        }));
        return pages.filter((page) => {
            return !!page;
        });
    }
    async overridePermissions(origin, permissions) {
        const protocolPermissions = permissions.map(permission => {
            const protocolPermission = WEB_PERMISSION_TO_PROTOCOL_PERMISSION.get(permission);
            if (!protocolPermission) {
                throw new Error('Unknown permission: ' + permission);
            }
            return protocolPermission;
        });
        await this.#connection.send('Browser.grantPermissions', {
            origin,
            browserContextId: this.#id || undefined,
            permissions: protocolPermissions,
        });
    }
    async setPermission(origin, ...permissions) {
        await Promise.all(permissions.map(async (permission) => {
            const protocolPermission = {
                name: permission.permission.name,
                userVisibleOnly: permission.permission.userVisibleOnly,
                sysex: permission.permission.sysex,
                allowWithoutSanitization: permission.permission.allowWithoutSanitization,
                panTiltZoom: permission.permission.panTiltZoom,
            };
            await this.#connection.send('Browser.setPermission', {
                origin: origin === '*' ? undefined : origin,
                browserContextId: this.#id || undefined,
                permission: protocolPermission,
                setting: permission.state,
            });
        }));
    }
    async clearPermissionOverrides() {
        await this.#connection.send('Browser.resetPermissions', {
            browserContextId: this.#id || undefined,
        });
    }
    async newPage(options) {
        const env_1 = { stack: [], error: void 0, hasError: false };
        try {
            const _guard = __addDisposableResource$1(env_1, await this.waitForScreenshotOperations(), false);
            return await this.#browser._createPageInContext(this.#id, options);
        }
        catch (e_1) {
            env_1.error = e_1;
            env_1.hasError = true;
        }
        finally {
            __disposeResources$1(env_1);
        }
    }
    browser() {
        return this.#browser;
    }
    async close() {
        assert(this.#id, 'Default BrowserContext cannot be closed!');
        await this.#browser._disposeContext(this.#id);
    }
    async cookies() {
        const { cookies } = await this.#connection.send('Storage.getCookies', {
            browserContextId: this.#id,
        });
        return cookies.map(cookie => {
            return {
                ...cookie,
                partitionKey: cookie.partitionKey
                    ? {
                        sourceOrigin: cookie.partitionKey.topLevelSite,
                        hasCrossSiteAncestor: cookie.partitionKey.hasCrossSiteAncestor,
                    }
                    : undefined,
                sameParty: false,
            };
        });
    }
    async setCookie(...cookies) {
        return await this.#connection.send('Storage.setCookies', {
            browserContextId: this.#id,
            cookies: cookies.map(cookie => {
                return {
                    ...cookie,
                    partitionKey: convertCookiesPartitionKeyFromPuppeteerToCdp(cookie.partitionKey),
                    sameSite: convertSameSiteFromPuppeteerToCdp(cookie.sameSite),
                };
            }),
        });
    }
    async setDownloadBehavior(downloadBehavior) {
        await this.#connection.send('Browser.setDownloadBehavior', {
            behavior: downloadBehavior.policy,
            downloadPath: downloadBehavior.downloadPath,
            browserContextId: this.#id,
        });
    }
}

/**
 * @license
 * Copyright 2019 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var InitializationStatus;
(function (InitializationStatus) {
    InitializationStatus["SUCCESS"] = "success";
    InitializationStatus["ABORTED"] = "aborted";
})(InitializationStatus || (InitializationStatus = {}));
class CdpTarget extends Target$1 {
    #browserContext;
    #session;
    #targetInfo;
    #targetManager;
    #sessionFactory;
    #childTargets = new Set();
    _initializedDeferred = Deferred.create();
    _isClosedDeferred = Deferred.create();
    _targetId;
    constructor(targetInfo, session, browserContext, targetManager, sessionFactory) {
        super();
        this.#session = session;
        this.#targetManager = targetManager;
        this.#targetInfo = targetInfo;
        this.#browserContext = browserContext;
        this._targetId = targetInfo.targetId;
        this.#sessionFactory = sessionFactory;
        if (this.#session) {
            this.#session.setTarget(this);
        }
    }
    async asPage() {
        const session = this._session();
        if (!session) {
            return await this.createCDPSession().then(client => {
                return CdpPage._create(client, this, null);
            });
        }
        return await CdpPage._create(session, this, null);
    }
    _subtype() {
        return this.#targetInfo.subtype;
    }
    _session() {
        return this.#session;
    }
    _addChildTarget(target) {
        this.#childTargets.add(target);
    }
    _removeChildTarget(target) {
        this.#childTargets.delete(target);
    }
    _childTargets() {
        return this.#childTargets;
    }
    _sessionFactory() {
        if (!this.#sessionFactory) {
            throw new Error('sessionFactory is not initialized');
        }
        return this.#sessionFactory;
    }
    createCDPSession() {
        if (!this.#sessionFactory) {
            throw new Error('sessionFactory is not initialized');
        }
        return this.#sessionFactory(false).then(session => {
            session.setTarget(this);
            return session;
        });
    }
    url() {
        return this.#targetInfo.url;
    }
    type() {
        const type = this.#targetInfo.type;
        switch (type) {
            case 'page':
                return TargetType.PAGE;
            case 'background_page':
                return TargetType.BACKGROUND_PAGE;
            case 'service_worker':
                return TargetType.SERVICE_WORKER;
            case 'shared_worker':
                return TargetType.SHARED_WORKER;
            case 'browser':
                return TargetType.BROWSER;
            case 'webview':
                return TargetType.WEBVIEW;
            case 'tab':
                return TargetType.TAB;
            default:
                return TargetType.OTHER;
        }
    }
    _targetManager() {
        if (!this.#targetManager) {
            throw new Error('targetManager is not initialized');
        }
        return this.#targetManager;
    }
    _getTargetInfo() {
        return this.#targetInfo;
    }
    browser() {
        if (!this.#browserContext) {
            throw new Error('browserContext is not initialized');
        }
        return this.#browserContext.browser();
    }
    browserContext() {
        if (!this.#browserContext) {
            throw new Error('browserContext is not initialized');
        }
        return this.#browserContext;
    }
    opener() {
        const { openerId } = this.#targetInfo;
        if (!openerId) {
            return;
        }
        return this.browser()
            .targets()
            .find(target => {
            return target._targetId === openerId;
        });
    }
    _targetInfoChanged(targetInfo) {
        this.#targetInfo = targetInfo;
        this._checkIfInitialized();
    }
    _initialize() {
        this._initializedDeferred.resolve(InitializationStatus.SUCCESS);
    }
    _isTargetExposed() {
        return this.type() !== TargetType.TAB && !this._subtype();
    }
    _checkIfInitialized() {
        if (!this._initializedDeferred.resolved()) {
            this._initializedDeferred.resolve(InitializationStatus.SUCCESS);
        }
    }
}
class PageTarget extends CdpTarget {
    #defaultViewport;
    pagePromise;
    constructor(targetInfo, session, browserContext, targetManager, sessionFactory, defaultViewport) {
        super(targetInfo, session, browserContext, targetManager, sessionFactory);
        this.#defaultViewport = defaultViewport ?? undefined;
    }
    _initialize() {
        this._initializedDeferred
            .valueOrThrow()
            .then(async (result) => {
            if (result === InitializationStatus.ABORTED) {
                return;
            }
            const opener = this.opener();
            if (!(opener instanceof PageTarget)) {
                return;
            }
            if (!opener || !opener.pagePromise || this.type() !== 'page') {
                return true;
            }
            const openerPage = await opener.pagePromise;
            if (!openerPage.listenerCount("popup" )) {
                return true;
            }
            const popupPage = await this.page();
            openerPage.emit("popup" , popupPage);
            return true;
        })
            .catch(debugError);
        this._checkIfInitialized();
    }
    async page() {
        if (!this.pagePromise) {
            const session = this._session();
            this.pagePromise = (session
                ? Promise.resolve(session)
                : this._sessionFactory()( false)).then(client => {
                return CdpPage._create(client, this, this.#defaultViewport ?? null);
            });
        }
        return (await this.pagePromise) ?? null;
    }
    _checkIfInitialized() {
        if (this._initializedDeferred.resolved()) {
            return;
        }
        if (this._getTargetInfo().url !== '') {
            this._initializedDeferred.resolve(InitializationStatus.SUCCESS);
        }
    }
}
class DevToolsTarget extends PageTarget {
}
class WorkerTarget extends CdpTarget {
    #workerPromise;
    async worker() {
        if (!this.#workerPromise) {
            const session = this._session();
            this.#workerPromise = (session
                ? Promise.resolve(session)
                : this._sessionFactory()( false)).then(client => {
                return new CdpWebWorker(client, this._getTargetInfo().url, this._targetId, this.type(), () => { } , () => { } , undefined );
            });
        }
        return await this.#workerPromise;
    }
}
class OtherTarget extends CdpTarget {
}

/**
 * @license
 * Copyright 2022 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function isPageTargetBecomingPrimary(target, newTargetInfo) {
    return Boolean(target._subtype()) && !newTargetInfo.subtype;
}
let TargetManager$1 = class TargetManager extends EventEmitter {
    #connection;
    #discoveredTargetsByTargetId = new Map();
    #attachedTargetsByTargetId = new Map();
    #attachedTargetsBySessionId = new Map();
    #ignoredTargets = new Set();
    #targetFilterCallback;
    #targetFactory;
    #attachedToTargetListenersBySession = new WeakMap();
    #detachedFromTargetListenersBySession = new WeakMap();
    #initializeDeferred = Deferred.create();
    #waitForInitiallyDiscoveredTargets = true;
    #discoveryFilter = [{}];
    #targetsIdsForInit = new Set();
    #initialAttachDone = false;
    constructor(connection, targetFactory, targetFilterCallback, waitForInitiallyDiscoveredTargets = true) {
        super();
        this.#connection = connection;
        this.#targetFilterCallback = targetFilterCallback;
        this.#targetFactory = targetFactory;
        this.#waitForInitiallyDiscoveredTargets = waitForInitiallyDiscoveredTargets;
        this.#connection.on('Target.targetCreated', this.#onTargetCreated);
        this.#connection.on('Target.targetDestroyed', this.#onTargetDestroyed);
        this.#connection.on('Target.targetInfoChanged', this.#onTargetInfoChanged);
        this.#connection.on(CDPSessionEvent.SessionDetached, this.#onSessionDetached);
        this.#setupAttachmentListeners(this.#connection);
    }
    async initialize() {
        await this.#connection.send('Target.setDiscoverTargets', {
            discover: true,
            filter: this.#discoveryFilter,
        });
        await this.#connection.send('Target.setAutoAttach', {
            waitForDebuggerOnStart: true,
            flatten: true,
            autoAttach: true,
            filter: [
                {
                    type: 'page',
                    exclude: true,
                },
                ...this.#discoveryFilter,
            ],
        });
        this.#initialAttachDone = true;
        this.#finishInitializationIfReady();
        await this.#initializeDeferred.valueOrThrow();
    }
    getChildTargets(target) {
        return target._childTargets();
    }
    dispose() {
        this.#connection.off('Target.targetCreated', this.#onTargetCreated);
        this.#connection.off('Target.targetDestroyed', this.#onTargetDestroyed);
        this.#connection.off('Target.targetInfoChanged', this.#onTargetInfoChanged);
        this.#connection.off(CDPSessionEvent.SessionDetached, this.#onSessionDetached);
        this.#removeAttachmentListeners(this.#connection);
    }
    getAvailableTargets() {
        return this.#attachedTargetsByTargetId;
    }
    #setupAttachmentListeners(session) {
        const listener = (event) => {
            void this.#onAttachedToTarget(session, event);
        };
        assert(!this.#attachedToTargetListenersBySession.has(session));
        this.#attachedToTargetListenersBySession.set(session, listener);
        session.on('Target.attachedToTarget', listener);
        const detachedListener = (event) => {
            return this.#onDetachedFromTarget(session, event);
        };
        assert(!this.#detachedFromTargetListenersBySession.has(session));
        this.#detachedFromTargetListenersBySession.set(session, detachedListener);
        session.on('Target.detachedFromTarget', detachedListener);
    }
    #removeAttachmentListeners(session) {
        const listener = this.#attachedToTargetListenersBySession.get(session);
        if (listener) {
            session.off('Target.attachedToTarget', listener);
            this.#attachedToTargetListenersBySession.delete(session);
        }
        const detachedListener = this.#detachedFromTargetListenersBySession.get(session);
        if (detachedListener) {
            session.off('Target.detachedFromTarget', detachedListener);
            this.#detachedFromTargetListenersBySession.delete(session);
        }
    }
    #silentDetach = async (session, parentSession) => {
        await session.send('Runtime.runIfWaitingForDebugger').catch(debugError);
        await parentSession
            .send('Target.detachFromTarget', {
            sessionId: session.id(),
        })
            .catch(debugError);
    };
    #getParentTarget = (parentSession) => {
        return parentSession instanceof CdpCDPSession
            ? parentSession.target()
            : null;
    };
    #onSessionDetached = (session) => {
        this.#removeAttachmentListeners(session);
    };
    #onTargetCreated = async (event) => {
        this.#discoveredTargetsByTargetId.set(event.targetInfo.targetId, event.targetInfo);
        this.emit("targetDiscovered" , event.targetInfo);
        if (event.targetInfo.type === 'browser' && event.targetInfo.attached) {
            if (this.#attachedTargetsByTargetId.has(event.targetInfo.targetId)) {
                return;
            }
            const target = this.#targetFactory(event.targetInfo, undefined);
            target._initialize();
            this.#attachedTargetsByTargetId.set(event.targetInfo.targetId, target);
        }
    };
    #onTargetDestroyed = (event) => {
        const targetInfo = this.#discoveredTargetsByTargetId.get(event.targetId);
        this.#discoveredTargetsByTargetId.delete(event.targetId);
        this.#finishInitializationIfReady(event.targetId);
        if (targetInfo?.type === 'service_worker') {
            const target = this.#attachedTargetsByTargetId.get(event.targetId);
            if (target) {
                this.emit("targetGone" , target);
                this.#attachedTargetsByTargetId.delete(event.targetId);
            }
        }
    };
    #onTargetInfoChanged = (event) => {
        this.#discoveredTargetsByTargetId.set(event.targetInfo.targetId, event.targetInfo);
        if (this.#ignoredTargets.has(event.targetInfo.targetId) ||
            !event.targetInfo.attached) {
            return;
        }
        const target = this.#attachedTargetsByTargetId.get(event.targetInfo.targetId);
        if (!target) {
            return;
        }
        const previousURL = target.url();
        const wasInitialized = target._initializedDeferred.value() === InitializationStatus.SUCCESS;
        if (isPageTargetBecomingPrimary(target, event.targetInfo)) {
            const session = target._session();
            assert(session, 'Target that is being activated is missing a CDPSession.');
            session.parentSession()?.emit(CDPSessionEvent.Swapped, session);
        }
        target._targetInfoChanged(event.targetInfo);
        if (wasInitialized && previousURL !== target.url()) {
            this.emit("targetChanged" , {
                target,
                wasInitialized,
                previousURL,
            });
        }
    };
    #onAttachedToTarget = async (parentSession, event) => {
        const targetInfo = event.targetInfo;
        const session = this.#connection._session(event.sessionId);
        if (!session) {
            throw new Error(`Session ${event.sessionId} was not created.`);
        }
        if (!this.#connection.isAutoAttached(targetInfo.targetId)) {
            return;
        }
        if (targetInfo.type === 'service_worker') {
            await this.#silentDetach(session, parentSession);
            if (this.#attachedTargetsByTargetId.has(targetInfo.targetId)) {
                return;
            }
            const target = this.#targetFactory(targetInfo);
            target._initialize();
            this.#attachedTargetsByTargetId.set(targetInfo.targetId, target);
            this.emit("targetAvailable" , target);
            return;
        }
        let target = this.#attachedTargetsByTargetId.get(targetInfo.targetId);
        const isExistingTarget = target !== undefined;
        if (!target) {
            target = this.#targetFactory(targetInfo, session, parentSession instanceof CdpCDPSession ? parentSession : undefined);
        }
        const parentTarget = this.#getParentTarget(parentSession);
        if (this.#targetFilterCallback && !this.#targetFilterCallback(target)) {
            this.#ignoredTargets.add(targetInfo.targetId);
            if (parentTarget?.type() === 'tab') {
                this.#finishInitializationIfReady(parentTarget._targetId);
            }
            await this.#silentDetach(session, parentSession);
            return;
        }
        if (this.#waitForInitiallyDiscoveredTargets &&
            event.targetInfo.type === 'tab' &&
            !this.#initialAttachDone) {
            this.#targetsIdsForInit.add(event.targetInfo.targetId);
        }
        this.#setupAttachmentListeners(session);
        if (isExistingTarget) {
            session.setTarget(target);
            this.#attachedTargetsBySessionId.set(session.id(), target);
        }
        else {
            target._initialize();
            this.#attachedTargetsByTargetId.set(targetInfo.targetId, target);
            this.#attachedTargetsBySessionId.set(session.id(), target);
        }
        parentTarget?._addChildTarget(target);
        parentSession.emit(CDPSessionEvent.Ready, session);
        if (!isExistingTarget) {
            this.emit("targetAvailable" , target);
        }
        if (parentTarget?.type() === 'tab') {
            this.#finishInitializationIfReady(parentTarget._targetId);
        }
        await Promise.all([
            session.send('Target.setAutoAttach', {
                waitForDebuggerOnStart: true,
                flatten: true,
                autoAttach: true,
                filter: this.#discoveryFilter,
            }),
            session.send('Runtime.runIfWaitingForDebugger'),
        ]).catch(debugError);
    };
    #finishInitializationIfReady(targetId) {
        if (targetId !== undefined) {
            this.#targetsIdsForInit.delete(targetId);
        }
        if (!this.#initialAttachDone) {
            return;
        }
        if (this.#targetsIdsForInit.size === 0) {
            this.#initializeDeferred.resolve();
        }
    }
    #onDetachedFromTarget = (parentSession, event) => {
        const target = this.#attachedTargetsBySessionId.get(event.sessionId);
        this.#attachedTargetsBySessionId.delete(event.sessionId);
        if (!target) {
            return;
        }
        if (parentSession instanceof CdpCDPSession) {
            parentSession.target()._removeChildTarget(target);
        }
        this.#attachedTargetsByTargetId.delete(target._targetId);
        this.emit("targetGone" , target);
    };
};

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function isDevToolsPageTarget(url) {
    return url.startsWith('devtools://devtools/bundled/devtools_app.html');
}
class CdpBrowser extends Browser$1 {
    protocol = 'cdp';
    static async _create(connection, contextIds, acceptInsecureCerts, defaultViewport, downloadBehavior, process, closeCallback, targetFilterCallback, isPageTargetCallback, waitForInitiallyDiscoveredTargets = true, networkEnabled = true, handleDevToolsAsPage = false) {
        const browser = new CdpBrowser(connection, contextIds, defaultViewport, process, closeCallback, targetFilterCallback, isPageTargetCallback, waitForInitiallyDiscoveredTargets, networkEnabled, handleDevToolsAsPage);
        if (acceptInsecureCerts) {
            await connection.send('Security.setIgnoreCertificateErrors', {
                ignore: true,
            });
        }
        await browser._attach(downloadBehavior);
        return browser;
    }
    #defaultViewport;
    #process;
    #connection;
    #closeCallback;
    #targetFilterCallback;
    #isPageTargetCallback;
    #defaultContext;
    #contexts = new Map();
    #networkEnabled = true;
    #targetManager;
    #handleDevToolsAsPage = false;
    constructor(connection, contextIds, defaultViewport, process, closeCallback, targetFilterCallback, isPageTargetCallback, waitForInitiallyDiscoveredTargets = true, networkEnabled = true, handleDevToolsAsPage = false) {
        super();
        this.#networkEnabled = networkEnabled;
        this.#defaultViewport = defaultViewport;
        this.#process = process;
        this.#connection = connection;
        this.#closeCallback = closeCallback || (() => { });
        this.#targetFilterCallback =
            targetFilterCallback ||
                (() => {
                    return true;
                });
        this.#handleDevToolsAsPage = handleDevToolsAsPage;
        this.#setIsPageTargetCallback(isPageTargetCallback);
        this.#targetManager = new TargetManager$1(connection, this.#createTarget, this.#targetFilterCallback, waitForInitiallyDiscoveredTargets);
        this.#defaultContext = new CdpBrowserContext(this.#connection, this);
        for (const contextId of contextIds) {
            this.#contexts.set(contextId, new CdpBrowserContext(this.#connection, this, contextId));
        }
    }
    #emitDisconnected = () => {
        this.emit("disconnected" , undefined);
    };
    async _attach(downloadBehavior) {
        this.#connection.on(CDPSessionEvent.Disconnected, this.#emitDisconnected);
        if (downloadBehavior) {
            await this.#defaultContext.setDownloadBehavior(downloadBehavior);
        }
        this.#targetManager.on("targetAvailable" , this.#onAttachedToTarget);
        this.#targetManager.on("targetGone" , this.#onDetachedFromTarget);
        this.#targetManager.on("targetChanged" , this.#onTargetChanged);
        this.#targetManager.on("targetDiscovered" , this.#onTargetDiscovered);
        await this.#targetManager.initialize();
    }
    _detach() {
        this.#connection.off(CDPSessionEvent.Disconnected, this.#emitDisconnected);
        this.#targetManager.off("targetAvailable" , this.#onAttachedToTarget);
        this.#targetManager.off("targetGone" , this.#onDetachedFromTarget);
        this.#targetManager.off("targetChanged" , this.#onTargetChanged);
        this.#targetManager.off("targetDiscovered" , this.#onTargetDiscovered);
    }
    process() {
        return this.#process ?? null;
    }
    _targetManager() {
        return this.#targetManager;
    }
    #setIsPageTargetCallback(isPageTargetCallback) {
        this.#isPageTargetCallback =
            isPageTargetCallback ||
                ((target) => {
                    return (target.type() === 'page' ||
                        target.type() === 'background_page' ||
                        target.type() === 'webview' ||
                        (this.#handleDevToolsAsPage &&
                            target.type() === 'other' &&
                            isDevToolsPageTarget(target.url())));
                });
    }
    _getIsPageTargetCallback() {
        return this.#isPageTargetCallback;
    }
    async createBrowserContext(options = {}) {
        const { proxyServer, proxyBypassList, downloadBehavior } = options;
        const { browserContextId } = await this.#connection.send('Target.createBrowserContext', {
            proxyServer,
            proxyBypassList: proxyBypassList && proxyBypassList.join(','),
        });
        const context = new CdpBrowserContext(this.#connection, this, browserContextId);
        if (downloadBehavior) {
            await context.setDownloadBehavior(downloadBehavior);
        }
        this.#contexts.set(browserContextId, context);
        return context;
    }
    browserContexts() {
        return [this.#defaultContext, ...Array.from(this.#contexts.values())];
    }
    defaultBrowserContext() {
        return this.#defaultContext;
    }
    async _disposeContext(contextId) {
        if (!contextId) {
            return;
        }
        await this.#connection.send('Target.disposeBrowserContext', {
            browserContextId: contextId,
        });
        this.#contexts.delete(contextId);
    }
    #createTarget = (targetInfo, session) => {
        const { browserContextId } = targetInfo;
        const context = browserContextId && this.#contexts.has(browserContextId)
            ? this.#contexts.get(browserContextId)
            : this.#defaultContext;
        if (!context) {
            throw new Error('Missing browser context');
        }
        const createSession = (isAutoAttachEmulated) => {
            return this.#connection._createSession(targetInfo, isAutoAttachEmulated);
        };
        const otherTarget = new OtherTarget(targetInfo, session, context, this.#targetManager, createSession);
        if (targetInfo.url && isDevToolsPageTarget(targetInfo.url)) {
            return new DevToolsTarget(targetInfo, session, context, this.#targetManager, createSession, this.#defaultViewport ?? null);
        }
        if (this.#isPageTargetCallback(otherTarget)) {
            return new PageTarget(targetInfo, session, context, this.#targetManager, createSession, this.#defaultViewport ?? null);
        }
        if (targetInfo.type === 'service_worker' ||
            targetInfo.type === 'shared_worker') {
            return new WorkerTarget(targetInfo, session, context, this.#targetManager, createSession);
        }
        return otherTarget;
    };
    #onAttachedToTarget = async (target) => {
        if (target._isTargetExposed() &&
            (await target._initializedDeferred.valueOrThrow()) ===
                InitializationStatus.SUCCESS) {
            this.emit("targetcreated" , target);
            target.browserContext().emit("targetcreated" , target);
        }
    };
    #onDetachedFromTarget = async (target) => {
        target._initializedDeferred.resolve(InitializationStatus.ABORTED);
        target._isClosedDeferred.resolve();
        if (target._isTargetExposed() &&
            (await target._initializedDeferred.valueOrThrow()) ===
                InitializationStatus.SUCCESS) {
            this.emit("targetdestroyed" , target);
            target.browserContext().emit("targetdestroyed" , target);
        }
    };
    #onTargetChanged = ({ target }) => {
        this.emit("targetchanged" , target);
        target.browserContext().emit("targetchanged" , target);
    };
    #onTargetDiscovered = (targetInfo) => {
        this.emit("targetdiscovered" , targetInfo);
    };
    wsEndpoint() {
        return this.#connection.url();
    }
    async newPage(options) {
        return await this.#defaultContext.newPage(options);
    }
    async _createPageInContext(contextId, options) {
        const hasTargets = this.targets().filter(t => {
            return t.browserContext().id === contextId;
        }).length > 0;
        const windowBounds = options?.type === 'window' ? options.windowBounds : undefined;
        const { targetId } = await this.#connection.send('Target.createTarget', {
            url: 'about:blank',
            browserContextId: contextId || undefined,
            left: windowBounds?.left,
            top: windowBounds?.top,
            width: windowBounds?.width,
            height: windowBounds?.height,
            windowState: windowBounds?.windowState,
            newWindow: hasTargets && options?.type === 'window' ? true : undefined,
            background: options?.background,
        });
        const target = (await this.waitForTarget(t => {
            return t._targetId === targetId;
        }));
        if (!target) {
            throw new Error(`Missing target for page (id = ${targetId})`);
        }
        const initialized = (await target._initializedDeferred.valueOrThrow()) ===
            InitializationStatus.SUCCESS;
        if (!initialized) {
            throw new Error(`Failed to create target for page (id = ${targetId})`);
        }
        const page = await target.page();
        if (!page) {
            throw new Error(`Failed to create a page for context (id = ${contextId})`);
        }
        return page;
    }
    async _createDevToolsPage(pageTargetId) {
        const openDevToolsResponse = await this.#connection.send('Target.openDevTools', {
            targetId: pageTargetId,
        });
        const target = (await this.waitForTarget(t => {
            return t._targetId === openDevToolsResponse.targetId;
        }));
        if (!target) {
            throw new Error(`Missing target for DevTools page (id = ${pageTargetId})`);
        }
        const initialized = (await target._initializedDeferred.valueOrThrow()) ===
            InitializationStatus.SUCCESS;
        if (!initialized) {
            throw new Error(`Failed to create target for DevTools page (id = ${pageTargetId})`);
        }
        const page = await target.page();
        if (!page) {
            throw new Error(`Failed to create a DevTools Page for target (id = ${pageTargetId})`);
        }
        return page;
    }
    async installExtension(path) {
        const { id } = await this.#connection.send('Extensions.loadUnpacked', { path });
        return id;
    }
    uninstallExtension(id) {
        return this.#connection.send('Extensions.uninstall', { id });
    }
    async screens() {
        const { screenInfos } = await this.#connection.send('Emulation.getScreenInfos');
        return screenInfos;
    }
    async addScreen(params) {
        const { screenInfo } = await this.#connection.send('Emulation.addScreen', params);
        return screenInfo;
    }
    async removeScreen(screenId) {
        return await this.#connection.send('Emulation.removeScreen', { screenId });
    }
    async getWindowBounds(windowId) {
        const { bounds } = await this.#connection.send('Browser.getWindowBounds', {
            windowId: Number(windowId),
        });
        return bounds;
    }
    async setWindowBounds(windowId, windowBounds) {
        await this.#connection.send('Browser.setWindowBounds', {
            windowId: Number(windowId),
            bounds: windowBounds,
        });
    }
    targets() {
        return Array.from(this.#targetManager.getAvailableTargets().values()).filter(target => {
            return (target._isTargetExposed() &&
                target._initializedDeferred.value() === InitializationStatus.SUCCESS);
        });
    }
    target() {
        const browserTarget = this.targets().find(target => {
            return target.type() === 'browser';
        });
        if (!browserTarget) {
            throw new Error('Browser target is not found');
        }
        return browserTarget;
    }
    async version() {
        const version = await this.#getVersion();
        return version.product;
    }
    async userAgent() {
        const version = await this.#getVersion();
        return version.userAgent;
    }
    async close() {
        await this.#closeCallback.call(null);
        await this.disconnect();
    }
    disconnect() {
        this.#targetManager.dispose();
        this.#connection.dispose();
        this._detach();
        return Promise.resolve();
    }
    get connected() {
        return !this.#connection._closed;
    }
    #getVersion() {
        return this.#connection.send('Browser.getVersion');
    }
    get debugInfo() {
        return {
            pendingProtocolErrors: this.#connection.getPendingProtocolErrors(),
        };
    }
    isNetworkEnabled() {
        return this.#networkEnabled;
    }
}

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
async function _connectToCdpBrowser(connectionTransport, url, options) {
    const { acceptInsecureCerts = false, networkEnabled = true, defaultViewport = DEFAULT_VIEWPORT, downloadBehavior, targetFilter, _isPageTarget: isPageTarget, slowMo = 0, protocolTimeout, handleDevToolsAsPage, idGenerator = createIncrementalIdGenerator(), } = options;
    const connection = new Connection(url, connectionTransport, slowMo, protocolTimeout,
     false, idGenerator);
    const { browserContextIds } = await connection.send('Target.getBrowserContexts');
    const browser = await CdpBrowser._create(connection, browserContextIds, acceptInsecureCerts, defaultViewport, downloadBehavior, undefined, () => {
        return connection.send('Browser.close').catch(debugError);
    }, targetFilter, isPageTarget, undefined, networkEnabled, handleDevToolsAsPage);
    return browser;
}

/**
 * @license
 * Copyright 2021 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const PredefinedNetworkConditions = Object.freeze({
    'Slow 3G': {
        download: ((500 * 1000) / 8) * 0.8,
        upload: ((500 * 1000) / 8) * 0.8,
        latency: 400 * 5,
    },
    'Fast 3G': {
        download: ((1.6 * 1000 * 1000) / 8) * 0.9,
        upload: ((750 * 1000) / 8) * 0.9,
        latency: 150 * 3.75,
    },
    'Slow 4G': {
        download: ((1.6 * 1000 * 1000) / 8) * 0.9,
        upload: ((750 * 1000) / 8) * 0.9,
        latency: 150 * 3.75,
    },
    'Fast 4G': {
        download: ((9 * 1000 * 1000) / 8) * 0.9,
        upload: ((1.5 * 1000 * 1000) / 8) * 0.9,
        latency: 60 * 2.75,
    },
});

class BrowserWebSocketTransport {
    static create(url) {
        return new Promise((resolve, reject) => {
            const ws = new WebSocket(url);
            ws.addEventListener('open', () => {
                return resolve(new BrowserWebSocketTransport(ws));
            });
            ws.addEventListener('error', reject);
        });
    }
    #ws;
    onmessage;
    onclose;
    constructor(ws) {
        this.#ws = ws;
        this.#ws.addEventListener('message', event => {
            if (this.onmessage) {
                this.onmessage.call(null, event.data);
            }
        });
        this.#ws.addEventListener('close', () => {
            if (this.onclose) {
                this.onclose.call(null);
            }
        });
        this.#ws.addEventListener('error', () => { });
    }
    send(message) {
        this.#ws.send(message);
    }
    close() {
        this.#ws.close();
    }
}

var BrowserWebSocketTransport$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	BrowserWebSocketTransport: BrowserWebSocketTransport
});

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const knownDevices = [
    {
        name: 'Blackberry PlayBook',
        userAgent: 'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+',
        viewport: {
            width: 600,
            height: 1024,
            deviceScaleFactor: 1,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Blackberry PlayBook landscape',
        userAgent: 'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+',
        viewport: {
            width: 1024,
            height: 600,
            deviceScaleFactor: 1,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'BlackBerry Z30',
        userAgent: 'Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+',
        viewport: {
            width: 360,
            height: 640,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'BlackBerry Z30 landscape',
        userAgent: 'Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+',
        viewport: {
            width: 640,
            height: 360,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Galaxy Note 3',
        userAgent: 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
        viewport: {
            width: 360,
            height: 640,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Galaxy Note 3 landscape',
        userAgent: 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
        viewport: {
            width: 640,
            height: 360,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Galaxy Note II',
        userAgent: 'Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
        viewport: {
            width: 360,
            height: 640,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Galaxy Note II landscape',
        userAgent: 'Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
        viewport: {
            width: 640,
            height: 360,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Galaxy S III',
        userAgent: 'Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
        viewport: {
            width: 360,
            height: 640,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Galaxy S III landscape',
        userAgent: 'Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
        viewport: {
            width: 640,
            height: 360,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Galaxy S5',
        userAgent: 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 360,
            height: 640,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Galaxy S5 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 640,
            height: 360,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Galaxy S8',
        userAgent: 'Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36',
        viewport: {
            width: 360,
            height: 740,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Galaxy S8 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36',
        viewport: {
            width: 740,
            height: 360,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Galaxy S9+',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36',
        viewport: {
            width: 320,
            height: 658,
            deviceScaleFactor: 4.5,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Galaxy S9+ landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36',
        viewport: {
            width: 658,
            height: 320,
            deviceScaleFactor: 4.5,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Galaxy Tab S4',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Safari/537.36',
        viewport: {
            width: 712,
            height: 1138,
            deviceScaleFactor: 2.25,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Galaxy Tab S4 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Safari/537.36',
        viewport: {
            width: 1138,
            height: 712,
            deviceScaleFactor: 2.25,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPad',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',
        viewport: {
            width: 768,
            height: 1024,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPad landscape',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',
        viewport: {
            width: 1024,
            height: 768,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPad (gen 6)',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 768,
            height: 1024,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPad (gen 6) landscape',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 1024,
            height: 768,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPad (gen 7)',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 810,
            height: 1080,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPad (gen 7) landscape',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 1080,
            height: 810,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPad Mini',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',
        viewport: {
            width: 768,
            height: 1024,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPad Mini landscape',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',
        viewport: {
            width: 1024,
            height: 768,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPad Pro',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',
        viewport: {
            width: 1024,
            height: 1366,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPad Pro landscape',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',
        viewport: {
            width: 1366,
            height: 1024,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPad Pro 11',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 834,
            height: 1194,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPad Pro 11 landscape',
        userAgent: 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 1194,
            height: 834,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 4',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53',
        viewport: {
            width: 320,
            height: 480,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 4 landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53',
        viewport: {
            width: 480,
            height: 320,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 5',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
        viewport: {
            width: 320,
            height: 568,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 5 landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
        viewport: {
            width: 568,
            height: 320,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 6',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 375,
            height: 667,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 6 landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 667,
            height: 375,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 6 Plus',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 414,
            height: 736,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 6 Plus landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 736,
            height: 414,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 7',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 375,
            height: 667,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 7 landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 667,
            height: 375,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 7 Plus',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 414,
            height: 736,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 7 Plus landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 736,
            height: 414,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 8',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 375,
            height: 667,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 8 landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 667,
            height: 375,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 8 Plus',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 414,
            height: 736,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 8 Plus landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 736,
            height: 414,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone SE',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
        viewport: {
            width: 320,
            height: 568,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone SE landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
        viewport: {
            width: 568,
            height: 320,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone X',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 375,
            height: 812,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone X landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
        viewport: {
            width: 812,
            height: 375,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone XR',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 414,
            height: 896,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone XR landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 896,
            height: 414,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 11',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 414,
            height: 828,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 11 landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 828,
            height: 414,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 11 Pro',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 375,
            height: 812,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 11 Pro landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 812,
            height: 375,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 11 Pro Max',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 414,
            height: 896,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 11 Pro Max landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 896,
            height: 414,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 12',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 390,
            height: 844,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 12 landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 844,
            height: 390,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 12 Pro',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 390,
            height: 844,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 12 Pro landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 844,
            height: 390,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 12 Pro Max',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 428,
            height: 926,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 12 Pro Max landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 926,
            height: 428,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 12 Mini',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 375,
            height: 812,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 12 Mini landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 812,
            height: 375,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 13',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 390,
            height: 844,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 13 landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 844,
            height: 390,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 13 Pro',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 390,
            height: 844,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 13 Pro landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 844,
            height: 390,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 13 Pro Max',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 428,
            height: 926,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 13 Pro Max landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 926,
            height: 428,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 13 Mini',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 375,
            height: 812,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 13 Mini landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 812,
            height: 375,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 14',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 390,
            height: 663,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 14 landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 750,
            height: 340,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 14 Plus',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 428,
            height: 745,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 14 Plus landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 832,
            height: 378,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 14 Pro',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 393,
            height: 659,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 14 Pro landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 734,
            height: 343,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 14 Pro Max',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 430,
            height: 739,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 14 Pro Max landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 814,
            height: 380,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 15',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 393,
            height: 659,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 15 landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 734,
            height: 343,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 15 Plus',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 430,
            height: 739,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 15 Plus landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 814,
            height: 380,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 15 Pro',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 393,
            height: 659,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 15 Pro landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 734,
            height: 343,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'iPhone 15 Pro Max',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 430,
            height: 739,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'iPhone 15 Pro Max landscape',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',
        viewport: {
            width: 814,
            height: 380,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'JioPhone 2',
        userAgent: 'Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5',
        viewport: {
            width: 240,
            height: 320,
            deviceScaleFactor: 1,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'JioPhone 2 landscape',
        userAgent: 'Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5',
        viewport: {
            width: 320,
            height: 240,
            deviceScaleFactor: 1,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Kindle Fire HDX',
        userAgent: 'Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true',
        viewport: {
            width: 800,
            height: 1280,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Kindle Fire HDX landscape',
        userAgent: 'Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true',
        viewport: {
            width: 1280,
            height: 800,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'LG Optimus L70',
        userAgent: 'Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 384,
            height: 640,
            deviceScaleFactor: 1.25,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'LG Optimus L70 landscape',
        userAgent: 'Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 640,
            height: 384,
            deviceScaleFactor: 1.25,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Microsoft Lumia 550',
        userAgent: 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263',
        viewport: {
            width: 640,
            height: 360,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Microsoft Lumia 950',
        userAgent: 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263',
        viewport: {
            width: 360,
            height: 640,
            deviceScaleFactor: 4,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Microsoft Lumia 950 landscape',
        userAgent: 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263',
        viewport: {
            width: 640,
            height: 360,
            deviceScaleFactor: 4,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Nexus 10',
        userAgent: 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36',
        viewport: {
            width: 800,
            height: 1280,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Nexus 10 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36',
        viewport: {
            width: 1280,
            height: 800,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Nexus 4',
        userAgent: 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 384,
            height: 640,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Nexus 4 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 640,
            height: 384,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Nexus 5',
        userAgent: 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 360,
            height: 640,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Nexus 5 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 640,
            height: 360,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Nexus 5X',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 412,
            height: 732,
            deviceScaleFactor: 2.625,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Nexus 5X landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 732,
            height: 412,
            deviceScaleFactor: 2.625,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Nexus 6',
        userAgent: 'Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 412,
            height: 732,
            deviceScaleFactor: 3.5,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Nexus 6 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 732,
            height: 412,
            deviceScaleFactor: 3.5,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Nexus 6P',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 412,
            height: 732,
            deviceScaleFactor: 3.5,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Nexus 6P landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 732,
            height: 412,
            deviceScaleFactor: 3.5,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Nexus 7',
        userAgent: 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36',
        viewport: {
            width: 600,
            height: 960,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Nexus 7 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36',
        viewport: {
            width: 960,
            height: 600,
            deviceScaleFactor: 2,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Nokia Lumia 520',
        userAgent: 'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)',
        viewport: {
            width: 320,
            height: 533,
            deviceScaleFactor: 1.5,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Nokia Lumia 520 landscape',
        userAgent: 'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)',
        viewport: {
            width: 533,
            height: 320,
            deviceScaleFactor: 1.5,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Nokia N9',
        userAgent: 'Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13',
        viewport: {
            width: 480,
            height: 854,
            deviceScaleFactor: 1,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Nokia N9 landscape',
        userAgent: 'Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13',
        viewport: {
            width: 854,
            height: 480,
            deviceScaleFactor: 1,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Pixel 2',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 411,
            height: 731,
            deviceScaleFactor: 2.625,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Pixel 2 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 731,
            height: 411,
            deviceScaleFactor: 2.625,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Pixel 2 XL',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 411,
            height: 823,
            deviceScaleFactor: 3.5,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Pixel 2 XL landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',
        viewport: {
            width: 823,
            height: 411,
            deviceScaleFactor: 3.5,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Pixel 3',
        userAgent: 'Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.158 Mobile Safari/537.36',
        viewport: {
            width: 393,
            height: 786,
            deviceScaleFactor: 2.75,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Pixel 3 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.158 Mobile Safari/537.36',
        viewport: {
            width: 786,
            height: 393,
            deviceScaleFactor: 2.75,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Pixel 4',
        userAgent: 'Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36',
        viewport: {
            width: 353,
            height: 745,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Pixel 4 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36',
        viewport: {
            width: 745,
            height: 353,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Pixel 4a (5G)',
        userAgent: 'Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36',
        viewport: {
            width: 353,
            height: 745,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Pixel 4a (5G) landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36',
        viewport: {
            width: 745,
            height: 353,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Pixel 5',
        userAgent: 'Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36',
        viewport: {
            width: 393,
            height: 851,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Pixel 5 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36',
        viewport: {
            width: 851,
            height: 393,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
    {
        name: 'Moto G4',
        userAgent: 'Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36',
        viewport: {
            width: 360,
            height: 640,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: false,
        },
    },
    {
        name: 'Moto G4 landscape',
        userAgent: 'Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36',
        viewport: {
            width: 640,
            height: 360,
            deviceScaleFactor: 3,
            isMobile: true,
            hasTouch: true,
            isLandscape: true,
        },
    },
];
const knownDevicesByName = {};
for (const device of knownDevices) {
    knownDevicesByName[device.name] = device;
}
const KnownDevices = Object.freeze(knownDevicesByName);

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
async function _connectToBiDiBrowser(connectionTransport, url, options) {
    const { acceptInsecureCerts = false, networkEnabled = true, defaultViewport = DEFAULT_VIEWPORT, } = options;
    const { bidiConnection, cdpConnection, closeCallback } = await getBiDiConnection(connectionTransport, url, options);
    const BiDi = await import( '../../../node_modules/puppeteer-core/lib/esm/puppeteer/bidi/bidi.js');
    const bidiBrowser = await BiDi.BidiBrowser.create({
        connection: bidiConnection,
        cdpConnection,
        closeCallback,
        process: undefined,
        defaultViewport: defaultViewport,
        acceptInsecureCerts: acceptInsecureCerts,
        networkEnabled,
        capabilities: options.capabilities,
    });
    return bidiBrowser;
}
async function getBiDiConnection(connectionTransport, url, options) {
    const BiDi = await import( '../../../node_modules/puppeteer-core/lib/esm/puppeteer/bidi/bidi.js');
    const { slowMo = 0, protocolTimeout, idGenerator = createIncrementalIdGenerator(), } = options;
    const pureBidiConnection = new BiDi.BidiConnection(url, connectionTransport, idGenerator, slowMo, protocolTimeout);
    try {
        const result = await pureBidiConnection.send('session.status', {});
        if ('type' in result && result.type === 'success') {
            return {
                bidiConnection: pureBidiConnection,
                closeCallback: async () => {
                    await pureBidiConnection.send('browser.close', {}).catch(debugError);
                },
            };
        }
    }
    catch (e) {
        if (!(e instanceof ProtocolError)) {
            throw e;
        }
    }
    pureBidiConnection.unbind();
    const cdpConnection = new Connection(url, connectionTransport, slowMo, protocolTimeout,
     true, idGenerator);
    const version = await cdpConnection.send('Browser.getVersion');
    if (version.product.toLowerCase().includes('firefox')) {
        throw new UnsupportedOperation('Firefox is not supported in BiDi over CDP mode.');
    }
    const bidiOverCdpConnection = await BiDi.connectBidiOverCdp(cdpConnection);
    return {
        cdpConnection,
        bidiConnection: bidiOverCdpConnection,
        closeCallback: async () => {
            await cdpConnection.send('Browser.close').catch(debugError);
        },
    };
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const getWebSocketTransportClass = async () => {
    return isNode
        ? (await Promise.resolve().then(function () { return NodeWebSocketTransport$1; })).NodeWebSocketTransport
        : (await Promise.resolve().then(function () { return BrowserWebSocketTransport$1; }))
            .BrowserWebSocketTransport;
};
async function _connectToBrowser(options) {
    const { connectionTransport, endpointUrl } = await getConnectionTransport(options);
    if (options.protocol === 'webDriverBiDi') {
        const bidiBrowser = await _connectToBiDiBrowser(connectionTransport, endpointUrl, options);
        return bidiBrowser;
    }
    else {
        const cdpBrowser = await _connectToCdpBrowser(connectionTransport, endpointUrl, options);
        return cdpBrowser;
    }
}
async function getConnectionTransport(options) {
    const { browserWSEndpoint, browserURL, channel, transport, headers = {}, } = options;
    assert(Number(!!browserWSEndpoint) +
        Number(!!browserURL) +
        Number(!!transport) +
        Number(!!channel) ===
        1, 'Exactly one of browserWSEndpoint, browserURL, transport or channel must be passed to puppeteer.connect');
    if (transport) {
        return { connectionTransport: transport, endpointUrl: '' };
    }
    else if (browserWSEndpoint) {
        const WebSocketClass = await getWebSocketTransportClass();
        const connectionTransport = await WebSocketClass.create(browserWSEndpoint, headers);
        return {
            connectionTransport: connectionTransport,
            endpointUrl: browserWSEndpoint,
        };
    }
    else if (browserURL) {
        const connectionURL = await getWSEndpoint(browserURL);
        const WebSocketClass = await getWebSocketTransportClass();
        const connectionTransport = await WebSocketClass.create(connectionURL);
        return {
            connectionTransport: connectionTransport,
            endpointUrl: connectionURL,
        };
    }
    else if (options.channel && isNode) {
        const { detectBrowserPlatform, resolveDefaultUserDataDir, Browser } = await Promise.resolve().then(function () { return main; });
        const platform = detectBrowserPlatform();
        if (!platform) {
            throw new Error('Could not detect required browser platform');
        }
        const { convertPuppeteerChannelToBrowsersChannel } = await Promise.resolve().then(function () { return LaunchOptions; });
        const { join } = await import('node:path');
        const userDataDir = resolveDefaultUserDataDir(Browser.CHROME, platform, convertPuppeteerChannelToBrowsersChannel(options.channel));
        const portPath = join(userDataDir, 'DevToolsActivePort');
        try {
            const fileContent = await environment.value.fs.promises.readFile(portPath, 'ascii');
            const [rawPort, rawPath] = fileContent
                .split('\n')
                .map(line => {
                return line.trim();
            })
                .filter(line => {
                return !!line;
            });
            if (!rawPort || !rawPath) {
                throw new Error(`Invalid DevToolsActivePort '${fileContent}' found`);
            }
            const port = parseInt(rawPort, 10);
            if (isNaN(port) || port <= 0 || port > 65535) {
                throw new Error(`Invalid port '${rawPort}' found`);
            }
            const browserWSEndpoint = `ws://localhost:${port}${rawPath}`;
            const WebSocketClass = await getWebSocketTransportClass();
            const connectionTransport = await WebSocketClass.create(browserWSEndpoint, headers);
            return {
                connectionTransport: connectionTransport,
                endpointUrl: browserWSEndpoint,
            };
        }
        catch (error) {
            throw new Error(`Could not find DevToolsActivePort for ${options.channel} at ${portPath}`, {
                cause: error,
            });
        }
    }
    throw new Error('Invalid connection options');
}
async function getWSEndpoint(browserURL) {
    const endpointURL = new URL('/json/version', browserURL);
    try {
        const result = await globalThis.fetch(endpointURL.toString(), {
            method: 'GET',
        });
        if (!result.ok) {
            throw new Error(`HTTP ${result.statusText}`);
        }
        const data = await result.json();
        return data.webSocketDebuggerUrl;
    }
    catch (error) {
        if (isErrorLike$1(error)) {
            error.message =
                `Failed to fetch browser webSocket URL from ${endpointURL}: ` +
                    error.message;
        }
        throw error;
    }
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class Puppeteer {
    static customQueryHandlers = customQueryHandlers;
    static registerCustomQueryHandler(name, queryHandler) {
        return this.customQueryHandlers.register(name, queryHandler);
    }
    static unregisterCustomQueryHandler(name) {
        return this.customQueryHandlers.unregister(name);
    }
    static customQueryHandlerNames() {
        return this.customQueryHandlers.names();
    }
    static clearCustomQueryHandlers() {
        return this.customQueryHandlers.clear();
    }
    _isPuppeteerCore;
    _changedBrowsers = false;
    constructor(settings) {
        this._isPuppeteerCore = settings.isPuppeteerCore;
        this.connect = this.connect.bind(this);
    }
    connect(options) {
        return _connectToBrowser(options);
    }
}

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const PUPPETEER_REVISIONS = Object.freeze({
    chrome: '146.0.7680.31',
    'chrome-headless-shell': '146.0.7680.31',
    firefox: 'stable_148.0',
});

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var Browser;
(function (Browser) {
    Browser["CHROME"] = "chrome";
    Browser["CHROMEHEADLESSSHELL"] = "chrome-headless-shell";
    Browser["CHROMIUM"] = "chromium";
    Browser["FIREFOX"] = "firefox";
    Browser["CHROMEDRIVER"] = "chromedriver";
})(Browser || (Browser = {}));
var BrowserPlatform;
(function (BrowserPlatform) {
    BrowserPlatform["LINUX"] = "linux";
    BrowserPlatform["LINUX_ARM"] = "linux_arm";
    BrowserPlatform["MAC"] = "mac";
    BrowserPlatform["MAC_ARM"] = "mac_arm";
    BrowserPlatform["WIN32"] = "win32";
    BrowserPlatform["WIN64"] = "win64";
})(BrowserPlatform || (BrowserPlatform = {}));
var BrowserTag;
(function (BrowserTag) {
    BrowserTag["CANARY"] = "canary";
    BrowserTag["NIGHTLY"] = "nightly";
    BrowserTag["BETA"] = "beta";
    BrowserTag["DEV"] = "dev";
    BrowserTag["DEVEDITION"] = "devedition";
    BrowserTag["STABLE"] = "stable";
    BrowserTag["ESR"] = "esr";
    BrowserTag["LATEST"] = "latest";
})(BrowserTag || (BrowserTag = {}));
var ChromeReleaseChannel;
(function (ChromeReleaseChannel) {
    ChromeReleaseChannel["STABLE"] = "stable";
    ChromeReleaseChannel["DEV"] = "dev";
    ChromeReleaseChannel["CANARY"] = "canary";
    ChromeReleaseChannel["BETA"] = "beta";
})(ChromeReleaseChannel || (ChromeReleaseChannel = {}));

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

var constants$4;
var hasRequiredConstants$4;

function requireConstants$4 () {
	if (hasRequiredConstants$4) return constants$4;
	hasRequiredConstants$4 = 1;
	const SEMVER_SPEC_VERSION = '2.0.0';
	const MAX_LENGTH = 256;
	const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
	 9007199254740991;
	const MAX_SAFE_COMPONENT_LENGTH = 16;
	const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
	const RELEASE_TYPES = [
	  'major',
	  'premajor',
	  'minor',
	  'preminor',
	  'patch',
	  'prepatch',
	  'prerelease',
	];
	constants$4 = {
	  MAX_LENGTH,
	  MAX_SAFE_COMPONENT_LENGTH,
	  MAX_SAFE_BUILD_LENGTH,
	  MAX_SAFE_INTEGER,
	  RELEASE_TYPES,
	  SEMVER_SPEC_VERSION,
	  FLAG_INCLUDE_PRERELEASE: 0b001,
	  FLAG_LOOSE: 0b010,
	};
	return constants$4;
}

var debug_1;
var hasRequiredDebug$1;

function requireDebug$1 () {
	if (hasRequiredDebug$1) return debug_1;
	hasRequiredDebug$1 = 1;
	const debug = (
	  typeof process === 'object' &&
	  process.env &&
	  process.env.NODE_DEBUG &&
	  /\bsemver\b/i.test(process.env.NODE_DEBUG)
	) ? (...args) => console.error('SEMVER', ...args)
	  : () => {};
	debug_1 = debug;
	return debug_1;
}

var hasRequiredRe;

function requireRe () {
	if (hasRequiredRe) return re$1.exports;
	hasRequiredRe = 1;
	(function (module, exports$1) {
		const {
		  MAX_SAFE_COMPONENT_LENGTH,
		  MAX_SAFE_BUILD_LENGTH,
		  MAX_LENGTH,
		} = requireConstants$4();
		const debug = requireDebug$1();
		exports$1 = module.exports = {};
		const re = exports$1.re = [];
		const safeRe = exports$1.safeRe = [];
		const src = exports$1.src = [];
		const safeSrc = exports$1.safeSrc = [];
		const t = exports$1.t = {};
		let R = 0;
		const LETTERDASHNUMBER = '[a-zA-Z0-9-]';
		const safeRegexReplacements = [
		  ['\\s', 1],
		  ['\\d', MAX_LENGTH],
		  [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
		];
		const makeSafeRegex = (value) => {
		  for (const [token, max] of safeRegexReplacements) {
		    value = value
		      .split(`${token}*`).join(`${token}{0,${max}}`)
		      .split(`${token}+`).join(`${token}{1,${max}}`);
		  }
		  return value
		};
		const createToken = (name, value, isGlobal) => {
		  const safe = makeSafeRegex(value);
		  const index = R++;
		  debug(name, index, value);
		  t[name] = index;
		  src[index] = value;
		  safeSrc[index] = safe;
		  re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
		  safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined);
		};
		createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
		createToken('NUMERICIDENTIFIERLOOSE', '\\d+');
		createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
		createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
		                   `(${src[t.NUMERICIDENTIFIER]})\\.` +
		                   `(${src[t.NUMERICIDENTIFIER]})`);
		createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
		                        `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
		                        `(${src[t.NUMERICIDENTIFIERLOOSE]})`);
		createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]
		}|${src[t.NUMERICIDENTIFIER]})`);
		createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]
		}|${src[t.NUMERICIDENTIFIERLOOSE]})`);
		createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
		}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
		createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
		}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
		createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`);
		createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
		}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
		createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
		}${src[t.PRERELEASE]}?${
		  src[t.BUILD]}?`);
		createToken('FULL', `^${src[t.FULLPLAIN]}$`);
		createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
		}${src[t.PRERELEASELOOSE]}?${
		  src[t.BUILD]}?`);
		createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);
		createToken('GTLT', '((?:<|>)?=?)');
		createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
		createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
		createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
		                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
		                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
		                   `(?:${src[t.PRERELEASE]})?${
		                     src[t.BUILD]}?` +
		                   `)?)?`);
		createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
		                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
		                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
		                        `(?:${src[t.PRERELEASELOOSE]})?${
		                          src[t.BUILD]}?` +
		                        `)?)?`);
		createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
		createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
		createToken('COERCEPLAIN', `${'(^|[^\\d])' +
		              '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
		              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
		              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
		createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
		createToken('COERCEFULL', src[t.COERCEPLAIN] +
		              `(?:${src[t.PRERELEASE]})?` +
		              `(?:${src[t.BUILD]})?` +
		              `(?:$|[^\\d])`);
		createToken('COERCERTL', src[t.COERCE], true);
		createToken('COERCERTLFULL', src[t.COERCEFULL], true);
		createToken('LONETILDE', '(?:~>?)');
		createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
		exports$1.tildeTrimReplace = '$1~';
		createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
		createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
		createToken('LONECARET', '(?:\\^)');
		createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
		exports$1.caretTrimReplace = '$1^';
		createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
		createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
		createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
		createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
		createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
		}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
		exports$1.comparatorTrimReplace = '$1$2$3';
		createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
		                   `\\s+-\\s+` +
		                   `(${src[t.XRANGEPLAIN]})` +
		                   `\\s*$`);
		createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
		                        `\\s+-\\s+` +
		                        `(${src[t.XRANGEPLAINLOOSE]})` +
		                        `\\s*$`);
		createToken('STAR', '(<|>)?=?\\s*\\*');
		createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$');
		createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$'); 
	} (re$1, re$1.exports));
	return re$1.exports;
}

var parseOptions_1;
var hasRequiredParseOptions;

function requireParseOptions () {
	if (hasRequiredParseOptions) return parseOptions_1;
	hasRequiredParseOptions = 1;
	const looseOption = Object.freeze({ loose: true });
	const emptyOpts = Object.freeze({ });
	const parseOptions = options => {
	  if (!options) {
	    return emptyOpts
	  }
	  if (typeof options !== 'object') {
	    return looseOption
	  }
	  return options
	};
	parseOptions_1 = parseOptions;
	return parseOptions_1;
}

var identifiers;
var hasRequiredIdentifiers;

function requireIdentifiers () {
	if (hasRequiredIdentifiers) return identifiers;
	hasRequiredIdentifiers = 1;
	const numeric = /^[0-9]+$/;
	const compareIdentifiers = (a, b) => {
	  if (typeof a === 'number' && typeof b === 'number') {
	    return a === b ? 0 : a < b ? -1 : 1
	  }
	  const anum = numeric.test(a);
	  const bnum = numeric.test(b);
	  if (anum && bnum) {
	    a = +a;
	    b = +b;
	  }
	  return a === b ? 0
	    : (anum && !bnum) ? -1
	    : (bnum && !anum) ? 1
	    : a < b ? -1
	    : 1
	};
	const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
	identifiers = {
	  compareIdentifiers,
	  rcompareIdentifiers,
	};
	return identifiers;
}

var semver$2;
var hasRequiredSemver$1;

function requireSemver$1 () {
	if (hasRequiredSemver$1) return semver$2;
	hasRequiredSemver$1 = 1;
	const debug = requireDebug$1();
	const { MAX_LENGTH, MAX_SAFE_INTEGER } = requireConstants$4();
	const { safeRe: re, t } = requireRe();
	const parseOptions = requireParseOptions();
	const { compareIdentifiers } = requireIdentifiers();
	class SemVer {
	  constructor (version, options) {
	    options = parseOptions(options);
	    if (version instanceof SemVer) {
	      if (version.loose === !!options.loose &&
	        version.includePrerelease === !!options.includePrerelease) {
	        return version
	      } else {
	        version = version.version;
	      }
	    } else if (typeof version !== 'string') {
	      throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
	    }
	    if (version.length > MAX_LENGTH) {
	      throw new TypeError(
	        `version is longer than ${MAX_LENGTH} characters`
	      )
	    }
	    debug('SemVer', version, options);
	    this.options = options;
	    this.loose = !!options.loose;
	    this.includePrerelease = !!options.includePrerelease;
	    const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
	    if (!m) {
	      throw new TypeError(`Invalid Version: ${version}`)
	    }
	    this.raw = version;
	    this.major = +m[1];
	    this.minor = +m[2];
	    this.patch = +m[3];
	    if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
	      throw new TypeError('Invalid major version')
	    }
	    if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
	      throw new TypeError('Invalid minor version')
	    }
	    if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
	      throw new TypeError('Invalid patch version')
	    }
	    if (!m[4]) {
	      this.prerelease = [];
	    } else {
	      this.prerelease = m[4].split('.').map((id) => {
	        if (/^[0-9]+$/.test(id)) {
	          const num = +id;
	          if (num >= 0 && num < MAX_SAFE_INTEGER) {
	            return num
	          }
	        }
	        return id
	      });
	    }
	    this.build = m[5] ? m[5].split('.') : [];
	    this.format();
	  }
	  format () {
	    this.version = `${this.major}.${this.minor}.${this.patch}`;
	    if (this.prerelease.length) {
	      this.version += `-${this.prerelease.join('.')}`;
	    }
	    return this.version
	  }
	  toString () {
	    return this.version
	  }
	  compare (other) {
	    debug('SemVer.compare', this.version, this.options, other);
	    if (!(other instanceof SemVer)) {
	      if (typeof other === 'string' && other === this.version) {
	        return 0
	      }
	      other = new SemVer(other, this.options);
	    }
	    if (other.version === this.version) {
	      return 0
	    }
	    return this.compareMain(other) || this.comparePre(other)
	  }
	  compareMain (other) {
	    if (!(other instanceof SemVer)) {
	      other = new SemVer(other, this.options);
	    }
	    if (this.major < other.major) {
	      return -1
	    }
	    if (this.major > other.major) {
	      return 1
	    }
	    if (this.minor < other.minor) {
	      return -1
	    }
	    if (this.minor > other.minor) {
	      return 1
	    }
	    if (this.patch < other.patch) {
	      return -1
	    }
	    if (this.patch > other.patch) {
	      return 1
	    }
	    return 0
	  }
	  comparePre (other) {
	    if (!(other instanceof SemVer)) {
	      other = new SemVer(other, this.options);
	    }
	    if (this.prerelease.length && !other.prerelease.length) {
	      return -1
	    } else if (!this.prerelease.length && other.prerelease.length) {
	      return 1
	    } else if (!this.prerelease.length && !other.prerelease.length) {
	      return 0
	    }
	    let i = 0;
	    do {
	      const a = this.prerelease[i];
	      const b = other.prerelease[i];
	      debug('prerelease compare', i, a, b);
	      if (a === undefined && b === undefined) {
	        return 0
	      } else if (b === undefined) {
	        return 1
	      } else if (a === undefined) {
	        return -1
	      } else if (a === b) {
	        continue
	      } else {
	        return compareIdentifiers(a, b)
	      }
	    } while (++i)
	  }
	  compareBuild (other) {
	    if (!(other instanceof SemVer)) {
	      other = new SemVer(other, this.options);
	    }
	    let i = 0;
	    do {
	      const a = this.build[i];
	      const b = other.build[i];
	      debug('build compare', i, a, b);
	      if (a === undefined && b === undefined) {
	        return 0
	      } else if (b === undefined) {
	        return 1
	      } else if (a === undefined) {
	        return -1
	      } else if (a === b) {
	        continue
	      } else {
	        return compareIdentifiers(a, b)
	      }
	    } while (++i)
	  }
	  inc (release, identifier, identifierBase) {
	    if (release.startsWith('pre')) {
	      if (!identifier && identifierBase === false) {
	        throw new Error('invalid increment argument: identifier is empty')
	      }
	      if (identifier) {
	        const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
	        if (!match || match[1] !== identifier) {
	          throw new Error(`invalid identifier: ${identifier}`)
	        }
	      }
	    }
	    switch (release) {
	      case 'premajor':
	        this.prerelease.length = 0;
	        this.patch = 0;
	        this.minor = 0;
	        this.major++;
	        this.inc('pre', identifier, identifierBase);
	        break
	      case 'preminor':
	        this.prerelease.length = 0;
	        this.patch = 0;
	        this.minor++;
	        this.inc('pre', identifier, identifierBase);
	        break
	      case 'prepatch':
	        this.prerelease.length = 0;
	        this.inc('patch', identifier, identifierBase);
	        this.inc('pre', identifier, identifierBase);
	        break
	      case 'prerelease':
	        if (this.prerelease.length === 0) {
	          this.inc('patch', identifier, identifierBase);
	        }
	        this.inc('pre', identifier, identifierBase);
	        break
	      case 'release':
	        if (this.prerelease.length === 0) {
	          throw new Error(`version ${this.raw} is not a prerelease`)
	        }
	        this.prerelease.length = 0;
	        break
	      case 'major':
	        if (
	          this.minor !== 0 ||
	          this.patch !== 0 ||
	          this.prerelease.length === 0
	        ) {
	          this.major++;
	        }
	        this.minor = 0;
	        this.patch = 0;
	        this.prerelease = [];
	        break
	      case 'minor':
	        if (this.patch !== 0 || this.prerelease.length === 0) {
	          this.minor++;
	        }
	        this.patch = 0;
	        this.prerelease = [];
	        break
	      case 'patch':
	        if (this.prerelease.length === 0) {
	          this.patch++;
	        }
	        this.prerelease = [];
	        break
	      case 'pre': {
	        const base = Number(identifierBase) ? 1 : 0;
	        if (this.prerelease.length === 0) {
	          this.prerelease = [base];
	        } else {
	          let i = this.prerelease.length;
	          while (--i >= 0) {
	            if (typeof this.prerelease[i] === 'number') {
	              this.prerelease[i]++;
	              i = -2;
	            }
	          }
	          if (i === -1) {
	            if (identifier === this.prerelease.join('.') && identifierBase === false) {
	              throw new Error('invalid increment argument: identifier already exists')
	            }
	            this.prerelease.push(base);
	          }
	        }
	        if (identifier) {
	          let prerelease = [identifier, base];
	          if (identifierBase === false) {
	            prerelease = [identifier];
	          }
	          if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
	            if (isNaN(this.prerelease[1])) {
	              this.prerelease = prerelease;
	            }
	          } else {
	            this.prerelease = prerelease;
	          }
	        }
	        break
	      }
	      default:
	        throw new Error(`invalid increment argument: ${release}`)
	    }
	    this.raw = this.format();
	    if (this.build.length) {
	      this.raw += `+${this.build.join('.')}`;
	    }
	    return this
	  }
	}
	semver$2 = SemVer;
	return semver$2;
}

var parse_1;
var hasRequiredParse;

function requireParse () {
	if (hasRequiredParse) return parse_1;
	hasRequiredParse = 1;
	const SemVer = requireSemver$1();
	const parse = (version, options, throwErrors = false) => {
	  if (version instanceof SemVer) {
	    return version
	  }
	  try {
	    return new SemVer(version, options)
	  } catch (er) {
	    if (!throwErrors) {
	      return null
	    }
	    throw er
	  }
	};
	parse_1 = parse;
	return parse_1;
}

var valid_1;
var hasRequiredValid$1;

function requireValid$1 () {
	if (hasRequiredValid$1) return valid_1;
	hasRequiredValid$1 = 1;
	const parse = requireParse();
	const valid = (version, options) => {
	  const v = parse(version, options);
	  return v ? v.version : null
	};
	valid_1 = valid;
	return valid_1;
}

var clean_1;
var hasRequiredClean;

function requireClean () {
	if (hasRequiredClean) return clean_1;
	hasRequiredClean = 1;
	const parse = requireParse();
	const clean = (version, options) => {
	  const s = parse(version.trim().replace(/^[=v]+/, ''), options);
	  return s ? s.version : null
	};
	clean_1 = clean;
	return clean_1;
}

var inc_1;
var hasRequiredInc;

function requireInc () {
	if (hasRequiredInc) return inc_1;
	hasRequiredInc = 1;
	const SemVer = requireSemver$1();
	const inc = (version, release, options, identifier, identifierBase) => {
	  if (typeof (options) === 'string') {
	    identifierBase = identifier;
	    identifier = options;
	    options = undefined;
	  }
	  try {
	    return new SemVer(
	      version instanceof SemVer ? version.version : version,
	      options
	    ).inc(release, identifier, identifierBase).version
	  } catch (er) {
	    return null
	  }
	};
	inc_1 = inc;
	return inc_1;
}

var diff_1;
var hasRequiredDiff;

function requireDiff () {
	if (hasRequiredDiff) return diff_1;
	hasRequiredDiff = 1;
	const parse = requireParse();
	const diff = (version1, version2) => {
	  const v1 = parse(version1, null, true);
	  const v2 = parse(version2, null, true);
	  const comparison = v1.compare(v2);
	  if (comparison === 0) {
	    return null
	  }
	  const v1Higher = comparison > 0;
	  const highVersion = v1Higher ? v1 : v2;
	  const lowVersion = v1Higher ? v2 : v1;
	  const highHasPre = !!highVersion.prerelease.length;
	  const lowHasPre = !!lowVersion.prerelease.length;
	  if (lowHasPre && !highHasPre) {
	    if (!lowVersion.patch && !lowVersion.minor) {
	      return 'major'
	    }
	    if (lowVersion.compareMain(highVersion) === 0) {
	      if (lowVersion.minor && !lowVersion.patch) {
	        return 'minor'
	      }
	      return 'patch'
	    }
	  }
	  const prefix = highHasPre ? 'pre' : '';
	  if (v1.major !== v2.major) {
	    return prefix + 'major'
	  }
	  if (v1.minor !== v2.minor) {
	    return prefix + 'minor'
	  }
	  if (v1.patch !== v2.patch) {
	    return prefix + 'patch'
	  }
	  return 'prerelease'
	};
	diff_1 = diff;
	return diff_1;
}

var major_1;
var hasRequiredMajor;

function requireMajor () {
	if (hasRequiredMajor) return major_1;
	hasRequiredMajor = 1;
	const SemVer = requireSemver$1();
	const major = (a, loose) => new SemVer(a, loose).major;
	major_1 = major;
	return major_1;
}

var minor_1;
var hasRequiredMinor;

function requireMinor () {
	if (hasRequiredMinor) return minor_1;
	hasRequiredMinor = 1;
	const SemVer = requireSemver$1();
	const minor = (a, loose) => new SemVer(a, loose).minor;
	minor_1 = minor;
	return minor_1;
}

var patch_1;
var hasRequiredPatch;

function requirePatch () {
	if (hasRequiredPatch) return patch_1;
	hasRequiredPatch = 1;
	const SemVer = requireSemver$1();
	const patch = (a, loose) => new SemVer(a, loose).patch;
	patch_1 = patch;
	return patch_1;
}

var prerelease_1;
var hasRequiredPrerelease;

function requirePrerelease () {
	if (hasRequiredPrerelease) return prerelease_1;
	hasRequiredPrerelease = 1;
	const parse = requireParse();
	const prerelease = (version, options) => {
	  const parsed = parse(version, options);
	  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
	};
	prerelease_1 = prerelease;
	return prerelease_1;
}

var compare_1;
var hasRequiredCompare;

function requireCompare () {
	if (hasRequiredCompare) return compare_1;
	hasRequiredCompare = 1;
	const SemVer = requireSemver$1();
	const compare = (a, b, loose) =>
	  new SemVer(a, loose).compare(new SemVer(b, loose));
	compare_1 = compare;
	return compare_1;
}

var rcompare_1;
var hasRequiredRcompare;

function requireRcompare () {
	if (hasRequiredRcompare) return rcompare_1;
	hasRequiredRcompare = 1;
	const compare = requireCompare();
	const rcompare = (a, b, loose) => compare(b, a, loose);
	rcompare_1 = rcompare;
	return rcompare_1;
}

var compareLoose_1;
var hasRequiredCompareLoose;

function requireCompareLoose () {
	if (hasRequiredCompareLoose) return compareLoose_1;
	hasRequiredCompareLoose = 1;
	const compare = requireCompare();
	const compareLoose = (a, b) => compare(a, b, true);
	compareLoose_1 = compareLoose;
	return compareLoose_1;
}

var compareBuild_1;
var hasRequiredCompareBuild;

function requireCompareBuild () {
	if (hasRequiredCompareBuild) return compareBuild_1;
	hasRequiredCompareBuild = 1;
	const SemVer = requireSemver$1();
	const compareBuild = (a, b, loose) => {
	  const versionA = new SemVer(a, loose);
	  const versionB = new SemVer(b, loose);
	  return versionA.compare(versionB) || versionA.compareBuild(versionB)
	};
	compareBuild_1 = compareBuild;
	return compareBuild_1;
}

var sort_1;
var hasRequiredSort;

function requireSort () {
	if (hasRequiredSort) return sort_1;
	hasRequiredSort = 1;
	const compareBuild = requireCompareBuild();
	const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
	sort_1 = sort;
	return sort_1;
}

var rsort_1;
var hasRequiredRsort;

function requireRsort () {
	if (hasRequiredRsort) return rsort_1;
	hasRequiredRsort = 1;
	const compareBuild = requireCompareBuild();
	const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
	rsort_1 = rsort;
	return rsort_1;
}

var gt_1;
var hasRequiredGt;

function requireGt () {
	if (hasRequiredGt) return gt_1;
	hasRequiredGt = 1;
	const compare = requireCompare();
	const gt = (a, b, loose) => compare(a, b, loose) > 0;
	gt_1 = gt;
	return gt_1;
}

var lt_1;
var hasRequiredLt;

function requireLt () {
	if (hasRequiredLt) return lt_1;
	hasRequiredLt = 1;
	const compare = requireCompare();
	const lt = (a, b, loose) => compare(a, b, loose) < 0;
	lt_1 = lt;
	return lt_1;
}

var eq_1;
var hasRequiredEq;

function requireEq () {
	if (hasRequiredEq) return eq_1;
	hasRequiredEq = 1;
	const compare = requireCompare();
	const eq = (a, b, loose) => compare(a, b, loose) === 0;
	eq_1 = eq;
	return eq_1;
}

var neq_1;
var hasRequiredNeq;

function requireNeq () {
	if (hasRequiredNeq) return neq_1;
	hasRequiredNeq = 1;
	const compare = requireCompare();
	const neq = (a, b, loose) => compare(a, b, loose) !== 0;
	neq_1 = neq;
	return neq_1;
}

var gte_1;
var hasRequiredGte;

function requireGte () {
	if (hasRequiredGte) return gte_1;
	hasRequiredGte = 1;
	const compare = requireCompare();
	const gte = (a, b, loose) => compare(a, b, loose) >= 0;
	gte_1 = gte;
	return gte_1;
}

var lte_1;
var hasRequiredLte;

function requireLte () {
	if (hasRequiredLte) return lte_1;
	hasRequiredLte = 1;
	const compare = requireCompare();
	const lte = (a, b, loose) => compare(a, b, loose) <= 0;
	lte_1 = lte;
	return lte_1;
}

var cmp_1;
var hasRequiredCmp;

function requireCmp () {
	if (hasRequiredCmp) return cmp_1;
	hasRequiredCmp = 1;
	const eq = requireEq();
	const neq = requireNeq();
	const gt = requireGt();
	const gte = requireGte();
	const lt = requireLt();
	const lte = requireLte();
	const cmp = (a, op, b, loose) => {
	  switch (op) {
	    case '===':
	      if (typeof a === 'object') {
	        a = a.version;
	      }
	      if (typeof b === 'object') {
	        b = b.version;
	      }
	      return a === b
	    case '!==':
	      if (typeof a === 'object') {
	        a = a.version;
	      }
	      if (typeof b === 'object') {
	        b = b.version;
	      }
	      return a !== b
	    case '':
	    case '=':
	    case '==':
	      return eq(a, b, loose)
	    case '!=':
	      return neq(a, b, loose)
	    case '>':
	      return gt(a, b, loose)
	    case '>=':
	      return gte(a, b, loose)
	    case '<':
	      return lt(a, b, loose)
	    case '<=':
	      return lte(a, b, loose)
	    default:
	      throw new TypeError(`Invalid operator: ${op}`)
	  }
	};
	cmp_1 = cmp;
	return cmp_1;
}

var coerce_1;
var hasRequiredCoerce;

function requireCoerce () {
	if (hasRequiredCoerce) return coerce_1;
	hasRequiredCoerce = 1;
	const SemVer = requireSemver$1();
	const parse = requireParse();
	const { safeRe: re, t } = requireRe();
	const coerce = (version, options) => {
	  if (version instanceof SemVer) {
	    return version
	  }
	  if (typeof version === 'number') {
	    version = String(version);
	  }
	  if (typeof version !== 'string') {
	    return null
	  }
	  options = options || {};
	  let match = null;
	  if (!options.rtl) {
	    match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);
	  } else {
	    const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];
	    let next;
	    while ((next = coerceRtlRegex.exec(version)) &&
	        (!match || match.index + match[0].length !== version.length)
	    ) {
	      if (!match ||
	            next.index + next[0].length !== match.index + match[0].length) {
	        match = next;
	      }
	      coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
	    }
	    coerceRtlRegex.lastIndex = -1;
	  }
	  if (match === null) {
	    return null
	  }
	  const major = match[2];
	  const minor = match[3] || '0';
	  const patch = match[4] || '0';
	  const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '';
	  const build = options.includePrerelease && match[6] ? `+${match[6]}` : '';
	  return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
	};
	coerce_1 = coerce;
	return coerce_1;
}

var lrucache;
var hasRequiredLrucache;

function requireLrucache () {
	if (hasRequiredLrucache) return lrucache;
	hasRequiredLrucache = 1;
	class LRUCache {
	  constructor () {
	    this.max = 1000;
	    this.map = new Map();
	  }
	  get (key) {
	    const value = this.map.get(key);
	    if (value === undefined) {
	      return undefined
	    } else {
	      this.map.delete(key);
	      this.map.set(key, value);
	      return value
	    }
	  }
	  delete (key) {
	    return this.map.delete(key)
	  }
	  set (key, value) {
	    const deleted = this.delete(key);
	    if (!deleted && value !== undefined) {
	      if (this.map.size >= this.max) {
	        const firstKey = this.map.keys().next().value;
	        this.delete(firstKey);
	      }
	      this.map.set(key, value);
	    }
	    return this
	  }
	}
	lrucache = LRUCache;
	return lrucache;
}

var range;
var hasRequiredRange;

function requireRange () {
	if (hasRequiredRange) return range;
	hasRequiredRange = 1;
	const SPACE_CHARACTERS = /\s+/g;
	class Range {
	  constructor (range, options) {
	    options = parseOptions(options);
	    if (range instanceof Range) {
	      if (
	        range.loose === !!options.loose &&
	        range.includePrerelease === !!options.includePrerelease
	      ) {
	        return range
	      } else {
	        return new Range(range.raw, options)
	      }
	    }
	    if (range instanceof Comparator) {
	      this.raw = range.value;
	      this.set = [[range]];
	      this.formatted = undefined;
	      return this
	    }
	    this.options = options;
	    this.loose = !!options.loose;
	    this.includePrerelease = !!options.includePrerelease;
	    this.raw = range.trim().replace(SPACE_CHARACTERS, ' ');
	    this.set = this.raw
	      .split('||')
	      .map(r => this.parseRange(r.trim()))
	      .filter(c => c.length);
	    if (!this.set.length) {
	      throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
	    }
	    if (this.set.length > 1) {
	      const first = this.set[0];
	      this.set = this.set.filter(c => !isNullSet(c[0]));
	      if (this.set.length === 0) {
	        this.set = [first];
	      } else if (this.set.length > 1) {
	        for (const c of this.set) {
	          if (c.length === 1 && isAny(c[0])) {
	            this.set = [c];
	            break
	          }
	        }
	      }
	    }
	    this.formatted = undefined;
	  }
	  get range () {
	    if (this.formatted === undefined) {
	      this.formatted = '';
	      for (let i = 0; i < this.set.length; i++) {
	        if (i > 0) {
	          this.formatted += '||';
	        }
	        const comps = this.set[i];
	        for (let k = 0; k < comps.length; k++) {
	          if (k > 0) {
	            this.formatted += ' ';
	          }
	          this.formatted += comps[k].toString().trim();
	        }
	      }
	    }
	    return this.formatted
	  }
	  format () {
	    return this.range
	  }
	  toString () {
	    return this.range
	  }
	  parseRange (range) {
	    const memoOpts =
	      (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
	      (this.options.loose && FLAG_LOOSE);
	    const memoKey = memoOpts + ':' + range;
	    const cached = cache.get(memoKey);
	    if (cached) {
	      return cached
	    }
	    const loose = this.options.loose;
	    const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
	    range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
	    debug('hyphen replace', range);
	    range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
	    debug('comparator trim', range);
	    range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
	    debug('tilde trim', range);
	    range = range.replace(re[t.CARETTRIM], caretTrimReplace);
	    debug('caret trim', range);
	    let rangeList = range
	      .split(' ')
	      .map(comp => parseComparator(comp, this.options))
	      .join(' ')
	      .split(/\s+/)
	      .map(comp => replaceGTE0(comp, this.options));
	    if (loose) {
	      rangeList = rangeList.filter(comp => {
	        debug('loose invalid filter', comp, this.options);
	        return !!comp.match(re[t.COMPARATORLOOSE])
	      });
	    }
	    debug('range list', rangeList);
	    const rangeMap = new Map();
	    const comparators = rangeList.map(comp => new Comparator(comp, this.options));
	    for (const comp of comparators) {
	      if (isNullSet(comp)) {
	        return [comp]
	      }
	      rangeMap.set(comp.value, comp);
	    }
	    if (rangeMap.size > 1 && rangeMap.has('')) {
	      rangeMap.delete('');
	    }
	    const result = [...rangeMap.values()];
	    cache.set(memoKey, result);
	    return result
	  }
	  intersects (range, options) {
	    if (!(range instanceof Range)) {
	      throw new TypeError('a Range is required')
	    }
	    return this.set.some((thisComparators) => {
	      return (
	        isSatisfiable(thisComparators, options) &&
	        range.set.some((rangeComparators) => {
	          return (
	            isSatisfiable(rangeComparators, options) &&
	            thisComparators.every((thisComparator) => {
	              return rangeComparators.every((rangeComparator) => {
	                return thisComparator.intersects(rangeComparator, options)
	              })
	            })
	          )
	        })
	      )
	    })
	  }
	  test (version) {
	    if (!version) {
	      return false
	    }
	    if (typeof version === 'string') {
	      try {
	        version = new SemVer(version, this.options);
	      } catch (er) {
	        return false
	      }
	    }
	    for (let i = 0; i < this.set.length; i++) {
	      if (testSet(this.set[i], version, this.options)) {
	        return true
	      }
	    }
	    return false
	  }
	}
	range = Range;
	const LRU = requireLrucache();
	const cache = new LRU();
	const parseOptions = requireParseOptions();
	const Comparator = requireComparator();
	const debug = requireDebug$1();
	const SemVer = requireSemver$1();
	const {
	  safeRe: re,
	  t,
	  comparatorTrimReplace,
	  tildeTrimReplace,
	  caretTrimReplace,
	} = requireRe();
	const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = requireConstants$4();
	const isNullSet = c => c.value === '<0.0.0-0';
	const isAny = c => c.value === '';
	const isSatisfiable = (comparators, options) => {
	  let result = true;
	  const remainingComparators = comparators.slice();
	  let testComparator = remainingComparators.pop();
	  while (result && remainingComparators.length) {
	    result = remainingComparators.every((otherComparator) => {
	      return testComparator.intersects(otherComparator, options)
	    });
	    testComparator = remainingComparators.pop();
	  }
	  return result
	};
	const parseComparator = (comp, options) => {
	  comp = comp.replace(re[t.BUILD], '');
	  debug('comp', comp, options);
	  comp = replaceCarets(comp, options);
	  debug('caret', comp);
	  comp = replaceTildes(comp, options);
	  debug('tildes', comp);
	  comp = replaceXRanges(comp, options);
	  debug('xrange', comp);
	  comp = replaceStars(comp, options);
	  debug('stars', comp);
	  return comp
	};
	const isX = id => !id || id.toLowerCase() === 'x' || id === '*';
	const replaceTildes = (comp, options) => {
	  return comp
	    .trim()
	    .split(/\s+/)
	    .map((c) => replaceTilde(c, options))
	    .join(' ')
	};
	const replaceTilde = (comp, options) => {
	  const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
	  return comp.replace(r, (_, M, m, p, pr) => {
	    debug('tilde', comp, _, M, m, p, pr);
	    let ret;
	    if (isX(M)) {
	      ret = '';
	    } else if (isX(m)) {
	      ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
	    } else if (isX(p)) {
	      ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
	    } else if (pr) {
	      debug('replaceTilde pr', pr);
	      ret = `>=${M}.${m}.${p}-${pr
	      } <${M}.${+m + 1}.0-0`;
	    } else {
	      ret = `>=${M}.${m}.${p
	      } <${M}.${+m + 1}.0-0`;
	    }
	    debug('tilde return', ret);
	    return ret
	  })
	};
	const replaceCarets = (comp, options) => {
	  return comp
	    .trim()
	    .split(/\s+/)
	    .map((c) => replaceCaret(c, options))
	    .join(' ')
	};
	const replaceCaret = (comp, options) => {
	  debug('caret', comp, options);
	  const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
	  const z = options.includePrerelease ? '-0' : '';
	  return comp.replace(r, (_, M, m, p, pr) => {
	    debug('caret', comp, _, M, m, p, pr);
	    let ret;
	    if (isX(M)) {
	      ret = '';
	    } else if (isX(m)) {
	      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
	    } else if (isX(p)) {
	      if (M === '0') {
	        ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
	      } else {
	        ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
	      }
	    } else if (pr) {
	      debug('replaceCaret pr', pr);
	      if (M === '0') {
	        if (m === '0') {
	          ret = `>=${M}.${m}.${p}-${pr
	          } <${M}.${m}.${+p + 1}-0`;
	        } else {
	          ret = `>=${M}.${m}.${p}-${pr
	          } <${M}.${+m + 1}.0-0`;
	        }
	      } else {
	        ret = `>=${M}.${m}.${p}-${pr
	        } <${+M + 1}.0.0-0`;
	      }
	    } else {
	      debug('no pr');
	      if (M === '0') {
	        if (m === '0') {
	          ret = `>=${M}.${m}.${p
	          }${z} <${M}.${m}.${+p + 1}-0`;
	        } else {
	          ret = `>=${M}.${m}.${p
	          }${z} <${M}.${+m + 1}.0-0`;
	        }
	      } else {
	        ret = `>=${M}.${m}.${p
	        } <${+M + 1}.0.0-0`;
	      }
	    }
	    debug('caret return', ret);
	    return ret
	  })
	};
	const replaceXRanges = (comp, options) => {
	  debug('replaceXRanges', comp, options);
	  return comp
	    .split(/\s+/)
	    .map((c) => replaceXRange(c, options))
	    .join(' ')
	};
	const replaceXRange = (comp, options) => {
	  comp = comp.trim();
	  const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
	  return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
	    debug('xRange', comp, ret, gtlt, M, m, p, pr);
	    const xM = isX(M);
	    const xm = xM || isX(m);
	    const xp = xm || isX(p);
	    const anyX = xp;
	    if (gtlt === '=' && anyX) {
	      gtlt = '';
	    }
	    pr = options.includePrerelease ? '-0' : '';
	    if (xM) {
	      if (gtlt === '>' || gtlt === '<') {
	        ret = '<0.0.0-0';
	      } else {
	        ret = '*';
	      }
	    } else if (gtlt && anyX) {
	      if (xm) {
	        m = 0;
	      }
	      p = 0;
	      if (gtlt === '>') {
	        gtlt = '>=';
	        if (xm) {
	          M = +M + 1;
	          m = 0;
	          p = 0;
	        } else {
	          m = +m + 1;
	          p = 0;
	        }
	      } else if (gtlt === '<=') {
	        gtlt = '<';
	        if (xm) {
	          M = +M + 1;
	        } else {
	          m = +m + 1;
	        }
	      }
	      if (gtlt === '<') {
	        pr = '-0';
	      }
	      ret = `${gtlt + M}.${m}.${p}${pr}`;
	    } else if (xm) {
	      ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
	    } else if (xp) {
	      ret = `>=${M}.${m}.0${pr
	      } <${M}.${+m + 1}.0-0`;
	    }
	    debug('xRange return', ret);
	    return ret
	  })
	};
	const replaceStars = (comp, options) => {
	  debug('replaceStars', comp, options);
	  return comp
	    .trim()
	    .replace(re[t.STAR], '')
	};
	const replaceGTE0 = (comp, options) => {
	  debug('replaceGTE0', comp, options);
	  return comp
	    .trim()
	    .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
	};
	const hyphenReplace = incPr => ($0,
	  from, fM, fm, fp, fpr, fb,
	  to, tM, tm, tp, tpr) => {
	  if (isX(fM)) {
	    from = '';
	  } else if (isX(fm)) {
	    from = `>=${fM}.0.0${incPr ? '-0' : ''}`;
	  } else if (isX(fp)) {
	    from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`;
	  } else if (fpr) {
	    from = `>=${from}`;
	  } else {
	    from = `>=${from}${incPr ? '-0' : ''}`;
	  }
	  if (isX(tM)) {
	    to = '';
	  } else if (isX(tm)) {
	    to = `<${+tM + 1}.0.0-0`;
	  } else if (isX(tp)) {
	    to = `<${tM}.${+tm + 1}.0-0`;
	  } else if (tpr) {
	    to = `<=${tM}.${tm}.${tp}-${tpr}`;
	  } else if (incPr) {
	    to = `<${tM}.${tm}.${+tp + 1}-0`;
	  } else {
	    to = `<=${to}`;
	  }
	  return `${from} ${to}`.trim()
	};
	const testSet = (set, version, options) => {
	  for (let i = 0; i < set.length; i++) {
	    if (!set[i].test(version)) {
	      return false
	    }
	  }
	  if (version.prerelease.length && !options.includePrerelease) {
	    for (let i = 0; i < set.length; i++) {
	      debug(set[i].semver);
	      if (set[i].semver === Comparator.ANY) {
	        continue
	      }
	      if (set[i].semver.prerelease.length > 0) {
	        const allowed = set[i].semver;
	        if (allowed.major === version.major &&
	            allowed.minor === version.minor &&
	            allowed.patch === version.patch) {
	          return true
	        }
	      }
	    }
	    return false
	  }
	  return true
	};
	return range;
}

var comparator;
var hasRequiredComparator;

function requireComparator () {
	if (hasRequiredComparator) return comparator;
	hasRequiredComparator = 1;
	const ANY = Symbol('SemVer ANY');
	class Comparator {
	  static get ANY () {
	    return ANY
	  }
	  constructor (comp, options) {
	    options = parseOptions(options);
	    if (comp instanceof Comparator) {
	      if (comp.loose === !!options.loose) {
	        return comp
	      } else {
	        comp = comp.value;
	      }
	    }
	    comp = comp.trim().split(/\s+/).join(' ');
	    debug('comparator', comp, options);
	    this.options = options;
	    this.loose = !!options.loose;
	    this.parse(comp);
	    if (this.semver === ANY) {
	      this.value = '';
	    } else {
	      this.value = this.operator + this.semver.version;
	    }
	    debug('comp', this);
	  }
	  parse (comp) {
	    const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
	    const m = comp.match(r);
	    if (!m) {
	      throw new TypeError(`Invalid comparator: ${comp}`)
	    }
	    this.operator = m[1] !== undefined ? m[1] : '';
	    if (this.operator === '=') {
	      this.operator = '';
	    }
	    if (!m[2]) {
	      this.semver = ANY;
	    } else {
	      this.semver = new SemVer(m[2], this.options.loose);
	    }
	  }
	  toString () {
	    return this.value
	  }
	  test (version) {
	    debug('Comparator.test', version, this.options.loose);
	    if (this.semver === ANY || version === ANY) {
	      return true
	    }
	    if (typeof version === 'string') {
	      try {
	        version = new SemVer(version, this.options);
	      } catch (er) {
	        return false
	      }
	    }
	    return cmp(version, this.operator, this.semver, this.options)
	  }
	  intersects (comp, options) {
	    if (!(comp instanceof Comparator)) {
	      throw new TypeError('a Comparator is required')
	    }
	    if (this.operator === '') {
	      if (this.value === '') {
	        return true
	      }
	      return new Range(comp.value, options).test(this.value)
	    } else if (comp.operator === '') {
	      if (comp.value === '') {
	        return true
	      }
	      return new Range(this.value, options).test(comp.semver)
	    }
	    options = parseOptions(options);
	    if (options.includePrerelease &&
	      (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
	      return false
	    }
	    if (!options.includePrerelease &&
	      (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
	      return false
	    }
	    if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
	      return true
	    }
	    if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
	      return true
	    }
	    if (
	      (this.semver.version === comp.semver.version) &&
	      this.operator.includes('=') && comp.operator.includes('=')) {
	      return true
	    }
	    if (cmp(this.semver, '<', comp.semver, options) &&
	      this.operator.startsWith('>') && comp.operator.startsWith('<')) {
	      return true
	    }
	    if (cmp(this.semver, '>', comp.semver, options) &&
	      this.operator.startsWith('<') && comp.operator.startsWith('>')) {
	      return true
	    }
	    return false
	  }
	}
	comparator = Comparator;
	const parseOptions = requireParseOptions();
	const { safeRe: re, t } = requireRe();
	const cmp = requireCmp();
	const debug = requireDebug$1();
	const SemVer = requireSemver$1();
	const Range = requireRange();
	return comparator;
}

var satisfies_1;
var hasRequiredSatisfies;

function requireSatisfies () {
	if (hasRequiredSatisfies) return satisfies_1;
	hasRequiredSatisfies = 1;
	const Range = requireRange();
	const satisfies = (version, range, options) => {
	  try {
	    range = new Range(range, options);
	  } catch (er) {
	    return false
	  }
	  return range.test(version)
	};
	satisfies_1 = satisfies;
	return satisfies_1;
}

var toComparators_1;
var hasRequiredToComparators;

function requireToComparators () {
	if (hasRequiredToComparators) return toComparators_1;
	hasRequiredToComparators = 1;
	const Range = requireRange();
	const toComparators = (range, options) =>
	  new Range(range, options).set
	    .map(comp => comp.map(c => c.value).join(' ').trim().split(' '));
	toComparators_1 = toComparators;
	return toComparators_1;
}

var maxSatisfying_1;
var hasRequiredMaxSatisfying;

function requireMaxSatisfying () {
	if (hasRequiredMaxSatisfying) return maxSatisfying_1;
	hasRequiredMaxSatisfying = 1;
	const SemVer = requireSemver$1();
	const Range = requireRange();
	const maxSatisfying = (versions, range, options) => {
	  let max = null;
	  let maxSV = null;
	  let rangeObj = null;
	  try {
	    rangeObj = new Range(range, options);
	  } catch (er) {
	    return null
	  }
	  versions.forEach((v) => {
	    if (rangeObj.test(v)) {
	      if (!max || maxSV.compare(v) === -1) {
	        max = v;
	        maxSV = new SemVer(max, options);
	      }
	    }
	  });
	  return max
	};
	maxSatisfying_1 = maxSatisfying;
	return maxSatisfying_1;
}

var minSatisfying_1;
var hasRequiredMinSatisfying;

function requireMinSatisfying () {
	if (hasRequiredMinSatisfying) return minSatisfying_1;
	hasRequiredMinSatisfying = 1;
	const SemVer = requireSemver$1();
	const Range = requireRange();
	const minSatisfying = (versions, range, options) => {
	  let min = null;
	  let minSV = null;
	  let rangeObj = null;
	  try {
	    rangeObj = new Range(range, options);
	  } catch (er) {
	    return null
	  }
	  versions.forEach((v) => {
	    if (rangeObj.test(v)) {
	      if (!min || minSV.compare(v) === 1) {
	        min = v;
	        minSV = new SemVer(min, options);
	      }
	    }
	  });
	  return min
	};
	minSatisfying_1 = minSatisfying;
	return minSatisfying_1;
}

var minVersion_1;
var hasRequiredMinVersion;

function requireMinVersion () {
	if (hasRequiredMinVersion) return minVersion_1;
	hasRequiredMinVersion = 1;
	const SemVer = requireSemver$1();
	const Range = requireRange();
	const gt = requireGt();
	const minVersion = (range, loose) => {
	  range = new Range(range, loose);
	  let minver = new SemVer('0.0.0');
	  if (range.test(minver)) {
	    return minver
	  }
	  minver = new SemVer('0.0.0-0');
	  if (range.test(minver)) {
	    return minver
	  }
	  minver = null;
	  for (let i = 0; i < range.set.length; ++i) {
	    const comparators = range.set[i];
	    let setMin = null;
	    comparators.forEach((comparator) => {
	      const compver = new SemVer(comparator.semver.version);
	      switch (comparator.operator) {
	        case '>':
	          if (compver.prerelease.length === 0) {
	            compver.patch++;
	          } else {
	            compver.prerelease.push(0);
	          }
	          compver.raw = compver.format();
	        case '':
	        case '>=':
	          if (!setMin || gt(compver, setMin)) {
	            setMin = compver;
	          }
	          break
	        case '<':
	        case '<=':
	          break
	        default:
	          throw new Error(`Unexpected operation: ${comparator.operator}`)
	      }
	    });
	    if (setMin && (!minver || gt(minver, setMin))) {
	      minver = setMin;
	    }
	  }
	  if (minver && range.test(minver)) {
	    return minver
	  }
	  return null
	};
	minVersion_1 = minVersion;
	return minVersion_1;
}

var valid;
var hasRequiredValid;

function requireValid () {
	if (hasRequiredValid) return valid;
	hasRequiredValid = 1;
	const Range = requireRange();
	const validRange = (range, options) => {
	  try {
	    return new Range(range, options).range || '*'
	  } catch (er) {
	    return null
	  }
	};
	valid = validRange;
	return valid;
}

var outside_1;
var hasRequiredOutside;

function requireOutside () {
	if (hasRequiredOutside) return outside_1;
	hasRequiredOutside = 1;
	const SemVer = requireSemver$1();
	const Comparator = requireComparator();
	const { ANY } = Comparator;
	const Range = requireRange();
	const satisfies = requireSatisfies();
	const gt = requireGt();
	const lt = requireLt();
	const lte = requireLte();
	const gte = requireGte();
	const outside = (version, range, hilo, options) => {
	  version = new SemVer(version, options);
	  range = new Range(range, options);
	  let gtfn, ltefn, ltfn, comp, ecomp;
	  switch (hilo) {
	    case '>':
	      gtfn = gt;
	      ltefn = lte;
	      ltfn = lt;
	      comp = '>';
	      ecomp = '>=';
	      break
	    case '<':
	      gtfn = lt;
	      ltefn = gte;
	      ltfn = gt;
	      comp = '<';
	      ecomp = '<=';
	      break
	    default:
	      throw new TypeError('Must provide a hilo val of "<" or ">"')
	  }
	  if (satisfies(version, range, options)) {
	    return false
	  }
	  for (let i = 0; i < range.set.length; ++i) {
	    const comparators = range.set[i];
	    let high = null;
	    let low = null;
	    comparators.forEach((comparator) => {
	      if (comparator.semver === ANY) {
	        comparator = new Comparator('>=0.0.0');
	      }
	      high = high || comparator;
	      low = low || comparator;
	      if (gtfn(comparator.semver, high.semver, options)) {
	        high = comparator;
	      } else if (ltfn(comparator.semver, low.semver, options)) {
	        low = comparator;
	      }
	    });
	    if (high.operator === comp || high.operator === ecomp) {
	      return false
	    }
	    if ((!low.operator || low.operator === comp) &&
	        ltefn(version, low.semver)) {
	      return false
	    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
	      return false
	    }
	  }
	  return true
	};
	outside_1 = outside;
	return outside_1;
}

var gtr_1;
var hasRequiredGtr;

function requireGtr () {
	if (hasRequiredGtr) return gtr_1;
	hasRequiredGtr = 1;
	const outside = requireOutside();
	const gtr = (version, range, options) => outside(version, range, '>', options);
	gtr_1 = gtr;
	return gtr_1;
}

var ltr_1;
var hasRequiredLtr;

function requireLtr () {
	if (hasRequiredLtr) return ltr_1;
	hasRequiredLtr = 1;
	const outside = requireOutside();
	const ltr = (version, range, options) => outside(version, range, '<', options);
	ltr_1 = ltr;
	return ltr_1;
}

var intersects_1;
var hasRequiredIntersects;

function requireIntersects () {
	if (hasRequiredIntersects) return intersects_1;
	hasRequiredIntersects = 1;
	const Range = requireRange();
	const intersects = (r1, r2, options) => {
	  r1 = new Range(r1, options);
	  r2 = new Range(r2, options);
	  return r1.intersects(r2, options)
	};
	intersects_1 = intersects;
	return intersects_1;
}

var simplify;
var hasRequiredSimplify;

function requireSimplify () {
	if (hasRequiredSimplify) return simplify;
	hasRequiredSimplify = 1;
	const satisfies = requireSatisfies();
	const compare = requireCompare();
	simplify = (versions, range, options) => {
	  const set = [];
	  let first = null;
	  let prev = null;
	  const v = versions.sort((a, b) => compare(a, b, options));
	  for (const version of v) {
	    const included = satisfies(version, range, options);
	    if (included) {
	      prev = version;
	      if (!first) {
	        first = version;
	      }
	    } else {
	      if (prev) {
	        set.push([first, prev]);
	      }
	      prev = null;
	      first = null;
	    }
	  }
	  if (first) {
	    set.push([first, null]);
	  }
	  const ranges = [];
	  for (const [min, max] of set) {
	    if (min === max) {
	      ranges.push(min);
	    } else if (!max && min === v[0]) {
	      ranges.push('*');
	    } else if (!max) {
	      ranges.push(`>=${min}`);
	    } else if (min === v[0]) {
	      ranges.push(`<=${max}`);
	    } else {
	      ranges.push(`${min} - ${max}`);
	    }
	  }
	  const simplified = ranges.join(' || ');
	  const original = typeof range.raw === 'string' ? range.raw : String(range);
	  return simplified.length < original.length ? simplified : range
	};
	return simplify;
}

var subset_1;
var hasRequiredSubset;

function requireSubset () {
	if (hasRequiredSubset) return subset_1;
	hasRequiredSubset = 1;
	const Range = requireRange();
	const Comparator = requireComparator();
	const { ANY } = Comparator;
	const satisfies = requireSatisfies();
	const compare = requireCompare();
	const subset = (sub, dom, options = {}) => {
	  if (sub === dom) {
	    return true
	  }
	  sub = new Range(sub, options);
	  dom = new Range(dom, options);
	  let sawNonNull = false;
	  OUTER: for (const simpleSub of sub.set) {
	    for (const simpleDom of dom.set) {
	      const isSub = simpleSubset(simpleSub, simpleDom, options);
	      sawNonNull = sawNonNull || isSub !== null;
	      if (isSub) {
	        continue OUTER
	      }
	    }
	    if (sawNonNull) {
	      return false
	    }
	  }
	  return true
	};
	const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')];
	const minimumVersion = [new Comparator('>=0.0.0')];
	const simpleSubset = (sub, dom, options) => {
	  if (sub === dom) {
	    return true
	  }
	  if (sub.length === 1 && sub[0].semver === ANY) {
	    if (dom.length === 1 && dom[0].semver === ANY) {
	      return true
	    } else if (options.includePrerelease) {
	      sub = minimumVersionWithPreRelease;
	    } else {
	      sub = minimumVersion;
	    }
	  }
	  if (dom.length === 1 && dom[0].semver === ANY) {
	    if (options.includePrerelease) {
	      return true
	    } else {
	      dom = minimumVersion;
	    }
	  }
	  const eqSet = new Set();
	  let gt, lt;
	  for (const c of sub) {
	    if (c.operator === '>' || c.operator === '>=') {
	      gt = higherGT(gt, c, options);
	    } else if (c.operator === '<' || c.operator === '<=') {
	      lt = lowerLT(lt, c, options);
	    } else {
	      eqSet.add(c.semver);
	    }
	  }
	  if (eqSet.size > 1) {
	    return null
	  }
	  let gtltComp;
	  if (gt && lt) {
	    gtltComp = compare(gt.semver, lt.semver, options);
	    if (gtltComp > 0) {
	      return null
	    } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
	      return null
	    }
	  }
	  for (const eq of eqSet) {
	    if (gt && !satisfies(eq, String(gt), options)) {
	      return null
	    }
	    if (lt && !satisfies(eq, String(lt), options)) {
	      return null
	    }
	    for (const c of dom) {
	      if (!satisfies(eq, String(c), options)) {
	        return false
	      }
	    }
	    return true
	  }
	  let higher, lower;
	  let hasDomLT, hasDomGT;
	  let needDomLTPre = lt &&
	    !options.includePrerelease &&
	    lt.semver.prerelease.length ? lt.semver : false;
	  let needDomGTPre = gt &&
	    !options.includePrerelease &&
	    gt.semver.prerelease.length ? gt.semver : false;
	  if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
	      lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
	    needDomLTPre = false;
	  }
	  for (const c of dom) {
	    hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=';
	    hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=';
	    if (gt) {
	      if (needDomGTPre) {
	        if (c.semver.prerelease && c.semver.prerelease.length &&
	            c.semver.major === needDomGTPre.major &&
	            c.semver.minor === needDomGTPre.minor &&
	            c.semver.patch === needDomGTPre.patch) {
	          needDomGTPre = false;
	        }
	      }
	      if (c.operator === '>' || c.operator === '>=') {
	        higher = higherGT(gt, c, options);
	        if (higher === c && higher !== gt) {
	          return false
	        }
	      } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
	        return false
	      }
	    }
	    if (lt) {
	      if (needDomLTPre) {
	        if (c.semver.prerelease && c.semver.prerelease.length &&
	            c.semver.major === needDomLTPre.major &&
	            c.semver.minor === needDomLTPre.minor &&
	            c.semver.patch === needDomLTPre.patch) {
	          needDomLTPre = false;
	        }
	      }
	      if (c.operator === '<' || c.operator === '<=') {
	        lower = lowerLT(lt, c, options);
	        if (lower === c && lower !== lt) {
	          return false
	        }
	      } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
	        return false
	      }
	    }
	    if (!c.operator && (lt || gt) && gtltComp !== 0) {
	      return false
	    }
	  }
	  if (gt && hasDomLT && !lt && gtltComp !== 0) {
	    return false
	  }
	  if (lt && hasDomGT && !gt && gtltComp !== 0) {
	    return false
	  }
	  if (needDomGTPre || needDomLTPre) {
	    return false
	  }
	  return true
	};
	const higherGT = (a, b, options) => {
	  if (!a) {
	    return b
	  }
	  const comp = compare(a.semver, b.semver, options);
	  return comp > 0 ? a
	    : comp < 0 ? b
	    : b.operator === '>' && a.operator === '>=' ? b
	    : a
	};
	const lowerLT = (a, b, options) => {
	  if (!a) {
	    return b
	  }
	  const comp = compare(a.semver, b.semver, options);
	  return comp < 0 ? a
	    : comp > 0 ? b
	    : b.operator === '<' && a.operator === '<=' ? b
	    : a
	};
	subset_1 = subset;
	return subset_1;
}

var semver$1;
var hasRequiredSemver;

function requireSemver () {
	if (hasRequiredSemver) return semver$1;
	hasRequiredSemver = 1;
	const internalRe = requireRe();
	const constants = requireConstants$4();
	const SemVer = requireSemver$1();
	const identifiers = requireIdentifiers();
	const parse = requireParse();
	const valid = requireValid$1();
	const clean = requireClean();
	const inc = requireInc();
	const diff = requireDiff();
	const major = requireMajor();
	const minor = requireMinor();
	const patch = requirePatch();
	const prerelease = requirePrerelease();
	const compare = requireCompare();
	const rcompare = requireRcompare();
	const compareLoose = requireCompareLoose();
	const compareBuild = requireCompareBuild();
	const sort = requireSort();
	const rsort = requireRsort();
	const gt = requireGt();
	const lt = requireLt();
	const eq = requireEq();
	const neq = requireNeq();
	const gte = requireGte();
	const lte = requireLte();
	const cmp = requireCmp();
	const coerce = requireCoerce();
	const Comparator = requireComparator();
	const Range = requireRange();
	const satisfies = requireSatisfies();
	const toComparators = requireToComparators();
	const maxSatisfying = requireMaxSatisfying();
	const minSatisfying = requireMinSatisfying();
	const minVersion = requireMinVersion();
	const validRange = requireValid();
	const outside = requireOutside();
	const gtr = requireGtr();
	const ltr = requireLtr();
	const intersects = requireIntersects();
	const simplifyRange = requireSimplify();
	const subset = requireSubset();
	semver$1 = {
	  parse,
	  valid,
	  clean,
	  inc,
	  diff,
	  major,
	  minor,
	  patch,
	  prerelease,
	  compare,
	  rcompare,
	  compareLoose,
	  compareBuild,
	  sort,
	  rsort,
	  gt,
	  lt,
	  eq,
	  neq,
	  gte,
	  lte,
	  cmp,
	  coerce,
	  Comparator,
	  Range,
	  satisfies,
	  toComparators,
	  maxSatisfying,
	  minSatisfying,
	  minVersion,
	  validRange,
	  outside,
	  gtr,
	  ltr,
	  intersects,
	  simplifyRange,
	  subset,
	  SemVer,
	  re: internalRe.re,
	  src: internalRe.src,
	  tokens: internalRe.t,
	  SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
	  RELEASE_TYPES: constants.RELEASE_TYPES,
	  compareIdentifiers: identifiers.compareIdentifiers,
	  rcompareIdentifiers: identifiers.rcompareIdentifiers,
	};
	return semver$1;
}

var semverExports = requireSemver();
var semver = /*@__PURE__*/getDefaultExportFromCjs(semverExports);

var dist$b = {};

var lruCache;
var hasRequiredLruCache;

function requireLruCache () {
	if (hasRequiredLruCache) return lruCache;
	hasRequiredLruCache = 1;
	const perf =
	  typeof performance === 'object' &&
	  performance &&
	  typeof performance.now === 'function'
	    ? performance
	    : Date;
	const hasAbortController = typeof AbortController === 'function';
	const AC = hasAbortController
	  ? AbortController
	  : class AbortController {
	      constructor() {
	        this.signal = new AS();
	      }
	      abort(reason = new Error('This operation was aborted')) {
	        this.signal.reason = this.signal.reason || reason;
	        this.signal.aborted = true;
	        this.signal.dispatchEvent({
	          type: 'abort',
	          target: this.signal,
	        });
	      }
	    };
	const hasAbortSignal = typeof AbortSignal === 'function';
	const hasACAbortSignal = typeof AC.AbortSignal === 'function';
	const AS = hasAbortSignal
	  ? AbortSignal
	  : hasACAbortSignal
	  ? AC.AbortController
	  : class AbortSignal {
	      constructor() {
	        this.reason = undefined;
	        this.aborted = false;
	        this._listeners = [];
	      }
	      dispatchEvent(e) {
	        if (e.type === 'abort') {
	          this.aborted = true;
	          this.onabort(e);
	          this._listeners.forEach(f => f(e), this);
	        }
	      }
	      onabort() {}
	      addEventListener(ev, fn) {
	        if (ev === 'abort') {
	          this._listeners.push(fn);
	        }
	      }
	      removeEventListener(ev, fn) {
	        if (ev === 'abort') {
	          this._listeners = this._listeners.filter(f => f !== fn);
	        }
	      }
	    };
	const warned = new Set();
	const deprecatedOption = (opt, instead) => {
	  const code = `LRU_CACHE_OPTION_${opt}`;
	  if (shouldWarn(code)) {
	    warn(code, `${opt} option`, `options.${instead}`, LRUCache);
	  }
	};
	const deprecatedMethod = (method, instead) => {
	  const code = `LRU_CACHE_METHOD_${method}`;
	  if (shouldWarn(code)) {
	    const { prototype } = LRUCache;
	    const { get } = Object.getOwnPropertyDescriptor(prototype, method);
	    warn(code, `${method} method`, `cache.${instead}()`, get);
	  }
	};
	const deprecatedProperty = (field, instead) => {
	  const code = `LRU_CACHE_PROPERTY_${field}`;
	  if (shouldWarn(code)) {
	    const { prototype } = LRUCache;
	    const { get } = Object.getOwnPropertyDescriptor(prototype, field);
	    warn(code, `${field} property`, `cache.${instead}`, get);
	  }
	};
	const emitWarning = (...a) => {
	  typeof process === 'object' &&
	  process &&
	  typeof process.emitWarning === 'function'
	    ? process.emitWarning(...a)
	    : console.error(...a);
	};
	const shouldWarn = code => !warned.has(code);
	const warn = (code, what, instead, fn) => {
	  warned.add(code);
	  const msg = `The ${what} is deprecated. Please use ${instead} instead.`;
	  emitWarning(msg, 'DeprecationWarning', code, fn);
	};
	const isPosInt = n => n && n === Math.floor(n) && n > 0 && isFinite(n);
	const getUintArray = max =>
	  !isPosInt(max)
	    ? null
	    : max <= Math.pow(2, 8)
	    ? Uint8Array
	    : max <= Math.pow(2, 16)
	    ? Uint16Array
	    : max <= Math.pow(2, 32)
	    ? Uint32Array
	    : max <= Number.MAX_SAFE_INTEGER
	    ? ZeroArray
	    : null;
	class ZeroArray extends Array {
	  constructor(size) {
	    super(size);
	    this.fill(0);
	  }
	}
	class Stack {
	  constructor(max) {
	    if (max === 0) {
	      return []
	    }
	    const UintArray = getUintArray(max);
	    this.heap = new UintArray(max);
	    this.length = 0;
	  }
	  push(n) {
	    this.heap[this.length++] = n;
	  }
	  pop() {
	    return this.heap[--this.length]
	  }
	}
	class LRUCache {
	  constructor(options = {}) {
	    const {
	      max = 0,
	      ttl,
	      ttlResolution = 1,
	      ttlAutopurge,
	      updateAgeOnGet,
	      updateAgeOnHas,
	      allowStale,
	      dispose,
	      disposeAfter,
	      noDisposeOnSet,
	      noUpdateTTL,
	      maxSize = 0,
	      maxEntrySize = 0,
	      sizeCalculation,
	      fetchMethod,
	      fetchContext,
	      noDeleteOnFetchRejection,
	      noDeleteOnStaleGet,
	      allowStaleOnFetchRejection,
	      allowStaleOnFetchAbort,
	      ignoreFetchAbort,
	    } = options;
	    const { length, maxAge, stale } =
	      options instanceof LRUCache ? {} : options;
	    if (max !== 0 && !isPosInt(max)) {
	      throw new TypeError('max option must be a nonnegative integer')
	    }
	    const UintArray = max ? getUintArray(max) : Array;
	    if (!UintArray) {
	      throw new Error('invalid max value: ' + max)
	    }
	    this.max = max;
	    this.maxSize = maxSize;
	    this.maxEntrySize = maxEntrySize || this.maxSize;
	    this.sizeCalculation = sizeCalculation || length;
	    if (this.sizeCalculation) {
	      if (!this.maxSize && !this.maxEntrySize) {
	        throw new TypeError(
	          'cannot set sizeCalculation without setting maxSize or maxEntrySize'
	        )
	      }
	      if (typeof this.sizeCalculation !== 'function') {
	        throw new TypeError('sizeCalculation set to non-function')
	      }
	    }
	    this.fetchMethod = fetchMethod || null;
	    if (this.fetchMethod && typeof this.fetchMethod !== 'function') {
	      throw new TypeError(
	        'fetchMethod must be a function if specified'
	      )
	    }
	    this.fetchContext = fetchContext;
	    if (!this.fetchMethod && fetchContext !== undefined) {
	      throw new TypeError(
	        'cannot set fetchContext without fetchMethod'
	      )
	    }
	    this.keyMap = new Map();
	    this.keyList = new Array(max).fill(null);
	    this.valList = new Array(max).fill(null);
	    this.next = new UintArray(max);
	    this.prev = new UintArray(max);
	    this.head = 0;
	    this.tail = 0;
	    this.free = new Stack(max);
	    this.initialFill = 1;
	    this.size = 0;
	    if (typeof dispose === 'function') {
	      this.dispose = dispose;
	    }
	    if (typeof disposeAfter === 'function') {
	      this.disposeAfter = disposeAfter;
	      this.disposed = [];
	    } else {
	      this.disposeAfter = null;
	      this.disposed = null;
	    }
	    this.noDisposeOnSet = !!noDisposeOnSet;
	    this.noUpdateTTL = !!noUpdateTTL;
	    this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
	    this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
	    this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
	    this.ignoreFetchAbort = !!ignoreFetchAbort;
	    if (this.maxEntrySize !== 0) {
	      if (this.maxSize !== 0) {
	        if (!isPosInt(this.maxSize)) {
	          throw new TypeError(
	            'maxSize must be a positive integer if specified'
	          )
	        }
	      }
	      if (!isPosInt(this.maxEntrySize)) {
	        throw new TypeError(
	          'maxEntrySize must be a positive integer if specified'
	        )
	      }
	      this.initializeSizeTracking();
	    }
	    this.allowStale = !!allowStale || !!stale;
	    this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
	    this.updateAgeOnGet = !!updateAgeOnGet;
	    this.updateAgeOnHas = !!updateAgeOnHas;
	    this.ttlResolution =
	      isPosInt(ttlResolution) || ttlResolution === 0
	        ? ttlResolution
	        : 1;
	    this.ttlAutopurge = !!ttlAutopurge;
	    this.ttl = ttl || maxAge || 0;
	    if (this.ttl) {
	      if (!isPosInt(this.ttl)) {
	        throw new TypeError(
	          'ttl must be a positive integer if specified'
	        )
	      }
	      this.initializeTTLTracking();
	    }
	    if (this.max === 0 && this.ttl === 0 && this.maxSize === 0) {
	      throw new TypeError(
	        'At least one of max, maxSize, or ttl is required'
	      )
	    }
	    if (!this.ttlAutopurge && !this.max && !this.maxSize) {
	      const code = 'LRU_CACHE_UNBOUNDED';
	      if (shouldWarn(code)) {
	        warned.add(code);
	        const msg =
	          'TTL caching without ttlAutopurge, max, or maxSize can ' +
	          'result in unbounded memory consumption.';
	        emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
	      }
	    }
	    if (stale) {
	      deprecatedOption('stale', 'allowStale');
	    }
	    if (maxAge) {
	      deprecatedOption('maxAge', 'ttl');
	    }
	    if (length) {
	      deprecatedOption('length', 'sizeCalculation');
	    }
	  }
	  getRemainingTTL(key) {
	    return this.has(key, { updateAgeOnHas: false }) ? Infinity : 0
	  }
	  initializeTTLTracking() {
	    this.ttls = new ZeroArray(this.max);
	    this.starts = new ZeroArray(this.max);
	    this.setItemTTL = (index, ttl, start = perf.now()) => {
	      this.starts[index] = ttl !== 0 ? start : 0;
	      this.ttls[index] = ttl;
	      if (ttl !== 0 && this.ttlAutopurge) {
	        const t = setTimeout(() => {
	          if (this.isStale(index)) {
	            this.delete(this.keyList[index]);
	          }
	        }, ttl + 1);
	        if (t.unref) {
	          t.unref();
	        }
	      }
	    };
	    this.updateItemAge = index => {
	      this.starts[index] = this.ttls[index] !== 0 ? perf.now() : 0;
	    };
	    this.statusTTL = (status, index) => {
	      if (status) {
	        status.ttl = this.ttls[index];
	        status.start = this.starts[index];
	        status.now = cachedNow || getNow();
	        status.remainingTTL = status.now + status.ttl - status.start;
	      }
	    };
	    let cachedNow = 0;
	    const getNow = () => {
	      const n = perf.now();
	      if (this.ttlResolution > 0) {
	        cachedNow = n;
	        const t = setTimeout(
	          () => (cachedNow = 0),
	          this.ttlResolution
	        );
	        if (t.unref) {
	          t.unref();
	        }
	      }
	      return n
	    };
	    this.getRemainingTTL = key => {
	      const index = this.keyMap.get(key);
	      if (index === undefined) {
	        return 0
	      }
	      return this.ttls[index] === 0 || this.starts[index] === 0
	        ? Infinity
	        : this.starts[index] +
	            this.ttls[index] -
	            (cachedNow || getNow())
	    };
	    this.isStale = index => {
	      return (
	        this.ttls[index] !== 0 &&
	        this.starts[index] !== 0 &&
	        (cachedNow || getNow()) - this.starts[index] >
	          this.ttls[index]
	      )
	    };
	  }
	  updateItemAge(_index) {}
	  statusTTL(_status, _index) {}
	  setItemTTL(_index, _ttl, _start) {}
	  isStale(_index) {
	    return false
	  }
	  initializeSizeTracking() {
	    this.calculatedSize = 0;
	    this.sizes = new ZeroArray(this.max);
	    this.removeItemSize = index => {
	      this.calculatedSize -= this.sizes[index];
	      this.sizes[index] = 0;
	    };
	    this.requireSize = (k, v, size, sizeCalculation) => {
	      if (this.isBackgroundFetch(v)) {
	        return 0
	      }
	      if (!isPosInt(size)) {
	        if (sizeCalculation) {
	          if (typeof sizeCalculation !== 'function') {
	            throw new TypeError('sizeCalculation must be a function')
	          }
	          size = sizeCalculation(v, k);
	          if (!isPosInt(size)) {
	            throw new TypeError(
	              'sizeCalculation return invalid (expect positive integer)'
	            )
	          }
	        } else {
	          throw new TypeError(
	            'invalid size value (must be positive integer). ' +
	              'When maxSize or maxEntrySize is used, sizeCalculation or size ' +
	              'must be set.'
	          )
	        }
	      }
	      return size
	    };
	    this.addItemSize = (index, size, status) => {
	      this.sizes[index] = size;
	      if (this.maxSize) {
	        const maxSize = this.maxSize - this.sizes[index];
	        while (this.calculatedSize > maxSize) {
	          this.evict(true);
	        }
	      }
	      this.calculatedSize += this.sizes[index];
	      if (status) {
	        status.entrySize = size;
	        status.totalCalculatedSize = this.calculatedSize;
	      }
	    };
	  }
	  removeItemSize(_index) {}
	  addItemSize(_index, _size) {}
	  requireSize(_k, _v, size, sizeCalculation) {
	    if (size || sizeCalculation) {
	      throw new TypeError(
	        'cannot set size without setting maxSize or maxEntrySize on cache'
	      )
	    }
	  }
	  *indexes({ allowStale = this.allowStale } = {}) {
	    if (this.size) {
	      for (let i = this.tail; true; ) {
	        if (!this.isValidIndex(i)) {
	          break
	        }
	        if (allowStale || !this.isStale(i)) {
	          yield i;
	        }
	        if (i === this.head) {
	          break
	        } else {
	          i = this.prev[i];
	        }
	      }
	    }
	  }
	  *rindexes({ allowStale = this.allowStale } = {}) {
	    if (this.size) {
	      for (let i = this.head; true; ) {
	        if (!this.isValidIndex(i)) {
	          break
	        }
	        if (allowStale || !this.isStale(i)) {
	          yield i;
	        }
	        if (i === this.tail) {
	          break
	        } else {
	          i = this.next[i];
	        }
	      }
	    }
	  }
	  isValidIndex(index) {
	    return (
	      index !== undefined &&
	      this.keyMap.get(this.keyList[index]) === index
	    )
	  }
	  *entries() {
	    for (const i of this.indexes()) {
	      if (
	        this.valList[i] !== undefined &&
	        this.keyList[i] !== undefined &&
	        !this.isBackgroundFetch(this.valList[i])
	      ) {
	        yield [this.keyList[i], this.valList[i]];
	      }
	    }
	  }
	  *rentries() {
	    for (const i of this.rindexes()) {
	      if (
	        this.valList[i] !== undefined &&
	        this.keyList[i] !== undefined &&
	        !this.isBackgroundFetch(this.valList[i])
	      ) {
	        yield [this.keyList[i], this.valList[i]];
	      }
	    }
	  }
	  *keys() {
	    for (const i of this.indexes()) {
	      if (
	        this.keyList[i] !== undefined &&
	        !this.isBackgroundFetch(this.valList[i])
	      ) {
	        yield this.keyList[i];
	      }
	    }
	  }
	  *rkeys() {
	    for (const i of this.rindexes()) {
	      if (
	        this.keyList[i] !== undefined &&
	        !this.isBackgroundFetch(this.valList[i])
	      ) {
	        yield this.keyList[i];
	      }
	    }
	  }
	  *values() {
	    for (const i of this.indexes()) {
	      if (
	        this.valList[i] !== undefined &&
	        !this.isBackgroundFetch(this.valList[i])
	      ) {
	        yield this.valList[i];
	      }
	    }
	  }
	  *rvalues() {
	    for (const i of this.rindexes()) {
	      if (
	        this.valList[i] !== undefined &&
	        !this.isBackgroundFetch(this.valList[i])
	      ) {
	        yield this.valList[i];
	      }
	    }
	  }
	  [Symbol.iterator]() {
	    return this.entries()
	  }
	  find(fn, getOptions) {
	    for (const i of this.indexes()) {
	      const v = this.valList[i];
	      const value = this.isBackgroundFetch(v)
	        ? v.__staleWhileFetching
	        : v;
	      if (value === undefined) continue
	      if (fn(value, this.keyList[i], this)) {
	        return this.get(this.keyList[i], getOptions)
	      }
	    }
	  }
	  forEach(fn, thisp = this) {
	    for (const i of this.indexes()) {
	      const v = this.valList[i];
	      const value = this.isBackgroundFetch(v)
	        ? v.__staleWhileFetching
	        : v;
	      if (value === undefined) continue
	      fn.call(thisp, value, this.keyList[i], this);
	    }
	  }
	  rforEach(fn, thisp = this) {
	    for (const i of this.rindexes()) {
	      const v = this.valList[i];
	      const value = this.isBackgroundFetch(v)
	        ? v.__staleWhileFetching
	        : v;
	      if (value === undefined) continue
	      fn.call(thisp, value, this.keyList[i], this);
	    }
	  }
	  get prune() {
	    deprecatedMethod('prune', 'purgeStale');
	    return this.purgeStale
	  }
	  purgeStale() {
	    let deleted = false;
	    for (const i of this.rindexes({ allowStale: true })) {
	      if (this.isStale(i)) {
	        this.delete(this.keyList[i]);
	        deleted = true;
	      }
	    }
	    return deleted
	  }
	  dump() {
	    const arr = [];
	    for (const i of this.indexes({ allowStale: true })) {
	      const key = this.keyList[i];
	      const v = this.valList[i];
	      const value = this.isBackgroundFetch(v)
	        ? v.__staleWhileFetching
	        : v;
	      if (value === undefined) continue
	      const entry = { value };
	      if (this.ttls) {
	        entry.ttl = this.ttls[i];
	        const age = perf.now() - this.starts[i];
	        entry.start = Math.floor(Date.now() - age);
	      }
	      if (this.sizes) {
	        entry.size = this.sizes[i];
	      }
	      arr.unshift([key, entry]);
	    }
	    return arr
	  }
	  load(arr) {
	    this.clear();
	    for (const [key, entry] of arr) {
	      if (entry.start) {
	        const age = Date.now() - entry.start;
	        entry.start = perf.now() - age;
	      }
	      this.set(key, entry.value, entry);
	    }
	  }
	  dispose(_v, _k, _reason) {}
	  set(
	    k,
	    v,
	    {
	      ttl = this.ttl,
	      start,
	      noDisposeOnSet = this.noDisposeOnSet,
	      size = 0,
	      sizeCalculation = this.sizeCalculation,
	      noUpdateTTL = this.noUpdateTTL,
	      status,
	    } = {}
	  ) {
	    size = this.requireSize(k, v, size, sizeCalculation);
	    if (this.maxEntrySize && size > this.maxEntrySize) {
	      if (status) {
	        status.set = 'miss';
	        status.maxEntrySizeExceeded = true;
	      }
	      this.delete(k);
	      return this
	    }
	    let index = this.size === 0 ? undefined : this.keyMap.get(k);
	    if (index === undefined) {
	      index = this.newIndex();
	      this.keyList[index] = k;
	      this.valList[index] = v;
	      this.keyMap.set(k, index);
	      this.next[this.tail] = index;
	      this.prev[index] = this.tail;
	      this.tail = index;
	      this.size++;
	      this.addItemSize(index, size, status);
	      if (status) {
	        status.set = 'add';
	      }
	      noUpdateTTL = false;
	    } else {
	      this.moveToTail(index);
	      const oldVal = this.valList[index];
	      if (v !== oldVal) {
	        if (this.isBackgroundFetch(oldVal)) {
	          oldVal.__abortController.abort(new Error('replaced'));
	        } else {
	          if (!noDisposeOnSet) {
	            this.dispose(oldVal, k, 'set');
	            if (this.disposeAfter) {
	              this.disposed.push([oldVal, k, 'set']);
	            }
	          }
	        }
	        this.removeItemSize(index);
	        this.valList[index] = v;
	        this.addItemSize(index, size, status);
	        if (status) {
	          status.set = 'replace';
	          const oldValue =
	            oldVal && this.isBackgroundFetch(oldVal)
	              ? oldVal.__staleWhileFetching
	              : oldVal;
	          if (oldValue !== undefined) status.oldValue = oldValue;
	        }
	      } else if (status) {
	        status.set = 'update';
	      }
	    }
	    if (ttl !== 0 && this.ttl === 0 && !this.ttls) {
	      this.initializeTTLTracking();
	    }
	    if (!noUpdateTTL) {
	      this.setItemTTL(index, ttl, start);
	    }
	    this.statusTTL(status, index);
	    if (this.disposeAfter) {
	      while (this.disposed.length) {
	        this.disposeAfter(...this.disposed.shift());
	      }
	    }
	    return this
	  }
	  newIndex() {
	    if (this.size === 0) {
	      return this.tail
	    }
	    if (this.size === this.max && this.max !== 0) {
	      return this.evict(false)
	    }
	    if (this.free.length !== 0) {
	      return this.free.pop()
	    }
	    return this.initialFill++
	  }
	  pop() {
	    if (this.size) {
	      const val = this.valList[this.head];
	      this.evict(true);
	      return val
	    }
	  }
	  evict(free) {
	    const head = this.head;
	    const k = this.keyList[head];
	    const v = this.valList[head];
	    if (this.isBackgroundFetch(v)) {
	      v.__abortController.abort(new Error('evicted'));
	    } else {
	      this.dispose(v, k, 'evict');
	      if (this.disposeAfter) {
	        this.disposed.push([v, k, 'evict']);
	      }
	    }
	    this.removeItemSize(head);
	    if (free) {
	      this.keyList[head] = null;
	      this.valList[head] = null;
	      this.free.push(head);
	    }
	    this.head = this.next[head];
	    this.keyMap.delete(k);
	    this.size--;
	    return head
	  }
	  has(k, { updateAgeOnHas = this.updateAgeOnHas, status } = {}) {
	    const index = this.keyMap.get(k);
	    if (index !== undefined) {
	      if (!this.isStale(index)) {
	        if (updateAgeOnHas) {
	          this.updateItemAge(index);
	        }
	        if (status) status.has = 'hit';
	        this.statusTTL(status, index);
	        return true
	      } else if (status) {
	        status.has = 'stale';
	        this.statusTTL(status, index);
	      }
	    } else if (status) {
	      status.has = 'miss';
	    }
	    return false
	  }
	  peek(k, { allowStale = this.allowStale } = {}) {
	    const index = this.keyMap.get(k);
	    if (index !== undefined && (allowStale || !this.isStale(index))) {
	      const v = this.valList[index];
	      return this.isBackgroundFetch(v) ? v.__staleWhileFetching : v
	    }
	  }
	  backgroundFetch(k, index, options, context) {
	    const v = index === undefined ? undefined : this.valList[index];
	    if (this.isBackgroundFetch(v)) {
	      return v
	    }
	    const ac = new AC();
	    if (options.signal) {
	      options.signal.addEventListener('abort', () =>
	        ac.abort(options.signal.reason)
	      );
	    }
	    const fetchOpts = {
	      signal: ac.signal,
	      options,
	      context,
	    };
	    const cb = (v, updateCache = false) => {
	      const { aborted } = ac.signal;
	      const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
	      if (options.status) {
	        if (aborted && !updateCache) {
	          options.status.fetchAborted = true;
	          options.status.fetchError = ac.signal.reason;
	          if (ignoreAbort) options.status.fetchAbortIgnored = true;
	        } else {
	          options.status.fetchResolved = true;
	        }
	      }
	      if (aborted && !ignoreAbort && !updateCache) {
	        return fetchFail(ac.signal.reason)
	      }
	      if (this.valList[index] === p) {
	        if (v === undefined) {
	          if (p.__staleWhileFetching) {
	            this.valList[index] = p.__staleWhileFetching;
	          } else {
	            this.delete(k);
	          }
	        } else {
	          if (options.status) options.status.fetchUpdated = true;
	          this.set(k, v, fetchOpts.options);
	        }
	      }
	      return v
	    };
	    const eb = er => {
	      if (options.status) {
	        options.status.fetchRejected = true;
	        options.status.fetchError = er;
	      }
	      return fetchFail(er)
	    };
	    const fetchFail = er => {
	      const { aborted } = ac.signal;
	      const allowStaleAborted =
	        aborted && options.allowStaleOnFetchAbort;
	      const allowStale =
	        allowStaleAborted || options.allowStaleOnFetchRejection;
	      const noDelete = allowStale || options.noDeleteOnFetchRejection;
	      if (this.valList[index] === p) {
	        const del = !noDelete || p.__staleWhileFetching === undefined;
	        if (del) {
	          this.delete(k);
	        } else if (!allowStaleAborted) {
	          this.valList[index] = p.__staleWhileFetching;
	        }
	      }
	      if (allowStale) {
	        if (options.status && p.__staleWhileFetching !== undefined) {
	          options.status.returnedStale = true;
	        }
	        return p.__staleWhileFetching
	      } else if (p.__returned === p) {
	        throw er
	      }
	    };
	    const pcall = (res, rej) => {
	      this.fetchMethod(k, v, fetchOpts).then(v => res(v), rej);
	      ac.signal.addEventListener('abort', () => {
	        if (
	          !options.ignoreFetchAbort ||
	          options.allowStaleOnFetchAbort
	        ) {
	          res();
	          if (options.allowStaleOnFetchAbort) {
	            res = v => cb(v, true);
	          }
	        }
	      });
	    };
	    if (options.status) options.status.fetchDispatched = true;
	    const p = new Promise(pcall).then(cb, eb);
	    p.__abortController = ac;
	    p.__staleWhileFetching = v;
	    p.__returned = null;
	    if (index === undefined) {
	      this.set(k, p, { ...fetchOpts.options, status: undefined });
	      index = this.keyMap.get(k);
	    } else {
	      this.valList[index] = p;
	    }
	    return p
	  }
	  isBackgroundFetch(p) {
	    return (
	      p &&
	      typeof p === 'object' &&
	      typeof p.then === 'function' &&
	      Object.prototype.hasOwnProperty.call(
	        p,
	        '__staleWhileFetching'
	      ) &&
	      Object.prototype.hasOwnProperty.call(p, '__returned') &&
	      (p.__returned === p || p.__returned === null)
	    )
	  }
	  async fetch(
	    k,
	    {
	      allowStale = this.allowStale,
	      updateAgeOnGet = this.updateAgeOnGet,
	      noDeleteOnStaleGet = this.noDeleteOnStaleGet,
	      ttl = this.ttl,
	      noDisposeOnSet = this.noDisposeOnSet,
	      size = 0,
	      sizeCalculation = this.sizeCalculation,
	      noUpdateTTL = this.noUpdateTTL,
	      noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
	      allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
	      ignoreFetchAbort = this.ignoreFetchAbort,
	      allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
	      fetchContext = this.fetchContext,
	      forceRefresh = false,
	      status,
	      signal,
	    } = {}
	  ) {
	    if (!this.fetchMethod) {
	      if (status) status.fetch = 'get';
	      return this.get(k, {
	        allowStale,
	        updateAgeOnGet,
	        noDeleteOnStaleGet,
	        status,
	      })
	    }
	    const options = {
	      allowStale,
	      updateAgeOnGet,
	      noDeleteOnStaleGet,
	      ttl,
	      noDisposeOnSet,
	      size,
	      sizeCalculation,
	      noUpdateTTL,
	      noDeleteOnFetchRejection,
	      allowStaleOnFetchRejection,
	      allowStaleOnFetchAbort,
	      ignoreFetchAbort,
	      status,
	      signal,
	    };
	    let index = this.keyMap.get(k);
	    if (index === undefined) {
	      if (status) status.fetch = 'miss';
	      const p = this.backgroundFetch(k, index, options, fetchContext);
	      return (p.__returned = p)
	    } else {
	      const v = this.valList[index];
	      if (this.isBackgroundFetch(v)) {
	        const stale =
	          allowStale && v.__staleWhileFetching !== undefined;
	        if (status) {
	          status.fetch = 'inflight';
	          if (stale) status.returnedStale = true;
	        }
	        return stale ? v.__staleWhileFetching : (v.__returned = v)
	      }
	      const isStale = this.isStale(index);
	      if (!forceRefresh && !isStale) {
	        if (status) status.fetch = 'hit';
	        this.moveToTail(index);
	        if (updateAgeOnGet) {
	          this.updateItemAge(index);
	        }
	        this.statusTTL(status, index);
	        return v
	      }
	      const p = this.backgroundFetch(k, index, options, fetchContext);
	      const hasStale = p.__staleWhileFetching !== undefined;
	      const staleVal = hasStale && allowStale;
	      if (status) {
	        status.fetch = hasStale && isStale ? 'stale' : 'refresh';
	        if (staleVal && isStale) status.returnedStale = true;
	      }
	      return staleVal ? p.__staleWhileFetching : (p.__returned = p)
	    }
	  }
	  get(
	    k,
	    {
	      allowStale = this.allowStale,
	      updateAgeOnGet = this.updateAgeOnGet,
	      noDeleteOnStaleGet = this.noDeleteOnStaleGet,
	      status,
	    } = {}
	  ) {
	    const index = this.keyMap.get(k);
	    if (index !== undefined) {
	      const value = this.valList[index];
	      const fetching = this.isBackgroundFetch(value);
	      this.statusTTL(status, index);
	      if (this.isStale(index)) {
	        if (status) status.get = 'stale';
	        if (!fetching) {
	          if (!noDeleteOnStaleGet) {
	            this.delete(k);
	          }
	          if (status) status.returnedStale = allowStale;
	          return allowStale ? value : undefined
	        } else {
	          if (status) {
	            status.returnedStale =
	              allowStale && value.__staleWhileFetching !== undefined;
	          }
	          return allowStale ? value.__staleWhileFetching : undefined
	        }
	      } else {
	        if (status) status.get = 'hit';
	        if (fetching) {
	          return value.__staleWhileFetching
	        }
	        this.moveToTail(index);
	        if (updateAgeOnGet) {
	          this.updateItemAge(index);
	        }
	        return value
	      }
	    } else if (status) {
	      status.get = 'miss';
	    }
	  }
	  connect(p, n) {
	    this.prev[n] = p;
	    this.next[p] = n;
	  }
	  moveToTail(index) {
	    if (index !== this.tail) {
	      if (index === this.head) {
	        this.head = this.next[index];
	      } else {
	        this.connect(this.prev[index], this.next[index]);
	      }
	      this.connect(this.tail, index);
	      this.tail = index;
	    }
	  }
	  get del() {
	    deprecatedMethod('del', 'delete');
	    return this.delete
	  }
	  delete(k) {
	    let deleted = false;
	    if (this.size !== 0) {
	      const index = this.keyMap.get(k);
	      if (index !== undefined) {
	        deleted = true;
	        if (this.size === 1) {
	          this.clear();
	        } else {
	          this.removeItemSize(index);
	          const v = this.valList[index];
	          if (this.isBackgroundFetch(v)) {
	            v.__abortController.abort(new Error('deleted'));
	          } else {
	            this.dispose(v, k, 'delete');
	            if (this.disposeAfter) {
	              this.disposed.push([v, k, 'delete']);
	            }
	          }
	          this.keyMap.delete(k);
	          this.keyList[index] = null;
	          this.valList[index] = null;
	          if (index === this.tail) {
	            this.tail = this.prev[index];
	          } else if (index === this.head) {
	            this.head = this.next[index];
	          } else {
	            this.next[this.prev[index]] = this.next[index];
	            this.prev[this.next[index]] = this.prev[index];
	          }
	          this.size--;
	          this.free.push(index);
	        }
	      }
	    }
	    if (this.disposed) {
	      while (this.disposed.length) {
	        this.disposeAfter(...this.disposed.shift());
	      }
	    }
	    return deleted
	  }
	  clear() {
	    for (const index of this.rindexes({ allowStale: true })) {
	      const v = this.valList[index];
	      if (this.isBackgroundFetch(v)) {
	        v.__abortController.abort(new Error('deleted'));
	      } else {
	        const k = this.keyList[index];
	        this.dispose(v, k, 'delete');
	        if (this.disposeAfter) {
	          this.disposed.push([v, k, 'delete']);
	        }
	      }
	    }
	    this.keyMap.clear();
	    this.valList.fill(null);
	    this.keyList.fill(null);
	    if (this.ttls) {
	      this.ttls.fill(0);
	      this.starts.fill(0);
	    }
	    if (this.sizes) {
	      this.sizes.fill(0);
	    }
	    this.head = 0;
	    this.tail = 0;
	    this.initialFill = 1;
	    this.free.length = 0;
	    this.calculatedSize = 0;
	    this.size = 0;
	    if (this.disposed) {
	      while (this.disposed.length) {
	        this.disposeAfter(...this.disposed.shift());
	      }
	    }
	  }
	  get reset() {
	    deprecatedMethod('reset', 'clear');
	    return this.clear
	  }
	  get length() {
	    deprecatedProperty('length', 'size');
	    return this.size
	  }
	  static get AbortController() {
	    return AC
	  }
	  static get AbortSignal() {
	    return AS
	  }
	}
	lruCache = LRUCache;
	return lruCache;
}

var dist$a = {};

var helpers$4 = {};

var hasRequiredHelpers$2;

function requireHelpers$2 () {
	if (hasRequiredHelpers$2) return helpers$4;
	hasRequiredHelpers$2 = 1;
	var __createBinding = (helpers$4 && helpers$4.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (helpers$4 && helpers$4.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (helpers$4 && helpers$4.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	Object.defineProperty(helpers$4, "__esModule", { value: true });
	helpers$4.req = helpers$4.json = helpers$4.toBuffer = void 0;
	const http = __importStar(require$$0$6);
	const https = __importStar(require$$1$1);
	async function toBuffer(stream) {
	    let length = 0;
	    const chunks = [];
	    for await (const chunk of stream) {
	        length += chunk.length;
	        chunks.push(chunk);
	    }
	    return Buffer.concat(chunks, length);
	}
	helpers$4.toBuffer = toBuffer;
	async function json(stream) {
	    const buf = await toBuffer(stream);
	    const str = buf.toString('utf8');
	    try {
	        return JSON.parse(str);
	    }
	    catch (_err) {
	        const err = _err;
	        err.message += ` (input: ${str})`;
	        throw err;
	    }
	}
	helpers$4.json = json;
	function req(url, opts = {}) {
	    const href = typeof url === 'string' ? url : url.href;
	    const req = (href.startsWith('https:') ? https : http).request(url, opts);
	    const promise = new Promise((resolve, reject) => {
	        req
	            .once('response', resolve)
	            .once('error', reject)
	            .end();
	    });
	    req.then = promise.then.bind(promise);
	    return req;
	}
	helpers$4.req = req;
	return helpers$4;
}

var hasRequiredDist$b;

function requireDist$b () {
	if (hasRequiredDist$b) return dist$a;
	hasRequiredDist$b = 1;
	(function (exports$1) {
		var __createBinding = (dist$a && dist$a.__createBinding) || (Object.create ? (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    var desc = Object.getOwnPropertyDescriptor(m, k);
		    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
		      desc = { enumerable: true, get: function() { return m[k]; } };
		    }
		    Object.defineProperty(o, k2, desc);
		}) : (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    o[k2] = m[k];
		}));
		var __setModuleDefault = (dist$a && dist$a.__setModuleDefault) || (Object.create ? (function(o, v) {
		    Object.defineProperty(o, "default", { enumerable: true, value: v });
		}) : function(o, v) {
		    o["default"] = v;
		});
		var __importStar = (dist$a && dist$a.__importStar) || function (mod) {
		    if (mod && mod.__esModule) return mod;
		    var result = {};
		    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
		    __setModuleDefault(result, mod);
		    return result;
		};
		var __exportStar = (dist$a && dist$a.__exportStar) || function(m, exports$1) {
		    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.Agent = void 0;
		const net = __importStar(require$$0$7);
		const http = __importStar(require$$0$6);
		const https_1 = require$$1$1;
		__exportStar(requireHelpers$2(), exports$1);
		const INTERNAL = Symbol('AgentBaseInternalState');
		class Agent extends http.Agent {
		    constructor(opts) {
		        super(opts);
		        this[INTERNAL] = {};
		    }
		    isSecureEndpoint(options) {
		        if (options) {
		            if (typeof options.secureEndpoint === 'boolean') {
		                return options.secureEndpoint;
		            }
		            if (typeof options.protocol === 'string') {
		                return options.protocol === 'https:';
		            }
		        }
		        const { stack } = new Error();
		        if (typeof stack !== 'string')
		            return false;
		        return stack
		            .split('\n')
		            .some((l) => l.indexOf('(https.js:') !== -1 ||
		            l.indexOf('node:https:') !== -1);
		    }
		    incrementSockets(name) {
		        if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
		            return null;
		        }
		        if (!this.sockets[name]) {
		            this.sockets[name] = [];
		        }
		        const fakeSocket = new net.Socket({ writable: false });
		        this.sockets[name].push(fakeSocket);
		        this.totalSocketCount++;
		        return fakeSocket;
		    }
		    decrementSockets(name, socket) {
		        if (!this.sockets[name] || socket === null) {
		            return;
		        }
		        const sockets = this.sockets[name];
		        const index = sockets.indexOf(socket);
		        if (index !== -1) {
		            sockets.splice(index, 1);
		            this.totalSocketCount--;
		            if (sockets.length === 0) {
		                delete this.sockets[name];
		            }
		        }
		    }
		    getName(options) {
		        const secureEndpoint = this.isSecureEndpoint(options);
		        if (secureEndpoint) {
		            return https_1.Agent.prototype.getName.call(this, options);
		        }
		        return super.getName(options);
		    }
		    createSocket(req, options, cb) {
		        const connectOpts = {
		            ...options,
		            secureEndpoint: this.isSecureEndpoint(options),
		        };
		        const name = this.getName(connectOpts);
		        const fakeSocket = this.incrementSockets(name);
		        Promise.resolve()
		            .then(() => this.connect(req, connectOpts))
		            .then((socket) => {
		            this.decrementSockets(name, fakeSocket);
		            if (socket instanceof http.Agent) {
		                try {
		                    return socket.addRequest(req, connectOpts);
		                }
		                catch (err) {
		                    return cb(err);
		                }
		            }
		            this[INTERNAL].currentSocket = socket;
		            super.createSocket(req, options, cb);
		        }, (err) => {
		            this.decrementSockets(name, fakeSocket);
		            cb(err);
		        });
		    }
		    createConnection() {
		        const socket = this[INTERNAL].currentSocket;
		        this[INTERNAL].currentSocket = undefined;
		        if (!socket) {
		            throw new Error('No socket was returned in the `connect()` function');
		        }
		        return socket;
		    }
		    get defaultPort() {
		        return (this[INTERNAL].defaultPort ??
		            (this.protocol === 'https:' ? 443 : 80));
		    }
		    set defaultPort(v) {
		        if (this[INTERNAL]) {
		            this[INTERNAL].defaultPort = v;
		        }
		    }
		    get protocol() {
		        return (this[INTERNAL].protocol ??
		            (this.isSecureEndpoint() ? 'https:' : 'http:'));
		    }
		    set protocol(v) {
		        if (this[INTERNAL]) {
		            this[INTERNAL].protocol = v;
		        }
		    }
		}
		exports$1.Agent = Agent; 
	} (dist$a));
	return dist$a;
}

var proxyFromEnv = {};

var hasRequiredProxyFromEnv;

function requireProxyFromEnv () {
	if (hasRequiredProxyFromEnv) return proxyFromEnv;
	hasRequiredProxyFromEnv = 1;
	var parseUrl = require$$5.parse;
	var DEFAULT_PORTS = {
	  ftp: 21,
	  gopher: 70,
	  http: 80,
	  https: 443,
	  ws: 80,
	  wss: 443,
	};
	var stringEndsWith = String.prototype.endsWith || function(s) {
	  return s.length <= this.length &&
	    this.indexOf(s, this.length - s.length) !== -1;
	};
	function getProxyForUrl(url) {
	  var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {};
	  var proto = parsedUrl.protocol;
	  var hostname = parsedUrl.host;
	  var port = parsedUrl.port;
	  if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') {
	    return '';
	  }
	  proto = proto.split(':', 1)[0];
	  hostname = hostname.replace(/:\d*$/, '');
	  port = parseInt(port) || DEFAULT_PORTS[proto] || 0;
	  if (!shouldProxy(hostname, port)) {
	    return '';
	  }
	  var proxy =
	    getEnv('npm_config_' + proto + '_proxy') ||
	    getEnv(proto + '_proxy') ||
	    getEnv('npm_config_proxy') ||
	    getEnv('all_proxy');
	  if (proxy && proxy.indexOf('://') === -1) {
	    proxy = proto + '://' + proxy;
	  }
	  return proxy;
	}
	function shouldProxy(hostname, port) {
	  var NO_PROXY =
	    (getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase();
	  if (!NO_PROXY) {
	    return true;
	  }
	  if (NO_PROXY === '*') {
	    return false;
	  }
	  return NO_PROXY.split(/[,\s]/).every(function(proxy) {
	    if (!proxy) {
	      return true;
	    }
	    var parsedProxy = proxy.match(/^(.+):(\d+)$/);
	    var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
	    var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
	    if (parsedProxyPort && parsedProxyPort !== port) {
	      return true;
	    }
	    if (!/^[.*]/.test(parsedProxyHostname)) {
	      return hostname !== parsedProxyHostname;
	    }
	    if (parsedProxyHostname.charAt(0) === '*') {
	      parsedProxyHostname = parsedProxyHostname.slice(1);
	    }
	    return !stringEndsWith.call(hostname, parsedProxyHostname);
	  });
	}
	function getEnv(key) {
	  return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
	}
	proxyFromEnv.getProxyForUrl = getProxyForUrl;
	return proxyFromEnv;
}

var dist$9 = {};

var hasRequiredDist$a;

function requireDist$a () {
	if (hasRequiredDist$a) return dist$9;
	hasRequiredDist$a = 1;
	var __createBinding = (dist$9 && dist$9.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (dist$9 && dist$9.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (dist$9 && dist$9.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	var __importDefault = (dist$9 && dist$9.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(dist$9, "__esModule", { value: true });
	dist$9.HttpProxyAgent = void 0;
	const net = __importStar(require$$0$7);
	const tls = __importStar(require$$1$2);
	const debug_1 = __importDefault(requireSrc());
	const events_1 = require$$0$8;
	const agent_base_1 = requireDist$b();
	const url_1 = require$$5;
	const debug = (0, debug_1.default)('http-proxy-agent');
	class HttpProxyAgent extends agent_base_1.Agent {
	    constructor(proxy, opts) {
	        super(opts);
	        this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
	        this.proxyHeaders = opts?.headers ?? {};
	        debug('Creating new HttpProxyAgent instance: %o', this.proxy.href);
	        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
	        const port = this.proxy.port
	            ? parseInt(this.proxy.port, 10)
	            : this.proxy.protocol === 'https:'
	                ? 443
	                : 80;
	        this.connectOpts = {
	            ...(opts ? omit(opts, 'headers') : null),
	            host,
	            port,
	        };
	    }
	    addRequest(req, opts) {
	        req._header = null;
	        this.setRequestProps(req, opts);
	        super.addRequest(req, opts);
	    }
	    setRequestProps(req, opts) {
	        const { proxy } = this;
	        const protocol = opts.secureEndpoint ? 'https:' : 'http:';
	        const hostname = req.getHeader('host') || 'localhost';
	        const base = `${protocol}//${hostname}`;
	        const url = new url_1.URL(req.path, base);
	        if (opts.port !== 80) {
	            url.port = String(opts.port);
	        }
	        req.path = String(url);
	        const headers = typeof this.proxyHeaders === 'function'
	            ? this.proxyHeaders()
	            : { ...this.proxyHeaders };
	        if (proxy.username || proxy.password) {
	            const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
	            headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
	        }
	        if (!headers['Proxy-Connection']) {
	            headers['Proxy-Connection'] = this.keepAlive
	                ? 'Keep-Alive'
	                : 'close';
	        }
	        for (const name of Object.keys(headers)) {
	            const value = headers[name];
	            if (value) {
	                req.setHeader(name, value);
	            }
	        }
	    }
	    async connect(req, opts) {
	        req._header = null;
	        if (!req.path.includes('://')) {
	            this.setRequestProps(req, opts);
	        }
	        let first;
	        let endOfHeaders;
	        debug('Regenerating stored HTTP header string for request');
	        req._implicitHeader();
	        if (req.outputData && req.outputData.length > 0) {
	            debug('Patching connection write() output buffer with updated header');
	            first = req.outputData[0].data;
	            endOfHeaders = first.indexOf('\r\n\r\n') + 4;
	            req.outputData[0].data =
	                req._header + first.substring(endOfHeaders);
	            debug('Output buffer: %o', req.outputData[0].data);
	        }
	        let socket;
	        if (this.proxy.protocol === 'https:') {
	            debug('Creating `tls.Socket`: %o', this.connectOpts);
	            socket = tls.connect(this.connectOpts);
	        }
	        else {
	            debug('Creating `net.Socket`: %o', this.connectOpts);
	            socket = net.connect(this.connectOpts);
	        }
	        await (0, events_1.once)(socket, 'connect');
	        return socket;
	    }
	}
	HttpProxyAgent.protocols = ['http', 'https'];
	dist$9.HttpProxyAgent = HttpProxyAgent;
	function omit(obj, ...keys) {
	    const ret = {};
	    let key;
	    for (key in obj) {
	        if (!keys.includes(key)) {
	            ret[key] = obj[key];
	        }
	    }
	    return ret;
	}
	return dist$9;
}

var dist$8 = {};

var parseProxyResponse = {};

var hasRequiredParseProxyResponse;

function requireParseProxyResponse () {
	if (hasRequiredParseProxyResponse) return parseProxyResponse;
	hasRequiredParseProxyResponse = 1;
	var __importDefault = (parseProxyResponse && parseProxyResponse.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(parseProxyResponse, "__esModule", { value: true });
	parseProxyResponse.parseProxyResponse = void 0;
	const debug_1 = __importDefault(requireSrc());
	const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response');
	function parseProxyResponse$1(socket) {
	    return new Promise((resolve, reject) => {
	        let buffersLength = 0;
	        const buffers = [];
	        function read() {
	            const b = socket.read();
	            if (b)
	                ondata(b);
	            else
	                socket.once('readable', read);
	        }
	        function cleanup() {
	            socket.removeListener('end', onend);
	            socket.removeListener('error', onerror);
	            socket.removeListener('readable', read);
	        }
	        function onend() {
	            cleanup();
	            debug('onend');
	            reject(new Error('Proxy connection ended before receiving CONNECT response'));
	        }
	        function onerror(err) {
	            cleanup();
	            debug('onerror %o', err);
	            reject(err);
	        }
	        function ondata(b) {
	            buffers.push(b);
	            buffersLength += b.length;
	            const buffered = Buffer.concat(buffers, buffersLength);
	            const endOfHeaders = buffered.indexOf('\r\n\r\n');
	            if (endOfHeaders === -1) {
	                debug('have not received end of HTTP headers yet...');
	                read();
	                return;
	            }
	            const headerParts = buffered
	                .slice(0, endOfHeaders)
	                .toString('ascii')
	                .split('\r\n');
	            const firstLine = headerParts.shift();
	            if (!firstLine) {
	                socket.destroy();
	                return reject(new Error('No header received from proxy CONNECT response'));
	            }
	            const firstLineParts = firstLine.split(' ');
	            const statusCode = +firstLineParts[1];
	            const statusText = firstLineParts.slice(2).join(' ');
	            const headers = {};
	            for (const header of headerParts) {
	                if (!header)
	                    continue;
	                const firstColon = header.indexOf(':');
	                if (firstColon === -1) {
	                    socket.destroy();
	                    return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
	                }
	                const key = header.slice(0, firstColon).toLowerCase();
	                const value = header.slice(firstColon + 1).trimStart();
	                const current = headers[key];
	                if (typeof current === 'string') {
	                    headers[key] = [current, value];
	                }
	                else if (Array.isArray(current)) {
	                    current.push(value);
	                }
	                else {
	                    headers[key] = value;
	                }
	            }
	            debug('got proxy server response: %o %o', firstLine, headers);
	            cleanup();
	            resolve({
	                connect: {
	                    statusCode,
	                    statusText,
	                    headers,
	                },
	                buffered,
	            });
	        }
	        socket.on('error', onerror);
	        socket.on('end', onend);
	        read();
	    });
	}
	parseProxyResponse.parseProxyResponse = parseProxyResponse$1;
	return parseProxyResponse;
}

var hasRequiredDist$9;

function requireDist$9 () {
	if (hasRequiredDist$9) return dist$8;
	hasRequiredDist$9 = 1;
	var __createBinding = (dist$8 && dist$8.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (dist$8 && dist$8.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (dist$8 && dist$8.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	var __importDefault = (dist$8 && dist$8.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(dist$8, "__esModule", { value: true });
	dist$8.HttpsProxyAgent = void 0;
	const net = __importStar(require$$0$7);
	const tls = __importStar(require$$1$2);
	const assert_1 = __importDefault(require$$2);
	const debug_1 = __importDefault(requireSrc());
	const agent_base_1 = requireDist$b();
	const url_1 = require$$5;
	const parse_proxy_response_1 = requireParseProxyResponse();
	const debug = (0, debug_1.default)('https-proxy-agent');
	const setServernameFromNonIpHost = (options) => {
	    if (options.servername === undefined &&
	        options.host &&
	        !net.isIP(options.host)) {
	        return {
	            ...options,
	            servername: options.host,
	        };
	    }
	    return options;
	};
	class HttpsProxyAgent extends agent_base_1.Agent {
	    constructor(proxy, opts) {
	        super(opts);
	        this.options = { path: undefined };
	        this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
	        this.proxyHeaders = opts?.headers ?? {};
	        debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);
	        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
	        const port = this.proxy.port
	            ? parseInt(this.proxy.port, 10)
	            : this.proxy.protocol === 'https:'
	                ? 443
	                : 80;
	        this.connectOpts = {
	            ALPNProtocols: ['http/1.1'],
	            ...(opts ? omit(opts, 'headers') : null),
	            host,
	            port,
	        };
	    }
	    async connect(req, opts) {
	        const { proxy } = this;
	        if (!opts.host) {
	            throw new TypeError('No "host" provided');
	        }
	        let socket;
	        if (proxy.protocol === 'https:') {
	            debug('Creating `tls.Socket`: %o', this.connectOpts);
	            socket = tls.connect(setServernameFromNonIpHost(this.connectOpts));
	        }
	        else {
	            debug('Creating `net.Socket`: %o', this.connectOpts);
	            socket = net.connect(this.connectOpts);
	        }
	        const headers = typeof this.proxyHeaders === 'function'
	            ? this.proxyHeaders()
	            : { ...this.proxyHeaders };
	        const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
	        let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
	        if (proxy.username || proxy.password) {
	            const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
	            headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
	        }
	        headers.Host = `${host}:${opts.port}`;
	        if (!headers['Proxy-Connection']) {
	            headers['Proxy-Connection'] = this.keepAlive
	                ? 'Keep-Alive'
	                : 'close';
	        }
	        for (const name of Object.keys(headers)) {
	            payload += `${name}: ${headers[name]}\r\n`;
	        }
	        const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
	        socket.write(`${payload}\r\n`);
	        const { connect, buffered } = await proxyResponsePromise;
	        req.emit('proxyConnect', connect);
	        this.emit('proxyConnect', connect, req);
	        if (connect.statusCode === 200) {
	            req.once('socket', resume);
	            if (opts.secureEndpoint) {
	                debug('Upgrading socket connection to TLS');
	                return tls.connect({
	                    ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'),
	                    socket,
	                });
	            }
	            return socket;
	        }
	        socket.destroy();
	        const fakeSocket = new net.Socket({ writable: false });
	        fakeSocket.readable = true;
	        req.once('socket', (s) => {
	            debug('Replaying proxy buffer for failed request');
	            (0, assert_1.default)(s.listenerCount('data') > 0);
	            s.push(buffered);
	            s.push(null);
	        });
	        return fakeSocket;
	    }
	}
	HttpsProxyAgent.protocols = ['http', 'https'];
	dist$8.HttpsProxyAgent = HttpsProxyAgent;
	function resume(socket) {
	    socket.resume();
	}
	function omit(obj, ...keys) {
	    const ret = {};
	    let key;
	    for (key in obj) {
	        if (!keys.includes(key)) {
	            ret[key] = obj[key];
	        }
	    }
	    return ret;
	}
	return dist$8;
}

var dist$7 = {};

var build = {};

var socksclient = {};

var smartbuffer = {};

var utils$1 = {};

var hasRequiredUtils$1;

function requireUtils$1 () {
	if (hasRequiredUtils$1) return utils$1;
	hasRequiredUtils$1 = 1;
	Object.defineProperty(utils$1, "__esModule", { value: true });
	const buffer_1 = require$$0$9;
	const ERRORS = {
	    INVALID_ENCODING: 'Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.',
	    INVALID_SMARTBUFFER_SIZE: 'Invalid size provided. Size must be a valid integer greater than zero.',
	    INVALID_SMARTBUFFER_BUFFER: 'Invalid Buffer provided in SmartBufferOptions.',
	    INVALID_SMARTBUFFER_OBJECT: 'Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.',
	    INVALID_OFFSET: 'An invalid offset value was provided.',
	    INVALID_OFFSET_NON_NUMBER: 'An invalid offset value was provided. A numeric value is required.',
	    INVALID_LENGTH: 'An invalid length value was provided.',
	    INVALID_LENGTH_NON_NUMBER: 'An invalid length value was provived. A numeric value is required.',
	    INVALID_TARGET_OFFSET: 'Target offset is beyond the bounds of the internal SmartBuffer data.',
	    INVALID_TARGET_LENGTH: 'Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.',
	    INVALID_READ_BEYOND_BOUNDS: 'Attempted to read beyond the bounds of the managed data.',
	    INVALID_WRITE_BEYOND_BOUNDS: 'Attempted to write beyond the bounds of the managed data.'
	};
	utils$1.ERRORS = ERRORS;
	function checkEncoding(encoding) {
	    if (!buffer_1.Buffer.isEncoding(encoding)) {
	        throw new Error(ERRORS.INVALID_ENCODING);
	    }
	}
	utils$1.checkEncoding = checkEncoding;
	function isFiniteInteger(value) {
	    return typeof value === 'number' && isFinite(value) && isInteger(value);
	}
	utils$1.isFiniteInteger = isFiniteInteger;
	function checkOffsetOrLengthValue(value, offset) {
	    if (typeof value === 'number') {
	        if (!isFiniteInteger(value) || value < 0) {
	            throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH);
	        }
	    }
	    else {
	        throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER);
	    }
	}
	function checkLengthValue(length) {
	    checkOffsetOrLengthValue(length, false);
	}
	utils$1.checkLengthValue = checkLengthValue;
	function checkOffsetValue(offset) {
	    checkOffsetOrLengthValue(offset, true);
	}
	utils$1.checkOffsetValue = checkOffsetValue;
	function checkTargetOffset(offset, buff) {
	    if (offset < 0 || offset > buff.length) {
	        throw new Error(ERRORS.INVALID_TARGET_OFFSET);
	    }
	}
	utils$1.checkTargetOffset = checkTargetOffset;
	function isInteger(value) {
	    return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
	}
	function bigIntAndBufferInt64Check(bufferMethod) {
	    if (typeof BigInt === 'undefined') {
	        throw new Error('Platform does not support JS BigInt type.');
	    }
	    if (typeof buffer_1.Buffer.prototype[bufferMethod] === 'undefined') {
	        throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`);
	    }
	}
	utils$1.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check;
	return utils$1;
}

var hasRequiredSmartbuffer;

function requireSmartbuffer () {
	if (hasRequiredSmartbuffer) return smartbuffer;
	hasRequiredSmartbuffer = 1;
	Object.defineProperty(smartbuffer, "__esModule", { value: true });
	const utils_1 = requireUtils$1();
	const DEFAULT_SMARTBUFFER_SIZE = 4096;
	const DEFAULT_SMARTBUFFER_ENCODING = 'utf8';
	class SmartBuffer {
	    constructor(options) {
	        this.length = 0;
	        this._encoding = DEFAULT_SMARTBUFFER_ENCODING;
	        this._writeOffset = 0;
	        this._readOffset = 0;
	        if (SmartBuffer.isSmartBufferOptions(options)) {
	            if (options.encoding) {
	                utils_1.checkEncoding(options.encoding);
	                this._encoding = options.encoding;
	            }
	            if (options.size) {
	                if (utils_1.isFiniteInteger(options.size) && options.size > 0) {
	                    this._buff = Buffer.allocUnsafe(options.size);
	                }
	                else {
	                    throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE);
	                }
	            }
	            else if (options.buff) {
	                if (Buffer.isBuffer(options.buff)) {
	                    this._buff = options.buff;
	                    this.length = options.buff.length;
	                }
	                else {
	                    throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER);
	                }
	            }
	            else {
	                this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE);
	            }
	        }
	        else {
	            if (typeof options !== 'undefined') {
	                throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT);
	            }
	            this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE);
	        }
	    }
	    static fromSize(size, encoding) {
	        return new this({
	            size: size,
	            encoding: encoding
	        });
	    }
	    static fromBuffer(buff, encoding) {
	        return new this({
	            buff: buff,
	            encoding: encoding
	        });
	    }
	    static fromOptions(options) {
	        return new this(options);
	    }
	    static isSmartBufferOptions(options) {
	        const castOptions = options;
	        return (castOptions &&
	            (castOptions.encoding !== undefined || castOptions.size !== undefined || castOptions.buff !== undefined));
	    }
	    readInt8(offset) {
	        return this._readNumberValue(Buffer.prototype.readInt8, 1, offset);
	    }
	    readInt16BE(offset) {
	        return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset);
	    }
	    readInt16LE(offset) {
	        return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset);
	    }
	    readInt32BE(offset) {
	        return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset);
	    }
	    readInt32LE(offset) {
	        return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset);
	    }
	    readBigInt64BE(offset) {
	        utils_1.bigIntAndBufferInt64Check('readBigInt64BE');
	        return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset);
	    }
	    readBigInt64LE(offset) {
	        utils_1.bigIntAndBufferInt64Check('readBigInt64LE');
	        return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset);
	    }
	    writeInt8(value, offset) {
	        this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset);
	        return this;
	    }
	    insertInt8(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset);
	    }
	    writeInt16BE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset);
	    }
	    insertInt16BE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset);
	    }
	    writeInt16LE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset);
	    }
	    insertInt16LE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset);
	    }
	    writeInt32BE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset);
	    }
	    insertInt32BE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset);
	    }
	    writeInt32LE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset);
	    }
	    insertInt32LE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset);
	    }
	    writeBigInt64BE(value, offset) {
	        utils_1.bigIntAndBufferInt64Check('writeBigInt64BE');
	        return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset);
	    }
	    insertBigInt64BE(value, offset) {
	        utils_1.bigIntAndBufferInt64Check('writeBigInt64BE');
	        return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset);
	    }
	    writeBigInt64LE(value, offset) {
	        utils_1.bigIntAndBufferInt64Check('writeBigInt64LE');
	        return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset);
	    }
	    insertBigInt64LE(value, offset) {
	        utils_1.bigIntAndBufferInt64Check('writeBigInt64LE');
	        return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset);
	    }
	    readUInt8(offset) {
	        return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset);
	    }
	    readUInt16BE(offset) {
	        return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset);
	    }
	    readUInt16LE(offset) {
	        return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset);
	    }
	    readUInt32BE(offset) {
	        return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset);
	    }
	    readUInt32LE(offset) {
	        return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset);
	    }
	    readBigUInt64BE(offset) {
	        utils_1.bigIntAndBufferInt64Check('readBigUInt64BE');
	        return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset);
	    }
	    readBigUInt64LE(offset) {
	        utils_1.bigIntAndBufferInt64Check('readBigUInt64LE');
	        return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset);
	    }
	    writeUInt8(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset);
	    }
	    insertUInt8(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset);
	    }
	    writeUInt16BE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset);
	    }
	    insertUInt16BE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset);
	    }
	    writeUInt16LE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset);
	    }
	    insertUInt16LE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset);
	    }
	    writeUInt32BE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset);
	    }
	    insertUInt32BE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset);
	    }
	    writeUInt32LE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset);
	    }
	    insertUInt32LE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset);
	    }
	    writeBigUInt64BE(value, offset) {
	        utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE');
	        return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset);
	    }
	    insertBigUInt64BE(value, offset) {
	        utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE');
	        return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset);
	    }
	    writeBigUInt64LE(value, offset) {
	        utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE');
	        return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset);
	    }
	    insertBigUInt64LE(value, offset) {
	        utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE');
	        return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset);
	    }
	    readFloatBE(offset) {
	        return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset);
	    }
	    readFloatLE(offset) {
	        return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset);
	    }
	    writeFloatBE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset);
	    }
	    insertFloatBE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset);
	    }
	    writeFloatLE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset);
	    }
	    insertFloatLE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset);
	    }
	    readDoubleBE(offset) {
	        return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset);
	    }
	    readDoubleLE(offset) {
	        return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset);
	    }
	    writeDoubleBE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset);
	    }
	    insertDoubleBE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset);
	    }
	    writeDoubleLE(value, offset) {
	        return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset);
	    }
	    insertDoubleLE(value, offset) {
	        return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset);
	    }
	    readString(arg1, encoding) {
	        let lengthVal;
	        if (typeof arg1 === 'number') {
	            utils_1.checkLengthValue(arg1);
	            lengthVal = Math.min(arg1, this.length - this._readOffset);
	        }
	        else {
	            encoding = arg1;
	            lengthVal = this.length - this._readOffset;
	        }
	        if (typeof encoding !== 'undefined') {
	            utils_1.checkEncoding(encoding);
	        }
	        const value = this._buff.slice(this._readOffset, this._readOffset + lengthVal).toString(encoding || this._encoding);
	        this._readOffset += lengthVal;
	        return value;
	    }
	    insertString(value, offset, encoding) {
	        utils_1.checkOffsetValue(offset);
	        return this._handleString(value, true, offset, encoding);
	    }
	    writeString(value, arg2, encoding) {
	        return this._handleString(value, false, arg2, encoding);
	    }
	    readStringNT(encoding) {
	        if (typeof encoding !== 'undefined') {
	            utils_1.checkEncoding(encoding);
	        }
	        let nullPos = this.length;
	        for (let i = this._readOffset; i < this.length; i++) {
	            if (this._buff[i] === 0x00) {
	                nullPos = i;
	                break;
	            }
	        }
	        const value = this._buff.slice(this._readOffset, nullPos);
	        this._readOffset = nullPos + 1;
	        return value.toString(encoding || this._encoding);
	    }
	    insertStringNT(value, offset, encoding) {
	        utils_1.checkOffsetValue(offset);
	        this.insertString(value, offset, encoding);
	        this.insertUInt8(0x00, offset + value.length);
	        return this;
	    }
	    writeStringNT(value, arg2, encoding) {
	        this.writeString(value, arg2, encoding);
	        this.writeUInt8(0x00, typeof arg2 === 'number' ? arg2 + value.length : this.writeOffset);
	        return this;
	    }
	    readBuffer(length) {
	        if (typeof length !== 'undefined') {
	            utils_1.checkLengthValue(length);
	        }
	        const lengthVal = typeof length === 'number' ? length : this.length;
	        const endPoint = Math.min(this.length, this._readOffset + lengthVal);
	        const value = this._buff.slice(this._readOffset, endPoint);
	        this._readOffset = endPoint;
	        return value;
	    }
	    insertBuffer(value, offset) {
	        utils_1.checkOffsetValue(offset);
	        return this._handleBuffer(value, true, offset);
	    }
	    writeBuffer(value, offset) {
	        return this._handleBuffer(value, false, offset);
	    }
	    readBufferNT() {
	        let nullPos = this.length;
	        for (let i = this._readOffset; i < this.length; i++) {
	            if (this._buff[i] === 0x00) {
	                nullPos = i;
	                break;
	            }
	        }
	        const value = this._buff.slice(this._readOffset, nullPos);
	        this._readOffset = nullPos + 1;
	        return value;
	    }
	    insertBufferNT(value, offset) {
	        utils_1.checkOffsetValue(offset);
	        this.insertBuffer(value, offset);
	        this.insertUInt8(0x00, offset + value.length);
	        return this;
	    }
	    writeBufferNT(value, offset) {
	        if (typeof offset !== 'undefined') {
	            utils_1.checkOffsetValue(offset);
	        }
	        this.writeBuffer(value, offset);
	        this.writeUInt8(0x00, typeof offset === 'number' ? offset + value.length : this._writeOffset);
	        return this;
	    }
	    clear() {
	        this._writeOffset = 0;
	        this._readOffset = 0;
	        this.length = 0;
	        return this;
	    }
	    remaining() {
	        return this.length - this._readOffset;
	    }
	    get readOffset() {
	        return this._readOffset;
	    }
	    set readOffset(offset) {
	        utils_1.checkOffsetValue(offset);
	        utils_1.checkTargetOffset(offset, this);
	        this._readOffset = offset;
	    }
	    get writeOffset() {
	        return this._writeOffset;
	    }
	    set writeOffset(offset) {
	        utils_1.checkOffsetValue(offset);
	        utils_1.checkTargetOffset(offset, this);
	        this._writeOffset = offset;
	    }
	    get encoding() {
	        return this._encoding;
	    }
	    set encoding(encoding) {
	        utils_1.checkEncoding(encoding);
	        this._encoding = encoding;
	    }
	    get internalBuffer() {
	        return this._buff;
	    }
	    toBuffer() {
	        return this._buff.slice(0, this.length);
	    }
	    toString(encoding) {
	        const encodingVal = typeof encoding === 'string' ? encoding : this._encoding;
	        utils_1.checkEncoding(encodingVal);
	        return this._buff.toString(encodingVal, 0, this.length);
	    }
	    destroy() {
	        this.clear();
	        return this;
	    }
	    _handleString(value, isInsert, arg3, encoding) {
	        let offsetVal = this._writeOffset;
	        let encodingVal = this._encoding;
	        if (typeof arg3 === 'number') {
	            offsetVal = arg3;
	        }
	        else if (typeof arg3 === 'string') {
	            utils_1.checkEncoding(arg3);
	            encodingVal = arg3;
	        }
	        if (typeof encoding === 'string') {
	            utils_1.checkEncoding(encoding);
	            encodingVal = encoding;
	        }
	        const byteLength = Buffer.byteLength(value, encodingVal);
	        if (isInsert) {
	            this.ensureInsertable(byteLength, offsetVal);
	        }
	        else {
	            this._ensureWriteable(byteLength, offsetVal);
	        }
	        this._buff.write(value, offsetVal, byteLength, encodingVal);
	        if (isInsert) {
	            this._writeOffset += byteLength;
	        }
	        else {
	            if (typeof arg3 === 'number') {
	                this._writeOffset = Math.max(this._writeOffset, offsetVal + byteLength);
	            }
	            else {
	                this._writeOffset += byteLength;
	            }
	        }
	        return this;
	    }
	    _handleBuffer(value, isInsert, offset) {
	        const offsetVal = typeof offset === 'number' ? offset : this._writeOffset;
	        if (isInsert) {
	            this.ensureInsertable(value.length, offsetVal);
	        }
	        else {
	            this._ensureWriteable(value.length, offsetVal);
	        }
	        value.copy(this._buff, offsetVal);
	        if (isInsert) {
	            this._writeOffset += value.length;
	        }
	        else {
	            if (typeof offset === 'number') {
	                this._writeOffset = Math.max(this._writeOffset, offsetVal + value.length);
	            }
	            else {
	                this._writeOffset += value.length;
	            }
	        }
	        return this;
	    }
	    ensureReadable(length, offset) {
	        let offsetVal = this._readOffset;
	        if (typeof offset !== 'undefined') {
	            utils_1.checkOffsetValue(offset);
	            offsetVal = offset;
	        }
	        if (offsetVal < 0 || offsetVal + length > this.length) {
	            throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS);
	        }
	    }
	    ensureInsertable(dataLength, offset) {
	        utils_1.checkOffsetValue(offset);
	        this._ensureCapacity(this.length + dataLength);
	        if (offset < this.length) {
	            this._buff.copy(this._buff, offset + dataLength, offset, this._buff.length);
	        }
	        if (offset + dataLength > this.length) {
	            this.length = offset + dataLength;
	        }
	        else {
	            this.length += dataLength;
	        }
	    }
	    _ensureWriteable(dataLength, offset) {
	        const offsetVal = typeof offset === 'number' ? offset : this._writeOffset;
	        this._ensureCapacity(offsetVal + dataLength);
	        if (offsetVal + dataLength > this.length) {
	            this.length = offsetVal + dataLength;
	        }
	    }
	    _ensureCapacity(minLength) {
	        const oldLength = this._buff.length;
	        if (minLength > oldLength) {
	            let data = this._buff;
	            let newLength = (oldLength * 3) / 2 + 1;
	            if (newLength < minLength) {
	                newLength = minLength;
	            }
	            this._buff = Buffer.allocUnsafe(newLength);
	            data.copy(this._buff, 0, 0, oldLength);
	        }
	    }
	    _readNumberValue(func, byteSize, offset) {
	        this.ensureReadable(byteSize, offset);
	        const value = func.call(this._buff, typeof offset === 'number' ? offset : this._readOffset);
	        if (typeof offset === 'undefined') {
	            this._readOffset += byteSize;
	        }
	        return value;
	    }
	    _insertNumberValue(func, byteSize, value, offset) {
	        utils_1.checkOffsetValue(offset);
	        this.ensureInsertable(byteSize, offset);
	        func.call(this._buff, value, offset);
	        this._writeOffset += byteSize;
	        return this;
	    }
	    _writeNumberValue(func, byteSize, value, offset) {
	        if (typeof offset === 'number') {
	            if (offset < 0) {
	                throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);
	            }
	            utils_1.checkOffsetValue(offset);
	        }
	        const offsetVal = typeof offset === 'number' ? offset : this._writeOffset;
	        this._ensureWriteable(byteSize, offsetVal);
	        func.call(this._buff, value, offsetVal);
	        if (typeof offset === 'number') {
	            this._writeOffset = Math.max(this._writeOffset, offsetVal + byteSize);
	        }
	        else {
	            this._writeOffset += byteSize;
	        }
	        return this;
	    }
	}
	smartbuffer.SmartBuffer = SmartBuffer;
	return smartbuffer;
}

var constants$3 = {};

var hasRequiredConstants$3;

function requireConstants$3 () {
	if (hasRequiredConstants$3) return constants$3;
	hasRequiredConstants$3 = 1;
	Object.defineProperty(constants$3, "__esModule", { value: true });
	constants$3.SOCKS5_NO_ACCEPTABLE_AUTH = constants$3.SOCKS5_CUSTOM_AUTH_END = constants$3.SOCKS5_CUSTOM_AUTH_START = constants$3.SOCKS_INCOMING_PACKET_SIZES = constants$3.SocksClientState = constants$3.Socks5Response = constants$3.Socks5HostType = constants$3.Socks5Auth = constants$3.Socks4Response = constants$3.SocksCommand = constants$3.ERRORS = constants$3.DEFAULT_TIMEOUT = void 0;
	const DEFAULT_TIMEOUT = 30000;
	constants$3.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
	const ERRORS = {
	    InvalidSocksCommand: 'An invalid SOCKS command was provided. Valid options are connect, bind, and associate.',
	    InvalidSocksCommandForOperation: 'An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.',
	    InvalidSocksCommandChain: 'An invalid SOCKS command was provided. Chaining currently only supports the connect command.',
	    InvalidSocksClientOptionsDestination: 'An invalid destination host was provided.',
	    InvalidSocksClientOptionsExistingSocket: 'An invalid existing socket was provided. This should be an instance of stream.Duplex.',
	    InvalidSocksClientOptionsProxy: 'Invalid SOCKS proxy details were provided.',
	    InvalidSocksClientOptionsTimeout: 'An invalid timeout value was provided. Please enter a value above 0 (in ms).',
	    InvalidSocksClientOptionsProxiesLength: 'At least two socks proxies must be provided for chaining.',
	    InvalidSocksClientOptionsCustomAuthRange: 'Custom auth must be a value between 0x80 and 0xFE.',
	    InvalidSocksClientOptionsCustomAuthOptions: 'When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.',
	    NegotiationError: 'Negotiation error',
	    SocketClosed: 'Socket closed',
	    ProxyConnectionTimedOut: 'Proxy connection timed out',
	    InternalError: 'SocksClient internal error (this should not happen)',
	    InvalidSocks4HandshakeResponse: 'Received invalid Socks4 handshake response',
	    Socks4ProxyRejectedConnection: 'Socks4 Proxy rejected connection',
	    InvalidSocks4IncomingConnectionResponse: 'Socks4 invalid incoming connection response',
	    Socks4ProxyRejectedIncomingBoundConnection: 'Socks4 Proxy rejected incoming bound connection',
	    InvalidSocks5InitialHandshakeResponse: 'Received invalid Socks5 initial handshake response',
	    InvalidSocks5IntiailHandshakeSocksVersion: 'Received invalid Socks5 initial handshake (invalid socks version)',
	    InvalidSocks5InitialHandshakeNoAcceptedAuthType: 'Received invalid Socks5 initial handshake (no accepted authentication type)',
	    InvalidSocks5InitialHandshakeUnknownAuthType: 'Received invalid Socks5 initial handshake (unknown authentication type)',
	    Socks5AuthenticationFailed: 'Socks5 Authentication failed',
	    InvalidSocks5FinalHandshake: 'Received invalid Socks5 final handshake response',
	    InvalidSocks5FinalHandshakeRejected: 'Socks5 proxy rejected connection',
	    InvalidSocks5IncomingConnectionResponse: 'Received invalid Socks5 incoming connection response',
	    Socks5ProxyRejectedIncomingBoundConnection: 'Socks5 Proxy rejected incoming bound connection',
	};
	constants$3.ERRORS = ERRORS;
	const SOCKS_INCOMING_PACKET_SIZES = {
	    Socks5InitialHandshakeResponse: 2,
	    Socks5UserPassAuthenticationResponse: 2,
	    Socks5ResponseHeader: 5,
	    Socks5ResponseIPv4: 10,
	    Socks5ResponseIPv6: 22,
	    Socks5ResponseHostname: (hostNameLength) => hostNameLength + 7,
	    Socks4Response: 8,
	};
	constants$3.SOCKS_INCOMING_PACKET_SIZES = SOCKS_INCOMING_PACKET_SIZES;
	var SocksCommand;
	(function (SocksCommand) {
	    SocksCommand[SocksCommand["connect"] = 1] = "connect";
	    SocksCommand[SocksCommand["bind"] = 2] = "bind";
	    SocksCommand[SocksCommand["associate"] = 3] = "associate";
	})(SocksCommand || (constants$3.SocksCommand = SocksCommand = {}));
	var Socks4Response;
	(function (Socks4Response) {
	    Socks4Response[Socks4Response["Granted"] = 90] = "Granted";
	    Socks4Response[Socks4Response["Failed"] = 91] = "Failed";
	    Socks4Response[Socks4Response["Rejected"] = 92] = "Rejected";
	    Socks4Response[Socks4Response["RejectedIdent"] = 93] = "RejectedIdent";
	})(Socks4Response || (constants$3.Socks4Response = Socks4Response = {}));
	var Socks5Auth;
	(function (Socks5Auth) {
	    Socks5Auth[Socks5Auth["NoAuth"] = 0] = "NoAuth";
	    Socks5Auth[Socks5Auth["GSSApi"] = 1] = "GSSApi";
	    Socks5Auth[Socks5Auth["UserPass"] = 2] = "UserPass";
	})(Socks5Auth || (constants$3.Socks5Auth = Socks5Auth = {}));
	const SOCKS5_CUSTOM_AUTH_START = 0x80;
	constants$3.SOCKS5_CUSTOM_AUTH_START = SOCKS5_CUSTOM_AUTH_START;
	const SOCKS5_CUSTOM_AUTH_END = 0xfe;
	constants$3.SOCKS5_CUSTOM_AUTH_END = SOCKS5_CUSTOM_AUTH_END;
	const SOCKS5_NO_ACCEPTABLE_AUTH = 0xff;
	constants$3.SOCKS5_NO_ACCEPTABLE_AUTH = SOCKS5_NO_ACCEPTABLE_AUTH;
	var Socks5Response;
	(function (Socks5Response) {
	    Socks5Response[Socks5Response["Granted"] = 0] = "Granted";
	    Socks5Response[Socks5Response["Failure"] = 1] = "Failure";
	    Socks5Response[Socks5Response["NotAllowed"] = 2] = "NotAllowed";
	    Socks5Response[Socks5Response["NetworkUnreachable"] = 3] = "NetworkUnreachable";
	    Socks5Response[Socks5Response["HostUnreachable"] = 4] = "HostUnreachable";
	    Socks5Response[Socks5Response["ConnectionRefused"] = 5] = "ConnectionRefused";
	    Socks5Response[Socks5Response["TTLExpired"] = 6] = "TTLExpired";
	    Socks5Response[Socks5Response["CommandNotSupported"] = 7] = "CommandNotSupported";
	    Socks5Response[Socks5Response["AddressNotSupported"] = 8] = "AddressNotSupported";
	})(Socks5Response || (constants$3.Socks5Response = Socks5Response = {}));
	var Socks5HostType;
	(function (Socks5HostType) {
	    Socks5HostType[Socks5HostType["IPv4"] = 1] = "IPv4";
	    Socks5HostType[Socks5HostType["Hostname"] = 3] = "Hostname";
	    Socks5HostType[Socks5HostType["IPv6"] = 4] = "IPv6";
	})(Socks5HostType || (constants$3.Socks5HostType = Socks5HostType = {}));
	var SocksClientState;
	(function (SocksClientState) {
	    SocksClientState[SocksClientState["Created"] = 0] = "Created";
	    SocksClientState[SocksClientState["Connecting"] = 1] = "Connecting";
	    SocksClientState[SocksClientState["Connected"] = 2] = "Connected";
	    SocksClientState[SocksClientState["SentInitialHandshake"] = 3] = "SentInitialHandshake";
	    SocksClientState[SocksClientState["ReceivedInitialHandshakeResponse"] = 4] = "ReceivedInitialHandshakeResponse";
	    SocksClientState[SocksClientState["SentAuthentication"] = 5] = "SentAuthentication";
	    SocksClientState[SocksClientState["ReceivedAuthenticationResponse"] = 6] = "ReceivedAuthenticationResponse";
	    SocksClientState[SocksClientState["SentFinalHandshake"] = 7] = "SentFinalHandshake";
	    SocksClientState[SocksClientState["ReceivedFinalResponse"] = 8] = "ReceivedFinalResponse";
	    SocksClientState[SocksClientState["BoundWaitingForConnection"] = 9] = "BoundWaitingForConnection";
	    SocksClientState[SocksClientState["Established"] = 10] = "Established";
	    SocksClientState[SocksClientState["Disconnected"] = 11] = "Disconnected";
	    SocksClientState[SocksClientState["Error"] = 99] = "Error";
	})(SocksClientState || (constants$3.SocksClientState = SocksClientState = {}));
	return constants$3;
}

var helpers$3 = {};

var util$2 = {};

var hasRequiredUtil$2;

function requireUtil$2 () {
	if (hasRequiredUtil$2) return util$2;
	hasRequiredUtil$2 = 1;
	Object.defineProperty(util$2, "__esModule", { value: true });
	util$2.shuffleArray = util$2.SocksClientError = void 0;
	class SocksClientError extends Error {
	    constructor(message, options) {
	        super(message);
	        this.options = options;
	    }
	}
	util$2.SocksClientError = SocksClientError;
	function shuffleArray(array) {
	    for (let i = array.length - 1; i > 0; i--) {
	        const j = Math.floor(Math.random() * (i + 1));
	        [array[i], array[j]] = [array[j], array[i]];
	    }
	}
	util$2.shuffleArray = shuffleArray;
	return util$2;
}

var ipAddress = {};

var ipv4 = {};

var common$2 = {};

var hasRequiredCommon$1;

function requireCommon$1 () {
	if (hasRequiredCommon$1) return common$2;
	hasRequiredCommon$1 = 1;
	Object.defineProperty(common$2, "__esModule", { value: true });
	common$2.isInSubnet = isInSubnet;
	common$2.isCorrect = isCorrect;
	common$2.numberToPaddedHex = numberToPaddedHex;
	common$2.stringToPaddedHex = stringToPaddedHex;
	common$2.testBit = testBit;
	function isInSubnet(address) {
	    if (this.subnetMask < address.subnetMask) {
	        return false;
	    }
	    if (this.mask(address.subnetMask) === address.mask()) {
	        return true;
	    }
	    return false;
	}
	function isCorrect(defaultBits) {
	    return function () {
	        if (this.addressMinusSuffix !== this.correctForm()) {
	            return false;
	        }
	        if (this.subnetMask === defaultBits && !this.parsedSubnet) {
	            return true;
	        }
	        return this.parsedSubnet === String(this.subnetMask);
	    };
	}
	function numberToPaddedHex(number) {
	    return number.toString(16).padStart(2, '0');
	}
	function stringToPaddedHex(numberString) {
	    return numberToPaddedHex(parseInt(numberString, 10));
	}
	function testBit(binaryValue, position) {
	    const { length } = binaryValue;
	    if (position > length) {
	        return false;
	    }
	    const positionInString = length - position;
	    return binaryValue.substring(positionInString, positionInString + 1) === '1';
	}
	return common$2;
}

var constants$2 = {};

var hasRequiredConstants$2;

function requireConstants$2 () {
	if (hasRequiredConstants$2) return constants$2;
	hasRequiredConstants$2 = 1;
	Object.defineProperty(constants$2, "__esModule", { value: true });
	constants$2.RE_SUBNET_STRING = constants$2.RE_ADDRESS = constants$2.GROUPS = constants$2.BITS = void 0;
	constants$2.BITS = 32;
	constants$2.GROUPS = 4;
	constants$2.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;
	constants$2.RE_SUBNET_STRING = /\/\d{1,2}$/;
	return constants$2;
}

var addressError = {};

var hasRequiredAddressError;

function requireAddressError () {
	if (hasRequiredAddressError) return addressError;
	hasRequiredAddressError = 1;
	Object.defineProperty(addressError, "__esModule", { value: true });
	addressError.AddressError = void 0;
	class AddressError extends Error {
	    constructor(message, parseMessage) {
	        super(message);
	        this.name = 'AddressError';
	        this.parseMessage = parseMessage;
	    }
	}
	addressError.AddressError = AddressError;
	return addressError;
}

var hasRequiredIpv4;

function requireIpv4 () {
	if (hasRequiredIpv4) return ipv4;
	hasRequiredIpv4 = 1;
	var __createBinding = (ipv4 && ipv4.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (ipv4 && ipv4.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (ipv4 && ipv4.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	Object.defineProperty(ipv4, "__esModule", { value: true });
	ipv4.Address4 = void 0;
	const common = __importStar(requireCommon$1());
	const constants = __importStar(requireConstants$2());
	const address_error_1 = requireAddressError();
	class Address4 {
	    constructor(address) {
	        this.groups = constants.GROUPS;
	        this.parsedAddress = [];
	        this.parsedSubnet = '';
	        this.subnet = '/32';
	        this.subnetMask = 32;
	        this.v4 = true;
	        this.isCorrect = common.isCorrect(constants.BITS);
	        this.isInSubnet = common.isInSubnet;
	        this.address = address;
	        const subnet = constants.RE_SUBNET_STRING.exec(address);
	        if (subnet) {
	            this.parsedSubnet = subnet[0].replace('/', '');
	            this.subnetMask = parseInt(this.parsedSubnet, 10);
	            this.subnet = `/${this.subnetMask}`;
	            if (this.subnetMask < 0 || this.subnetMask > constants.BITS) {
	                throw new address_error_1.AddressError('Invalid subnet mask.');
	            }
	            address = address.replace(constants.RE_SUBNET_STRING, '');
	        }
	        this.addressMinusSuffix = address;
	        this.parsedAddress = this.parse(address);
	    }
	    static isValid(address) {
	        try {
	            new Address4(address);
	            return true;
	        }
	        catch (e) {
	            return false;
	        }
	    }
	    parse(address) {
	        const groups = address.split('.');
	        if (!address.match(constants.RE_ADDRESS)) {
	            throw new address_error_1.AddressError('Invalid IPv4 address.');
	        }
	        return groups;
	    }
	    correctForm() {
	        return this.parsedAddress.map((part) => parseInt(part, 10)).join('.');
	    }
	    static fromHex(hex) {
	        const padded = hex.replace(/:/g, '').padStart(8, '0');
	        const groups = [];
	        let i;
	        for (i = 0; i < 8; i += 2) {
	            const h = padded.slice(i, i + 2);
	            groups.push(parseInt(h, 16));
	        }
	        return new Address4(groups.join('.'));
	    }
	    static fromInteger(integer) {
	        return Address4.fromHex(integer.toString(16));
	    }
	    static fromArpa(arpaFormAddress) {
	        const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, '');
	        const address = leader.split('.').reverse().join('.');
	        return new Address4(address);
	    }
	    toHex() {
	        return this.parsedAddress.map((part) => common.stringToPaddedHex(part)).join(':');
	    }
	    toArray() {
	        return this.parsedAddress.map((part) => parseInt(part, 10));
	    }
	    toGroup6() {
	        const output = [];
	        let i;
	        for (i = 0; i < constants.GROUPS; i += 2) {
	            output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`);
	        }
	        return output.join(':');
	    }
	    bigInt() {
	        return BigInt(`0x${this.parsedAddress.map((n) => common.stringToPaddedHex(n)).join('')}`);
	    }
	    _startAddress() {
	        return BigInt(`0b${this.mask() + '0'.repeat(constants.BITS - this.subnetMask)}`);
	    }
	    startAddress() {
	        return Address4.fromBigInt(this._startAddress());
	    }
	    startAddressExclusive() {
	        const adjust = BigInt('1');
	        return Address4.fromBigInt(this._startAddress() + adjust);
	    }
	    _endAddress() {
	        return BigInt(`0b${this.mask() + '1'.repeat(constants.BITS - this.subnetMask)}`);
	    }
	    endAddress() {
	        return Address4.fromBigInt(this._endAddress());
	    }
	    endAddressExclusive() {
	        const adjust = BigInt('1');
	        return Address4.fromBigInt(this._endAddress() - adjust);
	    }
	    static fromBigInt(bigInt) {
	        return Address4.fromHex(bigInt.toString(16));
	    }
	    static fromByteArray(bytes) {
	        if (bytes.length !== 4) {
	            throw new address_error_1.AddressError('IPv4 addresses require exactly 4 bytes');
	        }
	        for (let i = 0; i < bytes.length; i++) {
	            if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) {
	                throw new address_error_1.AddressError('All bytes must be integers between 0 and 255');
	            }
	        }
	        return this.fromUnsignedByteArray(bytes);
	    }
	    static fromUnsignedByteArray(bytes) {
	        if (bytes.length !== 4) {
	            throw new address_error_1.AddressError('IPv4 addresses require exactly 4 bytes');
	        }
	        const address = bytes.join('.');
	        return new Address4(address);
	    }
	    mask(mask) {
	        if (mask === undefined) {
	            mask = this.subnetMask;
	        }
	        return this.getBitsBase2(0, mask);
	    }
	    getBitsBase2(start, end) {
	        return this.binaryZeroPad().slice(start, end);
	    }
	    reverseForm(options) {
	        if (!options) {
	            options = {};
	        }
	        const reversed = this.correctForm().split('.').reverse().join('.');
	        if (options.omitSuffix) {
	            return reversed;
	        }
	        return `${reversed}.in-addr.arpa.`;
	    }
	    isMulticast() {
	        return this.isInSubnet(new Address4('224.0.0.0/4'));
	    }
	    binaryZeroPad() {
	        return this.bigInt().toString(2).padStart(constants.BITS, '0');
	    }
	    groupForV6() {
	        const segments = this.parsedAddress;
	        return this.address.replace(constants.RE_ADDRESS, `<span class="hover-group group-v4 group-6">${segments
	            .slice(0, 2)
	            .join('.')}</span>.<span class="hover-group group-v4 group-7">${segments
	            .slice(2, 4)
	            .join('.')}</span>`);
	    }
	}
	ipv4.Address4 = Address4;
	return ipv4;
}

var ipv6 = {};

var constants$1 = {};

var hasRequiredConstants$1;

function requireConstants$1 () {
	if (hasRequiredConstants$1) return constants$1;
	hasRequiredConstants$1 = 1;
	Object.defineProperty(constants$1, "__esModule", { value: true });
	constants$1.RE_URL_WITH_PORT = constants$1.RE_URL = constants$1.RE_ZONE_STRING = constants$1.RE_SUBNET_STRING = constants$1.RE_BAD_ADDRESS = constants$1.RE_BAD_CHARACTERS = constants$1.TYPES = constants$1.SCOPES = constants$1.GROUPS = constants$1.BITS = void 0;
	constants$1.BITS = 128;
	constants$1.GROUPS = 8;
	constants$1.SCOPES = {
	    0: 'Reserved',
	    1: 'Interface local',
	    2: 'Link local',
	    4: 'Admin local',
	    5: 'Site local',
	    8: 'Organization local',
	    14: 'Global',
	    15: 'Reserved',
	};
	constants$1.TYPES = {
	    'ff01::1/128': 'Multicast (All nodes on this interface)',
	    'ff01::2/128': 'Multicast (All routers on this interface)',
	    'ff02::1/128': 'Multicast (All nodes on this link)',
	    'ff02::2/128': 'Multicast (All routers on this link)',
	    'ff05::2/128': 'Multicast (All routers in this site)',
	    'ff02::5/128': 'Multicast (OSPFv3 AllSPF routers)',
	    'ff02::6/128': 'Multicast (OSPFv3 AllDR routers)',
	    'ff02::9/128': 'Multicast (RIP routers)',
	    'ff02::a/128': 'Multicast (EIGRP routers)',
	    'ff02::d/128': 'Multicast (PIM routers)',
	    'ff02::16/128': 'Multicast (MLDv2 reports)',
	    'ff01::fb/128': 'Multicast (mDNSv6)',
	    'ff02::fb/128': 'Multicast (mDNSv6)',
	    'ff05::fb/128': 'Multicast (mDNSv6)',
	    'ff02::1:2/128': 'Multicast (All DHCP servers and relay agents on this link)',
	    'ff05::1:2/128': 'Multicast (All DHCP servers and relay agents in this site)',
	    'ff02::1:3/128': 'Multicast (All DHCP servers on this link)',
	    'ff05::1:3/128': 'Multicast (All DHCP servers in this site)',
	    '::/128': 'Unspecified',
	    '::1/128': 'Loopback',
	    'ff00::/8': 'Multicast',
	    'fe80::/10': 'Link-local unicast',
	};
	constants$1.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi;
	constants$1.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;
	constants$1.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/;
	constants$1.RE_ZONE_STRING = /%.*$/;
	constants$1.RE_URL = /^\[{0,1}([0-9a-f:]+)\]{0,1}/;
	constants$1.RE_URL_WITH_PORT = /\[([0-9a-f:]+)\]:([0-9]{1,5})/;
	return constants$1;
}

var helpers$2 = {};

var hasRequiredHelpers$1;

function requireHelpers$1 () {
	if (hasRequiredHelpers$1) return helpers$2;
	hasRequiredHelpers$1 = 1;
	Object.defineProperty(helpers$2, "__esModule", { value: true });
	helpers$2.spanAllZeroes = spanAllZeroes;
	helpers$2.spanAll = spanAll;
	helpers$2.spanLeadingZeroes = spanLeadingZeroes;
	helpers$2.simpleGroup = simpleGroup;
	function spanAllZeroes(s) {
	    return s.replace(/(0+)/g, '<span class="zero">$1</span>');
	}
	function spanAll(s, offset = 0) {
	    const letters = s.split('');
	    return letters
	        .map((n, i) => `<span class="digit value-${n} position-${i + offset}">${spanAllZeroes(n)}</span>`)
	        .join('');
	}
	function spanLeadingZeroesSimple(group) {
	    return group.replace(/^(0+)/, '<span class="zero">$1</span>');
	}
	function spanLeadingZeroes(address) {
	    const groups = address.split(':');
	    return groups.map((g) => spanLeadingZeroesSimple(g)).join(':');
	}
	function simpleGroup(addressString, offset = 0) {
	    const groups = addressString.split(':');
	    return groups.map((g, i) => {
	        if (/group-v4/.test(g)) {
	            return g;
	        }
	        return `<span class="hover-group group-${i + offset}">${spanLeadingZeroesSimple(g)}</span>`;
	    });
	}
	return helpers$2;
}

var regularExpressions = {};

var hasRequiredRegularExpressions;

function requireRegularExpressions () {
	if (hasRequiredRegularExpressions) return regularExpressions;
	hasRequiredRegularExpressions = 1;
	var __createBinding = (regularExpressions && regularExpressions.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (regularExpressions && regularExpressions.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (regularExpressions && regularExpressions.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	Object.defineProperty(regularExpressions, "__esModule", { value: true });
	regularExpressions.ADDRESS_BOUNDARY = void 0;
	regularExpressions.groupPossibilities = groupPossibilities;
	regularExpressions.padGroup = padGroup;
	regularExpressions.simpleRegularExpression = simpleRegularExpression;
	regularExpressions.possibleElisions = possibleElisions;
	const v6 = __importStar(requireConstants$1());
	function groupPossibilities(possibilities) {
	    return `(${possibilities.join('|')})`;
	}
	function padGroup(group) {
	    if (group.length < 4) {
	        return `0{0,${4 - group.length}}${group}`;
	    }
	    return group;
	}
	regularExpressions.ADDRESS_BOUNDARY = '[^A-Fa-f0-9:]';
	function simpleRegularExpression(groups) {
	    const zeroIndexes = [];
	    groups.forEach((group, i) => {
	        const groupInteger = parseInt(group, 16);
	        if (groupInteger === 0) {
	            zeroIndexes.push(i);
	        }
	    });
	    const possibilities = zeroIndexes.map((zeroIndex) => groups
	        .map((group, i) => {
	        if (i === zeroIndex) {
	            const elision = i === 0 || i === v6.GROUPS - 1 ? ':' : '';
	            return groupPossibilities([padGroup(group), elision]);
	        }
	        return padGroup(group);
	    })
	        .join(':'));
	    possibilities.push(groups.map(padGroup).join(':'));
	    return groupPossibilities(possibilities);
	}
	function possibleElisions(elidedGroups, moreLeft, moreRight) {
	    const left = moreLeft ? '' : ':';
	    const right = moreRight ? '' : ':';
	    const possibilities = [];
	    if (!moreLeft && !moreRight) {
	        possibilities.push('::');
	    }
	    if (moreLeft && moreRight) {
	        possibilities.push('');
	    }
	    if ((moreRight && !moreLeft) || (!moreRight && moreLeft)) {
	        possibilities.push(':');
	    }
	    possibilities.push(`${left}(:0{1,4}){1,${elidedGroups - 1}}`);
	    possibilities.push(`(0{1,4}:){1,${elidedGroups - 1}}${right}`);
	    possibilities.push(`(0{1,4}:){${elidedGroups - 1}}0{1,4}`);
	    for (let groups = 1; groups < elidedGroups - 1; groups++) {
	        for (let position = 1; position < elidedGroups - groups; position++) {
	            possibilities.push(`(0{1,4}:){${position}}:(0{1,4}:){${elidedGroups - position - groups - 1}}0{1,4}`);
	        }
	    }
	    return groupPossibilities(possibilities);
	}
	return regularExpressions;
}

var hasRequiredIpv6;

function requireIpv6 () {
	if (hasRequiredIpv6) return ipv6;
	hasRequiredIpv6 = 1;
	var __createBinding = (ipv6 && ipv6.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (ipv6 && ipv6.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (ipv6 && ipv6.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	Object.defineProperty(ipv6, "__esModule", { value: true });
	ipv6.Address6 = void 0;
	const common = __importStar(requireCommon$1());
	const constants4 = __importStar(requireConstants$2());
	const constants6 = __importStar(requireConstants$1());
	const helpers = __importStar(requireHelpers$1());
	const ipv4_1 = requireIpv4();
	const regular_expressions_1 = requireRegularExpressions();
	const address_error_1 = requireAddressError();
	const common_1 = requireCommon$1();
	function assert(condition) {
	    if (!condition) {
	        throw new Error('Assertion failed.');
	    }
	}
	function addCommas(number) {
	    const r = /(\d+)(\d{3})/;
	    while (r.test(number)) {
	        number = number.replace(r, '$1,$2');
	    }
	    return number;
	}
	function spanLeadingZeroes4(n) {
	    n = n.replace(/^(0{1,})([1-9]+)$/, '<span class="parse-error">$1</span>$2');
	    n = n.replace(/^(0{1,})(0)$/, '<span class="parse-error">$1</span>$2');
	    return n;
	}
	function compact(address, slice) {
	    const s1 = [];
	    const s2 = [];
	    let i;
	    for (i = 0; i < address.length; i++) {
	        if (i < slice[0]) {
	            s1.push(address[i]);
	        }
	        else if (i > slice[1]) {
	            s2.push(address[i]);
	        }
	    }
	    return s1.concat(['compact']).concat(s2);
	}
	function paddedHex(octet) {
	    return parseInt(octet, 16).toString(16).padStart(4, '0');
	}
	function unsignByte(b) {
	    return b & 0xff;
	}
	class Address6 {
	    constructor(address, optionalGroups) {
	        this.addressMinusSuffix = '';
	        this.parsedSubnet = '';
	        this.subnet = '/128';
	        this.subnetMask = 128;
	        this.v4 = false;
	        this.zone = '';
	        this.isInSubnet = common.isInSubnet;
	        this.isCorrect = common.isCorrect(constants6.BITS);
	        if (optionalGroups === undefined) {
	            this.groups = constants6.GROUPS;
	        }
	        else {
	            this.groups = optionalGroups;
	        }
	        this.address = address;
	        const subnet = constants6.RE_SUBNET_STRING.exec(address);
	        if (subnet) {
	            this.parsedSubnet = subnet[0].replace('/', '');
	            this.subnetMask = parseInt(this.parsedSubnet, 10);
	            this.subnet = `/${this.subnetMask}`;
	            if (Number.isNaN(this.subnetMask) ||
	                this.subnetMask < 0 ||
	                this.subnetMask > constants6.BITS) {
	                throw new address_error_1.AddressError('Invalid subnet mask.');
	            }
	            address = address.replace(constants6.RE_SUBNET_STRING, '');
	        }
	        else if (/\//.test(address)) {
	            throw new address_error_1.AddressError('Invalid subnet mask.');
	        }
	        const zone = constants6.RE_ZONE_STRING.exec(address);
	        if (zone) {
	            this.zone = zone[0];
	            address = address.replace(constants6.RE_ZONE_STRING, '');
	        }
	        this.addressMinusSuffix = address;
	        this.parsedAddress = this.parse(this.addressMinusSuffix);
	    }
	    static isValid(address) {
	        try {
	            new Address6(address);
	            return true;
	        }
	        catch (e) {
	            return false;
	        }
	    }
	    static fromBigInt(bigInt) {
	        const hex = bigInt.toString(16).padStart(32, '0');
	        const groups = [];
	        let i;
	        for (i = 0; i < constants6.GROUPS; i++) {
	            groups.push(hex.slice(i * 4, (i + 1) * 4));
	        }
	        return new Address6(groups.join(':'));
	    }
	    static fromURL(url) {
	        let host;
	        let port = null;
	        let result;
	        if (url.indexOf('[') !== -1 && url.indexOf(']:') !== -1) {
	            result = constants6.RE_URL_WITH_PORT.exec(url);
	            if (result === null) {
	                return {
	                    error: 'failed to parse address with port',
	                    address: null,
	                    port: null,
	                };
	            }
	            host = result[1];
	            port = result[2];
	        }
	        else if (url.indexOf('/') !== -1) {
	            url = url.replace(/^[a-z0-9]+:\/\//, '');
	            result = constants6.RE_URL.exec(url);
	            if (result === null) {
	                return {
	                    error: 'failed to parse address from URL',
	                    address: null,
	                    port: null,
	                };
	            }
	            host = result[1];
	        }
	        else {
	            host = url;
	        }
	        if (port) {
	            port = parseInt(port, 10);
	            if (port < 0 || port > 65536) {
	                port = null;
	            }
	        }
	        else {
	            port = null;
	        }
	        return {
	            address: new Address6(host),
	            port,
	        };
	    }
	    static fromAddress4(address) {
	        const address4 = new ipv4_1.Address4(address);
	        const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask);
	        return new Address6(`::ffff:${address4.correctForm()}/${mask6}`);
	    }
	    static fromArpa(arpaFormAddress) {
	        let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, '');
	        const semicolonAmount = 7;
	        if (address.length !== 63) {
	            throw new address_error_1.AddressError("Invalid 'ip6.arpa' form.");
	        }
	        const parts = address.split('.').reverse();
	        for (let i = semicolonAmount; i > 0; i--) {
	            const insertIndex = i * 4;
	            parts.splice(insertIndex, 0, ':');
	        }
	        address = parts.join('');
	        return new Address6(address);
	    }
	    microsoftTranscription() {
	        return `${this.correctForm().replace(/:/g, '-')}.ipv6-literal.net`;
	    }
	    mask(mask = this.subnetMask) {
	        return this.getBitsBase2(0, mask);
	    }
	    possibleSubnets(subnetSize = 128) {
	        const availableBits = constants6.BITS - this.subnetMask;
	        const subnetBits = Math.abs(subnetSize - constants6.BITS);
	        const subnetPowers = availableBits - subnetBits;
	        if (subnetPowers < 0) {
	            return '0';
	        }
	        return addCommas((BigInt('2') ** BigInt(subnetPowers)).toString(10));
	    }
	    _startAddress() {
	        return BigInt(`0b${this.mask() + '0'.repeat(constants6.BITS - this.subnetMask)}`);
	    }
	    startAddress() {
	        return Address6.fromBigInt(this._startAddress());
	    }
	    startAddressExclusive() {
	        const adjust = BigInt('1');
	        return Address6.fromBigInt(this._startAddress() + adjust);
	    }
	    _endAddress() {
	        return BigInt(`0b${this.mask() + '1'.repeat(constants6.BITS - this.subnetMask)}`);
	    }
	    endAddress() {
	        return Address6.fromBigInt(this._endAddress());
	    }
	    endAddressExclusive() {
	        const adjust = BigInt('1');
	        return Address6.fromBigInt(this._endAddress() - adjust);
	    }
	    getScope() {
	        let scope = constants6.SCOPES[parseInt(this.getBits(12, 16).toString(10), 10)];
	        if (this.getType() === 'Global unicast' && scope !== 'Link local') {
	            scope = 'Global';
	        }
	        return scope || 'Unknown';
	    }
	    getType() {
	        for (const subnet of Object.keys(constants6.TYPES)) {
	            if (this.isInSubnet(new Address6(subnet))) {
	                return constants6.TYPES[subnet];
	            }
	        }
	        return 'Global unicast';
	    }
	    getBits(start, end) {
	        return BigInt(`0b${this.getBitsBase2(start, end)}`);
	    }
	    getBitsBase2(start, end) {
	        return this.binaryZeroPad().slice(start, end);
	    }
	    getBitsBase16(start, end) {
	        const length = end - start;
	        if (length % 4 !== 0) {
	            throw new Error('Length of bits to retrieve must be divisible by four');
	        }
	        return this.getBits(start, end)
	            .toString(16)
	            .padStart(length / 4, '0');
	    }
	    getBitsPastSubnet() {
	        return this.getBitsBase2(this.subnetMask, constants6.BITS);
	    }
	    reverseForm(options) {
	        if (!options) {
	            options = {};
	        }
	        const characters = Math.floor(this.subnetMask / 4);
	        const reversed = this.canonicalForm()
	            .replace(/:/g, '')
	            .split('')
	            .slice(0, characters)
	            .reverse()
	            .join('.');
	        if (characters > 0) {
	            if (options.omitSuffix) {
	                return reversed;
	            }
	            return `${reversed}.ip6.arpa.`;
	        }
	        if (options.omitSuffix) {
	            return '';
	        }
	        return 'ip6.arpa.';
	    }
	    correctForm() {
	        let i;
	        let groups = [];
	        let zeroCounter = 0;
	        const zeroes = [];
	        for (i = 0; i < this.parsedAddress.length; i++) {
	            const value = parseInt(this.parsedAddress[i], 16);
	            if (value === 0) {
	                zeroCounter++;
	            }
	            if (value !== 0 && zeroCounter > 0) {
	                if (zeroCounter > 1) {
	                    zeroes.push([i - zeroCounter, i - 1]);
	                }
	                zeroCounter = 0;
	            }
	        }
	        if (zeroCounter > 1) {
	            zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]);
	        }
	        const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1);
	        if (zeroes.length > 0) {
	            const index = zeroLengths.indexOf(Math.max(...zeroLengths));
	            groups = compact(this.parsedAddress, zeroes[index]);
	        }
	        else {
	            groups = this.parsedAddress;
	        }
	        for (i = 0; i < groups.length; i++) {
	            if (groups[i] !== 'compact') {
	                groups[i] = parseInt(groups[i], 16).toString(16);
	            }
	        }
	        let correct = groups.join(':');
	        correct = correct.replace(/^compact$/, '::');
	        correct = correct.replace(/(^compact)|(compact$)/, ':');
	        correct = correct.replace(/compact/, '');
	        return correct;
	    }
	    binaryZeroPad() {
	        return this.bigInt().toString(2).padStart(constants6.BITS, '0');
	    }
	    parse4in6(address) {
	        const groups = address.split(':');
	        const lastGroup = groups.slice(-1)[0];
	        const address4 = lastGroup.match(constants4.RE_ADDRESS);
	        if (address4) {
	            this.parsedAddress4 = address4[0];
	            this.address4 = new ipv4_1.Address4(this.parsedAddress4);
	            for (let i = 0; i < this.address4.groups; i++) {
	                if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) {
	                    throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join('.')));
	                }
	            }
	            this.v4 = true;
	            groups[groups.length - 1] = this.address4.toGroup6();
	            address = groups.join(':');
	        }
	        return address;
	    }
	    parse(address) {
	        address = this.parse4in6(address);
	        const badCharacters = address.match(constants6.RE_BAD_CHARACTERS);
	        if (badCharacters) {
	            throw new address_error_1.AddressError(`Bad character${badCharacters.length > 1 ? 's' : ''} detected in address: ${badCharacters.join('')}`, address.replace(constants6.RE_BAD_CHARACTERS, '<span class="parse-error">$1</span>'));
	        }
	        const badAddress = address.match(constants6.RE_BAD_ADDRESS);
	        if (badAddress) {
	            throw new address_error_1.AddressError(`Address failed regex: ${badAddress.join('')}`, address.replace(constants6.RE_BAD_ADDRESS, '<span class="parse-error">$1</span>'));
	        }
	        let groups = [];
	        const halves = address.split('::');
	        if (halves.length === 2) {
	            let first = halves[0].split(':');
	            let last = halves[1].split(':');
	            if (first.length === 1 && first[0] === '') {
	                first = [];
	            }
	            if (last.length === 1 && last[0] === '') {
	                last = [];
	            }
	            const remaining = this.groups - (first.length + last.length);
	            if (!remaining) {
	                throw new address_error_1.AddressError('Error parsing groups');
	            }
	            this.elidedGroups = remaining;
	            this.elisionBegin = first.length;
	            this.elisionEnd = first.length + this.elidedGroups;
	            groups = groups.concat(first);
	            for (let i = 0; i < remaining; i++) {
	                groups.push('0');
	            }
	            groups = groups.concat(last);
	        }
	        else if (halves.length === 1) {
	            groups = address.split(':');
	            this.elidedGroups = 0;
	        }
	        else {
	            throw new address_error_1.AddressError('Too many :: groups found');
	        }
	        groups = groups.map((group) => parseInt(group, 16).toString(16));
	        if (groups.length !== this.groups) {
	            throw new address_error_1.AddressError('Incorrect number of groups found');
	        }
	        return groups;
	    }
	    canonicalForm() {
	        return this.parsedAddress.map(paddedHex).join(':');
	    }
	    decimal() {
	        return this.parsedAddress.map((n) => parseInt(n, 16).toString(10).padStart(5, '0')).join(':');
	    }
	    bigInt() {
	        return BigInt(`0x${this.parsedAddress.map(paddedHex).join('')}`);
	    }
	    to4() {
	        const binary = this.binaryZeroPad().split('');
	        return ipv4_1.Address4.fromHex(BigInt(`0b${binary.slice(96, 128).join('')}`).toString(16));
	    }
	    to4in6() {
	        const address4 = this.to4();
	        const address6 = new Address6(this.parsedAddress.slice(0, 6).join(':'), 6);
	        const correct = address6.correctForm();
	        let infix = '';
	        if (!/:$/.test(correct)) {
	            infix = ':';
	        }
	        return correct + infix + address4.address;
	    }
	    inspectTeredo() {
	        const prefix = this.getBitsBase16(0, 32);
	        const bitsForUdpPort = this.getBits(80, 96);
	        const udpPort = (bitsForUdpPort ^ BigInt('0xffff')).toString();
	        const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64));
	        const bitsForClient4 = this.getBits(96, 128);
	        const client4 = ipv4_1.Address4.fromHex((bitsForClient4 ^ BigInt('0xffffffff')).toString(16));
	        const flagsBase2 = this.getBitsBase2(64, 80);
	        const coneNat = (0, common_1.testBit)(flagsBase2, 15);
	        const reserved = (0, common_1.testBit)(flagsBase2, 14);
	        const groupIndividual = (0, common_1.testBit)(flagsBase2, 8);
	        const universalLocal = (0, common_1.testBit)(flagsBase2, 9);
	        const nonce = BigInt(`0b${flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16)}`).toString(10);
	        return {
	            prefix: `${prefix.slice(0, 4)}:${prefix.slice(4, 8)}`,
	            server4: server4.address,
	            client4: client4.address,
	            flags: flagsBase2,
	            coneNat,
	            microsoft: {
	                reserved,
	                universalLocal,
	                groupIndividual,
	                nonce,
	            },
	            udpPort,
	        };
	    }
	    inspect6to4() {
	        const prefix = this.getBitsBase16(0, 16);
	        const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48));
	        return {
	            prefix: prefix.slice(0, 4),
	            gateway: gateway.address,
	        };
	    }
	    to6to4() {
	        if (!this.is4()) {
	            return null;
	        }
	        const addr6to4 = [
	            '2002',
	            this.getBitsBase16(96, 112),
	            this.getBitsBase16(112, 128),
	            '',
	            '/16',
	        ].join(':');
	        return new Address6(addr6to4);
	    }
	    toByteArray() {
	        const valueWithoutPadding = this.bigInt().toString(16);
	        const leadingPad = '0'.repeat(valueWithoutPadding.length % 2);
	        const value = `${leadingPad}${valueWithoutPadding}`;
	        const bytes = [];
	        for (let i = 0, length = value.length; i < length; i += 2) {
	            bytes.push(parseInt(value.substring(i, i + 2), 16));
	        }
	        return bytes;
	    }
	    toUnsignedByteArray() {
	        return this.toByteArray().map(unsignByte);
	    }
	    static fromByteArray(bytes) {
	        return this.fromUnsignedByteArray(bytes.map(unsignByte));
	    }
	    static fromUnsignedByteArray(bytes) {
	        const BYTE_MAX = BigInt('256');
	        let result = BigInt('0');
	        let multiplier = BigInt('1');
	        for (let i = bytes.length - 1; i >= 0; i--) {
	            result += multiplier * BigInt(bytes[i].toString(10));
	            multiplier *= BYTE_MAX;
	        }
	        return Address6.fromBigInt(result);
	    }
	    isCanonical() {
	        return this.addressMinusSuffix === this.canonicalForm();
	    }
	    isLinkLocal() {
	        if (this.getBitsBase2(0, 64) ===
	            '1111111010000000000000000000000000000000000000000000000000000000') {
	            return true;
	        }
	        return false;
	    }
	    isMulticast() {
	        return this.getType() === 'Multicast';
	    }
	    is4() {
	        return this.v4;
	    }
	    isTeredo() {
	        return this.isInSubnet(new Address6('2001::/32'));
	    }
	    is6to4() {
	        return this.isInSubnet(new Address6('2002::/16'));
	    }
	    isLoopback() {
	        return this.getType() === 'Loopback';
	    }
	    href(optionalPort) {
	        if (optionalPort === undefined) {
	            optionalPort = '';
	        }
	        else {
	            optionalPort = `:${optionalPort}`;
	        }
	        return `http://[${this.correctForm()}]${optionalPort}/`;
	    }
	    link(options) {
	        if (!options) {
	            options = {};
	        }
	        if (options.className === undefined) {
	            options.className = '';
	        }
	        if (options.prefix === undefined) {
	            options.prefix = '/#address=';
	        }
	        if (options.v4 === undefined) {
	            options.v4 = false;
	        }
	        let formFunction = this.correctForm;
	        if (options.v4) {
	            formFunction = this.to4in6;
	        }
	        const form = formFunction.call(this);
	        if (options.className) {
	            return `<a href="${options.prefix}${form}" class="${options.className}">${form}</a>`;
	        }
	        return `<a href="${options.prefix}${form}">${form}</a>`;
	    }
	    group() {
	        if (this.elidedGroups === 0) {
	            return helpers.simpleGroup(this.address).join(':');
	        }
	        assert(typeof this.elidedGroups === 'number');
	        assert(typeof this.elisionBegin === 'number');
	        const output = [];
	        const [left, right] = this.address.split('::');
	        if (left.length) {
	            output.push(...helpers.simpleGroup(left));
	        }
	        else {
	            output.push('');
	        }
	        const classes = ['hover-group'];
	        for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) {
	            classes.push(`group-${i}`);
	        }
	        output.push(`<span class="${classes.join(' ')}"></span>`);
	        if (right.length) {
	            output.push(...helpers.simpleGroup(right, this.elisionEnd));
	        }
	        else {
	            output.push('');
	        }
	        if (this.is4()) {
	            assert(this.address4 instanceof ipv4_1.Address4);
	            output.pop();
	            output.push(this.address4.groupForV6());
	        }
	        return output.join(':');
	    }
	    regularExpressionString(substringSearch = false) {
	        let output = [];
	        const address6 = new Address6(this.correctForm());
	        if (address6.elidedGroups === 0) {
	            output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress));
	        }
	        else if (address6.elidedGroups === constants6.GROUPS) {
	            output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS));
	        }
	        else {
	            const halves = address6.address.split('::');
	            if (halves[0].length) {
	                output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(':')));
	            }
	            assert(typeof address6.elidedGroups === 'number');
	            output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0));
	            if (halves[1].length) {
	                output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(':')));
	            }
	            output = [output.join(':')];
	        }
	        if (!substringSearch) {
	            output = [
	                '(?=^|',
	                regular_expressions_1.ADDRESS_BOUNDARY,
	                '|[^\\w\\:])(',
	                ...output,
	                ')(?=[^\\w\\:]|',
	                regular_expressions_1.ADDRESS_BOUNDARY,
	                '|$)',
	            ];
	        }
	        return output.join('');
	    }
	    regularExpression(substringSearch = false) {
	        return new RegExp(this.regularExpressionString(substringSearch), 'i');
	    }
	}
	ipv6.Address6 = Address6;
	return ipv6;
}

var hasRequiredIpAddress;

function requireIpAddress () {
	if (hasRequiredIpAddress) return ipAddress;
	hasRequiredIpAddress = 1;
	(function (exports$1) {
		var __createBinding = (ipAddress && ipAddress.__createBinding) || (Object.create ? (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    var desc = Object.getOwnPropertyDescriptor(m, k);
		    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
		      desc = { enumerable: true, get: function() { return m[k]; } };
		    }
		    Object.defineProperty(o, k2, desc);
		}) : (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    o[k2] = m[k];
		}));
		var __setModuleDefault = (ipAddress && ipAddress.__setModuleDefault) || (Object.create ? (function(o, v) {
		    Object.defineProperty(o, "default", { enumerable: true, value: v });
		}) : function(o, v) {
		    o["default"] = v;
		});
		var __importStar = (ipAddress && ipAddress.__importStar) || function (mod) {
		    if (mod && mod.__esModule) return mod;
		    var result = {};
		    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
		    __setModuleDefault(result, mod);
		    return result;
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.v6 = exports$1.AddressError = exports$1.Address6 = exports$1.Address4 = void 0;
		var ipv4_1 = requireIpv4();
		Object.defineProperty(exports$1, "Address4", { enumerable: true, get: function () { return ipv4_1.Address4; } });
		var ipv6_1 = requireIpv6();
		Object.defineProperty(exports$1, "Address6", { enumerable: true, get: function () { return ipv6_1.Address6; } });
		var address_error_1 = requireAddressError();
		Object.defineProperty(exports$1, "AddressError", { enumerable: true, get: function () { return address_error_1.AddressError; } });
		const helpers = __importStar(requireHelpers$1());
		exports$1.v6 = { helpers }; 
	} (ipAddress));
	return ipAddress;
}

var hasRequiredHelpers;

function requireHelpers () {
	if (hasRequiredHelpers) return helpers$3;
	hasRequiredHelpers = 1;
	Object.defineProperty(helpers$3, "__esModule", { value: true });
	helpers$3.ipToBuffer = helpers$3.int32ToIpv4 = helpers$3.ipv4ToInt32 = helpers$3.validateSocksClientChainOptions = helpers$3.validateSocksClientOptions = void 0;
	const util_1 = requireUtil$2();
	const constants_1 = requireConstants$3();
	const stream = require$$1$3;
	const ip_address_1 = requireIpAddress();
	const net = require$$0$7;
	function validateSocksClientOptions(options, acceptedCommands = ['connect', 'bind', 'associate']) {
	    if (!constants_1.SocksCommand[options.command]) {
	        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand, options);
	    }
	    if (acceptedCommands.indexOf(options.command) === -1) {
	        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation, options);
	    }
	    if (!isValidSocksRemoteHost(options.destination)) {
	        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options);
	    }
	    if (!isValidSocksProxy(options.proxy)) {
	        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options);
	    }
	    validateCustomProxyAuth(options.proxy, options);
	    if (options.timeout && !isValidTimeoutValue(options.timeout)) {
	        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options);
	    }
	    if (options.existing_socket &&
	        !(options.existing_socket instanceof stream.Duplex)) {
	        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket, options);
	    }
	}
	helpers$3.validateSocksClientOptions = validateSocksClientOptions;
	function validateSocksClientChainOptions(options) {
	    if (options.command !== 'connect') {
	        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain, options);
	    }
	    if (!isValidSocksRemoteHost(options.destination)) {
	        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options);
	    }
	    if (!(options.proxies &&
	        Array.isArray(options.proxies) &&
	        options.proxies.length >= 2)) {
	        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options);
	    }
	    options.proxies.forEach((proxy) => {
	        if (!isValidSocksProxy(proxy)) {
	            throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options);
	        }
	        validateCustomProxyAuth(proxy, options);
	    });
	    if (options.timeout && !isValidTimeoutValue(options.timeout)) {
	        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options);
	    }
	}
	helpers$3.validateSocksClientChainOptions = validateSocksClientChainOptions;
	function validateCustomProxyAuth(proxy, options) {
	    if (proxy.custom_auth_method !== undefined) {
	        if (proxy.custom_auth_method < constants_1.SOCKS5_CUSTOM_AUTH_START ||
	            proxy.custom_auth_method > constants_1.SOCKS5_CUSTOM_AUTH_END) {
	            throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange, options);
	        }
	        if (proxy.custom_auth_request_handler === undefined ||
	            typeof proxy.custom_auth_request_handler !== 'function') {
	            throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
	        }
	        if (proxy.custom_auth_response_size === undefined) {
	            throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
	        }
	        if (proxy.custom_auth_response_handler === undefined ||
	            typeof proxy.custom_auth_response_handler !== 'function') {
	            throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
	        }
	    }
	}
	function isValidSocksRemoteHost(remoteHost) {
	    return (remoteHost &&
	        typeof remoteHost.host === 'string' &&
	        Buffer.byteLength(remoteHost.host) < 256 &&
	        typeof remoteHost.port === 'number' &&
	        remoteHost.port >= 0 &&
	        remoteHost.port <= 65535);
	}
	function isValidSocksProxy(proxy) {
	    return (proxy &&
	        (typeof proxy.host === 'string' || typeof proxy.ipaddress === 'string') &&
	        typeof proxy.port === 'number' &&
	        proxy.port >= 0 &&
	        proxy.port <= 65535 &&
	        (proxy.type === 4 || proxy.type === 5));
	}
	function isValidTimeoutValue(value) {
	    return typeof value === 'number' && value > 0;
	}
	function ipv4ToInt32(ip) {
	    const address = new ip_address_1.Address4(ip);
	    return address.toArray().reduce((acc, part) => (acc << 8) + part, 0) >>> 0;
	}
	helpers$3.ipv4ToInt32 = ipv4ToInt32;
	function int32ToIpv4(int32) {
	    const octet1 = (int32 >>> 24) & 0xff;
	    const octet2 = (int32 >>> 16) & 0xff;
	    const octet3 = (int32 >>> 8) & 0xff;
	    const octet4 = int32 & 0xff;
	    return [octet1, octet2, octet3, octet4].join('.');
	}
	helpers$3.int32ToIpv4 = int32ToIpv4;
	function ipToBuffer(ip) {
	    if (net.isIPv4(ip)) {
	        const address = new ip_address_1.Address4(ip);
	        return Buffer.from(address.toArray());
	    }
	    else if (net.isIPv6(ip)) {
	        const address = new ip_address_1.Address6(ip);
	        return Buffer.from(address
	            .canonicalForm()
	            .split(':')
	            .map((segment) => segment.padStart(4, '0'))
	            .join(''), 'hex');
	    }
	    else {
	        throw new Error('Invalid IP address format');
	    }
	}
	helpers$3.ipToBuffer = ipToBuffer;
	return helpers$3;
}

var receivebuffer = {};

var hasRequiredReceivebuffer;

function requireReceivebuffer () {
	if (hasRequiredReceivebuffer) return receivebuffer;
	hasRequiredReceivebuffer = 1;
	Object.defineProperty(receivebuffer, "__esModule", { value: true });
	receivebuffer.ReceiveBuffer = void 0;
	class ReceiveBuffer {
	    constructor(size = 4096) {
	        this.buffer = Buffer.allocUnsafe(size);
	        this.offset = 0;
	        this.originalSize = size;
	    }
	    get length() {
	        return this.offset;
	    }
	    append(data) {
	        if (!Buffer.isBuffer(data)) {
	            throw new Error('Attempted to append a non-buffer instance to ReceiveBuffer.');
	        }
	        if (this.offset + data.length >= this.buffer.length) {
	            const tmp = this.buffer;
	            this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data.length));
	            tmp.copy(this.buffer);
	        }
	        data.copy(this.buffer, this.offset);
	        return (this.offset += data.length);
	    }
	    peek(length) {
	        if (length > this.offset) {
	            throw new Error('Attempted to read beyond the bounds of the managed internal data.');
	        }
	        return this.buffer.slice(0, length);
	    }
	    get(length) {
	        if (length > this.offset) {
	            throw new Error('Attempted to read beyond the bounds of the managed internal data.');
	        }
	        const value = Buffer.allocUnsafe(length);
	        this.buffer.slice(0, length).copy(value);
	        this.buffer.copyWithin(0, length, length + this.offset - length);
	        this.offset -= length;
	        return value;
	    }
	}
	receivebuffer.ReceiveBuffer = ReceiveBuffer;
	return receivebuffer;
}

var hasRequiredSocksclient;

function requireSocksclient () {
	if (hasRequiredSocksclient) return socksclient;
	hasRequiredSocksclient = 1;
	(function (exports$1) {
		var __awaiter = (socksclient && socksclient.__awaiter) || function (thisArg, _arguments, P, generator) {
		    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
		    return new (P || (P = Promise))(function (resolve, reject) {
		        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
		        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
		        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
		        step((generator = generator.apply(thisArg, _arguments || [])).next());
		    });
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.SocksClientError = exports$1.SocksClient = void 0;
		const events_1 = require$$0$8;
		const net = require$$0$7;
		const smart_buffer_1 = requireSmartbuffer();
		const constants_1 = requireConstants$3();
		const helpers_1 = requireHelpers();
		const receivebuffer_1 = requireReceivebuffer();
		const util_1 = requireUtil$2();
		Object.defineProperty(exports$1, "SocksClientError", { enumerable: true, get: function () { return util_1.SocksClientError; } });
		const ip_address_1 = requireIpAddress();
		class SocksClient extends events_1.EventEmitter {
		    constructor(options) {
		        super();
		        this.options = Object.assign({}, options);
		        (0, helpers_1.validateSocksClientOptions)(options);
		        this.setState(constants_1.SocksClientState.Created);
		    }
		    static createConnection(options, callback) {
		        return new Promise((resolve, reject) => {
		            try {
		                (0, helpers_1.validateSocksClientOptions)(options, ['connect']);
		            }
		            catch (err) {
		                if (typeof callback === 'function') {
		                    callback(err);
		                    return resolve(err);
		                }
		                else {
		                    return reject(err);
		                }
		            }
		            const client = new SocksClient(options);
		            client.connect(options.existing_socket);
		            client.once('established', (info) => {
		                client.removeAllListeners();
		                if (typeof callback === 'function') {
		                    callback(null, info);
		                    resolve(info);
		                }
		                else {
		                    resolve(info);
		                }
		            });
		            client.once('error', (err) => {
		                client.removeAllListeners();
		                if (typeof callback === 'function') {
		                    callback(err);
		                    resolve(err);
		                }
		                else {
		                    reject(err);
		                }
		            });
		        });
		    }
		    static createConnectionChain(options, callback) {
		        return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
		            try {
		                (0, helpers_1.validateSocksClientChainOptions)(options);
		            }
		            catch (err) {
		                if (typeof callback === 'function') {
		                    callback(err);
		                    return resolve(err);
		                }
		                else {
		                    return reject(err);
		                }
		            }
		            if (options.randomizeChain) {
		                (0, util_1.shuffleArray)(options.proxies);
		            }
		            try {
		                let sock;
		                for (let i = 0; i < options.proxies.length; i++) {
		                    const nextProxy = options.proxies[i];
		                    const nextDestination = i === options.proxies.length - 1
		                        ? options.destination
		                        : {
		                            host: options.proxies[i + 1].host ||
		                                options.proxies[i + 1].ipaddress,
		                            port: options.proxies[i + 1].port,
		                        };
		                    const result = yield SocksClient.createConnection({
		                        command: 'connect',
		                        proxy: nextProxy,
		                        destination: nextDestination,
		                        existing_socket: sock,
		                    });
		                    sock = sock || result.socket;
		                }
		                if (typeof callback === 'function') {
		                    callback(null, { socket: sock });
		                    resolve({ socket: sock });
		                }
		                else {
		                    resolve({ socket: sock });
		                }
		            }
		            catch (err) {
		                if (typeof callback === 'function') {
		                    callback(err);
		                    resolve(err);
		                }
		                else {
		                    reject(err);
		                }
		            }
		        }));
		    }
		    static createUDPFrame(options) {
		        const buff = new smart_buffer_1.SmartBuffer();
		        buff.writeUInt16BE(0);
		        buff.writeUInt8(options.frameNumber || 0);
		        if (net.isIPv4(options.remoteHost.host)) {
		            buff.writeUInt8(constants_1.Socks5HostType.IPv4);
		            buff.writeUInt32BE((0, helpers_1.ipv4ToInt32)(options.remoteHost.host));
		        }
		        else if (net.isIPv6(options.remoteHost.host)) {
		            buff.writeUInt8(constants_1.Socks5HostType.IPv6);
		            buff.writeBuffer((0, helpers_1.ipToBuffer)(options.remoteHost.host));
		        }
		        else {
		            buff.writeUInt8(constants_1.Socks5HostType.Hostname);
		            buff.writeUInt8(Buffer.byteLength(options.remoteHost.host));
		            buff.writeString(options.remoteHost.host);
		        }
		        buff.writeUInt16BE(options.remoteHost.port);
		        buff.writeBuffer(options.data);
		        return buff.toBuffer();
		    }
		    static parseUDPFrame(data) {
		        const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
		        buff.readOffset = 2;
		        const frameNumber = buff.readUInt8();
		        const hostType = buff.readUInt8();
		        let remoteHost;
		        if (hostType === constants_1.Socks5HostType.IPv4) {
		            remoteHost = (0, helpers_1.int32ToIpv4)(buff.readUInt32BE());
		        }
		        else if (hostType === constants_1.Socks5HostType.IPv6) {
		            remoteHost = ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm();
		        }
		        else {
		            remoteHost = buff.readString(buff.readUInt8());
		        }
		        const remotePort = buff.readUInt16BE();
		        return {
		            frameNumber,
		            remoteHost: {
		                host: remoteHost,
		                port: remotePort,
		            },
		            data: buff.readBuffer(),
		        };
		    }
		    setState(newState) {
		        if (this.state !== constants_1.SocksClientState.Error) {
		            this.state = newState;
		        }
		    }
		    connect(existingSocket) {
		        this.onDataReceived = (data) => this.onDataReceivedHandler(data);
		        this.onClose = () => this.onCloseHandler();
		        this.onError = (err) => this.onErrorHandler(err);
		        this.onConnect = () => this.onConnectHandler();
		        const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT);
		        if (timer.unref && typeof timer.unref === 'function') {
		            timer.unref();
		        }
		        if (existingSocket) {
		            this.socket = existingSocket;
		        }
		        else {
		            this.socket = new net.Socket();
		        }
		        this.socket.once('close', this.onClose);
		        this.socket.once('error', this.onError);
		        this.socket.once('connect', this.onConnect);
		        this.socket.on('data', this.onDataReceived);
		        this.setState(constants_1.SocksClientState.Connecting);
		        this.receiveBuffer = new receivebuffer_1.ReceiveBuffer();
		        if (existingSocket) {
		            this.socket.emit('connect');
		        }
		        else {
		            this.socket.connect(this.getSocketOptions());
		            if (this.options.set_tcp_nodelay !== undefined &&
		                this.options.set_tcp_nodelay !== null) {
		                this.socket.setNoDelay(!!this.options.set_tcp_nodelay);
		            }
		        }
		        this.prependOnceListener('established', (info) => {
		            setImmediate(() => {
		                if (this.receiveBuffer.length > 0) {
		                    const excessData = this.receiveBuffer.get(this.receiveBuffer.length);
		                    info.socket.emit('data', excessData);
		                }
		                info.socket.resume();
		            });
		        });
		    }
		    getSocketOptions() {
		        return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port });
		    }
		    onEstablishedTimeout() {
		        if (this.state !== constants_1.SocksClientState.Established &&
		            this.state !== constants_1.SocksClientState.BoundWaitingForConnection) {
		            this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut);
		        }
		    }
		    onConnectHandler() {
		        this.setState(constants_1.SocksClientState.Connected);
		        if (this.options.proxy.type === 4) {
		            this.sendSocks4InitialHandshake();
		        }
		        else {
		            this.sendSocks5InitialHandshake();
		        }
		        this.setState(constants_1.SocksClientState.SentInitialHandshake);
		    }
		    onDataReceivedHandler(data) {
		        this.receiveBuffer.append(data);
		        this.processData();
		    }
		    processData() {
		        while (this.state !== constants_1.SocksClientState.Established &&
		            this.state !== constants_1.SocksClientState.Error &&
		            this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) {
		            if (this.state === constants_1.SocksClientState.SentInitialHandshake) {
		                if (this.options.proxy.type === 4) {
		                    this.handleSocks4FinalHandshakeResponse();
		                }
		                else {
		                    this.handleInitialSocks5HandshakeResponse();
		                }
		            }
		            else if (this.state === constants_1.SocksClientState.SentAuthentication) {
		                this.handleInitialSocks5AuthenticationHandshakeResponse();
		            }
		            else if (this.state === constants_1.SocksClientState.SentFinalHandshake) {
		                this.handleSocks5FinalHandshakeResponse();
		            }
		            else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) {
		                if (this.options.proxy.type === 4) {
		                    this.handleSocks4IncomingConnectionResponse();
		                }
		                else {
		                    this.handleSocks5IncomingConnectionResponse();
		                }
		            }
		            else {
		                this.closeSocket(constants_1.ERRORS.InternalError);
		                break;
		            }
		        }
		    }
		    onCloseHandler() {
		        this.closeSocket(constants_1.ERRORS.SocketClosed);
		    }
		    onErrorHandler(err) {
		        this.closeSocket(err.message);
		    }
		    removeInternalSocketHandlers() {
		        this.socket.pause();
		        this.socket.removeListener('data', this.onDataReceived);
		        this.socket.removeListener('close', this.onClose);
		        this.socket.removeListener('error', this.onError);
		        this.socket.removeListener('connect', this.onConnect);
		    }
		    closeSocket(err) {
		        if (this.state !== constants_1.SocksClientState.Error) {
		            this.setState(constants_1.SocksClientState.Error);
		            this.socket.destroy();
		            this.removeInternalSocketHandlers();
		            this.emit('error', new util_1.SocksClientError(err, this.options));
		        }
		    }
		    sendSocks4InitialHandshake() {
		        const userId = this.options.proxy.userId || '';
		        const buff = new smart_buffer_1.SmartBuffer();
		        buff.writeUInt8(0x04);
		        buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
		        buff.writeUInt16BE(this.options.destination.port);
		        if (net.isIPv4(this.options.destination.host)) {
		            buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
		            buff.writeStringNT(userId);
		        }
		        else {
		            buff.writeUInt8(0x00);
		            buff.writeUInt8(0x00);
		            buff.writeUInt8(0x00);
		            buff.writeUInt8(0x01);
		            buff.writeStringNT(userId);
		            buff.writeStringNT(this.options.destination.host);
		        }
		        this.nextRequiredPacketBufferSize =
		            constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response;
		        this.socket.write(buff.toBuffer());
		    }
		    handleSocks4FinalHandshakeResponse() {
		        const data = this.receiveBuffer.get(8);
		        if (data[1] !== constants_1.Socks4Response.Granted) {
		            this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);
		        }
		        else {
		            if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
		                const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
		                buff.readOffset = 2;
		                const remoteHost = {
		                    port: buff.readUInt16BE(),
		                    host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
		                };
		                if (remoteHost.host === '0.0.0.0') {
		                    remoteHost.host = this.options.proxy.ipaddress;
		                }
		                this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
		                this.emit('bound', { remoteHost, socket: this.socket });
		            }
		            else {
		                this.setState(constants_1.SocksClientState.Established);
		                this.removeInternalSocketHandlers();
		                this.emit('established', { socket: this.socket });
		            }
		        }
		    }
		    handleSocks4IncomingConnectionResponse() {
		        const data = this.receiveBuffer.get(8);
		        if (data[1] !== constants_1.Socks4Response.Granted) {
		            this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`);
		        }
		        else {
		            const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
		            buff.readOffset = 2;
		            const remoteHost = {
		                port: buff.readUInt16BE(),
		                host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
		            };
		            this.setState(constants_1.SocksClientState.Established);
		            this.removeInternalSocketHandlers();
		            this.emit('established', { remoteHost, socket: this.socket });
		        }
		    }
		    sendSocks5InitialHandshake() {
		        const buff = new smart_buffer_1.SmartBuffer();
		        const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth];
		        if (this.options.proxy.userId || this.options.proxy.password) {
		            supportedAuthMethods.push(constants_1.Socks5Auth.UserPass);
		        }
		        if (this.options.proxy.custom_auth_method !== undefined) {
		            supportedAuthMethods.push(this.options.proxy.custom_auth_method);
		        }
		        buff.writeUInt8(0x05);
		        buff.writeUInt8(supportedAuthMethods.length);
		        for (const authMethod of supportedAuthMethods) {
		            buff.writeUInt8(authMethod);
		        }
		        this.nextRequiredPacketBufferSize =
		            constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse;
		        this.socket.write(buff.toBuffer());
		        this.setState(constants_1.SocksClientState.SentInitialHandshake);
		    }
		    handleInitialSocks5HandshakeResponse() {
		        const data = this.receiveBuffer.get(2);
		        if (data[0] !== 0x05) {
		            this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);
		        }
		        else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) {
		            this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);
		        }
		        else {
		            if (data[1] === constants_1.Socks5Auth.NoAuth) {
		                this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth;
		                this.sendSocks5CommandRequest();
		            }
		            else if (data[1] === constants_1.Socks5Auth.UserPass) {
		                this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass;
		                this.sendSocks5UserPassAuthentication();
		            }
		            else if (data[1] === this.options.proxy.custom_auth_method) {
		                this.socks5ChosenAuthType = this.options.proxy.custom_auth_method;
		                this.sendSocks5CustomAuthentication();
		            }
		            else {
		                this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType);
		            }
		        }
		    }
		    sendSocks5UserPassAuthentication() {
		        const userId = this.options.proxy.userId || '';
		        const password = this.options.proxy.password || '';
		        const buff = new smart_buffer_1.SmartBuffer();
		        buff.writeUInt8(0x01);
		        buff.writeUInt8(Buffer.byteLength(userId));
		        buff.writeString(userId);
		        buff.writeUInt8(Buffer.byteLength(password));
		        buff.writeString(password);
		        this.nextRequiredPacketBufferSize =
		            constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse;
		        this.socket.write(buff.toBuffer());
		        this.setState(constants_1.SocksClientState.SentAuthentication);
		    }
		    sendSocks5CustomAuthentication() {
		        return __awaiter(this, void 0, void 0, function* () {
		            this.nextRequiredPacketBufferSize =
		                this.options.proxy.custom_auth_response_size;
		            this.socket.write(yield this.options.proxy.custom_auth_request_handler());
		            this.setState(constants_1.SocksClientState.SentAuthentication);
		        });
		    }
		    handleSocks5CustomAuthHandshakeResponse(data) {
		        return __awaiter(this, void 0, void 0, function* () {
		            return yield this.options.proxy.custom_auth_response_handler(data);
		        });
		    }
		    handleSocks5AuthenticationNoAuthHandshakeResponse(data) {
		        return __awaiter(this, void 0, void 0, function* () {
		            return data[1] === 0x00;
		        });
		    }
		    handleSocks5AuthenticationUserPassHandshakeResponse(data) {
		        return __awaiter(this, void 0, void 0, function* () {
		            return data[1] === 0x00;
		        });
		    }
		    handleInitialSocks5AuthenticationHandshakeResponse() {
		        return __awaiter(this, void 0, void 0, function* () {
		            this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse);
		            let authResult = false;
		            if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) {
		                authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));
		            }
		            else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) {
		                authResult =
		                    yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));
		            }
		            else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) {
		                authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));
		            }
		            if (!authResult) {
		                this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed);
		            }
		            else {
		                this.sendSocks5CommandRequest();
		            }
		        });
		    }
		    sendSocks5CommandRequest() {
		        const buff = new smart_buffer_1.SmartBuffer();
		        buff.writeUInt8(0x05);
		        buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
		        buff.writeUInt8(0x00);
		        if (net.isIPv4(this.options.destination.host)) {
		            buff.writeUInt8(constants_1.Socks5HostType.IPv4);
		            buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
		        }
		        else if (net.isIPv6(this.options.destination.host)) {
		            buff.writeUInt8(constants_1.Socks5HostType.IPv6);
		            buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
		        }
		        else {
		            buff.writeUInt8(constants_1.Socks5HostType.Hostname);
		            buff.writeUInt8(this.options.destination.host.length);
		            buff.writeString(this.options.destination.host);
		        }
		        buff.writeUInt16BE(this.options.destination.port);
		        this.nextRequiredPacketBufferSize =
		            constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
		        this.socket.write(buff.toBuffer());
		        this.setState(constants_1.SocksClientState.SentFinalHandshake);
		    }
		    handleSocks5FinalHandshakeResponse() {
		        const header = this.receiveBuffer.peek(5);
		        if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) {
		            this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`);
		        }
		        else {
		            const addressType = header[3];
		            let remoteHost;
		            let buff;
		            if (addressType === constants_1.Socks5HostType.IPv4) {
		                const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
		                if (this.receiveBuffer.length < dataNeeded) {
		                    this.nextRequiredPacketBufferSize = dataNeeded;
		                    return;
		                }
		                buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
		                remoteHost = {
		                    host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
		                    port: buff.readUInt16BE(),
		                };
		                if (remoteHost.host === '0.0.0.0') {
		                    remoteHost.host = this.options.proxy.ipaddress;
		                }
		            }
		            else if (addressType === constants_1.Socks5HostType.Hostname) {
		                const hostLength = header[4];
		                const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);
		                if (this.receiveBuffer.length < dataNeeded) {
		                    this.nextRequiredPacketBufferSize = dataNeeded;
		                    return;
		                }
		                buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
		                remoteHost = {
		                    host: buff.readString(hostLength),
		                    port: buff.readUInt16BE(),
		                };
		            }
		            else if (addressType === constants_1.Socks5HostType.IPv6) {
		                const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
		                if (this.receiveBuffer.length < dataNeeded) {
		                    this.nextRequiredPacketBufferSize = dataNeeded;
		                    return;
		                }
		                buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
		                remoteHost = {
		                    host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),
		                    port: buff.readUInt16BE(),
		                };
		            }
		            this.setState(constants_1.SocksClientState.ReceivedFinalResponse);
		            if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.connect) {
		                this.setState(constants_1.SocksClientState.Established);
		                this.removeInternalSocketHandlers();
		                this.emit('established', { remoteHost, socket: this.socket });
		            }
		            else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
		                this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
		                this.nextRequiredPacketBufferSize =
		                    constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
		                this.emit('bound', { remoteHost, socket: this.socket });
		            }
		            else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.associate) {
		                this.setState(constants_1.SocksClientState.Established);
		                this.removeInternalSocketHandlers();
		                this.emit('established', {
		                    remoteHost,
		                    socket: this.socket,
		                });
		            }
		        }
		    }
		    handleSocks5IncomingConnectionResponse() {
		        const header = this.receiveBuffer.peek(5);
		        if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) {
		            this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`);
		        }
		        else {
		            const addressType = header[3];
		            let remoteHost;
		            let buff;
		            if (addressType === constants_1.Socks5HostType.IPv4) {
		                const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
		                if (this.receiveBuffer.length < dataNeeded) {
		                    this.nextRequiredPacketBufferSize = dataNeeded;
		                    return;
		                }
		                buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
		                remoteHost = {
		                    host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
		                    port: buff.readUInt16BE(),
		                };
		                if (remoteHost.host === '0.0.0.0') {
		                    remoteHost.host = this.options.proxy.ipaddress;
		                }
		            }
		            else if (addressType === constants_1.Socks5HostType.Hostname) {
		                const hostLength = header[4];
		                const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);
		                if (this.receiveBuffer.length < dataNeeded) {
		                    this.nextRequiredPacketBufferSize = dataNeeded;
		                    return;
		                }
		                buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
		                remoteHost = {
		                    host: buff.readString(hostLength),
		                    port: buff.readUInt16BE(),
		                };
		            }
		            else if (addressType === constants_1.Socks5HostType.IPv6) {
		                const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
		                if (this.receiveBuffer.length < dataNeeded) {
		                    this.nextRequiredPacketBufferSize = dataNeeded;
		                    return;
		                }
		                buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
		                remoteHost = {
		                    host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),
		                    port: buff.readUInt16BE(),
		                };
		            }
		            this.setState(constants_1.SocksClientState.Established);
		            this.removeInternalSocketHandlers();
		            this.emit('established', { remoteHost, socket: this.socket });
		        }
		    }
		    get socksClientOptions() {
		        return Object.assign({}, this.options);
		    }
		}
		exports$1.SocksClient = SocksClient; 
	} (socksclient));
	return socksclient;
}

var hasRequiredBuild;

function requireBuild () {
	if (hasRequiredBuild) return build;
	hasRequiredBuild = 1;
	(function (exports$1) {
		var __createBinding = (build && build.__createBinding) || (Object.create ? (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    var desc = Object.getOwnPropertyDescriptor(m, k);
		    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
		      desc = { enumerable: true, get: function() { return m[k]; } };
		    }
		    Object.defineProperty(o, k2, desc);
		}) : (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    o[k2] = m[k];
		}));
		var __exportStar = (build && build.__exportStar) || function(m, exports$1) {
		    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		__exportStar(requireSocksclient(), exports$1); 
	} (build));
	return build;
}

var hasRequiredDist$8;

function requireDist$8 () {
	if (hasRequiredDist$8) return dist$7;
	hasRequiredDist$8 = 1;
	var __createBinding = (dist$7 && dist$7.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (dist$7 && dist$7.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (dist$7 && dist$7.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	var __importDefault = (dist$7 && dist$7.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(dist$7, "__esModule", { value: true });
	dist$7.SocksProxyAgent = void 0;
	const socks_1 = requireBuild();
	const agent_base_1 = requireDist$b();
	const debug_1 = __importDefault(requireSrc());
	const dns = __importStar(require$$3$3);
	const net = __importStar(require$$0$7);
	const tls = __importStar(require$$1$2);
	const url_1 = require$$5;
	const debug = (0, debug_1.default)('socks-proxy-agent');
	const setServernameFromNonIpHost = (options) => {
	    if (options.servername === undefined &&
	        options.host &&
	        !net.isIP(options.host)) {
	        return {
	            ...options,
	            servername: options.host,
	        };
	    }
	    return options;
	};
	function parseSocksURL(url) {
	    let lookup = false;
	    let type = 5;
	    const host = url.hostname;
	    const port = parseInt(url.port, 10) || 1080;
	    switch (url.protocol.replace(':', '')) {
	        case 'socks4':
	            lookup = true;
	            type = 4;
	            break;
	        case 'socks4a':
	            type = 4;
	            break;
	        case 'socks5':
	            lookup = true;
	            type = 5;
	            break;
	        case 'socks':
	            type = 5;
	            break;
	        case 'socks5h':
	            type = 5;
	            break;
	        default:
	            throw new TypeError(`A "socks" protocol must be specified! Got: ${String(url.protocol)}`);
	    }
	    const proxy = {
	        host,
	        port,
	        type,
	    };
	    if (url.username) {
	        Object.defineProperty(proxy, 'userId', {
	            value: decodeURIComponent(url.username),
	            enumerable: false,
	        });
	    }
	    if (url.password != null) {
	        Object.defineProperty(proxy, 'password', {
	            value: decodeURIComponent(url.password),
	            enumerable: false,
	        });
	    }
	    return { lookup, proxy };
	}
	class SocksProxyAgent extends agent_base_1.Agent {
	    constructor(uri, opts) {
	        super(opts);
	        const url = typeof uri === 'string' ? new url_1.URL(uri) : uri;
	        const { proxy, lookup } = parseSocksURL(url);
	        this.shouldLookup = lookup;
	        this.proxy = proxy;
	        this.timeout = opts?.timeout ?? null;
	        this.socketOptions = opts?.socketOptions ?? null;
	    }
	    async connect(req, opts) {
	        const { shouldLookup, proxy, timeout } = this;
	        if (!opts.host) {
	            throw new Error('No `host` defined!');
	        }
	        let { host } = opts;
	        const { port, lookup: lookupFn = dns.lookup } = opts;
	        if (shouldLookup) {
	            host = await new Promise((resolve, reject) => {
	                lookupFn(host, {}, (err, res) => {
	                    if (err) {
	                        reject(err);
	                    }
	                    else {
	                        resolve(res);
	                    }
	                });
	            });
	        }
	        const socksOpts = {
	            proxy,
	            destination: {
	                host,
	                port: typeof port === 'number' ? port : parseInt(port, 10),
	            },
	            command: 'connect',
	            timeout: timeout ?? undefined,
	            socket_options: this.socketOptions ?? undefined,
	        };
	        const cleanup = (tlsSocket) => {
	            req.destroy();
	            socket.destroy();
	            if (tlsSocket)
	                tlsSocket.destroy();
	        };
	        debug('Creating socks proxy connection: %o', socksOpts);
	        const { socket } = await socks_1.SocksClient.createConnection(socksOpts);
	        debug('Successfully created socks proxy connection');
	        if (timeout !== null) {
	            socket.setTimeout(timeout);
	            socket.on('timeout', () => cleanup());
	        }
	        if (opts.secureEndpoint) {
	            debug('Upgrading socket connection to TLS');
	            const tlsSocket = tls.connect({
	                ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'),
	                socket,
	            });
	            tlsSocket.once('error', (error) => {
	                debug('Socket TLS error', error.message);
	                cleanup(tlsSocket);
	            });
	            return tlsSocket;
	        }
	        return socket;
	    }
	}
	SocksProxyAgent.protocols = [
	    'socks',
	    'socks4',
	    'socks4a',
	    'socks5',
	    'socks5h',
	];
	dist$7.SocksProxyAgent = SocksProxyAgent;
	function omit(obj, ...keys) {
	    const ret = {};
	    let key;
	    for (key in obj) {
	        if (!keys.includes(key)) {
	            ret[key] = obj[key];
	        }
	    }
	    return ret;
	}
	return dist$7;
}

var dist$6 = {};

var dist$5 = {};

var data$u = {};

var dist$4 = {};

var common$1 = {};

var hasRequiredCommon;

function requireCommon () {
	if (hasRequiredCommon) return common$1;
	hasRequiredCommon = 1;
	Object.defineProperty(common$1, "__esModule", { value: true });
	common$1.makeDataUriToBuffer = void 0;
	const makeDataUriToBuffer = (convert) => (uri) => {
	    uri = String(uri);
	    if (!/^data:/i.test(uri)) {
	        throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
	    }
	    uri = uri.replace(/\r?\n/g, '');
	    const firstComma = uri.indexOf(',');
	    if (firstComma === -1 || firstComma <= 4) {
	        throw new TypeError('malformed data: URI');
	    }
	    const meta = uri.substring(5, firstComma).split(';');
	    let charset = '';
	    let base64 = false;
	    const type = meta[0] || 'text/plain';
	    let typeFull = type;
	    for (let i = 1; i < meta.length; i++) {
	        if (meta[i] === 'base64') {
	            base64 = true;
	        }
	        else if (meta[i]) {
	            typeFull += `;${meta[i]}`;
	            if (meta[i].indexOf('charset=') === 0) {
	                charset = meta[i].substring(8);
	            }
	        }
	    }
	    if (!meta[0] && !charset.length) {
	        typeFull += ';charset=US-ASCII';
	        charset = 'US-ASCII';
	    }
	    const data = unescape(uri.substring(firstComma + 1));
	    const buffer = base64 ? convert.base64ToArrayBuffer(data) : convert.stringToBuffer(data);
	    return {
	        type,
	        typeFull,
	        charset,
	        buffer,
	    };
	};
	common$1.makeDataUriToBuffer = makeDataUriToBuffer;
	return common$1;
}

var hasRequiredDist$7;

function requireDist$7 () {
	if (hasRequiredDist$7) return dist$4;
	hasRequiredDist$7 = 1;
	Object.defineProperty(dist$4, "__esModule", { value: true });
	dist$4.dataUriToBuffer = void 0;
	const common_1 = requireCommon();
	function base64ToArrayBuffer(base64) {
	    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
	    const bytes = [];
	    for (let i = 0; i < base64.length; i += 4) {
	        const idx0 = chars.indexOf(base64.charAt(i));
	        const idx1 = chars.indexOf(base64.charAt(i + 1));
	        const idx2 = base64.charAt(i + 2) === '='
	            ? 0
	            : chars.indexOf(base64.charAt(i + 2));
	        const idx3 = base64.charAt(i + 3) === '='
	            ? 0
	            : chars.indexOf(base64.charAt(i + 3));
	        const bin0 = (idx0 << 2) | (idx1 >> 4);
	        const bin1 = ((idx1 & 15) << 4) | (idx2 >> 2);
	        const bin2 = ((idx2 & 3) << 6) | idx3;
	        bytes.push(bin0);
	        if (base64.charAt(i + 2) !== '=')
	            bytes.push(bin1);
	        if (base64.charAt(i + 3) !== '=')
	            bytes.push(bin2);
	    }
	    const buffer = new ArrayBuffer(bytes.length);
	    const view = new Uint8Array(buffer);
	    view.set(bytes);
	    return buffer;
	}
	function stringToBuffer(str) {
	    const buffer = new ArrayBuffer(str.length);
	    const view = new Uint8Array(buffer);
	    for (let i = 0; i < str.length; i++) {
	        view[i] = str.charCodeAt(i);
	    }
	    return buffer;
	}
	dist$4.dataUriToBuffer = (0, common_1.makeDataUriToBuffer)({ stringToBuffer, base64ToArrayBuffer });
	return dist$4;
}

var notmodified = {};

var hasRequiredNotmodified;

function requireNotmodified () {
	if (hasRequiredNotmodified) return notmodified;
	hasRequiredNotmodified = 1;
	Object.defineProperty(notmodified, "__esModule", { value: true });
	class NotModifiedError extends Error {
	    constructor(message) {
	        super(message ||
	            'Source has not been modified since the provied "cache", re-use previous results');
	        this.code = 'ENOTMODIFIED';
	    }
	}
	notmodified.default = NotModifiedError;
	return notmodified;
}

var hasRequiredData;

function requireData () {
	if (hasRequiredData) return data$u;
	hasRequiredData = 1;
	var __importDefault = (data$u && data$u.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(data$u, "__esModule", { value: true });
	data$u.data = void 0;
	const debug_1 = __importDefault(requireSrc());
	const stream_1 = require$$1$3;
	const crypto_1 = require$$2$1;
	const data_uri_to_buffer_1 = requireDist$7();
	const notmodified_1 = __importDefault(requireNotmodified());
	const debug = (0, debug_1.default)('get-uri:data');
	class DataReadable extends stream_1.Readable {
	    constructor(hash, buf) {
	        super();
	        this.push(buf);
	        this.push(null);
	        this.hash = hash;
	    }
	}
	const data = async ({ href: uri }, { cache } = {}) => {
	    const shasum = (0, crypto_1.createHash)('sha1');
	    shasum.update(uri);
	    const hash = shasum.digest('hex');
	    debug('generated SHA1 hash for "data:" URI: %o', hash);
	    if (cache?.hash === hash) {
	        debug('got matching cache SHA1 hash: %o', hash);
	        throw new notmodified_1.default();
	    }
	    else {
	        debug('creating Readable stream from "data:" URI buffer');
	        const { buffer } = (0, data_uri_to_buffer_1.dataUriToBuffer)(uri);
	        return new DataReadable(hash, Buffer.from(buffer));
	    }
	};
	data$u.data = data;
	return data$u;
}

var file = {};

var notfound = {};

var hasRequiredNotfound;

function requireNotfound () {
	if (hasRequiredNotfound) return notfound;
	hasRequiredNotfound = 1;
	Object.defineProperty(notfound, "__esModule", { value: true });
	class NotFoundError extends Error {
	    constructor(message) {
	        super(message || 'File does not exist at the specified endpoint');
	        this.code = 'ENOTFOUND';
	    }
	}
	notfound.default = NotFoundError;
	return notfound;
}

var hasRequiredFile;

function requireFile () {
	if (hasRequiredFile) return file;
	hasRequiredFile = 1;
	var __importDefault = (file && file.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(file, "__esModule", { value: true });
	file.file = void 0;
	const debug_1 = __importDefault(requireSrc());
	const fs_1 = require$$0$3;
	const notfound_1 = __importDefault(requireNotfound());
	const notmodified_1 = __importDefault(requireNotmodified());
	const url_1 = require$$5;
	const debug = (0, debug_1.default)('get-uri:file');
	const file$1 = async ({ href: uri }, opts = {}) => {
	    const { cache, flags = 'r', mode = 438,
	     } = opts;
	    try {
	        const filepath = (0, url_1.fileURLToPath)(uri);
	        debug('Normalized pathname: %o', filepath);
	        const fdHandle = await fs_1.promises.open(filepath, flags, mode);
	        const fd = fdHandle.fd;
	        const stat = await fdHandle.stat();
	        if (cache && cache.stat && stat && isNotModified(cache.stat, stat)) {
	            await fdHandle.close();
	            throw new notmodified_1.default();
	        }
	        const rs = (0, fs_1.createReadStream)(filepath, {
	            autoClose: true,
	            ...opts,
	            fd,
	        });
	        rs.stat = stat;
	        return rs;
	    }
	    catch (err) {
	        if (err.code === 'ENOENT') {
	            throw new notfound_1.default();
	        }
	        throw err;
	    }
	};
	file.file = file$1;
	function isNotModified(prev, curr) {
	    return +prev.mtime === +curr.mtime;
	}
	return file;
}

var ftp = {};

var dist$3 = {};

var Client = {};

var FtpContext = {};

var parseControlResponse = {};

var hasRequiredParseControlResponse;

function requireParseControlResponse () {
	if (hasRequiredParseControlResponse) return parseControlResponse;
	hasRequiredParseControlResponse = 1;
	Object.defineProperty(parseControlResponse, "__esModule", { value: true });
	parseControlResponse.parseControlResponse = parseControlResponse$1;
	parseControlResponse.isSingleLine = isSingleLine;
	parseControlResponse.isMultiline = isMultiline;
	parseControlResponse.positiveCompletion = positiveCompletion;
	parseControlResponse.positiveIntermediate = positiveIntermediate;
	const LF = "\n";
	function parseControlResponse$1(text) {
	    const lines = text.split(/\r?\n/).filter(isNotBlank);
	    const messages = [];
	    let startAt = 0;
	    let tokenRegex;
	    for (let i = 0; i < lines.length; i++) {
	        const line = lines[i];
	        if (!tokenRegex) {
	            if (isMultiline(line)) {
	                const token = line.substr(0, 3);
	                tokenRegex = new RegExp(`^${token}(?:$| )`);
	                startAt = i;
	            }
	            else if (isSingleLine(line)) {
	                messages.push(line);
	            }
	        }
	        else if (tokenRegex.test(line)) {
	            tokenRegex = undefined;
	            messages.push(lines.slice(startAt, i + 1).join(LF));
	        }
	    }
	    const rest = tokenRegex ? lines.slice(startAt).join(LF) + LF : "";
	    return { messages, rest };
	}
	function isSingleLine(line) {
	    return /^\d\d\d(?:$| )/.test(line);
	}
	function isMultiline(line) {
	    return /^\d\d\d-/.test(line);
	}
	function positiveCompletion(code) {
	    return code >= 200 && code < 300;
	}
	function positiveIntermediate(code) {
	    return code >= 300 && code < 400;
	}
	function isNotBlank(str) {
	    return str.trim() !== "";
	}
	return parseControlResponse;
}

var hasRequiredFtpContext;

function requireFtpContext () {
	if (hasRequiredFtpContext) return FtpContext;
	hasRequiredFtpContext = 1;
	Object.defineProperty(FtpContext, "__esModule", { value: true });
	FtpContext.FTPContext = FtpContext.FTPError = void 0;
	const net_1 = require$$0$7;
	const parseControlResponse_1 = requireParseControlResponse();
	class FTPError extends Error {
	    constructor(res) {
	        super(res.message);
	        this.name = this.constructor.name;
	        this.code = res.code;
	    }
	}
	FtpContext.FTPError = FTPError;
	function doNothing() {
	}
	class FTPContext {
	    constructor(timeout = 0, encoding = "utf8") {
	        this.timeout = timeout;
	        this.verbose = false;
	        this.ipFamily = undefined;
	        this.tlsOptions = {};
	        this._partialResponse = "";
	        this._encoding = encoding;
	        this._socket = this.socket = this._newSocket();
	        this._dataSocket = undefined;
	    }
	    close() {
	        const message = this._task ? "User closed client during task" : "User closed client";
	        const err = new Error(message);
	        this.closeWithError(err);
	    }
	    closeWithError(err) {
	        if (this._closingError) {
	            return;
	        }
	        this._closingError = err;
	        this._closeControlSocket();
	        this._closeSocket(this._dataSocket);
	        this._passToHandler(err);
	        this._stopTrackingTask();
	    }
	    get closed() {
	        return this.socket.remoteAddress === undefined || this._closingError !== undefined;
	    }
	    reset() {
	        this.socket = this._newSocket();
	    }
	    get socket() {
	        return this._socket;
	    }
	    set socket(socket) {
	        this.dataSocket = undefined;
	        this.tlsOptions = {};
	        this._partialResponse = "";
	        if (this._socket) {
	            const newSocketUpgradesExisting = socket.localPort === this._socket.localPort;
	            if (newSocketUpgradesExisting) {
	                this._removeSocketListeners(this.socket);
	            }
	            else {
	                this._closeControlSocket();
	            }
	        }
	        if (socket) {
	            this._closingError = undefined;
	            socket.setTimeout(0);
	            socket.setEncoding(this._encoding);
	            socket.setKeepAlive(true);
	            socket.on("data", data => this._onControlSocketData(data));
	            socket.on("end", () => this.closeWithError(new Error("Server sent FIN packet unexpectedly, closing connection.")));
	            socket.on("close", hadError => { if (!hadError)
	                this.closeWithError(new Error("Server closed connection unexpectedly.")); });
	            this._setupDefaultErrorHandlers(socket, "control socket");
	        }
	        this._socket = socket;
	    }
	    get dataSocket() {
	        return this._dataSocket;
	    }
	    set dataSocket(socket) {
	        this._closeSocket(this._dataSocket);
	        if (socket) {
	            socket.setTimeout(0);
	            this._setupDefaultErrorHandlers(socket, "data socket");
	        }
	        this._dataSocket = socket;
	    }
	    get encoding() {
	        return this._encoding;
	    }
	    set encoding(encoding) {
	        this._encoding = encoding;
	        if (this.socket) {
	            this.socket.setEncoding(encoding);
	        }
	    }
	    send(command) {
	        const containsPassword = command.startsWith("PASS");
	        const message = containsPassword ? "> PASS ###" : `> ${command}`;
	        this.log(message);
	        this._socket.write(command + "\r\n", this.encoding);
	    }
	    request(command) {
	        return this.handle(command, (res, task) => {
	            if (res instanceof Error) {
	                task.reject(res);
	            }
	            else {
	                task.resolve(res);
	            }
	        });
	    }
	    handle(command, responseHandler) {
	        if (this._task) {
	            const err = new Error("User launched a task while another one is still running. Forgot to use 'await' or '.then()'?");
	            err.stack += `\nRunning task launched at: ${this._task.stack}`;
	            this.closeWithError(err);
	        }
	        return new Promise((resolveTask, rejectTask) => {
	            this._task = {
	                stack: new Error().stack || "Unknown call stack",
	                responseHandler,
	                resolver: {
	                    resolve: arg => {
	                        this._stopTrackingTask();
	                        resolveTask(arg);
	                    },
	                    reject: err => {
	                        this._stopTrackingTask();
	                        rejectTask(err);
	                    }
	                }
	            };
	            if (this._closingError) {
	                const err = new Error(`Client is closed because ${this._closingError.message}`);
	                err.stack += `\nClosing reason: ${this._closingError.stack}`;
	                err.code = this._closingError.code !== undefined ? this._closingError.code : "0";
	                this._passToHandler(err);
	                return;
	            }
	            this.socket.setTimeout(this.timeout);
	            if (command) {
	                this.send(command);
	            }
	        });
	    }
	    log(message) {
	        if (this.verbose) {
	            console.log(message);
	        }
	    }
	    get hasTLS() {
	        return "encrypted" in this._socket;
	    }
	    _stopTrackingTask() {
	        this.socket.setTimeout(0);
	        this._task = undefined;
	    }
	    _onControlSocketData(chunk) {
	        this.log(`< ${chunk}`);
	        const completeResponse = this._partialResponse + chunk;
	        const parsed = (0, parseControlResponse_1.parseControlResponse)(completeResponse);
	        this._partialResponse = parsed.rest;
	        for (const message of parsed.messages) {
	            const code = parseInt(message.substr(0, 3), 10);
	            const response = { code, message };
	            const err = code >= 400 ? new FTPError(response) : undefined;
	            this._passToHandler(err ? err : response);
	        }
	    }
	    _passToHandler(response) {
	        if (this._task) {
	            this._task.responseHandler(response, this._task.resolver);
	        }
	    }
	    _setupDefaultErrorHandlers(socket, identifier) {
	        socket.once("error", error => {
	            error.message += ` (${identifier})`;
	            this.closeWithError(error);
	        });
	        socket.once("close", hadError => {
	            if (hadError) {
	                this.closeWithError(new Error(`Socket closed due to transmission error (${identifier})`));
	            }
	        });
	        socket.once("timeout", () => {
	            socket.destroy();
	            this.closeWithError(new Error(`Timeout (${identifier})`));
	        });
	    }
	    _closeControlSocket() {
	        this._removeSocketListeners(this._socket);
	        this._socket.on("error", doNothing);
	        this.send("QUIT");
	        this._closeSocket(this._socket);
	    }
	    _closeSocket(socket) {
	        if (socket) {
	            this._removeSocketListeners(socket);
	            socket.on("error", doNothing);
	            socket.destroy();
	        }
	    }
	    _removeSocketListeners(socket) {
	        socket.removeAllListeners();
	        socket.removeAllListeners("timeout");
	        socket.removeAllListeners("data");
	        socket.removeAllListeners("end");
	        socket.removeAllListeners("error");
	        socket.removeAllListeners("close");
	        socket.removeAllListeners("connect");
	    }
	    _newSocket() {
	        return new net_1.Socket();
	    }
	}
	FtpContext.FTPContext = FTPContext;
	return FtpContext;
}

var parseList = {};

var parseListDOS = {};

var FileInfo = {};

var hasRequiredFileInfo;

function requireFileInfo () {
	if (hasRequiredFileInfo) return FileInfo;
	hasRequiredFileInfo = 1;
	Object.defineProperty(FileInfo, "__esModule", { value: true });
	FileInfo.FileInfo = FileInfo.FileType = void 0;
	var FileType;
	(function (FileType) {
	    FileType[FileType["Unknown"] = 0] = "Unknown";
	    FileType[FileType["File"] = 1] = "File";
	    FileType[FileType["Directory"] = 2] = "Directory";
	    FileType[FileType["SymbolicLink"] = 3] = "SymbolicLink";
	})(FileType || (FileInfo.FileType = FileType = {}));
	let FileInfo$1 = class FileInfo {
	    constructor(name) {
	        this.name = name;
	        this.type = FileType.Unknown;
	        this.size = 0;
	        this.rawModifiedAt = "";
	        this.modifiedAt = undefined;
	        this.permissions = undefined;
	        this.hardLinkCount = undefined;
	        this.link = undefined;
	        this.group = undefined;
	        this.user = undefined;
	        this.uniqueID = undefined;
	        this.name = name;
	    }
	    get isDirectory() {
	        return this.type === FileType.Directory;
	    }
	    get isSymbolicLink() {
	        return this.type === FileType.SymbolicLink;
	    }
	    get isFile() {
	        return this.type === FileType.File;
	    }
	    get date() {
	        return this.rawModifiedAt;
	    }
	    set date(rawModifiedAt) {
	        this.rawModifiedAt = rawModifiedAt;
	    }
	};
	FileInfo.FileInfo = FileInfo$1;
	FileInfo$1.UnixPermission = {
	    Read: 4,
	    Write: 2,
	    Execute: 1
	};
	return FileInfo;
}

var hasRequiredParseListDOS;

function requireParseListDOS () {
	if (hasRequiredParseListDOS) return parseListDOS;
	hasRequiredParseListDOS = 1;
	Object.defineProperty(parseListDOS, "__esModule", { value: true });
	parseListDOS.testLine = testLine;
	parseListDOS.parseLine = parseLine;
	parseListDOS.transformList = transformList;
	const FileInfo_1 = requireFileInfo();
	const RE_LINE = new RegExp("(\\S+)\\s+(\\S+)\\s+"
	    + "(?:(<DIR>)|([0-9]+))\\s+"
	    + "(\\S.*)"
	);
	function testLine(line) {
	    return /^\d{2}/.test(line) && RE_LINE.test(line);
	}
	function parseLine(line) {
	    const groups = line.match(RE_LINE);
	    if (groups === null) {
	        return undefined;
	    }
	    const name = groups[5];
	    if (name === "." || name === "..") {
	        return undefined;
	    }
	    const file = new FileInfo_1.FileInfo(name);
	    const fileType = groups[3];
	    if (fileType === "<DIR>") {
	        file.type = FileInfo_1.FileType.Directory;
	        file.size = 0;
	    }
	    else {
	        file.type = FileInfo_1.FileType.File;
	        file.size = parseInt(groups[4], 10);
	    }
	    file.rawModifiedAt = groups[1] + " " + groups[2];
	    return file;
	}
	function transformList(files) {
	    return files;
	}
	return parseListDOS;
}

var parseListUnix = {};

var hasRequiredParseListUnix;

function requireParseListUnix () {
	if (hasRequiredParseListUnix) return parseListUnix;
	hasRequiredParseListUnix = 1;
	Object.defineProperty(parseListUnix, "__esModule", { value: true });
	parseListUnix.testLine = testLine;
	parseListUnix.parseLine = parseLine;
	parseListUnix.transformList = transformList;
	const FileInfo_1 = requireFileInfo();
	const JA_MONTH = "\u6708";
	const JA_DAY = "\u65e5";
	const JA_YEAR = "\u5e74";
	const RE_LINE = new RegExp("([bcdelfmpSs-])"
	    + "(((r|-)(w|-)([xsStTL-]))((r|-)(w|-)([xsStTL-]))((r|-)(w|-)([xsStTL-]?)))\\+?"
	    + "\\s*"
	    + "(\\d+)"
	    + "\\s+"
	    + "(?:(\\S+(?:\\s\\S+)*?)\\s+)?"
	    + "(?:(\\S+(?:\\s\\S+)*)\\s+)?"
	    + "(\\d+(?:,\\s*\\d+)?)"
	    + "\\s+"
	    + "(" +
	    "(?:\\d+[-/]\\d+[-/]\\d+)" +
	    "|(?:\\S{3}\\s+\\d{1,2})" +
	    "|(?:\\d{1,2}\\s+\\S{3})" +
	    "|(?:\\d{1,2}" + JA_MONTH + "\\s+\\d{1,2}" + JA_DAY + ")" +
	    ")"
	    + "\\s+"
	    + "((?:\\d+(?::\\d+)?)|(?:\\d{4}" + JA_YEAR + "))"
	    + "\\s"
	    + "(.*)");
	function testLine(line) {
	    return RE_LINE.test(line);
	}
	function parseLine(line) {
	    const groups = line.match(RE_LINE);
	    if (groups === null) {
	        return undefined;
	    }
	    const name = groups[21];
	    if (name === "." || name === "..") {
	        return undefined;
	    }
	    const file = new FileInfo_1.FileInfo(name);
	    file.size = parseInt(groups[18], 10);
	    file.user = groups[16];
	    file.group = groups[17];
	    file.hardLinkCount = parseInt(groups[15], 10);
	    file.rawModifiedAt = groups[19] + " " + groups[20];
	    file.permissions = {
	        user: parseMode(groups[4], groups[5], groups[6]),
	        group: parseMode(groups[8], groups[9], groups[10]),
	        world: parseMode(groups[12], groups[13], groups[14]),
	    };
	    switch (groups[1].charAt(0)) {
	        case "d":
	            file.type = FileInfo_1.FileType.Directory;
	            break;
	        case "e":
	            file.type = FileInfo_1.FileType.SymbolicLink;
	            break;
	        case "l":
	            file.type = FileInfo_1.FileType.SymbolicLink;
	            break;
	        case "b":
	        case "c":
	            file.type = FileInfo_1.FileType.File;
	            break;
	        case "f":
	        case "-":
	            file.type = FileInfo_1.FileType.File;
	            break;
	        default:
	            file.type = FileInfo_1.FileType.Unknown;
	    }
	    if (file.isSymbolicLink) {
	        const end = name.indexOf(" -> ");
	        if (end !== -1) {
	            file.name = name.substring(0, end);
	            file.link = name.substring(end + 4);
	        }
	    }
	    return file;
	}
	function transformList(files) {
	    return files;
	}
	function parseMode(r, w, x) {
	    let value = 0;
	    if (r !== "-") {
	        value += FileInfo_1.FileInfo.UnixPermission.Read;
	    }
	    if (w !== "-") {
	        value += FileInfo_1.FileInfo.UnixPermission.Write;
	    }
	    const execToken = x.charAt(0);
	    if (execToken !== "-" && execToken.toUpperCase() !== execToken) {
	        value += FileInfo_1.FileInfo.UnixPermission.Execute;
	    }
	    return value;
	}
	return parseListUnix;
}

var parseListMLSD = {};

var hasRequiredParseListMLSD;

function requireParseListMLSD () {
	if (hasRequiredParseListMLSD) return parseListMLSD;
	hasRequiredParseListMLSD = 1;
	Object.defineProperty(parseListMLSD, "__esModule", { value: true });
	parseListMLSD.testLine = testLine;
	parseListMLSD.parseLine = parseLine;
	parseListMLSD.transformList = transformList;
	parseListMLSD.parseMLSxDate = parseMLSxDate;
	const FileInfo_1 = requireFileInfo();
	function parseSize(value, info) {
	    info.size = parseInt(value, 10);
	}
	const factHandlersByName = {
	    "size": parseSize,
	    "sizd": parseSize,
	    "unique": (value, info) => {
	        info.uniqueID = value;
	    },
	    "modify": (value, info) => {
	        info.modifiedAt = parseMLSxDate(value);
	        info.rawModifiedAt = info.modifiedAt.toISOString();
	    },
	    "type": (value, info) => {
	        if (value.startsWith("OS.unix=slink")) {
	            info.type = FileInfo_1.FileType.SymbolicLink;
	            info.link = value.substr(value.indexOf(":") + 1);
	            return 1 ;
	        }
	        switch (value) {
	            case "file":
	                info.type = FileInfo_1.FileType.File;
	                break;
	            case "dir":
	                info.type = FileInfo_1.FileType.Directory;
	                break;
	            case "OS.unix=symlink":
	                info.type = FileInfo_1.FileType.SymbolicLink;
	                break;
	            case "cdir":
	            case "pdir":
	                return 2 ;
	            default:
	                info.type = FileInfo_1.FileType.Unknown;
	        }
	        return 1 ;
	    },
	    "unix.mode": (value, info) => {
	        const digits = value.substr(-3);
	        info.permissions = {
	            user: parseInt(digits[0], 10),
	            group: parseInt(digits[1], 10),
	            world: parseInt(digits[2], 10)
	        };
	    },
	    "unix.ownername": (value, info) => {
	        info.user = value;
	    },
	    "unix.owner": (value, info) => {
	        if (info.user === undefined)
	            info.user = value;
	    },
	    get "unix.uid"() {
	        return this["unix.owner"];
	    },
	    "unix.groupname": (value, info) => {
	        info.group = value;
	    },
	    "unix.group": (value, info) => {
	        if (info.group === undefined)
	            info.group = value;
	    },
	    get "unix.gid"() {
	        return this["unix.group"];
	    }
	};
	function splitStringOnce(str, delimiter) {
	    const pos = str.indexOf(delimiter);
	    const a = str.substr(0, pos);
	    const b = str.substr(pos + delimiter.length);
	    return [a, b];
	}
	function testLine(line) {
	    return /^\S+=\S+;/.test(line) || line.startsWith(" ");
	}
	function parseLine(line) {
	    const [packedFacts, name] = splitStringOnce(line, " ");
	    if (name === "" || name === "." || name === "..") {
	        return undefined;
	    }
	    const info = new FileInfo_1.FileInfo(name);
	    const facts = packedFacts.split(";");
	    for (const fact of facts) {
	        const [factName, factValue] = splitStringOnce(fact, "=");
	        if (!factValue) {
	            continue;
	        }
	        const factHandler = factHandlersByName[factName.toLowerCase()];
	        if (!factHandler) {
	            continue;
	        }
	        const result = factHandler(factValue, info);
	        if (result === 2 ) {
	            return undefined;
	        }
	    }
	    return info;
	}
	function transformList(files) {
	    const nonLinksByID = new Map();
	    for (const file of files) {
	        if (!file.isSymbolicLink && file.uniqueID !== undefined) {
	            nonLinksByID.set(file.uniqueID, file);
	        }
	    }
	    const resolvedFiles = [];
	    for (const file of files) {
	        if (file.isSymbolicLink && file.uniqueID !== undefined && file.link === undefined) {
	            const target = nonLinksByID.get(file.uniqueID);
	            if (target !== undefined) {
	                file.link = target.name;
	            }
	        }
	        const isPartOfDirectory = !file.name.includes("/");
	        if (isPartOfDirectory) {
	            resolvedFiles.push(file);
	        }
	    }
	    return resolvedFiles;
	}
	function parseMLSxDate(fact) {
	    return new Date(Date.UTC(+fact.slice(0, 4),
	    +fact.slice(4, 6) - 1,
	    +fact.slice(6, 8),
	    +fact.slice(8, 10),
	    +fact.slice(10, 12),
	    +fact.slice(12, 14),
	    +fact.slice(15, 18)
	    ));
	}
	return parseListMLSD;
}

var hasRequiredParseList;

function requireParseList () {
	if (hasRequiredParseList) return parseList;
	hasRequiredParseList = 1;
	var __createBinding = (parseList && parseList.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (parseList && parseList.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (parseList && parseList.__importStar) || (function () {
	    var ownKeys = function(o) {
	        ownKeys = Object.getOwnPropertyNames || function (o) {
	            var ar = [];
	            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
	            return ar;
	        };
	        return ownKeys(o);
	    };
	    return function (mod) {
	        if (mod && mod.__esModule) return mod;
	        var result = {};
	        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
	        __setModuleDefault(result, mod);
	        return result;
	    };
	})();
	Object.defineProperty(parseList, "__esModule", { value: true });
	parseList.parseList = parseList$1;
	const dosParser = __importStar(requireParseListDOS());
	const unixParser = __importStar(requireParseListUnix());
	const mlsdParser = __importStar(requireParseListMLSD());
	const availableParsers = [
	    dosParser,
	    unixParser,
	    mlsdParser
	];
	function firstCompatibleParser(line, parsers) {
	    return parsers.find(parser => parser.testLine(line) === true);
	}
	function isNotBlank(str) {
	    return str.trim() !== "";
	}
	function isNotMeta(str) {
	    return !str.startsWith("total");
	}
	const REGEX_NEWLINE = /\r?\n/;
	function parseList$1(rawList) {
	    const lines = rawList
	        .split(REGEX_NEWLINE)
	        .filter(isNotBlank)
	        .filter(isNotMeta);
	    if (lines.length === 0) {
	        return [];
	    }
	    const testLine = lines[lines.length - 1];
	    const parser = firstCompatibleParser(testLine, availableParsers);
	    if (!parser) {
	        throw new Error("This library only supports MLSD, Unix- or DOS-style directory listing. Your FTP server seems to be using another format. You can see the transmitted listing when setting `client.ftp.verbose = true`. You can then provide a custom parser to `client.parseList`, see the documentation for details.");
	    }
	    const files = lines
	        .map(parser.parseLine)
	        .filter((info) => info !== undefined);
	    return parser.transformList(files);
	}
	return parseList;
}

var ProgressTracker = {};

var hasRequiredProgressTracker;

function requireProgressTracker () {
	if (hasRequiredProgressTracker) return ProgressTracker;
	hasRequiredProgressTracker = 1;
	Object.defineProperty(ProgressTracker, "__esModule", { value: true });
	ProgressTracker.ProgressTracker = void 0;
	let ProgressTracker$1 = class ProgressTracker {
	    constructor() {
	        this.bytesOverall = 0;
	        this.intervalMs = 500;
	        this.onStop = noop;
	        this.onHandle = noop;
	    }
	    reportTo(onHandle = noop) {
	        this.onHandle = onHandle;
	    }
	    start(socket, name, type) {
	        let lastBytes = 0;
	        this.onStop = poll(this.intervalMs, () => {
	            const bytes = socket.bytesRead + socket.bytesWritten;
	            this.bytesOverall += bytes - lastBytes;
	            lastBytes = bytes;
	            this.onHandle({
	                name,
	                type,
	                bytes,
	                bytesOverall: this.bytesOverall
	            });
	        });
	    }
	    stop() {
	        this.onStop(false);
	    }
	    updateAndStop() {
	        this.onStop(true);
	    }
	};
	ProgressTracker.ProgressTracker = ProgressTracker$1;
	function poll(intervalMs, updateFunc) {
	    const id = setInterval(updateFunc, intervalMs);
	    const stopFunc = (stopWithUpdate) => {
	        clearInterval(id);
	        if (stopWithUpdate) {
	            updateFunc();
	        }
	        updateFunc = noop;
	    };
	    updateFunc();
	    return stopFunc;
	}
	function noop() { }
	return ProgressTracker;
}

var StringWriter = {};

var hasRequiredStringWriter;

function requireStringWriter () {
	if (hasRequiredStringWriter) return StringWriter;
	hasRequiredStringWriter = 1;
	Object.defineProperty(StringWriter, "__esModule", { value: true });
	StringWriter.StringWriter = void 0;
	const stream_1 = require$$1$3;
	let StringWriter$1 = class StringWriter extends stream_1.Writable {
	    constructor() {
	        super(...arguments);
	        this.buf = Buffer.alloc(0);
	    }
	    _write(chunk, _, callback) {
	        if (chunk instanceof Buffer) {
	            this.buf = Buffer.concat([this.buf, chunk]);
	            callback(null);
	        }
	        else {
	            callback(new Error("StringWriter expects chunks of type 'Buffer'."));
	        }
	    }
	    getText(encoding) {
	        return this.buf.toString(encoding);
	    }
	};
	StringWriter.StringWriter = StringWriter$1;
	return StringWriter;
}

var netUtils = {};

var hasRequiredNetUtils;

function requireNetUtils () {
	if (hasRequiredNetUtils) return netUtils;
	hasRequiredNetUtils = 1;
	Object.defineProperty(netUtils, "__esModule", { value: true });
	netUtils.describeTLS = describeTLS;
	netUtils.describeAddress = describeAddress;
	netUtils.upgradeSocket = upgradeSocket;
	netUtils.ipIsPrivateV4Address = ipIsPrivateV4Address;
	const tls_1 = require$$1$2;
	function describeTLS(socket) {
	    if (socket instanceof tls_1.TLSSocket) {
	        const protocol = socket.getProtocol();
	        return protocol ? protocol : "Server socket or disconnected client socket";
	    }
	    return "No encryption";
	}
	function describeAddress(socket) {
	    if (socket.remoteFamily === "IPv6") {
	        return `[${socket.remoteAddress}]:${socket.remotePort}`;
	    }
	    return `${socket.remoteAddress}:${socket.remotePort}`;
	}
	function upgradeSocket(socket, options) {
	    return new Promise((resolve, reject) => {
	        const tlsOptions = Object.assign({}, options, {
	            socket
	        });
	        const tlsSocket = (0, tls_1.connect)(tlsOptions, () => {
	            const expectCertificate = tlsOptions.rejectUnauthorized !== false;
	            if (expectCertificate && !tlsSocket.authorized) {
	                reject(tlsSocket.authorizationError);
	            }
	            else {
	                tlsSocket.removeAllListeners("error");
	                resolve(tlsSocket);
	            }
	        }).once("error", error => {
	            reject(error);
	        });
	    });
	}
	function ipIsPrivateV4Address(ip = "") {
	    if (ip.startsWith("::ffff:")) {
	        ip = ip.substr(7);
	    }
	    const octets = ip.split(".").map(o => parseInt(o, 10));
	    return octets[0] === 10
	        || (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31)
	        || (octets[0] === 192 && octets[1] === 168)
	        || ip === "127.0.0.1";
	}
	return netUtils;
}

var transfer = {};

var hasRequiredTransfer;

function requireTransfer () {
	if (hasRequiredTransfer) return transfer;
	hasRequiredTransfer = 1;
	Object.defineProperty(transfer, "__esModule", { value: true });
	transfer.enterPassiveModeIPv6 = enterPassiveModeIPv6;
	transfer.parseEpsvResponse = parseEpsvResponse;
	transfer.enterPassiveModeIPv4 = enterPassiveModeIPv4;
	transfer.enterPassiveModeIPv4_forceControlHostIP = enterPassiveModeIPv4_forceControlHostIP;
	transfer.parsePasvResponse = parsePasvResponse;
	transfer.connectForPassiveTransfer = connectForPassiveTransfer;
	transfer.uploadFrom = uploadFrom;
	transfer.downloadTo = downloadTo;
	const netUtils_1 = requireNetUtils();
	const stream_1 = require$$1$3;
	const tls_1 = require$$1$2;
	const parseControlResponse_1 = requireParseControlResponse();
	async function enterPassiveModeIPv6(ftp) {
	    const res = await ftp.request("EPSV");
	    const port = parseEpsvResponse(res.message);
	    if (!port) {
	        throw new Error("Can't parse EPSV response: " + res.message);
	    }
	    const controlHost = ftp.socket.remoteAddress;
	    if (controlHost === undefined) {
	        throw new Error("Control socket is disconnected, can't get remote address.");
	    }
	    await connectForPassiveTransfer(controlHost, port, ftp);
	    return res;
	}
	function parseEpsvResponse(message) {
	    const groups = message.match(/[|!]{3}(.+)[|!]/);
	    if (groups === null || groups[1] === undefined) {
	        throw new Error(`Can't parse response to 'EPSV': ${message}`);
	    }
	    const port = parseInt(groups[1], 10);
	    if (Number.isNaN(port)) {
	        throw new Error(`Can't parse response to 'EPSV', port is not a number: ${message}`);
	    }
	    return port;
	}
	async function enterPassiveModeIPv4(ftp) {
	    const res = await ftp.request("PASV");
	    const target = parsePasvResponse(res.message);
	    if (!target) {
	        throw new Error("Can't parse PASV response: " + res.message);
	    }
	    const controlHost = ftp.socket.remoteAddress;
	    if ((0, netUtils_1.ipIsPrivateV4Address)(target.host) && controlHost && !(0, netUtils_1.ipIsPrivateV4Address)(controlHost)) {
	        target.host = controlHost;
	    }
	    await connectForPassiveTransfer(target.host, target.port, ftp);
	    return res;
	}
	async function enterPassiveModeIPv4_forceControlHostIP(ftp) {
	    const res = await ftp.request("PASV");
	    const target = parsePasvResponse(res.message);
	    if (!target) {
	        throw new Error("Can't parse PASV response: " + res.message);
	    }
	    const controlHost = ftp.socket.remoteAddress;
	    if (controlHost === undefined) {
	        throw new Error("Control socket is disconnected, can't get remote address.");
	    }
	    await connectForPassiveTransfer(controlHost, target.port, ftp);
	    return res;
	}
	function parsePasvResponse(message) {
	    const groups = message.match(/([-\d]+,[-\d]+,[-\d]+,[-\d]+),([-\d]+),([-\d]+)/);
	    if (groups === null || groups.length !== 4) {
	        throw new Error(`Can't parse response to 'PASV': ${message}`);
	    }
	    return {
	        host: groups[1].replace(/,/g, "."),
	        port: (parseInt(groups[2], 10) & 255) * 256 + (parseInt(groups[3], 10) & 255)
	    };
	}
	function connectForPassiveTransfer(host, port, ftp) {
	    return new Promise((resolve, reject) => {
	        let socket = ftp._newSocket();
	        const handleConnErr = function (err) {
	            err.message = "Can't open data connection in passive mode: " + err.message;
	            reject(err);
	        };
	        const handleTimeout = function () {
	            socket.destroy();
	            reject(new Error(`Timeout when trying to open data connection to ${host}:${port}`));
	        };
	        socket.setTimeout(ftp.timeout);
	        socket.on("error", handleConnErr);
	        socket.on("timeout", handleTimeout);
	        socket.connect({ port, host, family: ftp.ipFamily }, () => {
	            if (ftp.socket instanceof tls_1.TLSSocket) {
	                socket = (0, tls_1.connect)(Object.assign({}, ftp.tlsOptions, {
	                    socket,
	                    session: ftp.socket.getSession()
	                }));
	            }
	            socket.removeListener("error", handleConnErr);
	            socket.removeListener("timeout", handleTimeout);
	            ftp.dataSocket = socket;
	            resolve();
	        });
	    });
	}
	class TransferResolver {
	    constructor(ftp, progress) {
	        this.ftp = ftp;
	        this.progress = progress;
	        this.response = undefined;
	        this.dataTransferDone = false;
	    }
	    onDataStart(name, type) {
	        if (this.ftp.dataSocket === undefined) {
	            throw new Error("Data transfer should start but there is no data connection.");
	        }
	        this.ftp.socket.setTimeout(0);
	        this.ftp.dataSocket.setTimeout(this.ftp.timeout);
	        this.progress.start(this.ftp.dataSocket, name, type);
	    }
	    onDataDone(task) {
	        this.progress.updateAndStop();
	        this.ftp.socket.setTimeout(this.ftp.timeout);
	        if (this.ftp.dataSocket) {
	            this.ftp.dataSocket.setTimeout(0);
	        }
	        this.dataTransferDone = true;
	        this.tryResolve(task);
	    }
	    onControlDone(task, response) {
	        this.response = response;
	        this.tryResolve(task);
	    }
	    onError(task, err) {
	        this.progress.updateAndStop();
	        this.ftp.socket.setTimeout(this.ftp.timeout);
	        this.ftp.dataSocket = undefined;
	        task.reject(err);
	    }
	    onUnexpectedRequest(response) {
	        const err = new Error(`Unexpected FTP response is requesting an answer: ${response.message}`);
	        this.ftp.closeWithError(err);
	    }
	    tryResolve(task) {
	        const canResolve = this.dataTransferDone && this.response !== undefined;
	        if (canResolve) {
	            this.ftp.dataSocket = undefined;
	            task.resolve(this.response);
	        }
	    }
	}
	function uploadFrom(source, config) {
	    const resolver = new TransferResolver(config.ftp, config.tracker);
	    const fullCommand = `${config.command} ${config.remotePath}`;
	    return config.ftp.handle(fullCommand, (res, task) => {
	        if (res instanceof Error) {
	            resolver.onError(task, res);
	        }
	        else if (res.code === 150 || res.code === 125) {
	            const dataSocket = config.ftp.dataSocket;
	            if (!dataSocket) {
	                resolver.onError(task, new Error("Upload should begin but no data connection is available."));
	                return;
	            }
	            const canUpload = "getCipher" in dataSocket ? dataSocket.getCipher() !== undefined : true;
	            onConditionOrEvent(canUpload, dataSocket, "secureConnect", () => {
	                config.ftp.log(`Uploading to ${(0, netUtils_1.describeAddress)(dataSocket)} (${(0, netUtils_1.describeTLS)(dataSocket)})`);
	                resolver.onDataStart(config.remotePath, config.type);
	                (0, stream_1.pipeline)(source, dataSocket, err => {
	                    if (err) {
	                        resolver.onError(task, err);
	                    }
	                    else {
	                        resolver.onDataDone(task);
	                    }
	                });
	            });
	        }
	        else if ((0, parseControlResponse_1.positiveCompletion)(res.code)) {
	            resolver.onControlDone(task, res);
	        }
	        else if ((0, parseControlResponse_1.positiveIntermediate)(res.code)) {
	            resolver.onUnexpectedRequest(res);
	        }
	    });
	}
	function downloadTo(destination, config) {
	    if (!config.ftp.dataSocket) {
	        throw new Error("Download will be initiated but no data connection is available.");
	    }
	    const resolver = new TransferResolver(config.ftp, config.tracker);
	    return config.ftp.handle(config.command, (res, task) => {
	        if (res instanceof Error) {
	            resolver.onError(task, res);
	        }
	        else if (res.code === 150 || res.code === 125) {
	            const dataSocket = config.ftp.dataSocket;
	            if (!dataSocket) {
	                resolver.onError(task, new Error("Download should begin but no data connection is available."));
	                return;
	            }
	            config.ftp.log(`Downloading from ${(0, netUtils_1.describeAddress)(dataSocket)} (${(0, netUtils_1.describeTLS)(dataSocket)})`);
	            resolver.onDataStart(config.remotePath, config.type);
	            (0, stream_1.pipeline)(dataSocket, destination, err => {
	                if (err) {
	                    resolver.onError(task, err);
	                }
	                else {
	                    resolver.onDataDone(task);
	                }
	            });
	        }
	        else if (res.code === 350) {
	            config.ftp.send("RETR " + config.remotePath);
	        }
	        else if ((0, parseControlResponse_1.positiveCompletion)(res.code)) {
	            resolver.onControlDone(task, res);
	        }
	        else if ((0, parseControlResponse_1.positiveIntermediate)(res.code)) {
	            resolver.onUnexpectedRequest(res);
	        }
	    });
	}
	function onConditionOrEvent(condition, emitter, eventName, action) {
	    if (condition === true) {
	        action();
	    }
	    else {
	        emitter.once(eventName, () => action());
	    }
	}
	return transfer;
}

var hasRequiredClient;

function requireClient () {
	if (hasRequiredClient) return Client;
	hasRequiredClient = 1;
	Object.defineProperty(Client, "__esModule", { value: true });
	Client.Client = void 0;
	const fs_1 = require$$0$3;
	const path_1 = require$$0$4;
	const tls_1 = require$$1$2;
	const util_1 = require$$0$2;
	const FtpContext_1 = requireFtpContext();
	const parseList_1 = requireParseList();
	const ProgressTracker_1 = requireProgressTracker();
	const StringWriter_1 = requireStringWriter();
	const parseListMLSD_1 = requireParseListMLSD();
	const netUtils_1 = requireNetUtils();
	const transfer_1 = requireTransfer();
	const parseControlResponse_1 = requireParseControlResponse();
	const fsReadDir = (0, util_1.promisify)(fs_1.readdir);
	const fsMkDir = (0, util_1.promisify)(fs_1.mkdir);
	const fsStat = (0, util_1.promisify)(fs_1.stat);
	const fsOpen = (0, util_1.promisify)(fs_1.open);
	const fsClose = (0, util_1.promisify)(fs_1.close);
	const fsUnlink = (0, util_1.promisify)(fs_1.unlink);
	const defaultClientOptions = {
	    allowSeparateTransferHost: true
	};
	const LIST_COMMANDS_DEFAULT = () => ["LIST -a", "LIST"];
	const LIST_COMMANDS_MLSD = () => ["MLSD", "LIST -a", "LIST"];
	let Client$1 = class Client {
	    constructor(timeout = 30000, options = defaultClientOptions) {
	        this.availableListCommands = LIST_COMMANDS_DEFAULT();
	        this.ftp = new FtpContext_1.FTPContext(timeout);
	        this.prepareTransfer = this._enterFirstCompatibleMode([
	            transfer_1.enterPassiveModeIPv6,
	            options.allowSeparateTransferHost ? transfer_1.enterPassiveModeIPv4 : transfer_1.enterPassiveModeIPv4_forceControlHostIP
	        ]);
	        this.parseList = parseList_1.parseList;
	        this._progressTracker = new ProgressTracker_1.ProgressTracker();
	    }
	    close() {
	        this.ftp.close();
	        this._progressTracker.stop();
	    }
	    get closed() {
	        return this.ftp.closed;
	    }
	    connect(host = "localhost", port = 21) {
	        this.ftp.reset();
	        this.ftp.socket.connect({
	            host,
	            port,
	            family: this.ftp.ipFamily
	        }, () => this.ftp.log(`Connected to ${(0, netUtils_1.describeAddress)(this.ftp.socket)} (${(0, netUtils_1.describeTLS)(this.ftp.socket)})`));
	        return this._handleConnectResponse();
	    }
	    connectImplicitTLS(host = "localhost", port = 21, tlsOptions = {}) {
	        this.ftp.reset();
	        this.ftp.socket = (0, tls_1.connect)(port, host, tlsOptions, () => this.ftp.log(`Connected to ${(0, netUtils_1.describeAddress)(this.ftp.socket)} (${(0, netUtils_1.describeTLS)(this.ftp.socket)})`));
	        this.ftp.tlsOptions = tlsOptions;
	        return this._handleConnectResponse();
	    }
	    _handleConnectResponse() {
	        return this.ftp.handle(undefined, (res, task) => {
	            if (res instanceof Error) {
	                task.reject(res);
	            }
	            else if ((0, parseControlResponse_1.positiveCompletion)(res.code)) {
	                task.resolve(res);
	            }
	            else {
	                task.reject(new FtpContext_1.FTPError(res));
	            }
	        });
	    }
	    send(command, ignoreErrorCodesDEPRECATED = false) {
	        if (ignoreErrorCodesDEPRECATED) {
	            this.ftp.log("Deprecated call using send(command, flag) with boolean flag to ignore errors. Use sendIgnoringError(command).");
	            return this.sendIgnoringError(command);
	        }
	        return this.ftp.request(command);
	    }
	    sendIgnoringError(command) {
	        return this.ftp.handle(command, (res, task) => {
	            if (res instanceof FtpContext_1.FTPError) {
	                task.resolve({ code: res.code, message: res.message });
	            }
	            else if (res instanceof Error) {
	                task.reject(res);
	            }
	            else {
	                task.resolve(res);
	            }
	        });
	    }
	    async useTLS(options = {}, command = "AUTH TLS") {
	        const ret = await this.send(command);
	        this.ftp.socket = await (0, netUtils_1.upgradeSocket)(this.ftp.socket, options);
	        this.ftp.tlsOptions = options;
	        this.ftp.log(`Control socket is using: ${(0, netUtils_1.describeTLS)(this.ftp.socket)}`);
	        return ret;
	    }
	    login(user = "anonymous", password = "guest") {
	        this.ftp.log(`Login security: ${(0, netUtils_1.describeTLS)(this.ftp.socket)}`);
	        return this.ftp.handle("USER " + user, (res, task) => {
	            if (res instanceof Error) {
	                task.reject(res);
	            }
	            else if ((0, parseControlResponse_1.positiveCompletion)(res.code)) {
	                task.resolve(res);
	            }
	            else if (res.code === 331) {
	                this.ftp.send("PASS " + password);
	            }
	            else {
	                task.reject(new FtpContext_1.FTPError(res));
	            }
	        });
	    }
	    async useDefaultSettings() {
	        const features = await this.features();
	        const supportsMLSD = features.has("MLST");
	        this.availableListCommands = supportsMLSD ? LIST_COMMANDS_MLSD() : LIST_COMMANDS_DEFAULT();
	        await this.send("TYPE I");
	        await this.sendIgnoringError("STRU F");
	        await this.sendIgnoringError("OPTS UTF8 ON");
	        if (supportsMLSD) {
	            await this.sendIgnoringError("OPTS MLST type;size;modify;unique;unix.mode;unix.owner;unix.group;unix.ownername;unix.groupname;");
	        }
	        if (this.ftp.hasTLS) {
	            await this.sendIgnoringError("PBSZ 0");
	            await this.sendIgnoringError("PROT P");
	        }
	    }
	    async access(options = {}) {
	        var _a, _b;
	        const useExplicitTLS = options.secure === true;
	        const useImplicitTLS = options.secure === "implicit";
	        let welcome;
	        if (useImplicitTLS) {
	            welcome = await this.connectImplicitTLS(options.host, options.port, options.secureOptions);
	        }
	        else {
	            welcome = await this.connect(options.host, options.port);
	        }
	        if (useExplicitTLS) {
	            const secureOptions = (_a = options.secureOptions) !== null && _a !== void 0 ? _a : {};
	            secureOptions.host = (_b = secureOptions.host) !== null && _b !== void 0 ? _b : options.host;
	            await this.useTLS(secureOptions);
	        }
	        await this.sendIgnoringError("OPTS UTF8 ON");
	        await this.login(options.user, options.password);
	        await this.useDefaultSettings();
	        return welcome;
	    }
	    async pwd() {
	        const res = await this.send("PWD");
	        const parsed = res.message.match(/"(.+)"/);
	        if (parsed === null || parsed[1] === undefined) {
	            throw new Error(`Can't parse response to command 'PWD': ${res.message}`);
	        }
	        return parsed[1];
	    }
	    async features() {
	        const res = await this.sendIgnoringError("FEAT");
	        const features = new Map();
	        if (res.code < 400 && (0, parseControlResponse_1.isMultiline)(res.message)) {
	            res.message.split("\n").slice(1, -1).forEach(line => {
	                const entry = line.trim().split(" ");
	                features.set(entry[0], entry[1] || "");
	            });
	        }
	        return features;
	    }
	    async cd(path) {
	        const validPath = await this.protectWhitespace(path);
	        return this.send("CWD " + validPath);
	    }
	    async cdup() {
	        return this.send("CDUP");
	    }
	    async lastMod(path) {
	        const validPath = await this.protectWhitespace(path);
	        const res = await this.send(`MDTM ${validPath}`);
	        const date = res.message.slice(4);
	        return (0, parseListMLSD_1.parseMLSxDate)(date);
	    }
	    async size(path) {
	        const validPath = await this.protectWhitespace(path);
	        const command = `SIZE ${validPath}`;
	        const res = await this.send(command);
	        const size = parseInt(res.message.slice(4), 10);
	        if (Number.isNaN(size)) {
	            throw new Error(`Can't parse response to command '${command}' as a numerical value: ${res.message}`);
	        }
	        return size;
	    }
	    async rename(srcPath, destPath) {
	        const validSrc = await this.protectWhitespace(srcPath);
	        const validDest = await this.protectWhitespace(destPath);
	        await this.send("RNFR " + validSrc);
	        return this.send("RNTO " + validDest);
	    }
	    async remove(path, ignoreErrorCodes = false) {
	        const validPath = await this.protectWhitespace(path);
	        if (ignoreErrorCodes) {
	            return this.sendIgnoringError(`DELE ${validPath}`);
	        }
	        return this.send(`DELE ${validPath}`);
	    }
	    trackProgress(handler) {
	        this._progressTracker.bytesOverall = 0;
	        this._progressTracker.reportTo(handler);
	    }
	    async uploadFrom(source, toRemotePath, options = {}) {
	        return this._uploadWithCommand(source, toRemotePath, "STOR", options);
	    }
	    async appendFrom(source, toRemotePath, options = {}) {
	        return this._uploadWithCommand(source, toRemotePath, "APPE", options);
	    }
	    async _uploadWithCommand(source, remotePath, command, options) {
	        if (typeof source === "string") {
	            return this._uploadLocalFile(source, remotePath, command, options);
	        }
	        return this._uploadFromStream(source, remotePath, command);
	    }
	    async _uploadLocalFile(localPath, remotePath, command, options) {
	        const fd = await fsOpen(localPath, "r");
	        const source = (0, fs_1.createReadStream)("", {
	            fd,
	            start: options.localStart,
	            end: options.localEndInclusive,
	            autoClose: false
	        });
	        try {
	            return await this._uploadFromStream(source, remotePath, command);
	        }
	        finally {
	            await ignoreError(() => fsClose(fd));
	        }
	    }
	    async _uploadFromStream(source, remotePath, command) {
	        const onError = (err) => this.ftp.closeWithError(err);
	        source.once("error", onError);
	        try {
	            const validPath = await this.protectWhitespace(remotePath);
	            await this.prepareTransfer(this.ftp);
	            return await (0, transfer_1.uploadFrom)(source, {
	                ftp: this.ftp,
	                tracker: this._progressTracker,
	                command,
	                remotePath: validPath,
	                type: "upload"
	            });
	        }
	        finally {
	            source.removeListener("error", onError);
	        }
	    }
	    async downloadTo(destination, fromRemotePath, startAt = 0) {
	        if (typeof destination === "string") {
	            return this._downloadToFile(destination, fromRemotePath, startAt);
	        }
	        return this._downloadToStream(destination, fromRemotePath, startAt);
	    }
	    async _downloadToFile(localPath, remotePath, startAt) {
	        const appendingToLocalFile = startAt > 0;
	        const fileSystemFlags = appendingToLocalFile ? "r+" : "w";
	        const fd = await fsOpen(localPath, fileSystemFlags);
	        const destination = (0, fs_1.createWriteStream)("", {
	            fd,
	            start: startAt,
	            autoClose: false
	        });
	        try {
	            return await this._downloadToStream(destination, remotePath, startAt);
	        }
	        catch (err) {
	            const localFileStats = await ignoreError(() => fsStat(localPath));
	            const hasDownloadedData = localFileStats && localFileStats.size > 0;
	            const shouldRemoveLocalFile = !appendingToLocalFile && !hasDownloadedData;
	            if (shouldRemoveLocalFile) {
	                await ignoreError(() => fsUnlink(localPath));
	            }
	            throw err;
	        }
	        finally {
	            await ignoreError(() => fsClose(fd));
	        }
	    }
	    async _downloadToStream(destination, remotePath, startAt) {
	        const onError = (err) => this.ftp.closeWithError(err);
	        destination.once("error", onError);
	        try {
	            const validPath = await this.protectWhitespace(remotePath);
	            await this.prepareTransfer(this.ftp);
	            return await (0, transfer_1.downloadTo)(destination, {
	                ftp: this.ftp,
	                tracker: this._progressTracker,
	                command: startAt > 0 ? `REST ${startAt}` : `RETR ${validPath}`,
	                remotePath: validPath,
	                type: "download"
	            });
	        }
	        finally {
	            destination.removeListener("error", onError);
	            destination.end();
	        }
	    }
	    async list(path = "") {
	        const validPath = await this.protectWhitespace(path);
	        let lastError;
	        for (const candidate of this.availableListCommands) {
	            const command = validPath === "" ? candidate : `${candidate} ${validPath}`;
	            await this.prepareTransfer(this.ftp);
	            try {
	                const parsedList = await this._requestListWithCommand(command);
	                this.availableListCommands = [candidate];
	                return parsedList;
	            }
	            catch (err) {
	                const shouldTryNext = err instanceof FtpContext_1.FTPError;
	                if (!shouldTryNext) {
	                    throw err;
	                }
	                lastError = err;
	            }
	        }
	        throw lastError;
	    }
	    async _requestListWithCommand(command) {
	        const buffer = new StringWriter_1.StringWriter();
	        await (0, transfer_1.downloadTo)(buffer, {
	            ftp: this.ftp,
	            tracker: this._progressTracker,
	            command,
	            remotePath: "",
	            type: "list"
	        });
	        const text = buffer.getText(this.ftp.encoding);
	        this.ftp.log(text);
	        return this.parseList(text);
	    }
	    async removeDir(remoteDirPath) {
	        return this._exitAtCurrentDirectory(async () => {
	            await this.cd(remoteDirPath);
	            const absoluteDirPath = await this.pwd();
	            await this.clearWorkingDir();
	            const dirIsRoot = absoluteDirPath === "/";
	            if (!dirIsRoot) {
	                await this.cdup();
	                await this.removeEmptyDir(absoluteDirPath);
	            }
	        });
	    }
	    async clearWorkingDir() {
	        for (const file of await this.list()) {
	            if (file.isDirectory) {
	                await this.cd(file.name);
	                await this.clearWorkingDir();
	                await this.cdup();
	                await this.removeEmptyDir(file.name);
	            }
	            else {
	                await this.remove(file.name);
	            }
	        }
	    }
	    async uploadFromDir(localDirPath, remoteDirPath) {
	        return this._exitAtCurrentDirectory(async () => {
	            if (remoteDirPath) {
	                await this.ensureDir(remoteDirPath);
	            }
	            return await this._uploadToWorkingDir(localDirPath);
	        });
	    }
	    async _uploadToWorkingDir(localDirPath) {
	        const files = await fsReadDir(localDirPath);
	        for (const file of files) {
	            const fullPath = (0, path_1.join)(localDirPath, file);
	            const stats = await fsStat(fullPath);
	            if (stats.isFile()) {
	                await this.uploadFrom(fullPath, file);
	            }
	            else if (stats.isDirectory()) {
	                await this._openDir(file);
	                await this._uploadToWorkingDir(fullPath);
	                await this.cdup();
	            }
	        }
	    }
	    async downloadToDir(localDirPath, remoteDirPath) {
	        return this._exitAtCurrentDirectory(async () => {
	            if (remoteDirPath) {
	                await this.cd(remoteDirPath);
	            }
	            return await this._downloadFromWorkingDir(localDirPath);
	        });
	    }
	    async _downloadFromWorkingDir(localDirPath) {
	        await ensureLocalDirectory(localDirPath);
	        for (const file of await this.list()) {
	            const hasInvalidName = !file.name || (0, path_1.basename)(file.name) !== file.name;
	            if (hasInvalidName) {
	                const safeName = JSON.stringify(file.name);
	                this.ftp.log(`Invalid filename from server listing, will skip file. (${safeName})`);
	                continue;
	            }
	            const localPath = (0, path_1.join)(localDirPath, file.name);
	            if (file.isDirectory) {
	                await this.cd(file.name);
	                await this._downloadFromWorkingDir(localPath);
	                await this.cdup();
	            }
	            else if (file.isFile) {
	                await this.downloadTo(localPath, file.name);
	            }
	        }
	    }
	    async ensureDir(remoteDirPath) {
	        if (remoteDirPath.startsWith("/")) {
	            await this.cd("/");
	        }
	        const names = remoteDirPath.split("/").filter(name => name !== "");
	        for (const name of names) {
	            await this._openDir(name);
	        }
	    }
	    async _openDir(dirName) {
	        await this.sendIgnoringError("MKD " + dirName);
	        await this.cd(dirName);
	    }
	    async removeEmptyDir(path) {
	        const validPath = await this.protectWhitespace(path);
	        return this.send(`RMD ${validPath}`);
	    }
	    async protectWhitespace(path) {
	        if (!path.startsWith(" ")) {
	            return path;
	        }
	        const pwd = await this.pwd();
	        const absolutePathPrefix = pwd.endsWith("/") ? pwd : pwd + "/";
	        return absolutePathPrefix + path;
	    }
	    async _exitAtCurrentDirectory(func) {
	        const userDir = await this.pwd();
	        try {
	            return await func();
	        }
	        finally {
	            if (!this.closed) {
	                await ignoreError(() => this.cd(userDir));
	            }
	        }
	    }
	    _enterFirstCompatibleMode(strategies) {
	        return async (ftp) => {
	            ftp.log("Trying to find optimal transfer strategy...");
	            let lastError = undefined;
	            for (const strategy of strategies) {
	                try {
	                    const res = await strategy(ftp);
	                    ftp.log("Optimal transfer strategy found.");
	                    this.prepareTransfer = strategy;
	                    return res;
	                }
	                catch (err) {
	                    lastError = err;
	                }
	            }
	            throw new Error(`None of the available transfer strategies work. Last error response was '${lastError}'.`);
	        };
	    }
	    async upload(source, toRemotePath, options = {}) {
	        this.ftp.log("Warning: upload() has been deprecated, use uploadFrom().");
	        return this.uploadFrom(source, toRemotePath, options);
	    }
	    async append(source, toRemotePath, options = {}) {
	        this.ftp.log("Warning: append() has been deprecated, use appendFrom().");
	        return this.appendFrom(source, toRemotePath, options);
	    }
	    async download(destination, fromRemotePath, startAt = 0) {
	        this.ftp.log("Warning: download() has been deprecated, use downloadTo().");
	        return this.downloadTo(destination, fromRemotePath, startAt);
	    }
	    async uploadDir(localDirPath, remoteDirPath) {
	        this.ftp.log("Warning: uploadDir() has been deprecated, use uploadFromDir().");
	        return this.uploadFromDir(localDirPath, remoteDirPath);
	    }
	    async downloadDir(localDirPath) {
	        this.ftp.log("Warning: downloadDir() has been deprecated, use downloadToDir().");
	        return this.downloadToDir(localDirPath);
	    }
	};
	Client.Client = Client$1;
	async function ensureLocalDirectory(path) {
	    try {
	        await fsStat(path);
	    }
	    catch (_a) {
	        await fsMkDir(path, { recursive: true });
	    }
	}
	async function ignoreError(func) {
	    try {
	        return await func();
	    }
	    catch (_a) {
	        return undefined;
	    }
	}
	return Client;
}

var StringEncoding = {};

var hasRequiredStringEncoding;

function requireStringEncoding () {
	if (hasRequiredStringEncoding) return StringEncoding;
	hasRequiredStringEncoding = 1;
	Object.defineProperty(StringEncoding, "__esModule", { value: true });
	return StringEncoding;
}

var hasRequiredDist$6;

function requireDist$6 () {
	if (hasRequiredDist$6) return dist$3;
	hasRequiredDist$6 = 1;
	(function (exports$1) {
		var __createBinding = (dist$3 && dist$3.__createBinding) || (Object.create ? (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    var desc = Object.getOwnPropertyDescriptor(m, k);
		    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
		      desc = { enumerable: true, get: function() { return m[k]; } };
		    }
		    Object.defineProperty(o, k2, desc);
		}) : (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    o[k2] = m[k];
		}));
		var __exportStar = (dist$3 && dist$3.__exportStar) || function(m, exports$1) {
		    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.enterPassiveModeIPv6 = exports$1.enterPassiveModeIPv4 = void 0;
		__exportStar(requireClient(), exports$1);
		__exportStar(requireFtpContext(), exports$1);
		__exportStar(requireFileInfo(), exports$1);
		__exportStar(requireParseList(), exports$1);
		__exportStar(requireStringEncoding(), exports$1);
		var transfer_1 = requireTransfer();
		Object.defineProperty(exports$1, "enterPassiveModeIPv4", { enumerable: true, get: function () { return transfer_1.enterPassiveModeIPv4; } });
		Object.defineProperty(exports$1, "enterPassiveModeIPv6", { enumerable: true, get: function () { return transfer_1.enterPassiveModeIPv6; } }); 
	} (dist$3));
	return dist$3;
}

var hasRequiredFtp;

function requireFtp () {
	if (hasRequiredFtp) return ftp;
	hasRequiredFtp = 1;
	var __importDefault = (ftp && ftp.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(ftp, "__esModule", { value: true });
	ftp.ftp = void 0;
	const basic_ftp_1 = requireDist$6();
	const stream_1 = require$$1$3;
	const path_1 = require$$0$4;
	const debug_1 = __importDefault(requireSrc());
	const notfound_1 = __importDefault(requireNotfound());
	const notmodified_1 = __importDefault(requireNotmodified());
	const debug = (0, debug_1.default)('get-uri:ftp');
	const ftp$1 = async (url, opts = {}) => {
	    const { cache } = opts;
	    const filepath = decodeURIComponent(url.pathname);
	    let lastModified;
	    if (!filepath) {
	        throw new TypeError('No "pathname"!');
	    }
	    const client = new basic_ftp_1.Client();
	    try {
	        const host = url.hostname || url.host || 'localhost';
	        const port = parseInt(url.port || '0', 10) || 21;
	        const user = url.username
	            ? decodeURIComponent(url.username)
	            : undefined;
	        const password = url.password
	            ? decodeURIComponent(url.password)
	            : undefined;
	        await client.access({
	            host,
	            port,
	            user,
	            password,
	            ...opts,
	        });
	        try {
	            lastModified = await client.lastMod(filepath);
	        }
	        catch (err) {
	            if (err.code === 550) {
	                throw new notfound_1.default();
	            }
	        }
	        if (!lastModified) {
	            const list = await client.list((0, path_1.dirname)(filepath));
	            const name = (0, path_1.basename)(filepath);
	            const entry = list.find((e) => e.name === name);
	            if (entry) {
	                lastModified = entry.modifiedAt;
	            }
	        }
	        if (lastModified) {
	            if (isNotModified()) {
	                throw new notmodified_1.default();
	            }
	        }
	        else {
	            throw new notfound_1.default();
	        }
	        const stream = new stream_1.PassThrough();
	        const rs = stream;
	        client.downloadTo(stream, filepath).then((result) => {
	            debug(result.message);
	            client.close();
	        });
	        rs.lastModified = lastModified;
	        return rs;
	    }
	    catch (err) {
	        client.close();
	        throw err;
	    }
	    function isNotModified() {
	        if (cache?.lastModified && lastModified) {
	            return +cache.lastModified === +lastModified;
	        }
	        return false;
	    }
	};
	ftp.ftp = ftp$1;
	return ftp;
}

var http = {};

var httpError = {};

var hasRequiredHttpError;

function requireHttpError () {
	if (hasRequiredHttpError) return httpError;
	hasRequiredHttpError = 1;
	Object.defineProperty(httpError, "__esModule", { value: true });
	const http_1 = require$$0$6;
	class HTTPError extends Error {
	    constructor(statusCode, message = http_1.STATUS_CODES[statusCode]) {
	        super(message);
	        this.statusCode = statusCode;
	        this.code = `E${String(message).toUpperCase().replace(/\s+/g, '')}`;
	    }
	}
	httpError.default = HTTPError;
	return httpError;
}

var hasRequiredHttp;

function requireHttp () {
	if (hasRequiredHttp) return http;
	hasRequiredHttp = 1;
	(function (exports$1) {
		var __importDefault = (http && http.__importDefault) || function (mod) {
		    return (mod && mod.__esModule) ? mod : { "default": mod };
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.http = void 0;
		const http_1 = __importDefault(require$$0$6);
		const https_1 = __importDefault(require$$1$1);
		const events_1 = require$$0$8;
		const debug_1 = __importDefault(requireSrc());
		const http_error_1 = __importDefault(requireHttpError());
		const notfound_1 = __importDefault(requireNotfound());
		const notmodified_1 = __importDefault(requireNotmodified());
		const debug = (0, debug_1.default)('get-uri:http');
		const http$1 = async (url, opts = {}) => {
		    debug('GET %o', url.href);
		    const cache = getCache(url, opts.cache);
		    if (cache && isFresh(cache) && typeof cache.statusCode === 'number') {
		        const type = (cache.statusCode / 100) | 0;
		        if (type === 3 && cache.headers.location) {
		            debug('cached redirect');
		            throw new Error('TODO: implement cached redirects!');
		        }
		        throw new notmodified_1.default();
		    }
		    const maxRedirects = typeof opts.maxRedirects === 'number' ? opts.maxRedirects : 5;
		    debug('allowing %o max redirects', maxRedirects);
		    let mod;
		    if (opts.http) {
		        mod = opts.http;
		        debug('using secure `https` core module');
		    }
		    else {
		        mod = http_1.default;
		        debug('using `http` core module');
		    }
		    const options = { ...opts };
		    if (cache) {
		        if (!options.headers) {
		            options.headers = {};
		        }
		        const lastModified = cache.headers['last-modified'];
		        if (lastModified) {
		            options.headers['If-Modified-Since'] = lastModified;
		            debug('added "If-Modified-Since" request header: %o', lastModified);
		        }
		        const etag = cache.headers.etag;
		        if (etag) {
		            options.headers['If-None-Match'] = etag;
		            debug('added "If-None-Match" request header: %o', etag);
		        }
		    }
		    const req = mod.get(url, options);
		    const [res] = await (0, events_1.once)(req, 'response');
		    const code = res.statusCode || 0;
		    res.date = Date.now();
		    res.parsed = url;
		    debug('got %o response status code', code);
		    const type = (code / 100) | 0;
		    const location = res.headers.location;
		    if (type === 3 && location) {
		        if (!opts.redirects)
		            opts.redirects = [];
		        const redirects = opts.redirects;
		        if (redirects.length < maxRedirects) {
		            debug('got a "redirect" status code with Location: %o', location);
		            res.resume();
		            redirects.push(res);
		            const newUri = new URL(location, url.href);
		            debug('resolved redirect URL: %o', newUri.href);
		            const left = maxRedirects - redirects.length;
		            debug('%o more redirects allowed after this one', left);
		            if (newUri.protocol !== url.protocol) {
		                opts.http = newUri.protocol === 'https:' ? https_1.default : undefined;
		            }
		            return (0, exports$1.http)(newUri, opts);
		        }
		    }
		    if (type !== 2) {
		        res.resume();
		        if (code === 304) {
		            throw new notmodified_1.default();
		        }
		        else if (code === 404) {
		            throw new notfound_1.default();
		        }
		        throw new http_error_1.default(code);
		    }
		    if (opts.redirects) {
		        res.redirects = opts.redirects;
		    }
		    return res;
		};
		exports$1.http = http$1;
		function isFresh(cache) {
		    let fresh = false;
		    let expires = parseInt(cache.headers.expires || '', 10);
		    const cacheControl = cache.headers['cache-control'];
		    if (cacheControl) {
		        debug('Cache-Control: %o', cacheControl);
		        const parts = cacheControl.split(/,\s*?\b/);
		        for (let i = 0; i < parts.length; i++) {
		            const part = parts[i];
		            const subparts = part.split('=');
		            const name = subparts[0];
		            switch (name) {
		                case 'max-age':
		                    expires =
		                        (cache.date || 0) + parseInt(subparts[1], 10) * 1000;
		                    fresh = Date.now() < expires;
		                    if (fresh) {
		                        debug('cache is "fresh" due to previous %o Cache-Control param', part);
		                    }
		                    return fresh;
		                case 'must-revalidate':
		                    break;
		                case 'no-cache':
		                case 'no-store':
		                    debug('cache is "stale" due to explicit %o Cache-Control param', name);
		                    return false;
		            }
		        }
		    }
		    else if (expires) {
		        debug('Expires: %o', expires);
		        fresh = Date.now() < expires;
		        if (fresh) {
		            debug('cache is "fresh" due to previous Expires response header');
		        }
		        return fresh;
		    }
		    return false;
		}
		function getCache(url, cache) {
		    if (cache) {
		        if (cache.parsed && cache.parsed.href === url.href) {
		            return cache;
		        }
		        if (cache.redirects) {
		            for (let i = 0; i < cache.redirects.length; i++) {
		                const c = getCache(url, cache.redirects[i]);
		                if (c) {
		                    return c;
		                }
		            }
		        }
		    }
		    return null;
		} 
	} (http));
	return http;
}

var https = {};

var hasRequiredHttps;

function requireHttps () {
	if (hasRequiredHttps) return https;
	hasRequiredHttps = 1;
	var __importDefault = (https && https.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(https, "__esModule", { value: true });
	https.https = void 0;
	const https_1 = __importDefault(require$$1$1);
	const http_1 = requireHttp();
	const https$1 = (url, opts) => {
	    return (0, http_1.http)(url, { ...opts, http: https_1.default });
	};
	https.https = https$1;
	return https;
}

var hasRequiredDist$5;

function requireDist$5 () {
	if (hasRequiredDist$5) return dist$5;
	hasRequiredDist$5 = 1;
	(function (exports$1) {
		var __importDefault = (dist$5 && dist$5.__importDefault) || function (mod) {
		    return (mod && mod.__esModule) ? mod : { "default": mod };
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.getUri = exports$1.isValidProtocol = exports$1.protocols = void 0;
		const debug_1 = __importDefault(requireSrc());
		const data_1 = requireData();
		const file_1 = requireFile();
		const ftp_1 = requireFtp();
		const http_1 = requireHttp();
		const https_1 = requireHttps();
		const debug = (0, debug_1.default)('get-uri');
		exports$1.protocols = {
		    data: data_1.data,
		    file: file_1.file,
		    ftp: ftp_1.ftp,
		    http: http_1.http,
		    https: https_1.https,
		};
		const VALID_PROTOCOLS = new Set(Object.keys(exports$1.protocols));
		function isValidProtocol(p) {
		    return VALID_PROTOCOLS.has(p);
		}
		exports$1.isValidProtocol = isValidProtocol;
		async function getUri(uri, opts) {
		    debug('getUri(%o)', uri);
		    if (!uri) {
		        throw new TypeError('Must pass in a URI to "getUri()"');
		    }
		    const url = typeof uri === 'string' ? new URL(uri) : uri;
		    const protocol = url.protocol.replace(/:$/, '');
		    if (!isValidProtocol(protocol)) {
		        throw new TypeError(`Unsupported protocol "${protocol}" specified in URI: "${uri}"`);
		    }
		    const getter = exports$1.protocols[protocol];
		    return getter(url, opts);
		}
		exports$1.getUri = getUri; 
	} (dist$5));
	return dist$5;
}

var dist$2 = {};

var dist$1 = {};

var degenerator = {};

var escodegen = {};

var estraverse = {};

/*
  Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
  Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var hasRequiredEstraverse;

function requireEstraverse () {
	if (hasRequiredEstraverse) return estraverse;
	hasRequiredEstraverse = 1;
	(function (exports$1) {
		(function clone(exports$1) {
		    var Syntax,
		        VisitorOption,
		        VisitorKeys,
		        BREAK,
		        SKIP,
		        REMOVE;
		    function deepCopy(obj) {
		        var ret = {}, key, val;
		        for (key in obj) {
		            if (obj.hasOwnProperty(key)) {
		                val = obj[key];
		                if (typeof val === 'object' && val !== null) {
		                    ret[key] = deepCopy(val);
		                } else {
		                    ret[key] = val;
		                }
		            }
		        }
		        return ret;
		    }
		    function upperBound(array, func) {
		        var diff, len, i, current;
		        len = array.length;
		        i = 0;
		        while (len) {
		            diff = len >>> 1;
		            current = i + diff;
		            if (func(array[current])) {
		                len = diff;
		            } else {
		                i = current + 1;
		                len -= diff + 1;
		            }
		        }
		        return i;
		    }
		    Syntax = {
		        AssignmentExpression: 'AssignmentExpression',
		        AssignmentPattern: 'AssignmentPattern',
		        ArrayExpression: 'ArrayExpression',
		        ArrayPattern: 'ArrayPattern',
		        ArrowFunctionExpression: 'ArrowFunctionExpression',
		        AwaitExpression: 'AwaitExpression',
		        BlockStatement: 'BlockStatement',
		        BinaryExpression: 'BinaryExpression',
		        BreakStatement: 'BreakStatement',
		        CallExpression: 'CallExpression',
		        CatchClause: 'CatchClause',
		        ChainExpression: 'ChainExpression',
		        ClassBody: 'ClassBody',
		        ClassDeclaration: 'ClassDeclaration',
		        ClassExpression: 'ClassExpression',
		        ComprehensionBlock: 'ComprehensionBlock',
		        ComprehensionExpression: 'ComprehensionExpression',
		        ConditionalExpression: 'ConditionalExpression',
		        ContinueStatement: 'ContinueStatement',
		        DebuggerStatement: 'DebuggerStatement',
		        DirectiveStatement: 'DirectiveStatement',
		        DoWhileStatement: 'DoWhileStatement',
		        EmptyStatement: 'EmptyStatement',
		        ExportAllDeclaration: 'ExportAllDeclaration',
		        ExportDefaultDeclaration: 'ExportDefaultDeclaration',
		        ExportNamedDeclaration: 'ExportNamedDeclaration',
		        ExportSpecifier: 'ExportSpecifier',
		        ExpressionStatement: 'ExpressionStatement',
		        ForStatement: 'ForStatement',
		        ForInStatement: 'ForInStatement',
		        ForOfStatement: 'ForOfStatement',
		        FunctionDeclaration: 'FunctionDeclaration',
		        FunctionExpression: 'FunctionExpression',
		        GeneratorExpression: 'GeneratorExpression',
		        Identifier: 'Identifier',
		        IfStatement: 'IfStatement',
		        ImportExpression: 'ImportExpression',
		        ImportDeclaration: 'ImportDeclaration',
		        ImportDefaultSpecifier: 'ImportDefaultSpecifier',
		        ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
		        ImportSpecifier: 'ImportSpecifier',
		        Literal: 'Literal',
		        LabeledStatement: 'LabeledStatement',
		        LogicalExpression: 'LogicalExpression',
		        MemberExpression: 'MemberExpression',
		        MetaProperty: 'MetaProperty',
		        MethodDefinition: 'MethodDefinition',
		        ModuleSpecifier: 'ModuleSpecifier',
		        NewExpression: 'NewExpression',
		        ObjectExpression: 'ObjectExpression',
		        ObjectPattern: 'ObjectPattern',
		        PrivateIdentifier: 'PrivateIdentifier',
		        Program: 'Program',
		        Property: 'Property',
		        PropertyDefinition: 'PropertyDefinition',
		        RestElement: 'RestElement',
		        ReturnStatement: 'ReturnStatement',
		        SequenceExpression: 'SequenceExpression',
		        SpreadElement: 'SpreadElement',
		        Super: 'Super',
		        SwitchStatement: 'SwitchStatement',
		        SwitchCase: 'SwitchCase',
		        TaggedTemplateExpression: 'TaggedTemplateExpression',
		        TemplateElement: 'TemplateElement',
		        TemplateLiteral: 'TemplateLiteral',
		        ThisExpression: 'ThisExpression',
		        ThrowStatement: 'ThrowStatement',
		        TryStatement: 'TryStatement',
		        UnaryExpression: 'UnaryExpression',
		        UpdateExpression: 'UpdateExpression',
		        VariableDeclaration: 'VariableDeclaration',
		        VariableDeclarator: 'VariableDeclarator',
		        WhileStatement: 'WhileStatement',
		        WithStatement: 'WithStatement',
		        YieldExpression: 'YieldExpression'
		    };
		    VisitorKeys = {
		        AssignmentExpression: ['left', 'right'],
		        AssignmentPattern: ['left', 'right'],
		        ArrayExpression: ['elements'],
		        ArrayPattern: ['elements'],
		        ArrowFunctionExpression: ['params', 'body'],
		        AwaitExpression: ['argument'],
		        BlockStatement: ['body'],
		        BinaryExpression: ['left', 'right'],
		        BreakStatement: ['label'],
		        CallExpression: ['callee', 'arguments'],
		        CatchClause: ['param', 'body'],
		        ChainExpression: ['expression'],
		        ClassBody: ['body'],
		        ClassDeclaration: ['id', 'superClass', 'body'],
		        ClassExpression: ['id', 'superClass', 'body'],
		        ComprehensionBlock: ['left', 'right'],
		        ComprehensionExpression: ['blocks', 'filter', 'body'],
		        ConditionalExpression: ['test', 'consequent', 'alternate'],
		        ContinueStatement: ['label'],
		        DebuggerStatement: [],
		        DirectiveStatement: [],
		        DoWhileStatement: ['body', 'test'],
		        EmptyStatement: [],
		        ExportAllDeclaration: ['source'],
		        ExportDefaultDeclaration: ['declaration'],
		        ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
		        ExportSpecifier: ['exported', 'local'],
		        ExpressionStatement: ['expression'],
		        ForStatement: ['init', 'test', 'update', 'body'],
		        ForInStatement: ['left', 'right', 'body'],
		        ForOfStatement: ['left', 'right', 'body'],
		        FunctionDeclaration: ['id', 'params', 'body'],
		        FunctionExpression: ['id', 'params', 'body'],
		        GeneratorExpression: ['blocks', 'filter', 'body'],
		        Identifier: [],
		        IfStatement: ['test', 'consequent', 'alternate'],
		        ImportExpression: ['source'],
		        ImportDeclaration: ['specifiers', 'source'],
		        ImportDefaultSpecifier: ['local'],
		        ImportNamespaceSpecifier: ['local'],
		        ImportSpecifier: ['imported', 'local'],
		        Literal: [],
		        LabeledStatement: ['label', 'body'],
		        LogicalExpression: ['left', 'right'],
		        MemberExpression: ['object', 'property'],
		        MetaProperty: ['meta', 'property'],
		        MethodDefinition: ['key', 'value'],
		        ModuleSpecifier: [],
		        NewExpression: ['callee', 'arguments'],
		        ObjectExpression: ['properties'],
		        ObjectPattern: ['properties'],
		        PrivateIdentifier: [],
		        Program: ['body'],
		        Property: ['key', 'value'],
		        PropertyDefinition: ['key', 'value'],
		        RestElement: [ 'argument' ],
		        ReturnStatement: ['argument'],
		        SequenceExpression: ['expressions'],
		        SpreadElement: ['argument'],
		        Super: [],
		        SwitchStatement: ['discriminant', 'cases'],
		        SwitchCase: ['test', 'consequent'],
		        TaggedTemplateExpression: ['tag', 'quasi'],
		        TemplateElement: [],
		        TemplateLiteral: ['quasis', 'expressions'],
		        ThisExpression: [],
		        ThrowStatement: ['argument'],
		        TryStatement: ['block', 'handler', 'finalizer'],
		        UnaryExpression: ['argument'],
		        UpdateExpression: ['argument'],
		        VariableDeclaration: ['declarations'],
		        VariableDeclarator: ['id', 'init'],
		        WhileStatement: ['test', 'body'],
		        WithStatement: ['object', 'body'],
		        YieldExpression: ['argument']
		    };
		    BREAK = {};
		    SKIP = {};
		    REMOVE = {};
		    VisitorOption = {
		        Break: BREAK,
		        Skip: SKIP,
		        Remove: REMOVE
		    };
		    function Reference(parent, key) {
		        this.parent = parent;
		        this.key = key;
		    }
		    Reference.prototype.replace = function replace(node) {
		        this.parent[this.key] = node;
		    };
		    Reference.prototype.remove = function remove() {
		        if (Array.isArray(this.parent)) {
		            this.parent.splice(this.key, 1);
		            return true;
		        } else {
		            this.replace(null);
		            return false;
		        }
		    };
		    function Element(node, path, wrap, ref) {
		        this.node = node;
		        this.path = path;
		        this.wrap = wrap;
		        this.ref = ref;
		    }
		    function Controller() { }
		    Controller.prototype.path = function path() {
		        var i, iz, j, jz, result, element;
		        function addToPath(result, path) {
		            if (Array.isArray(path)) {
		                for (j = 0, jz = path.length; j < jz; ++j) {
		                    result.push(path[j]);
		                }
		            } else {
		                result.push(path);
		            }
		        }
		        if (!this.__current.path) {
		            return null;
		        }
		        result = [];
		        for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
		            element = this.__leavelist[i];
		            addToPath(result, element.path);
		        }
		        addToPath(result, this.__current.path);
		        return result;
		    };
		    Controller.prototype.type = function () {
		        var node = this.current();
		        return node.type || this.__current.wrap;
		    };
		    Controller.prototype.parents = function parents() {
		        var i, iz, result;
		        result = [];
		        for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
		            result.push(this.__leavelist[i].node);
		        }
		        return result;
		    };
		    Controller.prototype.current = function current() {
		        return this.__current.node;
		    };
		    Controller.prototype.__execute = function __execute(callback, element) {
		        var previous, result;
		        result = undefined;
		        previous  = this.__current;
		        this.__current = element;
		        this.__state = null;
		        if (callback) {
		            result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
		        }
		        this.__current = previous;
		        return result;
		    };
		    Controller.prototype.notify = function notify(flag) {
		        this.__state = flag;
		    };
		    Controller.prototype.skip = function () {
		        this.notify(SKIP);
		    };
		    Controller.prototype['break'] = function () {
		        this.notify(BREAK);
		    };
		    Controller.prototype.remove = function () {
		        this.notify(REMOVE);
		    };
		    Controller.prototype.__initialize = function(root, visitor) {
		        this.visitor = visitor;
		        this.root = root;
		        this.__worklist = [];
		        this.__leavelist = [];
		        this.__current = null;
		        this.__state = null;
		        this.__fallback = null;
		        if (visitor.fallback === 'iteration') {
		            this.__fallback = Object.keys;
		        } else if (typeof visitor.fallback === 'function') {
		            this.__fallback = visitor.fallback;
		        }
		        this.__keys = VisitorKeys;
		        if (visitor.keys) {
		            this.__keys = Object.assign(Object.create(this.__keys), visitor.keys);
		        }
		    };
		    function isNode(node) {
		        if (node == null) {
		            return false;
		        }
		        return typeof node === 'object' && typeof node.type === 'string';
		    }
		    function isProperty(nodeType, key) {
		        return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
		    }
		    function candidateExistsInLeaveList(leavelist, candidate) {
		        for (var i = leavelist.length - 1; i >= 0; --i) {
		            if (leavelist[i].node === candidate) {
		                return true;
		            }
		        }
		        return false;
		    }
		    Controller.prototype.traverse = function traverse(root, visitor) {
		        var worklist,
		            leavelist,
		            element,
		            node,
		            nodeType,
		            ret,
		            key,
		            current,
		            current2,
		            candidates,
		            candidate,
		            sentinel;
		        this.__initialize(root, visitor);
		        sentinel = {};
		        worklist = this.__worklist;
		        leavelist = this.__leavelist;
		        worklist.push(new Element(root, null, null, null));
		        leavelist.push(new Element(null, null, null, null));
		        while (worklist.length) {
		            element = worklist.pop();
		            if (element === sentinel) {
		                element = leavelist.pop();
		                ret = this.__execute(visitor.leave, element);
		                if (this.__state === BREAK || ret === BREAK) {
		                    return;
		                }
		                continue;
		            }
		            if (element.node) {
		                ret = this.__execute(visitor.enter, element);
		                if (this.__state === BREAK || ret === BREAK) {
		                    return;
		                }
		                worklist.push(sentinel);
		                leavelist.push(element);
		                if (this.__state === SKIP || ret === SKIP) {
		                    continue;
		                }
		                node = element.node;
		                nodeType = node.type || element.wrap;
		                candidates = this.__keys[nodeType];
		                if (!candidates) {
		                    if (this.__fallback) {
		                        candidates = this.__fallback(node);
		                    } else {
		                        throw new Error('Unknown node type ' + nodeType + '.');
		                    }
		                }
		                current = candidates.length;
		                while ((current -= 1) >= 0) {
		                    key = candidates[current];
		                    candidate = node[key];
		                    if (!candidate) {
		                        continue;
		                    }
		                    if (Array.isArray(candidate)) {
		                        current2 = candidate.length;
		                        while ((current2 -= 1) >= 0) {
		                            if (!candidate[current2]) {
		                                continue;
		                            }
		                            if (candidateExistsInLeaveList(leavelist, candidate[current2])) {
		                              continue;
		                            }
		                            if (isProperty(nodeType, candidates[current])) {
		                                element = new Element(candidate[current2], [key, current2], 'Property', null);
		                            } else if (isNode(candidate[current2])) {
		                                element = new Element(candidate[current2], [key, current2], null, null);
		                            } else {
		                                continue;
		                            }
		                            worklist.push(element);
		                        }
		                    } else if (isNode(candidate)) {
		                        if (candidateExistsInLeaveList(leavelist, candidate)) {
		                          continue;
		                        }
		                        worklist.push(new Element(candidate, key, null, null));
		                    }
		                }
		            }
		        }
		    };
		    Controller.prototype.replace = function replace(root, visitor) {
		        var worklist,
		            leavelist,
		            node,
		            nodeType,
		            target,
		            element,
		            current,
		            current2,
		            candidates,
		            candidate,
		            sentinel,
		            outer,
		            key;
		        function removeElem(element) {
		            var i,
		                key,
		                nextElem,
		                parent;
		            if (element.ref.remove()) {
		                key = element.ref.key;
		                parent = element.ref.parent;
		                i = worklist.length;
		                while (i--) {
		                    nextElem = worklist[i];
		                    if (nextElem.ref && nextElem.ref.parent === parent) {
		                        if  (nextElem.ref.key < key) {
		                            break;
		                        }
		                        --nextElem.ref.key;
		                    }
		                }
		            }
		        }
		        this.__initialize(root, visitor);
		        sentinel = {};
		        worklist = this.__worklist;
		        leavelist = this.__leavelist;
		        outer = {
		            root: root
		        };
		        element = new Element(root, null, null, new Reference(outer, 'root'));
		        worklist.push(element);
		        leavelist.push(element);
		        while (worklist.length) {
		            element = worklist.pop();
		            if (element === sentinel) {
		                element = leavelist.pop();
		                target = this.__execute(visitor.leave, element);
		                if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
		                    element.ref.replace(target);
		                }
		                if (this.__state === REMOVE || target === REMOVE) {
		                    removeElem(element);
		                }
		                if (this.__state === BREAK || target === BREAK) {
		                    return outer.root;
		                }
		                continue;
		            }
		            target = this.__execute(visitor.enter, element);
		            if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
		                element.ref.replace(target);
		                element.node = target;
		            }
		            if (this.__state === REMOVE || target === REMOVE) {
		                removeElem(element);
		                element.node = null;
		            }
		            if (this.__state === BREAK || target === BREAK) {
		                return outer.root;
		            }
		            node = element.node;
		            if (!node) {
		                continue;
		            }
		            worklist.push(sentinel);
		            leavelist.push(element);
		            if (this.__state === SKIP || target === SKIP) {
		                continue;
		            }
		            nodeType = node.type || element.wrap;
		            candidates = this.__keys[nodeType];
		            if (!candidates) {
		                if (this.__fallback) {
		                    candidates = this.__fallback(node);
		                } else {
		                    throw new Error('Unknown node type ' + nodeType + '.');
		                }
		            }
		            current = candidates.length;
		            while ((current -= 1) >= 0) {
		                key = candidates[current];
		                candidate = node[key];
		                if (!candidate) {
		                    continue;
		                }
		                if (Array.isArray(candidate)) {
		                    current2 = candidate.length;
		                    while ((current2 -= 1) >= 0) {
		                        if (!candidate[current2]) {
		                            continue;
		                        }
		                        if (isProperty(nodeType, candidates[current])) {
		                            element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
		                        } else if (isNode(candidate[current2])) {
		                            element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
		                        } else {
		                            continue;
		                        }
		                        worklist.push(element);
		                    }
		                } else if (isNode(candidate)) {
		                    worklist.push(new Element(candidate, key, null, new Reference(node, key)));
		                }
		            }
		        }
		        return outer.root;
		    };
		    function traverse(root, visitor) {
		        var controller = new Controller();
		        return controller.traverse(root, visitor);
		    }
		    function replace(root, visitor) {
		        var controller = new Controller();
		        return controller.replace(root, visitor);
		    }
		    function extendCommentRange(comment, tokens) {
		        var target;
		        target = upperBound(tokens, function search(token) {
		            return token.range[0] > comment.range[0];
		        });
		        comment.extendedRange = [comment.range[0], comment.range[1]];
		        if (target !== tokens.length) {
		            comment.extendedRange[1] = tokens[target].range[0];
		        }
		        target -= 1;
		        if (target >= 0) {
		            comment.extendedRange[0] = tokens[target].range[1];
		        }
		        return comment;
		    }
		    function attachComments(tree, providedComments, tokens) {
		        var comments = [], comment, len, i, cursor;
		        if (!tree.range) {
		            throw new Error('attachComments needs range information');
		        }
		        if (!tokens.length) {
		            if (providedComments.length) {
		                for (i = 0, len = providedComments.length; i < len; i += 1) {
		                    comment = deepCopy(providedComments[i]);
		                    comment.extendedRange = [0, tree.range[0]];
		                    comments.push(comment);
		                }
		                tree.leadingComments = comments;
		            }
		            return tree;
		        }
		        for (i = 0, len = providedComments.length; i < len; i += 1) {
		            comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
		        }
		        cursor = 0;
		        traverse(tree, {
		            enter: function (node) {
		                var comment;
		                while (cursor < comments.length) {
		                    comment = comments[cursor];
		                    if (comment.extendedRange[1] > node.range[0]) {
		                        break;
		                    }
		                    if (comment.extendedRange[1] === node.range[0]) {
		                        if (!node.leadingComments) {
		                            node.leadingComments = [];
		                        }
		                        node.leadingComments.push(comment);
		                        comments.splice(cursor, 1);
		                    } else {
		                        cursor += 1;
		                    }
		                }
		                if (cursor === comments.length) {
		                    return VisitorOption.Break;
		                }
		                if (comments[cursor].extendedRange[0] > node.range[1]) {
		                    return VisitorOption.Skip;
		                }
		            }
		        });
		        cursor = 0;
		        traverse(tree, {
		            leave: function (node) {
		                var comment;
		                while (cursor < comments.length) {
		                    comment = comments[cursor];
		                    if (node.range[1] < comment.extendedRange[0]) {
		                        break;
		                    }
		                    if (node.range[1] === comment.extendedRange[0]) {
		                        if (!node.trailingComments) {
		                            node.trailingComments = [];
		                        }
		                        node.trailingComments.push(comment);
		                        comments.splice(cursor, 1);
		                    } else {
		                        cursor += 1;
		                    }
		                }
		                if (cursor === comments.length) {
		                    return VisitorOption.Break;
		                }
		                if (comments[cursor].extendedRange[0] > node.range[1]) {
		                    return VisitorOption.Skip;
		                }
		            }
		        });
		        return tree;
		    }
		    exports$1.Syntax = Syntax;
		    exports$1.traverse = traverse;
		    exports$1.replace = replace;
		    exports$1.attachComments = attachComments;
		    exports$1.VisitorKeys = VisitorKeys;
		    exports$1.VisitorOption = VisitorOption;
		    exports$1.Controller = Controller;
		    exports$1.cloneEnvironment = function () { return clone({}); };
		    return exports$1;
		}(exports$1)); 
	} (estraverse));
	return estraverse;
}

var utils = {};

var ast = {exports: {}};

/*
  Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var hasRequiredAst;

function requireAst () {
	if (hasRequiredAst) return ast.exports;
	hasRequiredAst = 1;
	(function () {
	    function isExpression(node) {
	        if (node == null) { return false; }
	        switch (node.type) {
	            case 'ArrayExpression':
	            case 'AssignmentExpression':
	            case 'BinaryExpression':
	            case 'CallExpression':
	            case 'ConditionalExpression':
	            case 'FunctionExpression':
	            case 'Identifier':
	            case 'Literal':
	            case 'LogicalExpression':
	            case 'MemberExpression':
	            case 'NewExpression':
	            case 'ObjectExpression':
	            case 'SequenceExpression':
	            case 'ThisExpression':
	            case 'UnaryExpression':
	            case 'UpdateExpression':
	                return true;
	        }
	        return false;
	    }
	    function isIterationStatement(node) {
	        if (node == null) { return false; }
	        switch (node.type) {
	            case 'DoWhileStatement':
	            case 'ForInStatement':
	            case 'ForStatement':
	            case 'WhileStatement':
	                return true;
	        }
	        return false;
	    }
	    function isStatement(node) {
	        if (node == null) { return false; }
	        switch (node.type) {
	            case 'BlockStatement':
	            case 'BreakStatement':
	            case 'ContinueStatement':
	            case 'DebuggerStatement':
	            case 'DoWhileStatement':
	            case 'EmptyStatement':
	            case 'ExpressionStatement':
	            case 'ForInStatement':
	            case 'ForStatement':
	            case 'IfStatement':
	            case 'LabeledStatement':
	            case 'ReturnStatement':
	            case 'SwitchStatement':
	            case 'ThrowStatement':
	            case 'TryStatement':
	            case 'VariableDeclaration':
	            case 'WhileStatement':
	            case 'WithStatement':
	                return true;
	        }
	        return false;
	    }
	    function isSourceElement(node) {
	      return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
	    }
	    function trailingStatement(node) {
	        switch (node.type) {
	        case 'IfStatement':
	            if (node.alternate != null) {
	                return node.alternate;
	            }
	            return node.consequent;
	        case 'LabeledStatement':
	        case 'ForStatement':
	        case 'ForInStatement':
	        case 'WhileStatement':
	        case 'WithStatement':
	            return node.body;
	        }
	        return null;
	    }
	    function isProblematicIfStatement(node) {
	        var current;
	        if (node.type !== 'IfStatement') {
	            return false;
	        }
	        if (node.alternate == null) {
	            return false;
	        }
	        current = node.consequent;
	        do {
	            if (current.type === 'IfStatement') {
	                if (current.alternate == null)  {
	                    return true;
	                }
	            }
	            current = trailingStatement(current);
	        } while (current);
	        return false;
	    }
	    ast.exports = {
	        isExpression: isExpression,
	        isStatement: isStatement,
	        isIterationStatement: isIterationStatement,
	        isSourceElement: isSourceElement,
	        isProblematicIfStatement: isProblematicIfStatement,
	        trailingStatement: trailingStatement
	    };
	}());
	return ast.exports;
}

var code = {exports: {}};

/*
  Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
  Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var hasRequiredCode;

function requireCode () {
	if (hasRequiredCode) return code.exports;
	hasRequiredCode = 1;
	(function () {
	    var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch;
	    ES5Regex = {
	        NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,
	        NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/
	    };
	    ES6Regex = {
	        NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
	        NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
	    };
	    function isDecimalDigit(ch) {
	        return 0x30 <= ch && ch <= 0x39;
	    }
	    function isHexDigit(ch) {
	        return 0x30 <= ch && ch <= 0x39 ||
	            0x61 <= ch && ch <= 0x66 ||
	            0x41 <= ch && ch <= 0x46;
	    }
	    function isOctalDigit(ch) {
	        return ch >= 0x30 && ch <= 0x37;
	    }
	    NON_ASCII_WHITESPACES = [
	        0x1680,
	        0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
	        0x202F, 0x205F,
	        0x3000,
	        0xFEFF
	    ];
	    function isWhiteSpace(ch) {
	        return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 ||
	            ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
	    }
	    function isLineTerminator(ch) {
	        return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
	    }
	    function fromCodePoint(cp) {
	        if (cp <= 0xFFFF) { return String.fromCharCode(cp); }
	        var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
	        var cu2 = String.fromCharCode(((cp - 0x10000) % 0x400) + 0xDC00);
	        return cu1 + cu2;
	    }
	    IDENTIFIER_START = new Array(0x80);
	    for(ch = 0; ch < 0x80; ++ch) {
	        IDENTIFIER_START[ch] =
	            ch >= 0x61 && ch <= 0x7A ||
	            ch >= 0x41 && ch <= 0x5A ||
	            ch === 0x24 || ch === 0x5F;
	    }
	    IDENTIFIER_PART = new Array(0x80);
	    for(ch = 0; ch < 0x80; ++ch) {
	        IDENTIFIER_PART[ch] =
	            ch >= 0x61 && ch <= 0x7A ||
	            ch >= 0x41 && ch <= 0x5A ||
	            ch >= 0x30 && ch <= 0x39 ||
	            ch === 0x24 || ch === 0x5F;
	    }
	    function isIdentifierStartES5(ch) {
	        return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
	    }
	    function isIdentifierPartES5(ch) {
	        return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
	    }
	    function isIdentifierStartES6(ch) {
	        return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
	    }
	    function isIdentifierPartES6(ch) {
	        return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
	    }
	    code.exports = {
	        isDecimalDigit: isDecimalDigit,
	        isHexDigit: isHexDigit,
	        isOctalDigit: isOctalDigit,
	        isWhiteSpace: isWhiteSpace,
	        isLineTerminator: isLineTerminator,
	        isIdentifierStartES5: isIdentifierStartES5,
	        isIdentifierPartES5: isIdentifierPartES5,
	        isIdentifierStartES6: isIdentifierStartES6,
	        isIdentifierPartES6: isIdentifierPartES6
	    };
	}());
	return code.exports;
}

var keyword = {exports: {}};

/*
  Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var hasRequiredKeyword;

function requireKeyword () {
	if (hasRequiredKeyword) return keyword.exports;
	hasRequiredKeyword = 1;
	(function () {
	    var code = requireCode();
	    function isStrictModeReservedWordES6(id) {
	        switch (id) {
	        case 'implements':
	        case 'interface':
	        case 'package':
	        case 'private':
	        case 'protected':
	        case 'public':
	        case 'static':
	        case 'let':
	            return true;
	        default:
	            return false;
	        }
	    }
	    function isKeywordES5(id, strict) {
	        if (!strict && id === 'yield') {
	            return false;
	        }
	        return isKeywordES6(id, strict);
	    }
	    function isKeywordES6(id, strict) {
	        if (strict && isStrictModeReservedWordES6(id)) {
	            return true;
	        }
	        switch (id.length) {
	        case 2:
	            return (id === 'if') || (id === 'in') || (id === 'do');
	        case 3:
	            return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try');
	        case 4:
	            return (id === 'this') || (id === 'else') || (id === 'case') ||
	                (id === 'void') || (id === 'with') || (id === 'enum');
	        case 5:
	            return (id === 'while') || (id === 'break') || (id === 'catch') ||
	                (id === 'throw') || (id === 'const') || (id === 'yield') ||
	                (id === 'class') || (id === 'super');
	        case 6:
	            return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
	                (id === 'switch') || (id === 'export') || (id === 'import');
	        case 7:
	            return (id === 'default') || (id === 'finally') || (id === 'extends');
	        case 8:
	            return (id === 'function') || (id === 'continue') || (id === 'debugger');
	        case 10:
	            return (id === 'instanceof');
	        default:
	            return false;
	        }
	    }
	    function isReservedWordES5(id, strict) {
	        return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
	    }
	    function isReservedWordES6(id, strict) {
	        return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
	    }
	    function isRestrictedWord(id) {
	        return id === 'eval' || id === 'arguments';
	    }
	    function isIdentifierNameES5(id) {
	        var i, iz, ch;
	        if (id.length === 0) { return false; }
	        ch = id.charCodeAt(0);
	        if (!code.isIdentifierStartES5(ch)) {
	            return false;
	        }
	        for (i = 1, iz = id.length; i < iz; ++i) {
	            ch = id.charCodeAt(i);
	            if (!code.isIdentifierPartES5(ch)) {
	                return false;
	            }
	        }
	        return true;
	    }
	    function decodeUtf16(lead, trail) {
	        return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
	    }
	    function isIdentifierNameES6(id) {
	        var i, iz, ch, lowCh, check;
	        if (id.length === 0) { return false; }
	        check = code.isIdentifierStartES6;
	        for (i = 0, iz = id.length; i < iz; ++i) {
	            ch = id.charCodeAt(i);
	            if (0xD800 <= ch && ch <= 0xDBFF) {
	                ++i;
	                if (i >= iz) { return false; }
	                lowCh = id.charCodeAt(i);
	                if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
	                    return false;
	                }
	                ch = decodeUtf16(ch, lowCh);
	            }
	            if (!check(ch)) {
	                return false;
	            }
	            check = code.isIdentifierPartES6;
	        }
	        return true;
	    }
	    function isIdentifierES5(id, strict) {
	        return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
	    }
	    function isIdentifierES6(id, strict) {
	        return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
	    }
	    keyword.exports = {
	        isKeywordES5: isKeywordES5,
	        isKeywordES6: isKeywordES6,
	        isReservedWordES5: isReservedWordES5,
	        isReservedWordES6: isReservedWordES6,
	        isRestrictedWord: isRestrictedWord,
	        isIdentifierNameES5: isIdentifierNameES5,
	        isIdentifierNameES6: isIdentifierNameES6,
	        isIdentifierES5: isIdentifierES5,
	        isIdentifierES6: isIdentifierES6
	    };
	}());
	return keyword.exports;
}

/*
  Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var hasRequiredUtils;

function requireUtils () {
	if (hasRequiredUtils) return utils;
	hasRequiredUtils = 1;
	(function () {
	    utils.ast = requireAst();
	    utils.code = requireCode();
	    utils.keyword = requireKeyword();
	}());
	return utils;
}

var sourceMap = {};

var sourceMapGenerator = {};

var base64Vlq = {};

var base64 = {};

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var hasRequiredBase64;

function requireBase64 () {
	if (hasRequiredBase64) return base64;
	hasRequiredBase64 = 1;
	var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
	base64.encode = function (number) {
	  if (0 <= number && number < intToCharMap.length) {
	    return intToCharMap[number];
	  }
	  throw new TypeError("Must be between 0 and 63: " + number);
	};
	base64.decode = function (charCode) {
	  var bigA = 65;
	  var bigZ = 90;
	  var littleA = 97;
	  var littleZ = 122;
	  var zero = 48;
	  var nine = 57;
	  var plus = 43;
	  var slash = 47;
	  var littleOffset = 26;
	  var numberOffset = 52;
	  if (bigA <= charCode && charCode <= bigZ) {
	    return (charCode - bigA);
	  }
	  if (littleA <= charCode && charCode <= littleZ) {
	    return (charCode - littleA + littleOffset);
	  }
	  if (zero <= charCode && charCode <= nine) {
	    return (charCode - zero + numberOffset);
	  }
	  if (charCode == plus) {
	    return 62;
	  }
	  if (charCode == slash) {
	    return 63;
	  }
	  return -1;
	};
	return base64;
}

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * Based on the Base 64 VLQ implementation in Closure Compiler:
 * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
 *
 * Copyright 2011 The Closure Compiler Authors. All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the following
 *    disclaimer in the documentation and/or other materials provided
 *    with the distribution.
 *  * Neither the name of Google Inc. nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

var hasRequiredBase64Vlq;

function requireBase64Vlq () {
	if (hasRequiredBase64Vlq) return base64Vlq;
	hasRequiredBase64Vlq = 1;
	var base64 = requireBase64();
	var VLQ_BASE_SHIFT = 5;
	var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
	var VLQ_BASE_MASK = VLQ_BASE - 1;
	var VLQ_CONTINUATION_BIT = VLQ_BASE;
	function toVLQSigned(aValue) {
	  return aValue < 0
	    ? ((-aValue) << 1) + 1
	    : (aValue << 1) + 0;
	}
	function fromVLQSigned(aValue) {
	  var isNegative = (aValue & 1) === 1;
	  var shifted = aValue >> 1;
	  return isNegative
	    ? -shifted
	    : shifted;
	}
	base64Vlq.encode = function base64VLQ_encode(aValue) {
	  var encoded = "";
	  var digit;
	  var vlq = toVLQSigned(aValue);
	  do {
	    digit = vlq & VLQ_BASE_MASK;
	    vlq >>>= VLQ_BASE_SHIFT;
	    if (vlq > 0) {
	      digit |= VLQ_CONTINUATION_BIT;
	    }
	    encoded += base64.encode(digit);
	  } while (vlq > 0);
	  return encoded;
	};
	base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
	  var strLen = aStr.length;
	  var result = 0;
	  var shift = 0;
	  var continuation, digit;
	  do {
	    if (aIndex >= strLen) {
	      throw new Error("Expected more digits in base 64 VLQ value.");
	    }
	    digit = base64.decode(aStr.charCodeAt(aIndex++));
	    if (digit === -1) {
	      throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
	    }
	    continuation = !!(digit & VLQ_CONTINUATION_BIT);
	    digit &= VLQ_BASE_MASK;
	    result = result + (digit << shift);
	    shift += VLQ_BASE_SHIFT;
	  } while (continuation);
	  aOutParam.value = fromVLQSigned(result);
	  aOutParam.rest = aIndex;
	};
	return base64Vlq;
}

var util$1 = {};

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var hasRequiredUtil$1;

function requireUtil$1 () {
	if (hasRequiredUtil$1) return util$1;
	hasRequiredUtil$1 = 1;
	(function (exports$1) {
		function getArg(aArgs, aName, aDefaultValue) {
		  if (aName in aArgs) {
		    return aArgs[aName];
		  } else if (arguments.length === 3) {
		    return aDefaultValue;
		  } else {
		    throw new Error('"' + aName + '" is a required argument.');
		  }
		}
		exports$1.getArg = getArg;
		var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
		var dataUrlRegexp = /^data:.+\,.+$/;
		function urlParse(aUrl) {
		  var match = aUrl.match(urlRegexp);
		  if (!match) {
		    return null;
		  }
		  return {
		    scheme: match[1],
		    auth: match[2],
		    host: match[3],
		    port: match[4],
		    path: match[5]
		  };
		}
		exports$1.urlParse = urlParse;
		function urlGenerate(aParsedUrl) {
		  var url = '';
		  if (aParsedUrl.scheme) {
		    url += aParsedUrl.scheme + ':';
		  }
		  url += '//';
		  if (aParsedUrl.auth) {
		    url += aParsedUrl.auth + '@';
		  }
		  if (aParsedUrl.host) {
		    url += aParsedUrl.host;
		  }
		  if (aParsedUrl.port) {
		    url += ":" + aParsedUrl.port;
		  }
		  if (aParsedUrl.path) {
		    url += aParsedUrl.path;
		  }
		  return url;
		}
		exports$1.urlGenerate = urlGenerate;
		function normalize(aPath) {
		  var path = aPath;
		  var url = urlParse(aPath);
		  if (url) {
		    if (!url.path) {
		      return aPath;
		    }
		    path = url.path;
		  }
		  var isAbsolute = exports$1.isAbsolute(path);
		  var parts = path.split(/\/+/);
		  for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
		    part = parts[i];
		    if (part === '.') {
		      parts.splice(i, 1);
		    } else if (part === '..') {
		      up++;
		    } else if (up > 0) {
		      if (part === '') {
		        parts.splice(i + 1, up);
		        up = 0;
		      } else {
		        parts.splice(i, 2);
		        up--;
		      }
		    }
		  }
		  path = parts.join('/');
		  if (path === '') {
		    path = isAbsolute ? '/' : '.';
		  }
		  if (url) {
		    url.path = path;
		    return urlGenerate(url);
		  }
		  return path;
		}
		exports$1.normalize = normalize;
		function join(aRoot, aPath) {
		  if (aRoot === "") {
		    aRoot = ".";
		  }
		  if (aPath === "") {
		    aPath = ".";
		  }
		  var aPathUrl = urlParse(aPath);
		  var aRootUrl = urlParse(aRoot);
		  if (aRootUrl) {
		    aRoot = aRootUrl.path || '/';
		  }
		  if (aPathUrl && !aPathUrl.scheme) {
		    if (aRootUrl) {
		      aPathUrl.scheme = aRootUrl.scheme;
		    }
		    return urlGenerate(aPathUrl);
		  }
		  if (aPathUrl || aPath.match(dataUrlRegexp)) {
		    return aPath;
		  }
		  if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
		    aRootUrl.host = aPath;
		    return urlGenerate(aRootUrl);
		  }
		  var joined = aPath.charAt(0) === '/'
		    ? aPath
		    : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
		  if (aRootUrl) {
		    aRootUrl.path = joined;
		    return urlGenerate(aRootUrl);
		  }
		  return joined;
		}
		exports$1.join = join;
		exports$1.isAbsolute = function (aPath) {
		  return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
		};
		function relative(aRoot, aPath) {
		  if (aRoot === "") {
		    aRoot = ".";
		  }
		  aRoot = aRoot.replace(/\/$/, '');
		  var level = 0;
		  while (aPath.indexOf(aRoot + '/') !== 0) {
		    var index = aRoot.lastIndexOf("/");
		    if (index < 0) {
		      return aPath;
		    }
		    aRoot = aRoot.slice(0, index);
		    if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
		      return aPath;
		    }
		    ++level;
		  }
		  return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
		}
		exports$1.relative = relative;
		var supportsNullProto = (function () {
		  var obj = Object.create(null);
		  return !('__proto__' in obj);
		}());
		function identity (s) {
		  return s;
		}
		function toSetString(aStr) {
		  if (isProtoString(aStr)) {
		    return '$' + aStr;
		  }
		  return aStr;
		}
		exports$1.toSetString = supportsNullProto ? identity : toSetString;
		function fromSetString(aStr) {
		  if (isProtoString(aStr)) {
		    return aStr.slice(1);
		  }
		  return aStr;
		}
		exports$1.fromSetString = supportsNullProto ? identity : fromSetString;
		function isProtoString(s) {
		  if (!s) {
		    return false;
		  }
		  var length = s.length;
		  if (length < 9 ) {
		    return false;
		  }
		  if (s.charCodeAt(length - 1) !== 95   ||
		      s.charCodeAt(length - 2) !== 95   ||
		      s.charCodeAt(length - 3) !== 111  ||
		      s.charCodeAt(length - 4) !== 116  ||
		      s.charCodeAt(length - 5) !== 111  ||
		      s.charCodeAt(length - 6) !== 114  ||
		      s.charCodeAt(length - 7) !== 112  ||
		      s.charCodeAt(length - 8) !== 95   ||
		      s.charCodeAt(length - 9) !== 95  ) {
		    return false;
		  }
		  for (var i = length - 10; i >= 0; i--) {
		    if (s.charCodeAt(i) !== 36 ) {
		      return false;
		    }
		  }
		  return true;
		}
		function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
		  var cmp = strcmp(mappingA.source, mappingB.source);
		  if (cmp !== 0) {
		    return cmp;
		  }
		  cmp = mappingA.originalLine - mappingB.originalLine;
		  if (cmp !== 0) {
		    return cmp;
		  }
		  cmp = mappingA.originalColumn - mappingB.originalColumn;
		  if (cmp !== 0 || onlyCompareOriginal) {
		    return cmp;
		  }
		  cmp = mappingA.generatedColumn - mappingB.generatedColumn;
		  if (cmp !== 0) {
		    return cmp;
		  }
		  cmp = mappingA.generatedLine - mappingB.generatedLine;
		  if (cmp !== 0) {
		    return cmp;
		  }
		  return strcmp(mappingA.name, mappingB.name);
		}
		exports$1.compareByOriginalPositions = compareByOriginalPositions;
		function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
		  var cmp = mappingA.generatedLine - mappingB.generatedLine;
		  if (cmp !== 0) {
		    return cmp;
		  }
		  cmp = mappingA.generatedColumn - mappingB.generatedColumn;
		  if (cmp !== 0 || onlyCompareGenerated) {
		    return cmp;
		  }
		  cmp = strcmp(mappingA.source, mappingB.source);
		  if (cmp !== 0) {
		    return cmp;
		  }
		  cmp = mappingA.originalLine - mappingB.originalLine;
		  if (cmp !== 0) {
		    return cmp;
		  }
		  cmp = mappingA.originalColumn - mappingB.originalColumn;
		  if (cmp !== 0) {
		    return cmp;
		  }
		  return strcmp(mappingA.name, mappingB.name);
		}
		exports$1.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
		function strcmp(aStr1, aStr2) {
		  if (aStr1 === aStr2) {
		    return 0;
		  }
		  if (aStr1 === null) {
		    return 1;
		  }
		  if (aStr2 === null) {
		    return -1;
		  }
		  if (aStr1 > aStr2) {
		    return 1;
		  }
		  return -1;
		}
		function compareByGeneratedPositionsInflated(mappingA, mappingB) {
		  var cmp = mappingA.generatedLine - mappingB.generatedLine;
		  if (cmp !== 0) {
		    return cmp;
		  }
		  cmp = mappingA.generatedColumn - mappingB.generatedColumn;
		  if (cmp !== 0) {
		    return cmp;
		  }
		  cmp = strcmp(mappingA.source, mappingB.source);
		  if (cmp !== 0) {
		    return cmp;
		  }
		  cmp = mappingA.originalLine - mappingB.originalLine;
		  if (cmp !== 0) {
		    return cmp;
		  }
		  cmp = mappingA.originalColumn - mappingB.originalColumn;
		  if (cmp !== 0) {
		    return cmp;
		  }
		  return strcmp(mappingA.name, mappingB.name);
		}
		exports$1.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
		function parseSourceMapInput(str) {
		  return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
		}
		exports$1.parseSourceMapInput = parseSourceMapInput;
		function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
		  sourceURL = sourceURL || '';
		  if (sourceRoot) {
		    if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
		      sourceRoot += '/';
		    }
		    sourceURL = sourceRoot + sourceURL;
		  }
		  if (sourceMapURL) {
		    var parsed = urlParse(sourceMapURL);
		    if (!parsed) {
		      throw new Error("sourceMapURL could not be parsed");
		    }
		    if (parsed.path) {
		      var index = parsed.path.lastIndexOf('/');
		      if (index >= 0) {
		        parsed.path = parsed.path.substring(0, index + 1);
		      }
		    }
		    sourceURL = join(urlGenerate(parsed), sourceURL);
		  }
		  return normalize(sourceURL);
		}
		exports$1.computeSourceURL = computeSourceURL; 
	} (util$1));
	return util$1;
}

var arraySet = {};

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var hasRequiredArraySet;

function requireArraySet () {
	if (hasRequiredArraySet) return arraySet;
	hasRequiredArraySet = 1;
	var util = requireUtil$1();
	var has = Object.prototype.hasOwnProperty;
	var hasNativeMap = typeof Map !== "undefined";
	function ArraySet() {
	  this._array = [];
	  this._set = hasNativeMap ? new Map() : Object.create(null);
	}
	ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
	  var set = new ArraySet();
	  for (var i = 0, len = aArray.length; i < len; i++) {
	    set.add(aArray[i], aAllowDuplicates);
	  }
	  return set;
	};
	ArraySet.prototype.size = function ArraySet_size() {
	  return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
	};
	ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
	  var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
	  var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
	  var idx = this._array.length;
	  if (!isDuplicate || aAllowDuplicates) {
	    this._array.push(aStr);
	  }
	  if (!isDuplicate) {
	    if (hasNativeMap) {
	      this._set.set(aStr, idx);
	    } else {
	      this._set[sStr] = idx;
	    }
	  }
	};
	ArraySet.prototype.has = function ArraySet_has(aStr) {
	  if (hasNativeMap) {
	    return this._set.has(aStr);
	  } else {
	    var sStr = util.toSetString(aStr);
	    return has.call(this._set, sStr);
	  }
	};
	ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
	  if (hasNativeMap) {
	    var idx = this._set.get(aStr);
	    if (idx >= 0) {
	        return idx;
	    }
	  } else {
	    var sStr = util.toSetString(aStr);
	    if (has.call(this._set, sStr)) {
	      return this._set[sStr];
	    }
	  }
	  throw new Error('"' + aStr + '" is not in the set.');
	};
	ArraySet.prototype.at = function ArraySet_at(aIdx) {
	  if (aIdx >= 0 && aIdx < this._array.length) {
	    return this._array[aIdx];
	  }
	  throw new Error('No element indexed by ' + aIdx);
	};
	ArraySet.prototype.toArray = function ArraySet_toArray() {
	  return this._array.slice();
	};
	arraySet.ArraySet = ArraySet;
	return arraySet;
}

var mappingList = {};

/*
 * Copyright 2014 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var hasRequiredMappingList;

function requireMappingList () {
	if (hasRequiredMappingList) return mappingList;
	hasRequiredMappingList = 1;
	var util = requireUtil$1();
	function generatedPositionAfter(mappingA, mappingB) {
	  var lineA = mappingA.generatedLine;
	  var lineB = mappingB.generatedLine;
	  var columnA = mappingA.generatedColumn;
	  var columnB = mappingB.generatedColumn;
	  return lineB > lineA || lineB == lineA && columnB >= columnA ||
	         util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
	}
	function MappingList() {
	  this._array = [];
	  this._sorted = true;
	  this._last = {generatedLine: -1, generatedColumn: 0};
	}
	MappingList.prototype.unsortedForEach =
	  function MappingList_forEach(aCallback, aThisArg) {
	    this._array.forEach(aCallback, aThisArg);
	  };
	MappingList.prototype.add = function MappingList_add(aMapping) {
	  if (generatedPositionAfter(this._last, aMapping)) {
	    this._last = aMapping;
	    this._array.push(aMapping);
	  } else {
	    this._sorted = false;
	    this._array.push(aMapping);
	  }
	};
	MappingList.prototype.toArray = function MappingList_toArray() {
	  if (!this._sorted) {
	    this._array.sort(util.compareByGeneratedPositionsInflated);
	    this._sorted = true;
	  }
	  return this._array;
	};
	mappingList.MappingList = MappingList;
	return mappingList;
}

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var hasRequiredSourceMapGenerator;

function requireSourceMapGenerator () {
	if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
	hasRequiredSourceMapGenerator = 1;
	var base64VLQ = requireBase64Vlq();
	var util = requireUtil$1();
	var ArraySet = requireArraySet().ArraySet;
	var MappingList = requireMappingList().MappingList;
	function SourceMapGenerator(aArgs) {
	  if (!aArgs) {
	    aArgs = {};
	  }
	  this._file = util.getArg(aArgs, 'file', null);
	  this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
	  this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
	  this._sources = new ArraySet();
	  this._names = new ArraySet();
	  this._mappings = new MappingList();
	  this._sourcesContents = null;
	}
	SourceMapGenerator.prototype._version = 3;
	SourceMapGenerator.fromSourceMap =
	  function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
	    var sourceRoot = aSourceMapConsumer.sourceRoot;
	    var generator = new SourceMapGenerator({
	      file: aSourceMapConsumer.file,
	      sourceRoot: sourceRoot
	    });
	    aSourceMapConsumer.eachMapping(function (mapping) {
	      var newMapping = {
	        generated: {
	          line: mapping.generatedLine,
	          column: mapping.generatedColumn
	        }
	      };
	      if (mapping.source != null) {
	        newMapping.source = mapping.source;
	        if (sourceRoot != null) {
	          newMapping.source = util.relative(sourceRoot, newMapping.source);
	        }
	        newMapping.original = {
	          line: mapping.originalLine,
	          column: mapping.originalColumn
	        };
	        if (mapping.name != null) {
	          newMapping.name = mapping.name;
	        }
	      }
	      generator.addMapping(newMapping);
	    });
	    aSourceMapConsumer.sources.forEach(function (sourceFile) {
	      var sourceRelative = sourceFile;
	      if (sourceRoot !== null) {
	        sourceRelative = util.relative(sourceRoot, sourceFile);
	      }
	      if (!generator._sources.has(sourceRelative)) {
	        generator._sources.add(sourceRelative);
	      }
	      var content = aSourceMapConsumer.sourceContentFor(sourceFile);
	      if (content != null) {
	        generator.setSourceContent(sourceFile, content);
	      }
	    });
	    return generator;
	  };
	SourceMapGenerator.prototype.addMapping =
	  function SourceMapGenerator_addMapping(aArgs) {
	    var generated = util.getArg(aArgs, 'generated');
	    var original = util.getArg(aArgs, 'original', null);
	    var source = util.getArg(aArgs, 'source', null);
	    var name = util.getArg(aArgs, 'name', null);
	    if (!this._skipValidation) {
	      this._validateMapping(generated, original, source, name);
	    }
	    if (source != null) {
	      source = String(source);
	      if (!this._sources.has(source)) {
	        this._sources.add(source);
	      }
	    }
	    if (name != null) {
	      name = String(name);
	      if (!this._names.has(name)) {
	        this._names.add(name);
	      }
	    }
	    this._mappings.add({
	      generatedLine: generated.line,
	      generatedColumn: generated.column,
	      originalLine: original != null && original.line,
	      originalColumn: original != null && original.column,
	      source: source,
	      name: name
	    });
	  };
	SourceMapGenerator.prototype.setSourceContent =
	  function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
	    var source = aSourceFile;
	    if (this._sourceRoot != null) {
	      source = util.relative(this._sourceRoot, source);
	    }
	    if (aSourceContent != null) {
	      if (!this._sourcesContents) {
	        this._sourcesContents = Object.create(null);
	      }
	      this._sourcesContents[util.toSetString(source)] = aSourceContent;
	    } else if (this._sourcesContents) {
	      delete this._sourcesContents[util.toSetString(source)];
	      if (Object.keys(this._sourcesContents).length === 0) {
	        this._sourcesContents = null;
	      }
	    }
	  };
	SourceMapGenerator.prototype.applySourceMap =
	  function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
	    var sourceFile = aSourceFile;
	    if (aSourceFile == null) {
	      if (aSourceMapConsumer.file == null) {
	        throw new Error(
	          'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
	          'or the source map\'s "file" property. Both were omitted.'
	        );
	      }
	      sourceFile = aSourceMapConsumer.file;
	    }
	    var sourceRoot = this._sourceRoot;
	    if (sourceRoot != null) {
	      sourceFile = util.relative(sourceRoot, sourceFile);
	    }
	    var newSources = new ArraySet();
	    var newNames = new ArraySet();
	    this._mappings.unsortedForEach(function (mapping) {
	      if (mapping.source === sourceFile && mapping.originalLine != null) {
	        var original = aSourceMapConsumer.originalPositionFor({
	          line: mapping.originalLine,
	          column: mapping.originalColumn
	        });
	        if (original.source != null) {
	          mapping.source = original.source;
	          if (aSourceMapPath != null) {
	            mapping.source = util.join(aSourceMapPath, mapping.source);
	          }
	          if (sourceRoot != null) {
	            mapping.source = util.relative(sourceRoot, mapping.source);
	          }
	          mapping.originalLine = original.line;
	          mapping.originalColumn = original.column;
	          if (original.name != null) {
	            mapping.name = original.name;
	          }
	        }
	      }
	      var source = mapping.source;
	      if (source != null && !newSources.has(source)) {
	        newSources.add(source);
	      }
	      var name = mapping.name;
	      if (name != null && !newNames.has(name)) {
	        newNames.add(name);
	      }
	    }, this);
	    this._sources = newSources;
	    this._names = newNames;
	    aSourceMapConsumer.sources.forEach(function (sourceFile) {
	      var content = aSourceMapConsumer.sourceContentFor(sourceFile);
	      if (content != null) {
	        if (aSourceMapPath != null) {
	          sourceFile = util.join(aSourceMapPath, sourceFile);
	        }
	        if (sourceRoot != null) {
	          sourceFile = util.relative(sourceRoot, sourceFile);
	        }
	        this.setSourceContent(sourceFile, content);
	      }
	    }, this);
	  };
	SourceMapGenerator.prototype._validateMapping =
	  function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
	                                              aName) {
	    if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
	        throw new Error(
	            'original.line and original.column are not numbers -- you probably meant to omit ' +
	            'the original mapping entirely and only map the generated position. If so, pass ' +
	            'null for the original mapping instead of an object with empty or null values.'
	        );
	    }
	    if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
	        && aGenerated.line > 0 && aGenerated.column >= 0
	        && !aOriginal && !aSource && !aName) {
	      return;
	    }
	    else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
	             && aOriginal && 'line' in aOriginal && 'column' in aOriginal
	             && aGenerated.line > 0 && aGenerated.column >= 0
	             && aOriginal.line > 0 && aOriginal.column >= 0
	             && aSource) {
	      return;
	    }
	    else {
	      throw new Error('Invalid mapping: ' + JSON.stringify({
	        generated: aGenerated,
	        source: aSource,
	        original: aOriginal,
	        name: aName
	      }));
	    }
	  };
	SourceMapGenerator.prototype._serializeMappings =
	  function SourceMapGenerator_serializeMappings() {
	    var previousGeneratedColumn = 0;
	    var previousGeneratedLine = 1;
	    var previousOriginalColumn = 0;
	    var previousOriginalLine = 0;
	    var previousName = 0;
	    var previousSource = 0;
	    var result = '';
	    var next;
	    var mapping;
	    var nameIdx;
	    var sourceIdx;
	    var mappings = this._mappings.toArray();
	    for (var i = 0, len = mappings.length; i < len; i++) {
	      mapping = mappings[i];
	      next = '';
	      if (mapping.generatedLine !== previousGeneratedLine) {
	        previousGeneratedColumn = 0;
	        while (mapping.generatedLine !== previousGeneratedLine) {
	          next += ';';
	          previousGeneratedLine++;
	        }
	      }
	      else {
	        if (i > 0) {
	          if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
	            continue;
	          }
	          next += ',';
	        }
	      }
	      next += base64VLQ.encode(mapping.generatedColumn
	                                 - previousGeneratedColumn);
	      previousGeneratedColumn = mapping.generatedColumn;
	      if (mapping.source != null) {
	        sourceIdx = this._sources.indexOf(mapping.source);
	        next += base64VLQ.encode(sourceIdx - previousSource);
	        previousSource = sourceIdx;
	        next += base64VLQ.encode(mapping.originalLine - 1
	                                   - previousOriginalLine);
	        previousOriginalLine = mapping.originalLine - 1;
	        next += base64VLQ.encode(mapping.originalColumn
	                                   - previousOriginalColumn);
	        previousOriginalColumn = mapping.originalColumn;
	        if (mapping.name != null) {
	          nameIdx = this._names.indexOf(mapping.name);
	          next += base64VLQ.encode(nameIdx - previousName);
	          previousName = nameIdx;
	        }
	      }
	      result += next;
	    }
	    return result;
	  };
	SourceMapGenerator.prototype._generateSourcesContent =
	  function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
	    return aSources.map(function (source) {
	      if (!this._sourcesContents) {
	        return null;
	      }
	      if (aSourceRoot != null) {
	        source = util.relative(aSourceRoot, source);
	      }
	      var key = util.toSetString(source);
	      return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
	        ? this._sourcesContents[key]
	        : null;
	    }, this);
	  };
	SourceMapGenerator.prototype.toJSON =
	  function SourceMapGenerator_toJSON() {
	    var map = {
	      version: this._version,
	      sources: this._sources.toArray(),
	      names: this._names.toArray(),
	      mappings: this._serializeMappings()
	    };
	    if (this._file != null) {
	      map.file = this._file;
	    }
	    if (this._sourceRoot != null) {
	      map.sourceRoot = this._sourceRoot;
	    }
	    if (this._sourcesContents) {
	      map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
	    }
	    return map;
	  };
	SourceMapGenerator.prototype.toString =
	  function SourceMapGenerator_toString() {
	    return JSON.stringify(this.toJSON());
	  };
	sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
	return sourceMapGenerator;
}

var sourceMapConsumer = {};

var binarySearch = {};

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var hasRequiredBinarySearch;

function requireBinarySearch () {
	if (hasRequiredBinarySearch) return binarySearch;
	hasRequiredBinarySearch = 1;
	(function (exports$1) {
		exports$1.GREATEST_LOWER_BOUND = 1;
		exports$1.LEAST_UPPER_BOUND = 2;
		function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
		  var mid = Math.floor((aHigh - aLow) / 2) + aLow;
		  var cmp = aCompare(aNeedle, aHaystack[mid], true);
		  if (cmp === 0) {
		    return mid;
		  }
		  else if (cmp > 0) {
		    if (aHigh - mid > 1) {
		      return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
		    }
		    if (aBias == exports$1.LEAST_UPPER_BOUND) {
		      return aHigh < aHaystack.length ? aHigh : -1;
		    } else {
		      return mid;
		    }
		  }
		  else {
		    if (mid - aLow > 1) {
		      return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
		    }
		    if (aBias == exports$1.LEAST_UPPER_BOUND) {
		      return mid;
		    } else {
		      return aLow < 0 ? -1 : aLow;
		    }
		  }
		}
		exports$1.search = function search(aNeedle, aHaystack, aCompare, aBias) {
		  if (aHaystack.length === 0) {
		    return -1;
		  }
		  var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
		                              aCompare, aBias || exports$1.GREATEST_LOWER_BOUND);
		  if (index < 0) {
		    return -1;
		  }
		  while (index - 1 >= 0) {
		    if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
		      break;
		    }
		    --index;
		  }
		  return index;
		}; 
	} (binarySearch));
	return binarySearch;
}

var quickSort = {};

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var hasRequiredQuickSort;

function requireQuickSort () {
	if (hasRequiredQuickSort) return quickSort;
	hasRequiredQuickSort = 1;
	function swap(ary, x, y) {
	  var temp = ary[x];
	  ary[x] = ary[y];
	  ary[y] = temp;
	}
	function randomIntInRange(low, high) {
	  return Math.round(low + (Math.random() * (high - low)));
	}
	function doQuickSort(ary, comparator, p, r) {
	  if (p < r) {
	    var pivotIndex = randomIntInRange(p, r);
	    var i = p - 1;
	    swap(ary, pivotIndex, r);
	    var pivot = ary[r];
	    for (var j = p; j < r; j++) {
	      if (comparator(ary[j], pivot) <= 0) {
	        i += 1;
	        swap(ary, i, j);
	      }
	    }
	    swap(ary, i + 1, j);
	    var q = i + 1;
	    doQuickSort(ary, comparator, p, q - 1);
	    doQuickSort(ary, comparator, q + 1, r);
	  }
	}
	quickSort.quickSort = function (ary, comparator) {
	  doQuickSort(ary, comparator, 0, ary.length - 1);
	};
	return quickSort;
}

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var hasRequiredSourceMapConsumer;

function requireSourceMapConsumer () {
	if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
	hasRequiredSourceMapConsumer = 1;
	var util = requireUtil$1();
	var binarySearch = requireBinarySearch();
	var ArraySet = requireArraySet().ArraySet;
	var base64VLQ = requireBase64Vlq();
	var quickSort = requireQuickSort().quickSort;
	function SourceMapConsumer(aSourceMap, aSourceMapURL) {
	  var sourceMap = aSourceMap;
	  if (typeof aSourceMap === 'string') {
	    sourceMap = util.parseSourceMapInput(aSourceMap);
	  }
	  return sourceMap.sections != null
	    ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
	    : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
	}
	SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
	  return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
	};
	SourceMapConsumer.prototype._version = 3;
	SourceMapConsumer.prototype.__generatedMappings = null;
	Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
	  configurable: true,
	  enumerable: true,
	  get: function () {
	    if (!this.__generatedMappings) {
	      this._parseMappings(this._mappings, this.sourceRoot);
	    }
	    return this.__generatedMappings;
	  }
	});
	SourceMapConsumer.prototype.__originalMappings = null;
	Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
	  configurable: true,
	  enumerable: true,
	  get: function () {
	    if (!this.__originalMappings) {
	      this._parseMappings(this._mappings, this.sourceRoot);
	    }
	    return this.__originalMappings;
	  }
	});
	SourceMapConsumer.prototype._charIsMappingSeparator =
	  function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
	    var c = aStr.charAt(index);
	    return c === ";" || c === ",";
	  };
	SourceMapConsumer.prototype._parseMappings =
	  function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
	    throw new Error("Subclasses must implement _parseMappings");
	  };
	SourceMapConsumer.GENERATED_ORDER = 1;
	SourceMapConsumer.ORIGINAL_ORDER = 2;
	SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
	SourceMapConsumer.LEAST_UPPER_BOUND = 2;
	SourceMapConsumer.prototype.eachMapping =
	  function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
	    var context = aContext || null;
	    var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
	    var mappings;
	    switch (order) {
	    case SourceMapConsumer.GENERATED_ORDER:
	      mappings = this._generatedMappings;
	      break;
	    case SourceMapConsumer.ORIGINAL_ORDER:
	      mappings = this._originalMappings;
	      break;
	    default:
	      throw new Error("Unknown order of iteration.");
	    }
	    var sourceRoot = this.sourceRoot;
	    mappings.map(function (mapping) {
	      var source = mapping.source === null ? null : this._sources.at(mapping.source);
	      source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
	      return {
	        source: source,
	        generatedLine: mapping.generatedLine,
	        generatedColumn: mapping.generatedColumn,
	        originalLine: mapping.originalLine,
	        originalColumn: mapping.originalColumn,
	        name: mapping.name === null ? null : this._names.at(mapping.name)
	      };
	    }, this).forEach(aCallback, context);
	  };
	SourceMapConsumer.prototype.allGeneratedPositionsFor =
	  function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
	    var line = util.getArg(aArgs, 'line');
	    var needle = {
	      source: util.getArg(aArgs, 'source'),
	      originalLine: line,
	      originalColumn: util.getArg(aArgs, 'column', 0)
	    };
	    needle.source = this._findSourceIndex(needle.source);
	    if (needle.source < 0) {
	      return [];
	    }
	    var mappings = [];
	    var index = this._findMapping(needle,
	                                  this._originalMappings,
	                                  "originalLine",
	                                  "originalColumn",
	                                  util.compareByOriginalPositions,
	                                  binarySearch.LEAST_UPPER_BOUND);
	    if (index >= 0) {
	      var mapping = this._originalMappings[index];
	      if (aArgs.column === undefined) {
	        var originalLine = mapping.originalLine;
	        while (mapping && mapping.originalLine === originalLine) {
	          mappings.push({
	            line: util.getArg(mapping, 'generatedLine', null),
	            column: util.getArg(mapping, 'generatedColumn', null),
	            lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
	          });
	          mapping = this._originalMappings[++index];
	        }
	      } else {
	        var originalColumn = mapping.originalColumn;
	        while (mapping &&
	               mapping.originalLine === line &&
	               mapping.originalColumn == originalColumn) {
	          mappings.push({
	            line: util.getArg(mapping, 'generatedLine', null),
	            column: util.getArg(mapping, 'generatedColumn', null),
	            lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
	          });
	          mapping = this._originalMappings[++index];
	        }
	      }
	    }
	    return mappings;
	  };
	sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
	function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
	  var sourceMap = aSourceMap;
	  if (typeof aSourceMap === 'string') {
	    sourceMap = util.parseSourceMapInput(aSourceMap);
	  }
	  var version = util.getArg(sourceMap, 'version');
	  var sources = util.getArg(sourceMap, 'sources');
	  var names = util.getArg(sourceMap, 'names', []);
	  var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
	  var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
	  var mappings = util.getArg(sourceMap, 'mappings');
	  var file = util.getArg(sourceMap, 'file', null);
	  if (version != this._version) {
	    throw new Error('Unsupported version: ' + version);
	  }
	  if (sourceRoot) {
	    sourceRoot = util.normalize(sourceRoot);
	  }
	  sources = sources
	    .map(String)
	    .map(util.normalize)
	    .map(function (source) {
	      return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
	        ? util.relative(sourceRoot, source)
	        : source;
	    });
	  this._names = ArraySet.fromArray(names.map(String), true);
	  this._sources = ArraySet.fromArray(sources, true);
	  this._absoluteSources = this._sources.toArray().map(function (s) {
	    return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
	  });
	  this.sourceRoot = sourceRoot;
	  this.sourcesContent = sourcesContent;
	  this._mappings = mappings;
	  this._sourceMapURL = aSourceMapURL;
	  this.file = file;
	}
	BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
	BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
	BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
	  var relativeSource = aSource;
	  if (this.sourceRoot != null) {
	    relativeSource = util.relative(this.sourceRoot, relativeSource);
	  }
	  if (this._sources.has(relativeSource)) {
	    return this._sources.indexOf(relativeSource);
	  }
	  var i;
	  for (i = 0; i < this._absoluteSources.length; ++i) {
	    if (this._absoluteSources[i] == aSource) {
	      return i;
	    }
	  }
	  return -1;
	};
	BasicSourceMapConsumer.fromSourceMap =
	  function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
	    var smc = Object.create(BasicSourceMapConsumer.prototype);
	    var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
	    var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
	    smc.sourceRoot = aSourceMap._sourceRoot;
	    smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
	                                                            smc.sourceRoot);
	    smc.file = aSourceMap._file;
	    smc._sourceMapURL = aSourceMapURL;
	    smc._absoluteSources = smc._sources.toArray().map(function (s) {
	      return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
	    });
	    var generatedMappings = aSourceMap._mappings.toArray().slice();
	    var destGeneratedMappings = smc.__generatedMappings = [];
	    var destOriginalMappings = smc.__originalMappings = [];
	    for (var i = 0, length = generatedMappings.length; i < length; i++) {
	      var srcMapping = generatedMappings[i];
	      var destMapping = new Mapping;
	      destMapping.generatedLine = srcMapping.generatedLine;
	      destMapping.generatedColumn = srcMapping.generatedColumn;
	      if (srcMapping.source) {
	        destMapping.source = sources.indexOf(srcMapping.source);
	        destMapping.originalLine = srcMapping.originalLine;
	        destMapping.originalColumn = srcMapping.originalColumn;
	        if (srcMapping.name) {
	          destMapping.name = names.indexOf(srcMapping.name);
	        }
	        destOriginalMappings.push(destMapping);
	      }
	      destGeneratedMappings.push(destMapping);
	    }
	    quickSort(smc.__originalMappings, util.compareByOriginalPositions);
	    return smc;
	  };
	BasicSourceMapConsumer.prototype._version = 3;
	Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
	  get: function () {
	    return this._absoluteSources.slice();
	  }
	});
	function Mapping() {
	  this.generatedLine = 0;
	  this.generatedColumn = 0;
	  this.source = null;
	  this.originalLine = null;
	  this.originalColumn = null;
	  this.name = null;
	}
	BasicSourceMapConsumer.prototype._parseMappings =
	  function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
	    var generatedLine = 1;
	    var previousGeneratedColumn = 0;
	    var previousOriginalLine = 0;
	    var previousOriginalColumn = 0;
	    var previousSource = 0;
	    var previousName = 0;
	    var length = aStr.length;
	    var index = 0;
	    var cachedSegments = {};
	    var temp = {};
	    var originalMappings = [];
	    var generatedMappings = [];
	    var mapping, str, segment, end, value;
	    while (index < length) {
	      if (aStr.charAt(index) === ';') {
	        generatedLine++;
	        index++;
	        previousGeneratedColumn = 0;
	      }
	      else if (aStr.charAt(index) === ',') {
	        index++;
	      }
	      else {
	        mapping = new Mapping();
	        mapping.generatedLine = generatedLine;
	        for (end = index; end < length; end++) {
	          if (this._charIsMappingSeparator(aStr, end)) {
	            break;
	          }
	        }
	        str = aStr.slice(index, end);
	        segment = cachedSegments[str];
	        if (segment) {
	          index += str.length;
	        } else {
	          segment = [];
	          while (index < end) {
	            base64VLQ.decode(aStr, index, temp);
	            value = temp.value;
	            index = temp.rest;
	            segment.push(value);
	          }
	          if (segment.length === 2) {
	            throw new Error('Found a source, but no line and column');
	          }
	          if (segment.length === 3) {
	            throw new Error('Found a source and line, but no column');
	          }
	          cachedSegments[str] = segment;
	        }
	        mapping.generatedColumn = previousGeneratedColumn + segment[0];
	        previousGeneratedColumn = mapping.generatedColumn;
	        if (segment.length > 1) {
	          mapping.source = previousSource + segment[1];
	          previousSource += segment[1];
	          mapping.originalLine = previousOriginalLine + segment[2];
	          previousOriginalLine = mapping.originalLine;
	          mapping.originalLine += 1;
	          mapping.originalColumn = previousOriginalColumn + segment[3];
	          previousOriginalColumn = mapping.originalColumn;
	          if (segment.length > 4) {
	            mapping.name = previousName + segment[4];
	            previousName += segment[4];
	          }
	        }
	        generatedMappings.push(mapping);
	        if (typeof mapping.originalLine === 'number') {
	          originalMappings.push(mapping);
	        }
	      }
	    }
	    quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
	    this.__generatedMappings = generatedMappings;
	    quickSort(originalMappings, util.compareByOriginalPositions);
	    this.__originalMappings = originalMappings;
	  };
	BasicSourceMapConsumer.prototype._findMapping =
	  function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
	                                         aColumnName, aComparator, aBias) {
	    if (aNeedle[aLineName] <= 0) {
	      throw new TypeError('Line must be greater than or equal to 1, got '
	                          + aNeedle[aLineName]);
	    }
	    if (aNeedle[aColumnName] < 0) {
	      throw new TypeError('Column must be greater than or equal to 0, got '
	                          + aNeedle[aColumnName]);
	    }
	    return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
	  };
	BasicSourceMapConsumer.prototype.computeColumnSpans =
	  function SourceMapConsumer_computeColumnSpans() {
	    for (var index = 0; index < this._generatedMappings.length; ++index) {
	      var mapping = this._generatedMappings[index];
	      if (index + 1 < this._generatedMappings.length) {
	        var nextMapping = this._generatedMappings[index + 1];
	        if (mapping.generatedLine === nextMapping.generatedLine) {
	          mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
	          continue;
	        }
	      }
	      mapping.lastGeneratedColumn = Infinity;
	    }
	  };
	BasicSourceMapConsumer.prototype.originalPositionFor =
	  function SourceMapConsumer_originalPositionFor(aArgs) {
	    var needle = {
	      generatedLine: util.getArg(aArgs, 'line'),
	      generatedColumn: util.getArg(aArgs, 'column')
	    };
	    var index = this._findMapping(
	      needle,
	      this._generatedMappings,
	      "generatedLine",
	      "generatedColumn",
	      util.compareByGeneratedPositionsDeflated,
	      util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
	    );
	    if (index >= 0) {
	      var mapping = this._generatedMappings[index];
	      if (mapping.generatedLine === needle.generatedLine) {
	        var source = util.getArg(mapping, 'source', null);
	        if (source !== null) {
	          source = this._sources.at(source);
	          source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
	        }
	        var name = util.getArg(mapping, 'name', null);
	        if (name !== null) {
	          name = this._names.at(name);
	        }
	        return {
	          source: source,
	          line: util.getArg(mapping, 'originalLine', null),
	          column: util.getArg(mapping, 'originalColumn', null),
	          name: name
	        };
	      }
	    }
	    return {
	      source: null,
	      line: null,
	      column: null,
	      name: null
	    };
	  };
	BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
	  function BasicSourceMapConsumer_hasContentsOfAllSources() {
	    if (!this.sourcesContent) {
	      return false;
	    }
	    return this.sourcesContent.length >= this._sources.size() &&
	      !this.sourcesContent.some(function (sc) { return sc == null; });
	  };
	BasicSourceMapConsumer.prototype.sourceContentFor =
	  function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
	    if (!this.sourcesContent) {
	      return null;
	    }
	    var index = this._findSourceIndex(aSource);
	    if (index >= 0) {
	      return this.sourcesContent[index];
	    }
	    var relativeSource = aSource;
	    if (this.sourceRoot != null) {
	      relativeSource = util.relative(this.sourceRoot, relativeSource);
	    }
	    var url;
	    if (this.sourceRoot != null
	        && (url = util.urlParse(this.sourceRoot))) {
	      var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
	      if (url.scheme == "file"
	          && this._sources.has(fileUriAbsPath)) {
	        return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
	      }
	      if ((!url.path || url.path == "/")
	          && this._sources.has("/" + relativeSource)) {
	        return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
	      }
	    }
	    if (nullOnMissing) {
	      return null;
	    }
	    else {
	      throw new Error('"' + relativeSource + '" is not in the SourceMap.');
	    }
	  };
	BasicSourceMapConsumer.prototype.generatedPositionFor =
	  function SourceMapConsumer_generatedPositionFor(aArgs) {
	    var source = util.getArg(aArgs, 'source');
	    source = this._findSourceIndex(source);
	    if (source < 0) {
	      return {
	        line: null,
	        column: null,
	        lastColumn: null
	      };
	    }
	    var needle = {
	      source: source,
	      originalLine: util.getArg(aArgs, 'line'),
	      originalColumn: util.getArg(aArgs, 'column')
	    };
	    var index = this._findMapping(
	      needle,
	      this._originalMappings,
	      "originalLine",
	      "originalColumn",
	      util.compareByOriginalPositions,
	      util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
	    );
	    if (index >= 0) {
	      var mapping = this._originalMappings[index];
	      if (mapping.source === needle.source) {
	        return {
	          line: util.getArg(mapping, 'generatedLine', null),
	          column: util.getArg(mapping, 'generatedColumn', null),
	          lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
	        };
	      }
	    }
	    return {
	      line: null,
	      column: null,
	      lastColumn: null
	    };
	  };
	sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
	function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
	  var sourceMap = aSourceMap;
	  if (typeof aSourceMap === 'string') {
	    sourceMap = util.parseSourceMapInput(aSourceMap);
	  }
	  var version = util.getArg(sourceMap, 'version');
	  var sections = util.getArg(sourceMap, 'sections');
	  if (version != this._version) {
	    throw new Error('Unsupported version: ' + version);
	  }
	  this._sources = new ArraySet();
	  this._names = new ArraySet();
	  var lastOffset = {
	    line: -1,
	    column: 0
	  };
	  this._sections = sections.map(function (s) {
	    if (s.url) {
	      throw new Error('Support for url field in sections not implemented.');
	    }
	    var offset = util.getArg(s, 'offset');
	    var offsetLine = util.getArg(offset, 'line');
	    var offsetColumn = util.getArg(offset, 'column');
	    if (offsetLine < lastOffset.line ||
	        (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
	      throw new Error('Section offsets must be ordered and non-overlapping.');
	    }
	    lastOffset = offset;
	    return {
	      generatedOffset: {
	        generatedLine: offsetLine + 1,
	        generatedColumn: offsetColumn + 1
	      },
	      consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
	    }
	  });
	}
	IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
	IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
	IndexedSourceMapConsumer.prototype._version = 3;
	Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
	  get: function () {
	    var sources = [];
	    for (var i = 0; i < this._sections.length; i++) {
	      for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
	        sources.push(this._sections[i].consumer.sources[j]);
	      }
	    }
	    return sources;
	  }
	});
	IndexedSourceMapConsumer.prototype.originalPositionFor =
	  function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
	    var needle = {
	      generatedLine: util.getArg(aArgs, 'line'),
	      generatedColumn: util.getArg(aArgs, 'column')
	    };
	    var sectionIndex = binarySearch.search(needle, this._sections,
	      function(needle, section) {
	        var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
	        if (cmp) {
	          return cmp;
	        }
	        return (needle.generatedColumn -
	                section.generatedOffset.generatedColumn);
	      });
	    var section = this._sections[sectionIndex];
	    if (!section) {
	      return {
	        source: null,
	        line: null,
	        column: null,
	        name: null
	      };
	    }
	    return section.consumer.originalPositionFor({
	      line: needle.generatedLine -
	        (section.generatedOffset.generatedLine - 1),
	      column: needle.generatedColumn -
	        (section.generatedOffset.generatedLine === needle.generatedLine
	         ? section.generatedOffset.generatedColumn - 1
	         : 0),
	      bias: aArgs.bias
	    });
	  };
	IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
	  function IndexedSourceMapConsumer_hasContentsOfAllSources() {
	    return this._sections.every(function (s) {
	      return s.consumer.hasContentsOfAllSources();
	    });
	  };
	IndexedSourceMapConsumer.prototype.sourceContentFor =
	  function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
	    for (var i = 0; i < this._sections.length; i++) {
	      var section = this._sections[i];
	      var content = section.consumer.sourceContentFor(aSource, true);
	      if (content) {
	        return content;
	      }
	    }
	    if (nullOnMissing) {
	      return null;
	    }
	    else {
	      throw new Error('"' + aSource + '" is not in the SourceMap.');
	    }
	  };
	IndexedSourceMapConsumer.prototype.generatedPositionFor =
	  function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
	    for (var i = 0; i < this._sections.length; i++) {
	      var section = this._sections[i];
	      if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
	        continue;
	      }
	      var generatedPosition = section.consumer.generatedPositionFor(aArgs);
	      if (generatedPosition) {
	        var ret = {
	          line: generatedPosition.line +
	            (section.generatedOffset.generatedLine - 1),
	          column: generatedPosition.column +
	            (section.generatedOffset.generatedLine === generatedPosition.line
	             ? section.generatedOffset.generatedColumn - 1
	             : 0)
	        };
	        return ret;
	      }
	    }
	    return {
	      line: null,
	      column: null
	    };
	  };
	IndexedSourceMapConsumer.prototype._parseMappings =
	  function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
	    this.__generatedMappings = [];
	    this.__originalMappings = [];
	    for (var i = 0; i < this._sections.length; i++) {
	      var section = this._sections[i];
	      var sectionMappings = section.consumer._generatedMappings;
	      for (var j = 0; j < sectionMappings.length; j++) {
	        var mapping = sectionMappings[j];
	        var source = section.consumer._sources.at(mapping.source);
	        source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
	        this._sources.add(source);
	        source = this._sources.indexOf(source);
	        var name = null;
	        if (mapping.name) {
	          name = section.consumer._names.at(mapping.name);
	          this._names.add(name);
	          name = this._names.indexOf(name);
	        }
	        var adjustedMapping = {
	          source: source,
	          generatedLine: mapping.generatedLine +
	            (section.generatedOffset.generatedLine - 1),
	          generatedColumn: mapping.generatedColumn +
	            (section.generatedOffset.generatedLine === mapping.generatedLine
	            ? section.generatedOffset.generatedColumn - 1
	            : 0),
	          originalLine: mapping.originalLine,
	          originalColumn: mapping.originalColumn,
	          name: name
	        };
	        this.__generatedMappings.push(adjustedMapping);
	        if (typeof adjustedMapping.originalLine === 'number') {
	          this.__originalMappings.push(adjustedMapping);
	        }
	      }
	    }
	    quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
	    quickSort(this.__originalMappings, util.compareByOriginalPositions);
	  };
	sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
	return sourceMapConsumer;
}

var sourceNode = {};

/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var hasRequiredSourceNode;

function requireSourceNode () {
	if (hasRequiredSourceNode) return sourceNode;
	hasRequiredSourceNode = 1;
	var SourceMapGenerator = requireSourceMapGenerator().SourceMapGenerator;
	var util = requireUtil$1();
	var REGEX_NEWLINE = /(\r?\n)/;
	var NEWLINE_CODE = 10;
	var isSourceNode = "$$$isSourceNode$$$";
	function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
	  this.children = [];
	  this.sourceContents = {};
	  this.line = aLine == null ? null : aLine;
	  this.column = aColumn == null ? null : aColumn;
	  this.source = aSource == null ? null : aSource;
	  this.name = aName == null ? null : aName;
	  this[isSourceNode] = true;
	  if (aChunks != null) this.add(aChunks);
	}
	SourceNode.fromStringWithSourceMap =
	  function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
	    var node = new SourceNode();
	    var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
	    var remainingLinesIndex = 0;
	    var shiftNextLine = function() {
	      var lineContents = getNextLine();
	      var newLine = getNextLine() || "";
	      return lineContents + newLine;
	      function getNextLine() {
	        return remainingLinesIndex < remainingLines.length ?
	            remainingLines[remainingLinesIndex++] : undefined;
	      }
	    };
	    var lastGeneratedLine = 1, lastGeneratedColumn = 0;
	    var lastMapping = null;
	    aSourceMapConsumer.eachMapping(function (mapping) {
	      if (lastMapping !== null) {
	        if (lastGeneratedLine < mapping.generatedLine) {
	          addMappingWithCode(lastMapping, shiftNextLine());
	          lastGeneratedLine++;
	          lastGeneratedColumn = 0;
	        } else {
	          var nextLine = remainingLines[remainingLinesIndex] || '';
	          var code = nextLine.substr(0, mapping.generatedColumn -
	                                        lastGeneratedColumn);
	          remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
	                                              lastGeneratedColumn);
	          lastGeneratedColumn = mapping.generatedColumn;
	          addMappingWithCode(lastMapping, code);
	          lastMapping = mapping;
	          return;
	        }
	      }
	      while (lastGeneratedLine < mapping.generatedLine) {
	        node.add(shiftNextLine());
	        lastGeneratedLine++;
	      }
	      if (lastGeneratedColumn < mapping.generatedColumn) {
	        var nextLine = remainingLines[remainingLinesIndex] || '';
	        node.add(nextLine.substr(0, mapping.generatedColumn));
	        remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
	        lastGeneratedColumn = mapping.generatedColumn;
	      }
	      lastMapping = mapping;
	    }, this);
	    if (remainingLinesIndex < remainingLines.length) {
	      if (lastMapping) {
	        addMappingWithCode(lastMapping, shiftNextLine());
	      }
	      node.add(remainingLines.splice(remainingLinesIndex).join(""));
	    }
	    aSourceMapConsumer.sources.forEach(function (sourceFile) {
	      var content = aSourceMapConsumer.sourceContentFor(sourceFile);
	      if (content != null) {
	        if (aRelativePath != null) {
	          sourceFile = util.join(aRelativePath, sourceFile);
	        }
	        node.setSourceContent(sourceFile, content);
	      }
	    });
	    return node;
	    function addMappingWithCode(mapping, code) {
	      if (mapping === null || mapping.source === undefined) {
	        node.add(code);
	      } else {
	        var source = aRelativePath
	          ? util.join(aRelativePath, mapping.source)
	          : mapping.source;
	        node.add(new SourceNode(mapping.originalLine,
	                                mapping.originalColumn,
	                                source,
	                                code,
	                                mapping.name));
	      }
	    }
	  };
	SourceNode.prototype.add = function SourceNode_add(aChunk) {
	  if (Array.isArray(aChunk)) {
	    aChunk.forEach(function (chunk) {
	      this.add(chunk);
	    }, this);
	  }
	  else if (aChunk[isSourceNode] || typeof aChunk === "string") {
	    if (aChunk) {
	      this.children.push(aChunk);
	    }
	  }
	  else {
	    throw new TypeError(
	      "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
	    );
	  }
	  return this;
	};
	SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
	  if (Array.isArray(aChunk)) {
	    for (var i = aChunk.length-1; i >= 0; i--) {
	      this.prepend(aChunk[i]);
	    }
	  }
	  else if (aChunk[isSourceNode] || typeof aChunk === "string") {
	    this.children.unshift(aChunk);
	  }
	  else {
	    throw new TypeError(
	      "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
	    );
	  }
	  return this;
	};
	SourceNode.prototype.walk = function SourceNode_walk(aFn) {
	  var chunk;
	  for (var i = 0, len = this.children.length; i < len; i++) {
	    chunk = this.children[i];
	    if (chunk[isSourceNode]) {
	      chunk.walk(aFn);
	    }
	    else {
	      if (chunk !== '') {
	        aFn(chunk, { source: this.source,
	                     line: this.line,
	                     column: this.column,
	                     name: this.name });
	      }
	    }
	  }
	};
	SourceNode.prototype.join = function SourceNode_join(aSep) {
	  var newChildren;
	  var i;
	  var len = this.children.length;
	  if (len > 0) {
	    newChildren = [];
	    for (i = 0; i < len-1; i++) {
	      newChildren.push(this.children[i]);
	      newChildren.push(aSep);
	    }
	    newChildren.push(this.children[i]);
	    this.children = newChildren;
	  }
	  return this;
	};
	SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
	  var lastChild = this.children[this.children.length - 1];
	  if (lastChild[isSourceNode]) {
	    lastChild.replaceRight(aPattern, aReplacement);
	  }
	  else if (typeof lastChild === 'string') {
	    this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
	  }
	  else {
	    this.children.push(''.replace(aPattern, aReplacement));
	  }
	  return this;
	};
	SourceNode.prototype.setSourceContent =
	  function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
	    this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
	  };
	SourceNode.prototype.walkSourceContents =
	  function SourceNode_walkSourceContents(aFn) {
	    for (var i = 0, len = this.children.length; i < len; i++) {
	      if (this.children[i][isSourceNode]) {
	        this.children[i].walkSourceContents(aFn);
	      }
	    }
	    var sources = Object.keys(this.sourceContents);
	    for (var i = 0, len = sources.length; i < len; i++) {
	      aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
	    }
	  };
	SourceNode.prototype.toString = function SourceNode_toString() {
	  var str = "";
	  this.walk(function (chunk) {
	    str += chunk;
	  });
	  return str;
	};
	SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
	  var generated = {
	    code: "",
	    line: 1,
	    column: 0
	  };
	  var map = new SourceMapGenerator(aArgs);
	  var sourceMappingActive = false;
	  var lastOriginalSource = null;
	  var lastOriginalLine = null;
	  var lastOriginalColumn = null;
	  var lastOriginalName = null;
	  this.walk(function (chunk, original) {
	    generated.code += chunk;
	    if (original.source !== null
	        && original.line !== null
	        && original.column !== null) {
	      if(lastOriginalSource !== original.source
	         || lastOriginalLine !== original.line
	         || lastOriginalColumn !== original.column
	         || lastOriginalName !== original.name) {
	        map.addMapping({
	          source: original.source,
	          original: {
	            line: original.line,
	            column: original.column
	          },
	          generated: {
	            line: generated.line,
	            column: generated.column
	          },
	          name: original.name
	        });
	      }
	      lastOriginalSource = original.source;
	      lastOriginalLine = original.line;
	      lastOriginalColumn = original.column;
	      lastOriginalName = original.name;
	      sourceMappingActive = true;
	    } else if (sourceMappingActive) {
	      map.addMapping({
	        generated: {
	          line: generated.line,
	          column: generated.column
	        }
	      });
	      lastOriginalSource = null;
	      sourceMappingActive = false;
	    }
	    for (var idx = 0, length = chunk.length; idx < length; idx++) {
	      if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
	        generated.line++;
	        generated.column = 0;
	        if (idx + 1 === length) {
	          lastOriginalSource = null;
	          sourceMappingActive = false;
	        } else if (sourceMappingActive) {
	          map.addMapping({
	            source: original.source,
	            original: {
	              line: original.line,
	              column: original.column
	            },
	            generated: {
	              line: generated.line,
	              column: generated.column
	            },
	            name: original.name
	          });
	        }
	      } else {
	        generated.column++;
	      }
	    }
	  });
	  this.walkSourceContents(function (sourceFile, sourceContent) {
	    map.setSourceContent(sourceFile, sourceContent);
	  });
	  return { code: generated.code, map: map };
	};
	sourceNode.SourceNode = SourceNode;
	return sourceNode;
}

/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var hasRequiredSourceMap;

function requireSourceMap () {
	if (hasRequiredSourceMap) return sourceMap;
	hasRequiredSourceMap = 1;
	sourceMap.SourceMapGenerator = requireSourceMapGenerator().SourceMapGenerator;
	sourceMap.SourceMapConsumer = requireSourceMapConsumer().SourceMapConsumer;
	sourceMap.SourceNode = requireSourceNode().SourceNode;
	return sourceMap;
}

var version = "2.1.0";
var require$$3 = {
	version: version};

/*
  Copyright (C) 2012-2014 Yusuke Suzuki <utatane.tea@gmail.com>
  Copyright (C) 2015 Ingvar Stepanyan <me@rreverser.com>
  Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
  Copyright (C) 2012-2013 Michael Ficarra <escodegen.copyright@michael.ficarra.me>
  Copyright (C) 2012-2013 Mathias Bynens <mathias@qiwi.be>
  Copyright (C) 2013 Irakli Gozalishvili <rfobic@gmail.com>
  Copyright (C) 2012 Robert Gust-Bardon <donate@robert.gust-bardon.org>
  Copyright (C) 2012 John Freeman <jfreeman08@gmail.com>
  Copyright (C) 2011-2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  Copyright (C) 2020 Apple Inc. All rights reserved.
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var hasRequiredEscodegen;

function requireEscodegen () {
	if (hasRequiredEscodegen) return escodegen;
	hasRequiredEscodegen = 1;
	(function (exports$1) {
		(function () {
		    var Syntax,
		        Precedence,
		        BinaryPrecedence,
		        SourceNode,
		        estraverse,
		        esutils,
		        base,
		        indent,
		        json,
		        renumber,
		        hexadecimal,
		        quotes,
		        escapeless,
		        newline,
		        space,
		        parentheses,
		        semicolons,
		        safeConcatenation,
		        directive,
		        extra,
		        parse,
		        sourceMap,
		        sourceCode,
		        preserveBlankLines,
		        FORMAT_MINIFY,
		        FORMAT_DEFAULTS;
		    estraverse = requireEstraverse();
		    esutils = requireUtils();
		    Syntax = estraverse.Syntax;
		    function isExpression(node) {
		        return CodeGenerator.Expression.hasOwnProperty(node.type);
		    }
		    function isStatement(node) {
		        return CodeGenerator.Statement.hasOwnProperty(node.type);
		    }
		    Precedence = {
		        Sequence: 0,
		        Yield: 1,
		        Assignment: 1,
		        Conditional: 2,
		        ArrowFunction: 2,
		        Coalesce: 3,
		        LogicalOR: 4,
		        LogicalAND: 5,
		        BitwiseOR: 6,
		        BitwiseXOR: 7,
		        BitwiseAND: 8,
		        Equality: 9,
		        Relational: 10,
		        BitwiseSHIFT: 11,
		        Additive: 12,
		        Multiplicative: 13,
		        Exponentiation: 14,
		        Await: 15,
		        Unary: 15,
		        Postfix: 16,
		        OptionalChaining: 17,
		        Call: 18,
		        New: 19,
		        TaggedTemplate: 20,
		        Member: 21,
		        Primary: 22
		    };
		    BinaryPrecedence = {
		        '??': Precedence.Coalesce,
		        '||': Precedence.LogicalOR,
		        '&&': Precedence.LogicalAND,
		        '|': Precedence.BitwiseOR,
		        '^': Precedence.BitwiseXOR,
		        '&': Precedence.BitwiseAND,
		        '==': Precedence.Equality,
		        '!=': Precedence.Equality,
		        '===': Precedence.Equality,
		        '!==': Precedence.Equality,
		        'is': Precedence.Equality,
		        'isnt': Precedence.Equality,
		        '<': Precedence.Relational,
		        '>': Precedence.Relational,
		        '<=': Precedence.Relational,
		        '>=': Precedence.Relational,
		        'in': Precedence.Relational,
		        'instanceof': Precedence.Relational,
		        '<<': Precedence.BitwiseSHIFT,
		        '>>': Precedence.BitwiseSHIFT,
		        '>>>': Precedence.BitwiseSHIFT,
		        '+': Precedence.Additive,
		        '-': Precedence.Additive,
		        '*': Precedence.Multiplicative,
		        '%': Precedence.Multiplicative,
		        '/': Precedence.Multiplicative,
		        '**': Precedence.Exponentiation
		    };
		    var F_ALLOW_IN = 1,
		        F_ALLOW_CALL = 1 << 1,
		        F_ALLOW_UNPARATH_NEW = 1 << 2,
		        F_FUNC_BODY = 1 << 3,
		        F_DIRECTIVE_CTX = 1 << 4,
		        F_SEMICOLON_OPT = 1 << 5,
		        F_FOUND_COALESCE = 1 << 6;
		    var E_FTT = F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW,
		        E_TTF = F_ALLOW_IN | F_ALLOW_CALL,
		        E_TTT = F_ALLOW_IN | F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW,
		        E_TFF = F_ALLOW_IN,
		        E_FFT = F_ALLOW_UNPARATH_NEW,
		        E_TFT = F_ALLOW_IN | F_ALLOW_UNPARATH_NEW;
		    var S_TFFF = F_ALLOW_IN,
		        S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT,
		        S_FFFF = 0x00,
		        S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX,
		        S_TTFF = F_ALLOW_IN | F_FUNC_BODY;
		    function getDefaultOptions() {
		        return {
		            indent: null,
		            base: null,
		            parse: null,
		            comment: false,
		            format: {
		                indent: {
		                    style: '    ',
		                    base: 0,
		                    adjustMultilineComment: false
		                },
		                newline: '\n',
		                space: ' ',
		                json: false,
		                renumber: false,
		                hexadecimal: false,
		                quotes: 'single',
		                escapeless: false,
		                compact: false,
		                parentheses: true,
		                semicolons: true,
		                safeConcatenation: false,
		                preserveBlankLines: false
		            },
		            moz: {
		                comprehensionExpressionStartsWithAssignment: false,
		                starlessGenerator: false
		            },
		            sourceMap: null,
		            sourceMapRoot: null,
		            sourceMapWithCode: false,
		            directive: false,
		            raw: true,
		            verbatim: null,
		            sourceCode: null
		        };
		    }
		    function stringRepeat(str, num) {
		        var result = '';
		        for (num |= 0; num > 0; num >>>= 1, str += str) {
		            if (num & 1) {
		                result += str;
		            }
		        }
		        return result;
		    }
		    function hasLineTerminator(str) {
		        return (/[\r\n]/g).test(str);
		    }
		    function endsWithLineTerminator(str) {
		        var len = str.length;
		        return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1));
		    }
		    function merge(target, override) {
		        var key;
		        for (key in override) {
		            if (override.hasOwnProperty(key)) {
		                target[key] = override[key];
		            }
		        }
		        return target;
		    }
		    function updateDeeply(target, override) {
		        var key, val;
		        function isHashObject(target) {
		            return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp);
		        }
		        for (key in override) {
		            if (override.hasOwnProperty(key)) {
		                val = override[key];
		                if (isHashObject(val)) {
		                    if (isHashObject(target[key])) {
		                        updateDeeply(target[key], val);
		                    } else {
		                        target[key] = updateDeeply({}, val);
		                    }
		                } else {
		                    target[key] = val;
		                }
		            }
		        }
		        return target;
		    }
		    function generateNumber(value) {
		        var result, point, temp, exponent, pos;
		        if (value !== value) {
		            throw new Error('Numeric literal whose value is NaN');
		        }
		        if (value < 0 || (value === 0 && 1 / value < 0)) {
		            throw new Error('Numeric literal whose value is negative');
		        }
		        if (value === 1 / 0) {
		            return json ? 'null' : renumber ? '1e400' : '1e+400';
		        }
		        result = '' + value;
		        if (!renumber || result.length < 3) {
		            return result;
		        }
		        point = result.indexOf('.');
		        if (!json && result.charCodeAt(0) === 0x30   && point === 1) {
		            point = 0;
		            result = result.slice(1);
		        }
		        temp = result;
		        result = result.replace('e+', 'e');
		        exponent = 0;
		        if ((pos = temp.indexOf('e')) > 0) {
		            exponent = +temp.slice(pos + 1);
		            temp = temp.slice(0, pos);
		        }
		        if (point >= 0) {
		            exponent -= temp.length - point - 1;
		            temp = +(temp.slice(0, point) + temp.slice(point + 1)) + '';
		        }
		        pos = 0;
		        while (temp.charCodeAt(temp.length + pos - 1) === 0x30  ) {
		            --pos;
		        }
		        if (pos !== 0) {
		            exponent -= pos;
		            temp = temp.slice(0, pos);
		        }
		        if (exponent !== 0) {
		            temp += 'e' + exponent;
		        }
		        if ((temp.length < result.length ||
		                    (hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length)) &&
		                +temp === value) {
		            result = temp;
		        }
		        return result;
		    }
		    function escapeRegExpCharacter(ch, previousIsBackslash) {
		        if ((ch & -2) === 0x2028) {
		            return (previousIsBackslash ? 'u' : '\\u') + ((ch === 0x2028) ? '2028' : '2029');
		        } else if (ch === 10 || ch === 13) {
		            return (previousIsBackslash ? '' : '\\') + ((ch === 10) ? 'n' : 'r');
		        }
		        return String.fromCharCode(ch);
		    }
		    function generateRegExp(reg) {
		        var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash;
		        result = reg.toString();
		        if (reg.source) {
		            match = result.match(/\/([^/]*)$/);
		            if (!match) {
		                return result;
		            }
		            flags = match[1];
		            result = '';
		            characterInBrack = false;
		            previousIsBackslash = false;
		            for (i = 0, iz = reg.source.length; i < iz; ++i) {
		                ch = reg.source.charCodeAt(i);
		                if (!previousIsBackslash) {
		                    if (characterInBrack) {
		                        if (ch === 93) {
		                            characterInBrack = false;
		                        }
		                    } else {
		                        if (ch === 47) {
		                            result += '\\';
		                        } else if (ch === 91) {
		                            characterInBrack = true;
		                        }
		                    }
		                    result += escapeRegExpCharacter(ch, previousIsBackslash);
		                    previousIsBackslash = ch === 92;
		                } else {
		                    result += escapeRegExpCharacter(ch, previousIsBackslash);
		                    previousIsBackslash = false;
		                }
		            }
		            return '/' + result + '/' + flags;
		        }
		        return result;
		    }
		    function escapeAllowedCharacter(code, next) {
		        var hex;
		        if (code === 0x08  ) {
		            return '\\b';
		        }
		        if (code === 0x0C  ) {
		            return '\\f';
		        }
		        if (code === 0x09  ) {
		            return '\\t';
		        }
		        hex = code.toString(16).toUpperCase();
		        if (json || code > 0xFF) {
		            return '\\u' + '0000'.slice(hex.length) + hex;
		        } else if (code === 0x0000 && !esutils.code.isDecimalDigit(next)) {
		            return '\\0';
		        } else if (code === 0x000B  ) {
		            return '\\x0B';
		        } else {
		            return '\\x' + '00'.slice(hex.length) + hex;
		        }
		    }
		    function escapeDisallowedCharacter(code) {
		        if (code === 0x5C  ) {
		            return '\\\\';
		        }
		        if (code === 0x0A  ) {
		            return '\\n';
		        }
		        if (code === 0x0D  ) {
		            return '\\r';
		        }
		        if (code === 0x2028) {
		            return '\\u2028';
		        }
		        if (code === 0x2029) {
		            return '\\u2029';
		        }
		        throw new Error('Incorrectly classified character');
		    }
		    function escapeDirective(str) {
		        var i, iz, code, quote;
		        quote = quotes === 'double' ? '"' : '\'';
		        for (i = 0, iz = str.length; i < iz; ++i) {
		            code = str.charCodeAt(i);
		            if (code === 0x27  ) {
		                quote = '"';
		                break;
		            } else if (code === 0x22  ) {
		                quote = '\'';
		                break;
		            } else if (code === 0x5C  ) {
		                ++i;
		            }
		        }
		        return quote + str + quote;
		    }
		    function escapeString(str) {
		        var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote;
		        for (i = 0, len = str.length; i < len; ++i) {
		            code = str.charCodeAt(i);
		            if (code === 0x27  ) {
		                ++singleQuotes;
		            } else if (code === 0x22  ) {
		                ++doubleQuotes;
		            } else if (code === 0x2F   && json) {
		                result += '\\';
		            } else if (esutils.code.isLineTerminator(code) || code === 0x5C  ) {
		                result += escapeDisallowedCharacter(code);
		                continue;
		            } else if (!esutils.code.isIdentifierPartES5(code) && (json && code < 0x20   || !json && !escapeless && (code < 0x20   || code > 0x7E  ))) {
		                result += escapeAllowedCharacter(code, str.charCodeAt(i + 1));
		                continue;
		            }
		            result += String.fromCharCode(code);
		        }
		        single = !(quotes === 'double' || (quotes === 'auto' && doubleQuotes < singleQuotes));
		        quote = single ? '\'' : '"';
		        if (!(single ? singleQuotes : doubleQuotes)) {
		            return quote + result + quote;
		        }
		        str = result;
		        result = quote;
		        for (i = 0, len = str.length; i < len; ++i) {
		            code = str.charCodeAt(i);
		            if ((code === 0x27   && single) || (code === 0x22   && !single)) {
		                result += '\\';
		            }
		            result += String.fromCharCode(code);
		        }
		        return result + quote;
		    }
		    function flattenToString(arr) {
		        var i, iz, elem, result = '';
		        for (i = 0, iz = arr.length; i < iz; ++i) {
		            elem = arr[i];
		            result += Array.isArray(elem) ? flattenToString(elem) : elem;
		        }
		        return result;
		    }
		    function toSourceNodeWhenNeeded(generated, node) {
		        if (!sourceMap) {
		            if (Array.isArray(generated)) {
		                return flattenToString(generated);
		            } else {
		                return generated;
		            }
		        }
		        if (node == null) {
		            if (generated instanceof SourceNode) {
		                return generated;
		            } else {
		                node = {};
		            }
		        }
		        if (node.loc == null) {
		            return new SourceNode(null, null, sourceMap, generated, node.name || null);
		        }
		        return new SourceNode(node.loc.start.line, node.loc.start.column, (sourceMap === true ? node.loc.source || null : sourceMap), generated, node.name || null);
		    }
		    function noEmptySpace() {
		        return (space) ? space : ' ';
		    }
		    function join(left, right) {
		        var leftSource,
		            rightSource,
		            leftCharCode,
		            rightCharCode;
		        leftSource = toSourceNodeWhenNeeded(left).toString();
		        if (leftSource.length === 0) {
		            return [right];
		        }
		        rightSource = toSourceNodeWhenNeeded(right).toString();
		        if (rightSource.length === 0) {
		            return [left];
		        }
		        leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
		        rightCharCode = rightSource.charCodeAt(0);
		        if ((leftCharCode === 0x2B   || leftCharCode === 0x2D  ) && leftCharCode === rightCharCode ||
		            esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode) ||
		            leftCharCode === 0x2F   && rightCharCode === 0x69  ) {
		            return [left, noEmptySpace(), right];
		        } else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) ||
		                esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) {
		            return [left, right];
		        }
		        return [left, space, right];
		    }
		    function addIndent(stmt) {
		        return [base, stmt];
		    }
		    function withIndent(fn) {
		        var previousBase;
		        previousBase = base;
		        base += indent;
		        fn(base);
		        base = previousBase;
		    }
		    function calculateSpaces(str) {
		        var i;
		        for (i = str.length - 1; i >= 0; --i) {
		            if (esutils.code.isLineTerminator(str.charCodeAt(i))) {
		                break;
		            }
		        }
		        return (str.length - 1) - i;
		    }
		    function adjustMultilineComment(value, specialBase) {
		        var array, i, len, line, j, spaces, previousBase, sn;
		        array = value.split(/\r\n|[\r\n]/);
		        spaces = Number.MAX_VALUE;
		        for (i = 1, len = array.length; i < len; ++i) {
		            line = array[i];
		            j = 0;
		            while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) {
		                ++j;
		            }
		            if (spaces > j) {
		                spaces = j;
		            }
		        }
		        if (typeof specialBase !== 'undefined') {
		            previousBase = base;
		            if (array[1][spaces] === '*') {
		                specialBase += ' ';
		            }
		            base = specialBase;
		        } else {
		            if (spaces & 1) {
		                --spaces;
		            }
		            previousBase = base;
		        }
		        for (i = 1, len = array.length; i < len; ++i) {
		            sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces)));
		            array[i] = sourceMap ? sn.join('') : sn;
		        }
		        base = previousBase;
		        return array.join('\n');
		    }
		    function generateComment(comment, specialBase) {
		        if (comment.type === 'Line') {
		            if (endsWithLineTerminator(comment.value)) {
		                return '//' + comment.value;
		            } else {
		                var result = '//' + comment.value;
		                if (!preserveBlankLines) {
		                    result += '\n';
		                }
		                return result;
		            }
		        }
		        if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) {
		            return adjustMultilineComment('/*' + comment.value + '*/', specialBase);
		        }
		        return '/*' + comment.value + '*/';
		    }
		    function addComments(stmt, result) {
		        var i, len, comment, save, tailingToStatement, specialBase, fragment,
		            extRange, range, prevRange, prefix, infix, suffix, count;
		        if (stmt.leadingComments && stmt.leadingComments.length > 0) {
		            save = result;
		            if (preserveBlankLines) {
		                comment = stmt.leadingComments[0];
		                result = [];
		                extRange = comment.extendedRange;
		                range = comment.range;
		                prefix = sourceCode.substring(extRange[0], range[0]);
		                count = (prefix.match(/\n/g) || []).length;
		                if (count > 0) {
		                    result.push(stringRepeat('\n', count));
		                    result.push(addIndent(generateComment(comment)));
		                } else {
		                    result.push(prefix);
		                    result.push(generateComment(comment));
		                }
		                prevRange = range;
		                for (i = 1, len = stmt.leadingComments.length; i < len; i++) {
		                    comment = stmt.leadingComments[i];
		                    range = comment.range;
		                    infix = sourceCode.substring(prevRange[1], range[0]);
		                    count = (infix.match(/\n/g) || []).length;
		                    result.push(stringRepeat('\n', count));
		                    result.push(addIndent(generateComment(comment)));
		                    prevRange = range;
		                }
		                suffix = sourceCode.substring(range[1], extRange[1]);
		                count = (suffix.match(/\n/g) || []).length;
		                result.push(stringRepeat('\n', count));
		            } else {
		                comment = stmt.leadingComments[0];
		                result = [];
		                if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) {
		                    result.push('\n');
		                }
		                result.push(generateComment(comment));
		                if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
		                    result.push('\n');
		                }
		                for (i = 1, len = stmt.leadingComments.length; i < len; ++i) {
		                    comment = stmt.leadingComments[i];
		                    fragment = [generateComment(comment)];
		                    if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
		                        fragment.push('\n');
		                    }
		                    result.push(addIndent(fragment));
		                }
		            }
		            result.push(addIndent(save));
		        }
		        if (stmt.trailingComments) {
		            if (preserveBlankLines) {
		                comment = stmt.trailingComments[0];
		                extRange = comment.extendedRange;
		                range = comment.range;
		                prefix = sourceCode.substring(extRange[0], range[0]);
		                count = (prefix.match(/\n/g) || []).length;
		                if (count > 0) {
		                    result.push(stringRepeat('\n', count));
		                    result.push(addIndent(generateComment(comment)));
		                } else {
		                    result.push(prefix);
		                    result.push(generateComment(comment));
		                }
		            } else {
		                tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
		                specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([base, result, indent]).toString()));
		                for (i = 0, len = stmt.trailingComments.length; i < len; ++i) {
		                    comment = stmt.trailingComments[i];
		                    if (tailingToStatement) {
		                        if (i === 0) {
		                            result = [result, indent];
		                        } else {
		                            result = [result, specialBase];
		                        }
		                        result.push(generateComment(comment, specialBase));
		                    } else {
		                        result = [result, addIndent(generateComment(comment))];
		                    }
		                    if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
		                        result = [result, '\n'];
		                    }
		                }
		            }
		        }
		        return result;
		    }
		    function generateBlankLines(start, end, result) {
		        var j, newlineCount = 0;
		        for (j = start; j < end; j++) {
		            if (sourceCode[j] === '\n') {
		                newlineCount++;
		            }
		        }
		        for (j = 1; j < newlineCount; j++) {
		            result.push(newline);
		        }
		    }
		    function parenthesize(text, current, should) {
		        if (current < should) {
		            return ['(', text, ')'];
		        }
		        return text;
		    }
		    function generateVerbatimString(string) {
		        var i, iz, result;
		        result = string.split(/\r\n|\n/);
		        for (i = 1, iz = result.length; i < iz; i++) {
		            result[i] = newline + base + result[i];
		        }
		        return result;
		    }
		    function generateVerbatim(expr, precedence) {
		        var verbatim, result, prec;
		        verbatim = expr[extra.verbatim];
		        if (typeof verbatim === 'string') {
		            result = parenthesize(generateVerbatimString(verbatim), Precedence.Sequence, precedence);
		        } else {
		            result = generateVerbatimString(verbatim.content);
		            prec = (verbatim.precedence != null) ? verbatim.precedence : Precedence.Sequence;
		            result = parenthesize(result, prec, precedence);
		        }
		        return toSourceNodeWhenNeeded(result, expr);
		    }
		    function CodeGenerator() {
		    }
		    CodeGenerator.prototype.maybeBlock = function(stmt, flags) {
		        var result, noLeadingComment, that = this;
		        noLeadingComment = !extra.comment || !stmt.leadingComments;
		        if (stmt.type === Syntax.BlockStatement && noLeadingComment) {
		            return [space, this.generateStatement(stmt, flags)];
		        }
		        if (stmt.type === Syntax.EmptyStatement && noLeadingComment) {
		            return ';';
		        }
		        withIndent(function () {
		            result = [
		                newline,
		                addIndent(that.generateStatement(stmt, flags))
		            ];
		        });
		        return result;
		    };
		    CodeGenerator.prototype.maybeBlockSuffix = function (stmt, result) {
		        var ends = endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
		        if (stmt.type === Syntax.BlockStatement && (!extra.comment || !stmt.leadingComments) && !ends) {
		            return [result, space];
		        }
		        if (ends) {
		            return [result, base];
		        }
		        return [result, newline, base];
		    };
		    function generateIdentifier(node) {
		        return toSourceNodeWhenNeeded(node.name, node);
		    }
		    function generateAsyncPrefix(node, spaceRequired) {
		        return node.async ? 'async' + (spaceRequired ? noEmptySpace() : space) : '';
		    }
		    function generateStarSuffix(node) {
		        var isGenerator = node.generator && !extra.moz.starlessGenerator;
		        return isGenerator ? '*' + space : '';
		    }
		    function generateMethodPrefix(prop) {
		        var func = prop.value, prefix = '';
		        if (func.async) {
		            prefix += generateAsyncPrefix(func, !prop.computed);
		        }
		        if (func.generator) {
		            prefix += generateStarSuffix(func) ? '*' : '';
		        }
		        return prefix;
		    }
		    CodeGenerator.prototype.generatePattern = function (node, precedence, flags) {
		        if (node.type === Syntax.Identifier) {
		            return generateIdentifier(node);
		        }
		        return this.generateExpression(node, precedence, flags);
		    };
		    CodeGenerator.prototype.generateFunctionParams = function (node) {
		        var i, iz, result, hasDefault;
		        hasDefault = false;
		        if (node.type === Syntax.ArrowFunctionExpression &&
		                !node.rest && (!node.defaults || node.defaults.length === 0) &&
		                node.params.length === 1 && node.params[0].type === Syntax.Identifier) {
		            result = [generateAsyncPrefix(node, true), generateIdentifier(node.params[0])];
		        } else {
		            result = node.type === Syntax.ArrowFunctionExpression ? [generateAsyncPrefix(node, false)] : [];
		            result.push('(');
		            if (node.defaults) {
		                hasDefault = true;
		            }
		            for (i = 0, iz = node.params.length; i < iz; ++i) {
		                if (hasDefault && node.defaults[i]) {
		                    result.push(this.generateAssignment(node.params[i], node.defaults[i], '=', Precedence.Assignment, E_TTT));
		                } else {
		                    result.push(this.generatePattern(node.params[i], Precedence.Assignment, E_TTT));
		                }
		                if (i + 1 < iz) {
		                    result.push(',' + space);
		                }
		            }
		            if (node.rest) {
		                if (node.params.length) {
		                    result.push(',' + space);
		                }
		                result.push('...');
		                result.push(generateIdentifier(node.rest));
		            }
		            result.push(')');
		        }
		        return result;
		    };
		    CodeGenerator.prototype.generateFunctionBody = function (node) {
		        var result, expr;
		        result = this.generateFunctionParams(node);
		        if (node.type === Syntax.ArrowFunctionExpression) {
		            result.push(space);
		            result.push('=>');
		        }
		        if (node.expression) {
		            result.push(space);
		            expr = this.generateExpression(node.body, Precedence.Assignment, E_TTT);
		            if (expr.toString().charAt(0) === '{') {
		                expr = ['(', expr, ')'];
		            }
		            result.push(expr);
		        } else {
		            result.push(this.maybeBlock(node.body, S_TTFF));
		        }
		        return result;
		    };
		    CodeGenerator.prototype.generateIterationForStatement = function (operator, stmt, flags) {
		        var result = ['for' + (stmt.await ? noEmptySpace() + 'await' : '') + space + '('], that = this;
		        withIndent(function () {
		            if (stmt.left.type === Syntax.VariableDeclaration) {
		                withIndent(function () {
		                    result.push(stmt.left.kind + noEmptySpace());
		                    result.push(that.generateStatement(stmt.left.declarations[0], S_FFFF));
		                });
		            } else {
		                result.push(that.generateExpression(stmt.left, Precedence.Call, E_TTT));
		            }
		            result = join(result, operator);
		            result = [join(
		                result,
		                that.generateExpression(stmt.right, Precedence.Assignment, E_TTT)
		            ), ')'];
		        });
		        result.push(this.maybeBlock(stmt.body, flags));
		        return result;
		    };
		    CodeGenerator.prototype.generatePropertyKey = function (expr, computed) {
		        var result = [];
		        if (computed) {
		            result.push('[');
		        }
		        result.push(this.generateExpression(expr, Precedence.Assignment, E_TTT));
		        if (computed) {
		            result.push(']');
		        }
		        return result;
		    };
		    CodeGenerator.prototype.generateAssignment = function (left, right, operator, precedence, flags) {
		        if (Precedence.Assignment < precedence) {
		            flags |= F_ALLOW_IN;
		        }
		        return parenthesize(
		            [
		                this.generateExpression(left, Precedence.Call, flags),
		                space + operator + space,
		                this.generateExpression(right, Precedence.Assignment, flags)
		            ],
		            Precedence.Assignment,
		            precedence
		        );
		    };
		    CodeGenerator.prototype.semicolon = function (flags) {
		        if (!semicolons && flags & F_SEMICOLON_OPT) {
		            return '';
		        }
		        return ';';
		    };
		    CodeGenerator.Statement = {
		        BlockStatement: function (stmt, flags) {
		            var range, content, result = ['{', newline], that = this;
		            withIndent(function () {
		                if (stmt.body.length === 0 && preserveBlankLines) {
		                    range = stmt.range;
		                    if (range[1] - range[0] > 2) {
		                        content = sourceCode.substring(range[0] + 1, range[1] - 1);
		                        if (content[0] === '\n') {
		                            result = ['{'];
		                        }
		                        result.push(content);
		                    }
		                }
		                var i, iz, fragment, bodyFlags;
		                bodyFlags = S_TFFF;
		                if (flags & F_FUNC_BODY) {
		                    bodyFlags |= F_DIRECTIVE_CTX;
		                }
		                for (i = 0, iz = stmt.body.length; i < iz; ++i) {
		                    if (preserveBlankLines) {
		                        if (i === 0) {
		                            if (stmt.body[0].leadingComments) {
		                                range = stmt.body[0].leadingComments[0].extendedRange;
		                                content = sourceCode.substring(range[0], range[1]);
		                                if (content[0] === '\n') {
		                                    result = ['{'];
		                                }
		                            }
		                            if (!stmt.body[0].leadingComments) {
		                                generateBlankLines(stmt.range[0], stmt.body[0].range[0], result);
		                            }
		                        }
		                        if (i > 0) {
		                            if (!stmt.body[i - 1].trailingComments  && !stmt.body[i].leadingComments) {
		                                generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
		                            }
		                        }
		                    }
		                    if (i === iz - 1) {
		                        bodyFlags |= F_SEMICOLON_OPT;
		                    }
		                    if (stmt.body[i].leadingComments && preserveBlankLines) {
		                        fragment = that.generateStatement(stmt.body[i], bodyFlags);
		                    } else {
		                        fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags));
		                    }
		                    result.push(fragment);
		                    if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
		                        if (preserveBlankLines && i < iz - 1) {
		                            if (!stmt.body[i + 1].leadingComments) {
		                                result.push(newline);
		                            }
		                        } else {
		                            result.push(newline);
		                        }
		                    }
		                    if (preserveBlankLines) {
		                        if (i === iz - 1) {
		                            if (!stmt.body[i].trailingComments) {
		                                generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
		                            }
		                        }
		                    }
		                }
		            });
		            result.push(addIndent('}'));
		            return result;
		        },
		        BreakStatement: function (stmt, flags) {
		            if (stmt.label) {
		                return 'break ' + stmt.label.name + this.semicolon(flags);
		            }
		            return 'break' + this.semicolon(flags);
		        },
		        ContinueStatement: function (stmt, flags) {
		            if (stmt.label) {
		                return 'continue ' + stmt.label.name + this.semicolon(flags);
		            }
		            return 'continue' + this.semicolon(flags);
		        },
		        ClassBody: function (stmt, flags) {
		            var result = [ '{', newline], that = this;
		            withIndent(function (indent) {
		                var i, iz;
		                for (i = 0, iz = stmt.body.length; i < iz; ++i) {
		                    result.push(indent);
		                    result.push(that.generateExpression(stmt.body[i], Precedence.Sequence, E_TTT));
		                    if (i + 1 < iz) {
		                        result.push(newline);
		                    }
		                }
		            });
		            if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
		                result.push(newline);
		            }
		            result.push(base);
		            result.push('}');
		            return result;
		        },
		        ClassDeclaration: function (stmt, flags) {
		            var result, fragment;
		            result  = ['class'];
		            if (stmt.id) {
		                result = join(result, this.generateExpression(stmt.id, Precedence.Sequence, E_TTT));
		            }
		            if (stmt.superClass) {
		                fragment = join('extends', this.generateExpression(stmt.superClass, Precedence.Unary, E_TTT));
		                result = join(result, fragment);
		            }
		            result.push(space);
		            result.push(this.generateStatement(stmt.body, S_TFFT));
		            return result;
		        },
		        DirectiveStatement: function (stmt, flags) {
		            if (extra.raw && stmt.raw) {
		                return stmt.raw + this.semicolon(flags);
		            }
		            return escapeDirective(stmt.directive) + this.semicolon(flags);
		        },
		        DoWhileStatement: function (stmt, flags) {
		            var result = join('do', this.maybeBlock(stmt.body, S_TFFF));
		            result = this.maybeBlockSuffix(stmt.body, result);
		            return join(result, [
		                'while' + space + '(',
		                this.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
		                ')' + this.semicolon(flags)
		            ]);
		        },
		        CatchClause: function (stmt, flags) {
		            var result, that = this;
		            withIndent(function () {
		                var guard;
		                if (stmt.param) {
		                    result = [
		                        'catch' + space + '(',
		                        that.generateExpression(stmt.param, Precedence.Sequence, E_TTT),
		                        ')'
		                    ];
		                    if (stmt.guard) {
		                        guard = that.generateExpression(stmt.guard, Precedence.Sequence, E_TTT);
		                        result.splice(2, 0, ' if ', guard);
		                    }
		                } else {
		                    result = ['catch'];
		                }
		            });
		            result.push(this.maybeBlock(stmt.body, S_TFFF));
		            return result;
		        },
		        DebuggerStatement: function (stmt, flags) {
		            return 'debugger' + this.semicolon(flags);
		        },
		        EmptyStatement: function (stmt, flags) {
		            return ';';
		        },
		        ExportDefaultDeclaration: function (stmt, flags) {
		            var result = [ 'export' ], bodyFlags;
		            bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;
		            result = join(result, 'default');
		            if (isStatement(stmt.declaration)) {
		                result = join(result, this.generateStatement(stmt.declaration, bodyFlags));
		            } else {
		                result = join(result, this.generateExpression(stmt.declaration, Precedence.Assignment, E_TTT) + this.semicolon(flags));
		            }
		            return result;
		        },
		        ExportNamedDeclaration: function (stmt, flags) {
		            var result = [ 'export' ], bodyFlags, that = this;
		            bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;
		            if (stmt.declaration) {
		                return join(result, this.generateStatement(stmt.declaration, bodyFlags));
		            }
		            if (stmt.specifiers) {
		                if (stmt.specifiers.length === 0) {
		                    result = join(result, '{' + space + '}');
		                } else if (stmt.specifiers[0].type === Syntax.ExportBatchSpecifier) {
		                    result = join(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT));
		                } else {
		                    result = join(result, '{');
		                    withIndent(function (indent) {
		                        var i, iz;
		                        result.push(newline);
		                        for (i = 0, iz = stmt.specifiers.length; i < iz; ++i) {
		                            result.push(indent);
		                            result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
		                            if (i + 1 < iz) {
		                                result.push(',' + newline);
		                            }
		                        }
		                    });
		                    if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
		                        result.push(newline);
		                    }
		                    result.push(base + '}');
		                }
		                if (stmt.source) {
		                    result = join(result, [
		                        'from' + space,
		                        this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
		                        this.semicolon(flags)
		                    ]);
		                } else {
		                    result.push(this.semicolon(flags));
		                }
		            }
		            return result;
		        },
		        ExportAllDeclaration: function (stmt, flags) {
		            return [
		                'export' + space,
		                '*' + space,
		                'from' + space,
		                this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
		                this.semicolon(flags)
		            ];
		        },
		        ExpressionStatement: function (stmt, flags) {
		            var result, fragment;
		            function isClassPrefixed(fragment) {
		                var code;
		                if (fragment.slice(0, 5) !== 'class') {
		                    return false;
		                }
		                code = fragment.charCodeAt(5);
		                return code === 0x7B   || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code);
		            }
		            function isFunctionPrefixed(fragment) {
		                var code;
		                if (fragment.slice(0, 8) !== 'function') {
		                    return false;
		                }
		                code = fragment.charCodeAt(8);
		                return code === 0x28  || esutils.code.isWhiteSpace(code) || code === 0x2A   || esutils.code.isLineTerminator(code);
		            }
		            function isAsyncPrefixed(fragment) {
		                var code, i, iz;
		                if (fragment.slice(0, 5) !== 'async') {
		                    return false;
		                }
		                if (!esutils.code.isWhiteSpace(fragment.charCodeAt(5))) {
		                    return false;
		                }
		                for (i = 6, iz = fragment.length; i < iz; ++i) {
		                    if (!esutils.code.isWhiteSpace(fragment.charCodeAt(i))) {
		                        break;
		                    }
		                }
		                if (i === iz) {
		                    return false;
		                }
		                if (fragment.slice(i, i + 8) !== 'function') {
		                    return false;
		                }
		                code = fragment.charCodeAt(i + 8);
		                return code === 0x28  || esutils.code.isWhiteSpace(code) || code === 0x2A   || esutils.code.isLineTerminator(code);
		            }
		            result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT)];
		            fragment = toSourceNodeWhenNeeded(result).toString();
		            if (fragment.charCodeAt(0) === 0x7B   ||
		                    isClassPrefixed(fragment) ||
		                    isFunctionPrefixed(fragment) ||
		                    isAsyncPrefixed(fragment) ||
		                    (directive && (flags & F_DIRECTIVE_CTX) && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === 'string')) {
		                result = ['(', result, ')' + this.semicolon(flags)];
		            } else {
		                result.push(this.semicolon(flags));
		            }
		            return result;
		        },
		        ImportDeclaration: function (stmt, flags) {
		            var result, cursor, that = this;
		            if (stmt.specifiers.length === 0) {
		                return [
		                    'import',
		                    space,
		                    this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
		                    this.semicolon(flags)
		                ];
		            }
		            result = [
		                'import'
		            ];
		            cursor = 0;
		            if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) {
		                result = join(result, [
		                        this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
		                ]);
		                ++cursor;
		            }
		            if (stmt.specifiers[cursor]) {
		                if (cursor !== 0) {
		                    result.push(',');
		                }
		                if (stmt.specifiers[cursor].type === Syntax.ImportNamespaceSpecifier) {
		                    result = join(result, [
		                            space,
		                            this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
		                    ]);
		                } else {
		                    result.push(space + '{');
		                    if ((stmt.specifiers.length - cursor) === 1) {
		                        result.push(space);
		                        result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT));
		                        result.push(space + '}' + space);
		                    } else {
		                        withIndent(function (indent) {
		                            var i, iz;
		                            result.push(newline);
		                            for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) {
		                                result.push(indent);
		                                result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
		                                if (i + 1 < iz) {
		                                    result.push(',' + newline);
		                                }
		                            }
		                        });
		                        if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
		                            result.push(newline);
		                        }
		                        result.push(base + '}' + space);
		                    }
		                }
		            }
		            result = join(result, [
		                'from' + space,
		                this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
		                this.semicolon(flags)
		            ]);
		            return result;
		        },
		        VariableDeclarator: function (stmt, flags) {
		            var itemFlags = (flags & F_ALLOW_IN) ? E_TTT : E_FTT;
		            if (stmt.init) {
		                return [
		                    this.generateExpression(stmt.id, Precedence.Assignment, itemFlags),
		                    space,
		                    '=',
		                    space,
		                    this.generateExpression(stmt.init, Precedence.Assignment, itemFlags)
		                ];
		            }
		            return this.generatePattern(stmt.id, Precedence.Assignment, itemFlags);
		        },
		        VariableDeclaration: function (stmt, flags) {
		            var result, i, iz, node, bodyFlags, that = this;
		            result = [ stmt.kind ];
		            bodyFlags = (flags & F_ALLOW_IN) ? S_TFFF : S_FFFF;
		            function block() {
		                node = stmt.declarations[0];
		                if (extra.comment && node.leadingComments) {
		                    result.push('\n');
		                    result.push(addIndent(that.generateStatement(node, bodyFlags)));
		                } else {
		                    result.push(noEmptySpace());
		                    result.push(that.generateStatement(node, bodyFlags));
		                }
		                for (i = 1, iz = stmt.declarations.length; i < iz; ++i) {
		                    node = stmt.declarations[i];
		                    if (extra.comment && node.leadingComments) {
		                        result.push(',' + newline);
		                        result.push(addIndent(that.generateStatement(node, bodyFlags)));
		                    } else {
		                        result.push(',' + space);
		                        result.push(that.generateStatement(node, bodyFlags));
		                    }
		                }
		            }
		            if (stmt.declarations.length > 1) {
		                withIndent(block);
		            } else {
		                block();
		            }
		            result.push(this.semicolon(flags));
		            return result;
		        },
		        ThrowStatement: function (stmt, flags) {
		            return [join(
		                'throw',
		                this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
		            ), this.semicolon(flags)];
		        },
		        TryStatement: function (stmt, flags) {
		            var result, i, iz, guardedHandlers;
		            result = ['try', this.maybeBlock(stmt.block, S_TFFF)];
		            result = this.maybeBlockSuffix(stmt.block, result);
		            if (stmt.handlers) {
		                for (i = 0, iz = stmt.handlers.length; i < iz; ++i) {
		                    result = join(result, this.generateStatement(stmt.handlers[i], S_TFFF));
		                    if (stmt.finalizer || i + 1 !== iz) {
		                        result = this.maybeBlockSuffix(stmt.handlers[i].body, result);
		                    }
		                }
		            } else {
		                guardedHandlers = stmt.guardedHandlers || [];
		                for (i = 0, iz = guardedHandlers.length; i < iz; ++i) {
		                    result = join(result, this.generateStatement(guardedHandlers[i], S_TFFF));
		                    if (stmt.finalizer || i + 1 !== iz) {
		                        result = this.maybeBlockSuffix(guardedHandlers[i].body, result);
		                    }
		                }
		                if (stmt.handler) {
		                    if (Array.isArray(stmt.handler)) {
		                        for (i = 0, iz = stmt.handler.length; i < iz; ++i) {
		                            result = join(result, this.generateStatement(stmt.handler[i], S_TFFF));
		                            if (stmt.finalizer || i + 1 !== iz) {
		                                result = this.maybeBlockSuffix(stmt.handler[i].body, result);
		                            }
		                        }
		                    } else {
		                        result = join(result, this.generateStatement(stmt.handler, S_TFFF));
		                        if (stmt.finalizer) {
		                            result = this.maybeBlockSuffix(stmt.handler.body, result);
		                        }
		                    }
		                }
		            }
		            if (stmt.finalizer) {
		                result = join(result, ['finally', this.maybeBlock(stmt.finalizer, S_TFFF)]);
		            }
		            return result;
		        },
		        SwitchStatement: function (stmt, flags) {
		            var result, fragment, i, iz, bodyFlags, that = this;
		            withIndent(function () {
		                result = [
		                    'switch' + space + '(',
		                    that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT),
		                    ')' + space + '{' + newline
		                ];
		            });
		            if (stmt.cases) {
		                bodyFlags = S_TFFF;
		                for (i = 0, iz = stmt.cases.length; i < iz; ++i) {
		                    if (i === iz - 1) {
		                        bodyFlags |= F_SEMICOLON_OPT;
		                    }
		                    fragment = addIndent(this.generateStatement(stmt.cases[i], bodyFlags));
		                    result.push(fragment);
		                    if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
		                        result.push(newline);
		                    }
		                }
		            }
		            result.push(addIndent('}'));
		            return result;
		        },
		        SwitchCase: function (stmt, flags) {
		            var result, fragment, i, iz, bodyFlags, that = this;
		            withIndent(function () {
		                if (stmt.test) {
		                    result = [
		                        join('case', that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)),
		                        ':'
		                    ];
		                } else {
		                    result = ['default:'];
		                }
		                i = 0;
		                iz = stmt.consequent.length;
		                if (iz && stmt.consequent[0].type === Syntax.BlockStatement) {
		                    fragment = that.maybeBlock(stmt.consequent[0], S_TFFF);
		                    result.push(fragment);
		                    i = 1;
		                }
		                if (i !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
		                    result.push(newline);
		                }
		                bodyFlags = S_TFFF;
		                for (; i < iz; ++i) {
		                    if (i === iz - 1 && flags & F_SEMICOLON_OPT) {
		                        bodyFlags |= F_SEMICOLON_OPT;
		                    }
		                    fragment = addIndent(that.generateStatement(stmt.consequent[i], bodyFlags));
		                    result.push(fragment);
		                    if (i + 1 !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
		                        result.push(newline);
		                    }
		                }
		            });
		            return result;
		        },
		        IfStatement: function (stmt, flags) {
		            var result, bodyFlags, semicolonOptional, that = this;
		            withIndent(function () {
		                result = [
		                    'if' + space + '(',
		                    that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
		                    ')'
		                ];
		            });
		            semicolonOptional = flags & F_SEMICOLON_OPT;
		            bodyFlags = S_TFFF;
		            if (semicolonOptional) {
		                bodyFlags |= F_SEMICOLON_OPT;
		            }
		            if (stmt.alternate) {
		                result.push(this.maybeBlock(stmt.consequent, S_TFFF));
		                result = this.maybeBlockSuffix(stmt.consequent, result);
		                if (stmt.alternate.type === Syntax.IfStatement) {
		                    result = join(result, ['else ', this.generateStatement(stmt.alternate, bodyFlags)]);
		                } else {
		                    result = join(result, join('else', this.maybeBlock(stmt.alternate, bodyFlags)));
		                }
		            } else {
		                result.push(this.maybeBlock(stmt.consequent, bodyFlags));
		            }
		            return result;
		        },
		        ForStatement: function (stmt, flags) {
		            var result, that = this;
		            withIndent(function () {
		                result = ['for' + space + '('];
		                if (stmt.init) {
		                    if (stmt.init.type === Syntax.VariableDeclaration) {
		                        result.push(that.generateStatement(stmt.init, S_FFFF));
		                    } else {
		                        result.push(that.generateExpression(stmt.init, Precedence.Sequence, E_FTT));
		                        result.push(';');
		                    }
		                } else {
		                    result.push(';');
		                }
		                if (stmt.test) {
		                    result.push(space);
		                    result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT));
		                    result.push(';');
		                } else {
		                    result.push(';');
		                }
		                if (stmt.update) {
		                    result.push(space);
		                    result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT));
		                    result.push(')');
		                } else {
		                    result.push(')');
		                }
		            });
		            result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
		            return result;
		        },
		        ForInStatement: function (stmt, flags) {
		            return this.generateIterationForStatement('in', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
		        },
		        ForOfStatement: function (stmt, flags) {
		            return this.generateIterationForStatement('of', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
		        },
		        LabeledStatement: function (stmt, flags) {
		            return [stmt.label.name + ':', this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)];
		        },
		        Program: function (stmt, flags) {
		            var result, fragment, i, iz, bodyFlags;
		            iz = stmt.body.length;
		            result = [safeConcatenation && iz > 0 ? '\n' : ''];
		            bodyFlags = S_TFTF;
		            for (i = 0; i < iz; ++i) {
		                if (!safeConcatenation && i === iz - 1) {
		                    bodyFlags |= F_SEMICOLON_OPT;
		                }
		                if (preserveBlankLines) {
		                    if (i === 0) {
		                        if (!stmt.body[0].leadingComments) {
		                            generateBlankLines(stmt.range[0], stmt.body[i].range[0], result);
		                        }
		                    }
		                    if (i > 0) {
		                        if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
		                            generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
		                        }
		                    }
		                }
		                fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags));
		                result.push(fragment);
		                if (i + 1 < iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
		                    if (preserveBlankLines) {
		                        if (!stmt.body[i + 1].leadingComments) {
		                            result.push(newline);
		                        }
		                    } else {
		                        result.push(newline);
		                    }
		                }
		                if (preserveBlankLines) {
		                    if (i === iz - 1) {
		                        if (!stmt.body[i].trailingComments) {
		                            generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
		                        }
		                    }
		                }
		            }
		            return result;
		        },
		        FunctionDeclaration: function (stmt, flags) {
		            return [
		                generateAsyncPrefix(stmt, true),
		                'function',
		                generateStarSuffix(stmt) || noEmptySpace(),
		                stmt.id ? generateIdentifier(stmt.id) : '',
		                this.generateFunctionBody(stmt)
		            ];
		        },
		        ReturnStatement: function (stmt, flags) {
		            if (stmt.argument) {
		                return [join(
		                    'return',
		                    this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
		                ), this.semicolon(flags)];
		            }
		            return ['return' + this.semicolon(flags)];
		        },
		        WhileStatement: function (stmt, flags) {
		            var result, that = this;
		            withIndent(function () {
		                result = [
		                    'while' + space + '(',
		                    that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
		                    ')'
		                ];
		            });
		            result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
		            return result;
		        },
		        WithStatement: function (stmt, flags) {
		            var result, that = this;
		            withIndent(function () {
		                result = [
		                    'with' + space + '(',
		                    that.generateExpression(stmt.object, Precedence.Sequence, E_TTT),
		                    ')'
		                ];
		            });
		            result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
		            return result;
		        }
		    };
		    merge(CodeGenerator.prototype, CodeGenerator.Statement);
		    CodeGenerator.Expression = {
		        SequenceExpression: function (expr, precedence, flags) {
		            var result, i, iz;
		            if (Precedence.Sequence < precedence) {
		                flags |= F_ALLOW_IN;
		            }
		            result = [];
		            for (i = 0, iz = expr.expressions.length; i < iz; ++i) {
		                result.push(this.generateExpression(expr.expressions[i], Precedence.Assignment, flags));
		                if (i + 1 < iz) {
		                    result.push(',' + space);
		                }
		            }
		            return parenthesize(result, Precedence.Sequence, precedence);
		        },
		        AssignmentExpression: function (expr, precedence, flags) {
		            return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags);
		        },
		        ArrowFunctionExpression: function (expr, precedence, flags) {
		            return parenthesize(this.generateFunctionBody(expr), Precedence.ArrowFunction, precedence);
		        },
		        ConditionalExpression: function (expr, precedence, flags) {
		            if (Precedence.Conditional < precedence) {
		                flags |= F_ALLOW_IN;
		            }
		            return parenthesize(
		                [
		                    this.generateExpression(expr.test, Precedence.Coalesce, flags),
		                    space + '?' + space,
		                    this.generateExpression(expr.consequent, Precedence.Assignment, flags),
		                    space + ':' + space,
		                    this.generateExpression(expr.alternate, Precedence.Assignment, flags)
		                ],
		                Precedence.Conditional,
		                precedence
		            );
		        },
		        LogicalExpression: function (expr, precedence, flags) {
		            if (expr.operator === '??') {
		                flags |= F_FOUND_COALESCE;
		            }
		            return this.BinaryExpression(expr, precedence, flags);
		        },
		        BinaryExpression: function (expr, precedence, flags) {
		            var result, leftPrecedence, rightPrecedence, currentPrecedence, fragment, leftSource;
		            currentPrecedence = BinaryPrecedence[expr.operator];
		            leftPrecedence = expr.operator === '**' ? Precedence.Postfix : currentPrecedence;
		            rightPrecedence = expr.operator === '**' ? currentPrecedence : currentPrecedence + 1;
		            if (currentPrecedence < precedence) {
		                flags |= F_ALLOW_IN;
		            }
		            fragment = this.generateExpression(expr.left, leftPrecedence, flags);
		            leftSource = fragment.toString();
		            if (leftSource.charCodeAt(leftSource.length - 1) === 0x2F  && esutils.code.isIdentifierPartES5(expr.operator.charCodeAt(0))) {
		                result = [fragment, noEmptySpace(), expr.operator];
		            } else {
		                result = join(fragment, expr.operator);
		            }
		            fragment = this.generateExpression(expr.right, rightPrecedence, flags);
		            if (expr.operator === '/' && fragment.toString().charAt(0) === '/' ||
		            expr.operator.slice(-1) === '<' && fragment.toString().slice(0, 3) === '!--') {
		                result.push(noEmptySpace());
		                result.push(fragment);
		            } else {
		                result = join(result, fragment);
		            }
		            if (expr.operator === 'in' && !(flags & F_ALLOW_IN)) {
		                return ['(', result, ')'];
		            }
		            if ((expr.operator === '||' || expr.operator === '&&') && (flags & F_FOUND_COALESCE)) {
		                return ['(', result, ')'];
		            }
		            return parenthesize(result, currentPrecedence, precedence);
		        },
		        CallExpression: function (expr, precedence, flags) {
		            var result, i, iz;
		            result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)];
		            if (expr.optional) {
		                result.push('?.');
		            }
		            result.push('(');
		            for (i = 0, iz = expr['arguments'].length; i < iz; ++i) {
		                result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
		                if (i + 1 < iz) {
		                    result.push(',' + space);
		                }
		            }
		            result.push(')');
		            if (!(flags & F_ALLOW_CALL)) {
		                return ['(', result, ')'];
		            }
		            return parenthesize(result, Precedence.Call, precedence);
		        },
		        ChainExpression: function (expr, precedence, flags) {
		            if (Precedence.OptionalChaining < precedence) {
		                flags |= F_ALLOW_CALL;
		            }
		            var result = this.generateExpression(expr.expression, Precedence.OptionalChaining, flags);
		            return parenthesize(result, Precedence.OptionalChaining, precedence);
		        },
		        NewExpression: function (expr, precedence, flags) {
		            var result, length, i, iz, itemFlags;
		            length = expr['arguments'].length;
		            itemFlags = (flags & F_ALLOW_UNPARATH_NEW && !parentheses && length === 0) ? E_TFT : E_TFF;
		            result = join(
		                'new',
		                this.generateExpression(expr.callee, Precedence.New, itemFlags)
		            );
		            if (!(flags & F_ALLOW_UNPARATH_NEW) || parentheses || length > 0) {
		                result.push('(');
		                for (i = 0, iz = length; i < iz; ++i) {
		                    result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
		                    if (i + 1 < iz) {
		                        result.push(',' + space);
		                    }
		                }
		                result.push(')');
		            }
		            return parenthesize(result, Precedence.New, precedence);
		        },
		        MemberExpression: function (expr, precedence, flags) {
		            var result, fragment;
		            result = [this.generateExpression(expr.object, Precedence.Call, (flags & F_ALLOW_CALL) ? E_TTF : E_TFF)];
		            if (expr.computed) {
		                if (expr.optional) {
		                    result.push('?.');
		                }
		                result.push('[');
		                result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT));
		                result.push(']');
		            } else {
		                if (!expr.optional && expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') {
		                    fragment = toSourceNodeWhenNeeded(result).toString();
		                    if (
		                            fragment.indexOf('.') < 0 &&
		                            !/[eExX]/.test(fragment) &&
		                            esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) &&
		                            !(fragment.length >= 2 && fragment.charCodeAt(0) === 48)
		                            ) {
		                        result.push(' ');
		                    }
		                }
		                result.push(expr.optional ? '?.' : '.');
		                result.push(generateIdentifier(expr.property));
		            }
		            return parenthesize(result, Precedence.Member, precedence);
		        },
		        MetaProperty: function (expr, precedence, flags) {
		            var result;
		            result = [];
		            result.push(typeof expr.meta === "string" ? expr.meta : generateIdentifier(expr.meta));
		            result.push('.');
		            result.push(typeof expr.property === "string" ? expr.property : generateIdentifier(expr.property));
		            return parenthesize(result, Precedence.Member, precedence);
		        },
		        UnaryExpression: function (expr, precedence, flags) {
		            var result, fragment, rightCharCode, leftSource, leftCharCode;
		            fragment = this.generateExpression(expr.argument, Precedence.Unary, E_TTT);
		            if (space === '') {
		                result = join(expr.operator, fragment);
		            } else {
		                result = [expr.operator];
		                if (expr.operator.length > 2) {
		                    result = join(result, fragment);
		                } else {
		                    leftSource = toSourceNodeWhenNeeded(result).toString();
		                    leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
		                    rightCharCode = fragment.toString().charCodeAt(0);
		                    if (((leftCharCode === 0x2B   || leftCharCode === 0x2D  ) && leftCharCode === rightCharCode) ||
		                            (esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode))) {
		                        result.push(noEmptySpace());
		                        result.push(fragment);
		                    } else {
		                        result.push(fragment);
		                    }
		                }
		            }
		            return parenthesize(result, Precedence.Unary, precedence);
		        },
		        YieldExpression: function (expr, precedence, flags) {
		            var result;
		            if (expr.delegate) {
		                result = 'yield*';
		            } else {
		                result = 'yield';
		            }
		            if (expr.argument) {
		                result = join(
		                    result,
		                    this.generateExpression(expr.argument, Precedence.Yield, E_TTT)
		                );
		            }
		            return parenthesize(result, Precedence.Yield, precedence);
		        },
		        AwaitExpression: function (expr, precedence, flags) {
		            var result = join(
		                expr.all ? 'await*' : 'await',
		                this.generateExpression(expr.argument, Precedence.Await, E_TTT)
		            );
		            return parenthesize(result, Precedence.Await, precedence);
		        },
		        UpdateExpression: function (expr, precedence, flags) {
		            if (expr.prefix) {
		                return parenthesize(
		                    [
		                        expr.operator,
		                        this.generateExpression(expr.argument, Precedence.Unary, E_TTT)
		                    ],
		                    Precedence.Unary,
		                    precedence
		                );
		            }
		            return parenthesize(
		                [
		                    this.generateExpression(expr.argument, Precedence.Postfix, E_TTT),
		                    expr.operator
		                ],
		                Precedence.Postfix,
		                precedence
		            );
		        },
		        FunctionExpression: function (expr, precedence, flags) {
		            var result = [
		                generateAsyncPrefix(expr, true),
		                'function'
		            ];
		            if (expr.id) {
		                result.push(generateStarSuffix(expr) || noEmptySpace());
		                result.push(generateIdentifier(expr.id));
		            } else {
		                result.push(generateStarSuffix(expr) || space);
		            }
		            result.push(this.generateFunctionBody(expr));
		            return result;
		        },
		        ArrayPattern: function (expr, precedence, flags) {
		            return this.ArrayExpression(expr, precedence, flags, true);
		        },
		        ArrayExpression: function (expr, precedence, flags, isPattern) {
		            var result, multiline, that = this;
		            if (!expr.elements.length) {
		                return '[]';
		            }
		            multiline = isPattern ? false : expr.elements.length > 1;
		            result = ['[', multiline ? newline : ''];
		            withIndent(function (indent) {
		                var i, iz;
		                for (i = 0, iz = expr.elements.length; i < iz; ++i) {
		                    if (!expr.elements[i]) {
		                        if (multiline) {
		                            result.push(indent);
		                        }
		                        if (i + 1 === iz) {
		                            result.push(',');
		                        }
		                    } else {
		                        result.push(multiline ? indent : '');
		                        result.push(that.generateExpression(expr.elements[i], Precedence.Assignment, E_TTT));
		                    }
		                    if (i + 1 < iz) {
		                        result.push(',' + (multiline ? newline : space));
		                    }
		                }
		            });
		            if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
		                result.push(newline);
		            }
		            result.push(multiline ? base : '');
		            result.push(']');
		            return result;
		        },
		        RestElement: function(expr, precedence, flags) {
		            return '...' + this.generatePattern(expr.argument);
		        },
		        ClassExpression: function (expr, precedence, flags) {
		            var result, fragment;
		            result = ['class'];
		            if (expr.id) {
		                result = join(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT));
		            }
		            if (expr.superClass) {
		                fragment = join('extends', this.generateExpression(expr.superClass, Precedence.Unary, E_TTT));
		                result = join(result, fragment);
		            }
		            result.push(space);
		            result.push(this.generateStatement(expr.body, S_TFFT));
		            return result;
		        },
		        MethodDefinition: function (expr, precedence, flags) {
		            var result, fragment;
		            if (expr['static']) {
		                result = ['static' + space];
		            } else {
		                result = [];
		            }
		            if (expr.kind === 'get' || expr.kind === 'set') {
		                fragment = [
		                    join(expr.kind, this.generatePropertyKey(expr.key, expr.computed)),
		                    this.generateFunctionBody(expr.value)
		                ];
		            } else {
		                fragment = [
		                    generateMethodPrefix(expr),
		                    this.generatePropertyKey(expr.key, expr.computed),
		                    this.generateFunctionBody(expr.value)
		                ];
		            }
		            return join(result, fragment);
		        },
		        Property: function (expr, precedence, flags) {
		            if (expr.kind === 'get' || expr.kind === 'set') {
		                return [
		                    expr.kind, noEmptySpace(),
		                    this.generatePropertyKey(expr.key, expr.computed),
		                    this.generateFunctionBody(expr.value)
		                ];
		            }
		            if (expr.shorthand) {
		                if (expr.value.type === "AssignmentPattern") {
		                    return this.AssignmentPattern(expr.value, Precedence.Sequence, E_TTT);
		                }
		                return this.generatePropertyKey(expr.key, expr.computed);
		            }
		            if (expr.method) {
		                return [
		                    generateMethodPrefix(expr),
		                    this.generatePropertyKey(expr.key, expr.computed),
		                    this.generateFunctionBody(expr.value)
		                ];
		            }
		            return [
		                this.generatePropertyKey(expr.key, expr.computed),
		                ':' + space,
		                this.generateExpression(expr.value, Precedence.Assignment, E_TTT)
		            ];
		        },
		        ObjectExpression: function (expr, precedence, flags) {
		            var multiline, result, fragment, that = this;
		            if (!expr.properties.length) {
		                return '{}';
		            }
		            multiline = expr.properties.length > 1;
		            withIndent(function () {
		                fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT);
		            });
		            if (!multiline) {
		                if (!hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
		                    return [ '{', space, fragment, space, '}' ];
		                }
		            }
		            withIndent(function (indent) {
		                var i, iz;
		                result = [ '{', newline, indent, fragment ];
		                if (multiline) {
		                    result.push(',' + newline);
		                    for (i = 1, iz = expr.properties.length; i < iz; ++i) {
		                        result.push(indent);
		                        result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));
		                        if (i + 1 < iz) {
		                            result.push(',' + newline);
		                        }
		                    }
		                }
		            });
		            if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
		                result.push(newline);
		            }
		            result.push(base);
		            result.push('}');
		            return result;
		        },
		        AssignmentPattern: function(expr, precedence, flags) {
		            return this.generateAssignment(expr.left, expr.right, '=', precedence, flags);
		        },
		        ObjectPattern: function (expr, precedence, flags) {
		            var result, i, iz, multiline, property, that = this;
		            if (!expr.properties.length) {
		                return '{}';
		            }
		            multiline = false;
		            if (expr.properties.length === 1) {
		                property = expr.properties[0];
		                if (
		                    property.type === Syntax.Property
		                    && property.value.type !== Syntax.Identifier
		                ) {
		                    multiline = true;
		                }
		            } else {
		                for (i = 0, iz = expr.properties.length; i < iz; ++i) {
		                    property = expr.properties[i];
		                    if (
		                        property.type === Syntax.Property
		                        && !property.shorthand
		                    ) {
		                        multiline = true;
		                        break;
		                    }
		                }
		            }
		            result = ['{', multiline ? newline : '' ];
		            withIndent(function (indent) {
		                var i, iz;
		                for (i = 0, iz = expr.properties.length; i < iz; ++i) {
		                    result.push(multiline ? indent : '');
		                    result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));
		                    if (i + 1 < iz) {
		                        result.push(',' + (multiline ? newline : space));
		                    }
		                }
		            });
		            if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
		                result.push(newline);
		            }
		            result.push(multiline ? base : '');
		            result.push('}');
		            return result;
		        },
		        ThisExpression: function (expr, precedence, flags) {
		            return 'this';
		        },
		        Super: function (expr, precedence, flags) {
		            return 'super';
		        },
		        Identifier: function (expr, precedence, flags) {
		            return generateIdentifier(expr);
		        },
		        ImportDefaultSpecifier: function (expr, precedence, flags) {
		            return generateIdentifier(expr.id || expr.local);
		        },
		        ImportNamespaceSpecifier: function (expr, precedence, flags) {
		            var result = ['*'];
		            var id = expr.id || expr.local;
		            if (id) {
		                result.push(space + 'as' + noEmptySpace() + generateIdentifier(id));
		            }
		            return result;
		        },
		        ImportSpecifier: function (expr, precedence, flags) {
		            var imported = expr.imported;
		            var result = [ imported.name ];
		            var local = expr.local;
		            if (local && local.name !== imported.name) {
		                result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(local));
		            }
		            return result;
		        },
		        ExportSpecifier: function (expr, precedence, flags) {
		            var local = expr.local;
		            var result = [ local.name ];
		            var exported = expr.exported;
		            if (exported && exported.name !== local.name) {
		                result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(exported));
		            }
		            return result;
		        },
		        Literal: function (expr, precedence, flags) {
		            var raw;
		            if (expr.hasOwnProperty('raw') && parse && extra.raw) {
		                try {
		                    raw = parse(expr.raw).body[0].expression;
		                    if (raw.type === Syntax.Literal) {
		                        if (raw.value === expr.value) {
		                            return expr.raw;
		                        }
		                    }
		                } catch (e) {
		                }
		            }
		            if (expr.regex) {
		              return '/' + expr.regex.pattern + '/' + expr.regex.flags;
		            }
		            if (typeof expr.value === 'bigint') {
		                return expr.value.toString() + 'n';
		            }
		            if (expr.bigint) {
		                return expr.bigint + 'n';
		            }
		            if (expr.value === null) {
		                return 'null';
		            }
		            if (typeof expr.value === 'string') {
		                return escapeString(expr.value);
		            }
		            if (typeof expr.value === 'number') {
		                return generateNumber(expr.value);
		            }
		            if (typeof expr.value === 'boolean') {
		                return expr.value ? 'true' : 'false';
		            }
		            return generateRegExp(expr.value);
		        },
		        GeneratorExpression: function (expr, precedence, flags) {
		            return this.ComprehensionExpression(expr, precedence, flags);
		        },
		        ComprehensionExpression: function (expr, precedence, flags) {
		            var result, i, iz, fragment, that = this;
		            result = (expr.type === Syntax.GeneratorExpression) ? ['('] : ['['];
		            if (extra.moz.comprehensionExpressionStartsWithAssignment) {
		                fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
		                result.push(fragment);
		            }
		            if (expr.blocks) {
		                withIndent(function () {
		                    for (i = 0, iz = expr.blocks.length; i < iz; ++i) {
		                        fragment = that.generateExpression(expr.blocks[i], Precedence.Sequence, E_TTT);
		                        if (i > 0 || extra.moz.comprehensionExpressionStartsWithAssignment) {
		                            result = join(result, fragment);
		                        } else {
		                            result.push(fragment);
		                        }
		                    }
		                });
		            }
		            if (expr.filter) {
		                result = join(result, 'if' + space);
		                fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT);
		                result = join(result, [ '(', fragment, ')' ]);
		            }
		            if (!extra.moz.comprehensionExpressionStartsWithAssignment) {
		                fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
		                result = join(result, fragment);
		            }
		            result.push((expr.type === Syntax.GeneratorExpression) ? ')' : ']');
		            return result;
		        },
		        ComprehensionBlock: function (expr, precedence, flags) {
		            var fragment;
		            if (expr.left.type === Syntax.VariableDeclaration) {
		                fragment = [
		                    expr.left.kind, noEmptySpace(),
		                    this.generateStatement(expr.left.declarations[0], S_FFFF)
		                ];
		            } else {
		                fragment = this.generateExpression(expr.left, Precedence.Call, E_TTT);
		            }
		            fragment = join(fragment, expr.of ? 'of' : 'in');
		            fragment = join(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT));
		            return [ 'for' + space + '(', fragment, ')' ];
		        },
		        SpreadElement: function (expr, precedence, flags) {
		            return [
		                '...',
		                this.generateExpression(expr.argument, Precedence.Assignment, E_TTT)
		            ];
		        },
		        TaggedTemplateExpression: function (expr, precedence, flags) {
		            var itemFlags = E_TTF;
		            if (!(flags & F_ALLOW_CALL)) {
		                itemFlags = E_TFF;
		            }
		            var result = [
		                this.generateExpression(expr.tag, Precedence.Call, itemFlags),
		                this.generateExpression(expr.quasi, Precedence.Primary, E_FFT)
		            ];
		            return parenthesize(result, Precedence.TaggedTemplate, precedence);
		        },
		        TemplateElement: function (expr, precedence, flags) {
		            return expr.value.raw;
		        },
		        TemplateLiteral: function (expr, precedence, flags) {
		            var result, i, iz;
		            result = [ '`' ];
		            for (i = 0, iz = expr.quasis.length; i < iz; ++i) {
		                result.push(this.generateExpression(expr.quasis[i], Precedence.Primary, E_TTT));
		                if (i + 1 < iz) {
		                    result.push('${' + space);
		                    result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT));
		                    result.push(space + '}');
		                }
		            }
		            result.push('`');
		            return result;
		        },
		        ModuleSpecifier: function (expr, precedence, flags) {
		            return this.Literal(expr, precedence, flags);
		        },
		        ImportExpression: function(expr, precedence, flag) {
		            return parenthesize([
		                'import(',
		                this.generateExpression(expr.source, Precedence.Assignment, E_TTT),
		                ')'
		            ], Precedence.Call, precedence);
		        }
		    };
		    merge(CodeGenerator.prototype, CodeGenerator.Expression);
		    CodeGenerator.prototype.generateExpression = function (expr, precedence, flags) {
		        var result, type;
		        type = expr.type || Syntax.Property;
		        if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) {
		            return generateVerbatim(expr, precedence);
		        }
		        result = this[type](expr, precedence, flags);
		        if (extra.comment) {
		            result = addComments(expr, result);
		        }
		        return toSourceNodeWhenNeeded(result, expr);
		    };
		    CodeGenerator.prototype.generateStatement = function (stmt, flags) {
		        var result,
		            fragment;
		        result = this[stmt.type](stmt, flags);
		        if (extra.comment) {
		            result = addComments(stmt, result);
		        }
		        fragment = toSourceNodeWhenNeeded(result).toString();
		        if (stmt.type === Syntax.Program && !safeConcatenation && newline === '' &&  fragment.charAt(fragment.length - 1) === '\n') {
		            result = sourceMap ? toSourceNodeWhenNeeded(result).replaceRight(/\s+$/, '') : fragment.replace(/\s+$/, '');
		        }
		        return toSourceNodeWhenNeeded(result, stmt);
		    };
		    function generateInternal(node) {
		        var codegen;
		        codegen = new CodeGenerator();
		        if (isStatement(node)) {
		            return codegen.generateStatement(node, S_TFFF);
		        }
		        if (isExpression(node)) {
		            return codegen.generateExpression(node, Precedence.Sequence, E_TTT);
		        }
		        throw new Error('Unknown node type: ' + node.type);
		    }
		    function generate(node, options) {
		        var defaultOptions = getDefaultOptions(), result, pair;
		        if (options != null) {
		            if (typeof options.indent === 'string') {
		                defaultOptions.format.indent.style = options.indent;
		            }
		            if (typeof options.base === 'number') {
		                defaultOptions.format.indent.base = options.base;
		            }
		            options = updateDeeply(defaultOptions, options);
		            indent = options.format.indent.style;
		            if (typeof options.base === 'string') {
		                base = options.base;
		            } else {
		                base = stringRepeat(indent, options.format.indent.base);
		            }
		        } else {
		            options = defaultOptions;
		            indent = options.format.indent.style;
		            base = stringRepeat(indent, options.format.indent.base);
		        }
		        json = options.format.json;
		        renumber = options.format.renumber;
		        hexadecimal = json ? false : options.format.hexadecimal;
		        quotes = json ? 'double' : options.format.quotes;
		        escapeless = options.format.escapeless;
		        newline = options.format.newline;
		        space = options.format.space;
		        if (options.format.compact) {
		            newline = space = indent = base = '';
		        }
		        parentheses = options.format.parentheses;
		        semicolons = options.format.semicolons;
		        safeConcatenation = options.format.safeConcatenation;
		        directive = options.directive;
		        parse = json ? null : options.parse;
		        sourceMap = options.sourceMap;
		        sourceCode = options.sourceCode;
		        preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null;
		        extra = options;
		        if (sourceMap) {
		            if (!exports$1.browser) {
		                SourceNode = requireSourceMap().SourceNode;
		            } else {
		                SourceNode = commonjsGlobal.sourceMap.SourceNode;
		            }
		        }
		        result = generateInternal(node);
		        if (!sourceMap) {
		            pair = {code: result.toString(), map: null};
		            return options.sourceMapWithCode ? pair : pair.code;
		        }
		        pair = result.toStringWithSourceMap({
		            file: options.file,
		            sourceRoot: options.sourceMapRoot
		        });
		        if (options.sourceContent) {
		            pair.map.setSourceContent(options.sourceMap,
		                                      options.sourceContent);
		        }
		        if (options.sourceMapWithCode) {
		            return pair;
		        }
		        return pair.map.toString();
		    }
		    FORMAT_MINIFY = {
		        indent: {
		            style: '',
		            base: 0
		        },
		        renumber: true,
		        hexadecimal: true,
		        quotes: 'auto',
		        escapeless: true,
		        compact: true,
		        parentheses: false,
		        semicolons: false
		    };
		    FORMAT_DEFAULTS = getDefaultOptions().format;
		    exports$1.version = require$$3.version;
		    exports$1.generate = generate;
		    exports$1.attachComments = estraverse.attachComments;
		    exports$1.Precedence = updateDeeply({}, Precedence);
		    exports$1.browser = false;
		    exports$1.FORMAT_MINIFY = FORMAT_MINIFY;
		    exports$1.FORMAT_DEFAULTS = FORMAT_DEFAULTS;
		}()); 
	} (escodegen));
	return escodegen;
}

var esprima$2 = {exports: {}};

var esprima$1 = esprima$2.exports;

var hasRequiredEsprima$1;

function requireEsprima$1 () {
	if (hasRequiredEsprima$1) return esprima$2.exports;
	hasRequiredEsprima$1 = 1;
	(function (module, exports$1) {
		(function webpackUniversalModuleDefinition(root, factory) {
			module.exports = factory();
		})(esprima$1, function() {
		return  (function(modules) {
		 	var installedModules = {};
		 	function __webpack_require__(moduleId) {
		 		if(installedModules[moduleId])
		 			return installedModules[moduleId].exports;
		 		var module = installedModules[moduleId] = {
		 			exports: {},
		 			id: moduleId,
		 			loaded: false
		 		};
		 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
		 		module.loaded = true;
		 		return module.exports;
		 	}
		 	__webpack_require__.m = modules;
		 	__webpack_require__.c = installedModules;
		 	__webpack_require__.p = "";
		 	return __webpack_require__(0);
		 })
		 ([
		 function(module, exports$1, __webpack_require__) {
			/*
			  Copyright JS Foundation and other contributors, https://js.foundation/
			  Redistribution and use in source and binary forms, with or without
			  modification, are permitted provided that the following conditions are met:
			    * Redistributions of source code must retain the above copyright
			      notice, this list of conditions and the following disclaimer.
			    * Redistributions in binary form must reproduce the above copyright
			      notice, this list of conditions and the following disclaimer in the
			      documentation and/or other materials provided with the distribution.
			  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
			  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
			  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
			  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
			  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
			  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
			  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
			  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
			  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
			  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
			*/
			Object.defineProperty(exports$1, "__esModule", { value: true });
			var comment_handler_1 = __webpack_require__(1);
			var jsx_parser_1 = __webpack_require__(3);
			var parser_1 = __webpack_require__(8);
			var tokenizer_1 = __webpack_require__(15);
			function parse(code, options, delegate) {
			    var commentHandler = null;
			    var proxyDelegate = function (node, metadata) {
			        if (delegate) {
			            delegate(node, metadata);
			        }
			        if (commentHandler) {
			            commentHandler.visit(node, metadata);
			        }
			    };
			    var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null;
			    var collectComment = false;
			    if (options) {
			        collectComment = (typeof options.comment === 'boolean' && options.comment);
			        var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment);
			        if (collectComment || attachComment) {
			            commentHandler = new comment_handler_1.CommentHandler();
			            commentHandler.attach = attachComment;
			            options.comment = true;
			            parserDelegate = proxyDelegate;
			        }
			    }
			    var isModule = false;
			    if (options && typeof options.sourceType === 'string') {
			        isModule = (options.sourceType === 'module');
			    }
			    var parser;
			    if (options && typeof options.jsx === 'boolean' && options.jsx) {
			        parser = new jsx_parser_1.JSXParser(code, options, parserDelegate);
			    }
			    else {
			        parser = new parser_1.Parser(code, options, parserDelegate);
			    }
			    var program = isModule ? parser.parseModule() : parser.parseScript();
			    var ast = program;
			    if (collectComment && commentHandler) {
			        ast.comments = commentHandler.comments;
			    }
			    if (parser.config.tokens) {
			        ast.tokens = parser.tokens;
			    }
			    if (parser.config.tolerant) {
			        ast.errors = parser.errorHandler.errors;
			    }
			    return ast;
			}
			exports$1.parse = parse;
			function parseModule(code, options, delegate) {
			    var parsingOptions = options || {};
			    parsingOptions.sourceType = 'module';
			    return parse(code, parsingOptions, delegate);
			}
			exports$1.parseModule = parseModule;
			function parseScript(code, options, delegate) {
			    var parsingOptions = options || {};
			    parsingOptions.sourceType = 'script';
			    return parse(code, parsingOptions, delegate);
			}
			exports$1.parseScript = parseScript;
			function tokenize(code, options, delegate) {
			    var tokenizer = new tokenizer_1.Tokenizer(code, options);
			    var tokens;
			    tokens = [];
			    try {
			        while (true) {
			            var token = tokenizer.getNextToken();
			            if (!token) {
			                break;
			            }
			            if (delegate) {
			                token = delegate(token);
			            }
			            tokens.push(token);
			        }
			    }
			    catch (e) {
			        tokenizer.errorHandler.tolerate(e);
			    }
			    if (tokenizer.errorHandler.tolerant) {
			        tokens.errors = tokenizer.errors();
			    }
			    return tokens;
			}
			exports$1.tokenize = tokenize;
			var syntax_1 = __webpack_require__(2);
			exports$1.Syntax = syntax_1.Syntax;
			exports$1.version = '4.0.1';
		 },
		 function(module, exports$1, __webpack_require__) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			var syntax_1 = __webpack_require__(2);
			var CommentHandler = (function () {
			    function CommentHandler() {
			        this.attach = false;
			        this.comments = [];
			        this.stack = [];
			        this.leading = [];
			        this.trailing = [];
			    }
			    CommentHandler.prototype.insertInnerComments = function (node, metadata) {
			        if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) {
			            var innerComments = [];
			            for (var i = this.leading.length - 1; i >= 0; --i) {
			                var entry = this.leading[i];
			                if (metadata.end.offset >= entry.start) {
			                    innerComments.unshift(entry.comment);
			                    this.leading.splice(i, 1);
			                    this.trailing.splice(i, 1);
			                }
			            }
			            if (innerComments.length) {
			                node.innerComments = innerComments;
			            }
			        }
			    };
			    CommentHandler.prototype.findTrailingComments = function (metadata) {
			        var trailingComments = [];
			        if (this.trailing.length > 0) {
			            for (var i = this.trailing.length - 1; i >= 0; --i) {
			                var entry_1 = this.trailing[i];
			                if (entry_1.start >= metadata.end.offset) {
			                    trailingComments.unshift(entry_1.comment);
			                }
			            }
			            this.trailing.length = 0;
			            return trailingComments;
			        }
			        var entry = this.stack[this.stack.length - 1];
			        if (entry && entry.node.trailingComments) {
			            var firstComment = entry.node.trailingComments[0];
			            if (firstComment && firstComment.range[0] >= metadata.end.offset) {
			                trailingComments = entry.node.trailingComments;
			                delete entry.node.trailingComments;
			            }
			        }
			        return trailingComments;
			    };
			    CommentHandler.prototype.findLeadingComments = function (metadata) {
			        var leadingComments = [];
			        var target;
			        while (this.stack.length > 0) {
			            var entry = this.stack[this.stack.length - 1];
			            if (entry && entry.start >= metadata.start.offset) {
			                target = entry.node;
			                this.stack.pop();
			            }
			            else {
			                break;
			            }
			        }
			        if (target) {
			            var count = target.leadingComments ? target.leadingComments.length : 0;
			            for (var i = count - 1; i >= 0; --i) {
			                var comment = target.leadingComments[i];
			                if (comment.range[1] <= metadata.start.offset) {
			                    leadingComments.unshift(comment);
			                    target.leadingComments.splice(i, 1);
			                }
			            }
			            if (target.leadingComments && target.leadingComments.length === 0) {
			                delete target.leadingComments;
			            }
			            return leadingComments;
			        }
			        for (var i = this.leading.length - 1; i >= 0; --i) {
			            var entry = this.leading[i];
			            if (entry.start <= metadata.start.offset) {
			                leadingComments.unshift(entry.comment);
			                this.leading.splice(i, 1);
			            }
			        }
			        return leadingComments;
			    };
			    CommentHandler.prototype.visitNode = function (node, metadata) {
			        if (node.type === syntax_1.Syntax.Program && node.body.length > 0) {
			            return;
			        }
			        this.insertInnerComments(node, metadata);
			        var trailingComments = this.findTrailingComments(metadata);
			        var leadingComments = this.findLeadingComments(metadata);
			        if (leadingComments.length > 0) {
			            node.leadingComments = leadingComments;
			        }
			        if (trailingComments.length > 0) {
			            node.trailingComments = trailingComments;
			        }
			        this.stack.push({
			            node: node,
			            start: metadata.start.offset
			        });
			    };
			    CommentHandler.prototype.visitComment = function (node, metadata) {
			        var type = (node.type[0] === 'L') ? 'Line' : 'Block';
			        var comment = {
			            type: type,
			            value: node.value
			        };
			        if (node.range) {
			            comment.range = node.range;
			        }
			        if (node.loc) {
			            comment.loc = node.loc;
			        }
			        this.comments.push(comment);
			        if (this.attach) {
			            var entry = {
			                comment: {
			                    type: type,
			                    value: node.value,
			                    range: [metadata.start.offset, metadata.end.offset]
			                },
			                start: metadata.start.offset
			            };
			            if (node.loc) {
			                entry.comment.loc = node.loc;
			            }
			            node.type = type;
			            this.leading.push(entry);
			            this.trailing.push(entry);
			        }
			    };
			    CommentHandler.prototype.visit = function (node, metadata) {
			        if (node.type === 'LineComment') {
			            this.visitComment(node, metadata);
			        }
			        else if (node.type === 'BlockComment') {
			            this.visitComment(node, metadata);
			        }
			        else if (this.attach) {
			            this.visitNode(node, metadata);
			        }
			    };
			    return CommentHandler;
			}());
			exports$1.CommentHandler = CommentHandler;
		 },
		 function(module, exports$1) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			exports$1.Syntax = {
			    AssignmentExpression: 'AssignmentExpression',
			    AssignmentPattern: 'AssignmentPattern',
			    ArrayExpression: 'ArrayExpression',
			    ArrayPattern: 'ArrayPattern',
			    ArrowFunctionExpression: 'ArrowFunctionExpression',
			    AwaitExpression: 'AwaitExpression',
			    BlockStatement: 'BlockStatement',
			    BinaryExpression: 'BinaryExpression',
			    BreakStatement: 'BreakStatement',
			    CallExpression: 'CallExpression',
			    CatchClause: 'CatchClause',
			    ClassBody: 'ClassBody',
			    ClassDeclaration: 'ClassDeclaration',
			    ClassExpression: 'ClassExpression',
			    ConditionalExpression: 'ConditionalExpression',
			    ContinueStatement: 'ContinueStatement',
			    DoWhileStatement: 'DoWhileStatement',
			    DebuggerStatement: 'DebuggerStatement',
			    EmptyStatement: 'EmptyStatement',
			    ExportAllDeclaration: 'ExportAllDeclaration',
			    ExportDefaultDeclaration: 'ExportDefaultDeclaration',
			    ExportNamedDeclaration: 'ExportNamedDeclaration',
			    ExportSpecifier: 'ExportSpecifier',
			    ExpressionStatement: 'ExpressionStatement',
			    ForStatement: 'ForStatement',
			    ForOfStatement: 'ForOfStatement',
			    ForInStatement: 'ForInStatement',
			    FunctionDeclaration: 'FunctionDeclaration',
			    FunctionExpression: 'FunctionExpression',
			    Identifier: 'Identifier',
			    IfStatement: 'IfStatement',
			    ImportDeclaration: 'ImportDeclaration',
			    ImportDefaultSpecifier: 'ImportDefaultSpecifier',
			    ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
			    ImportSpecifier: 'ImportSpecifier',
			    Literal: 'Literal',
			    LabeledStatement: 'LabeledStatement',
			    LogicalExpression: 'LogicalExpression',
			    MemberExpression: 'MemberExpression',
			    MetaProperty: 'MetaProperty',
			    MethodDefinition: 'MethodDefinition',
			    NewExpression: 'NewExpression',
			    ObjectExpression: 'ObjectExpression',
			    ObjectPattern: 'ObjectPattern',
			    Program: 'Program',
			    Property: 'Property',
			    RestElement: 'RestElement',
			    ReturnStatement: 'ReturnStatement',
			    SequenceExpression: 'SequenceExpression',
			    SpreadElement: 'SpreadElement',
			    Super: 'Super',
			    SwitchCase: 'SwitchCase',
			    SwitchStatement: 'SwitchStatement',
			    TaggedTemplateExpression: 'TaggedTemplateExpression',
			    TemplateElement: 'TemplateElement',
			    TemplateLiteral: 'TemplateLiteral',
			    ThisExpression: 'ThisExpression',
			    ThrowStatement: 'ThrowStatement',
			    TryStatement: 'TryStatement',
			    UnaryExpression: 'UnaryExpression',
			    UpdateExpression: 'UpdateExpression',
			    VariableDeclaration: 'VariableDeclaration',
			    VariableDeclarator: 'VariableDeclarator',
			    WhileStatement: 'WhileStatement',
			    WithStatement: 'WithStatement',
			    YieldExpression: 'YieldExpression'
			};
		 },
		 function(module, exports$1, __webpack_require__) {
			var __extends = (this && this.__extends) || (function () {
			    var extendStatics = Object.setPrototypeOf ||
			        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
			        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
			    return function (d, b) {
			        extendStatics(d, b);
			        function __() { this.constructor = d; }
			        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
			    };
			})();
			Object.defineProperty(exports$1, "__esModule", { value: true });
			var character_1 = __webpack_require__(4);
			var JSXNode = __webpack_require__(5);
			var jsx_syntax_1 = __webpack_require__(6);
			var Node = __webpack_require__(7);
			var parser_1 = __webpack_require__(8);
			var token_1 = __webpack_require__(13);
			var xhtml_entities_1 = __webpack_require__(14);
			token_1.TokenName[100 ] = 'JSXIdentifier';
			token_1.TokenName[101 ] = 'JSXText';
			function getQualifiedElementName(elementName) {
			    var qualifiedName;
			    switch (elementName.type) {
			        case jsx_syntax_1.JSXSyntax.JSXIdentifier:
			            var id = elementName;
			            qualifiedName = id.name;
			            break;
			        case jsx_syntax_1.JSXSyntax.JSXNamespacedName:
			            var ns = elementName;
			            qualifiedName = getQualifiedElementName(ns.namespace) + ':' +
			                getQualifiedElementName(ns.name);
			            break;
			        case jsx_syntax_1.JSXSyntax.JSXMemberExpression:
			            var expr = elementName;
			            qualifiedName = getQualifiedElementName(expr.object) + '.' +
			                getQualifiedElementName(expr.property);
			            break;
			    }
			    return qualifiedName;
			}
			var JSXParser = (function (_super) {
			    __extends(JSXParser, _super);
			    function JSXParser(code, options, delegate) {
			        return _super.call(this, code, options, delegate) || this;
			    }
			    JSXParser.prototype.parsePrimaryExpression = function () {
			        return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this);
			    };
			    JSXParser.prototype.startJSX = function () {
			        this.scanner.index = this.startMarker.index;
			        this.scanner.lineNumber = this.startMarker.line;
			        this.scanner.lineStart = this.startMarker.index - this.startMarker.column;
			    };
			    JSXParser.prototype.finishJSX = function () {
			        this.nextToken();
			    };
			    JSXParser.prototype.reenterJSX = function () {
			        this.startJSX();
			        this.expectJSX('}');
			        if (this.config.tokens) {
			            this.tokens.pop();
			        }
			    };
			    JSXParser.prototype.createJSXNode = function () {
			        this.collectComments();
			        return {
			            index: this.scanner.index,
			            line: this.scanner.lineNumber,
			            column: this.scanner.index - this.scanner.lineStart
			        };
			    };
			    JSXParser.prototype.createJSXChildNode = function () {
			        return {
			            index: this.scanner.index,
			            line: this.scanner.lineNumber,
			            column: this.scanner.index - this.scanner.lineStart
			        };
			    };
			    JSXParser.prototype.scanXHTMLEntity = function (quote) {
			        var result = '&';
			        var valid = true;
			        var terminated = false;
			        var numeric = false;
			        var hex = false;
			        while (!this.scanner.eof() && valid && !terminated) {
			            var ch = this.scanner.source[this.scanner.index];
			            if (ch === quote) {
			                break;
			            }
			            terminated = (ch === ';');
			            result += ch;
			            ++this.scanner.index;
			            if (!terminated) {
			                switch (result.length) {
			                    case 2:
			                        numeric = (ch === '#');
			                        break;
			                    case 3:
			                        if (numeric) {
			                            hex = (ch === 'x');
			                            valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0));
			                            numeric = numeric && !hex;
			                        }
			                        break;
			                    default:
			                        valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0)));
			                        valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0)));
			                        break;
			                }
			            }
			        }
			        if (valid && terminated && result.length > 2) {
			            var str = result.substr(1, result.length - 2);
			            if (numeric && str.length > 1) {
			                result = String.fromCharCode(parseInt(str.substr(1), 10));
			            }
			            else if (hex && str.length > 2) {
			                result = String.fromCharCode(parseInt('0' + str.substr(1), 16));
			            }
			            else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) {
			                result = xhtml_entities_1.XHTMLEntities[str];
			            }
			        }
			        return result;
			    };
			    JSXParser.prototype.lexJSX = function () {
			        var cp = this.scanner.source.charCodeAt(this.scanner.index);
			        if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) {
			            var value = this.scanner.source[this.scanner.index++];
			            return {
			                type: 7 ,
			                value: value,
			                lineNumber: this.scanner.lineNumber,
			                lineStart: this.scanner.lineStart,
			                start: this.scanner.index - 1,
			                end: this.scanner.index
			            };
			        }
			        if (cp === 34 || cp === 39) {
			            var start = this.scanner.index;
			            var quote = this.scanner.source[this.scanner.index++];
			            var str = '';
			            while (!this.scanner.eof()) {
			                var ch = this.scanner.source[this.scanner.index++];
			                if (ch === quote) {
			                    break;
			                }
			                else if (ch === '&') {
			                    str += this.scanXHTMLEntity(quote);
			                }
			                else {
			                    str += ch;
			                }
			            }
			            return {
			                type: 8 ,
			                value: str,
			                lineNumber: this.scanner.lineNumber,
			                lineStart: this.scanner.lineStart,
			                start: start,
			                end: this.scanner.index
			            };
			        }
			        if (cp === 46) {
			            var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1);
			            var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2);
			            var value = (n1 === 46 && n2 === 46) ? '...' : '.';
			            var start = this.scanner.index;
			            this.scanner.index += value.length;
			            return {
			                type: 7 ,
			                value: value,
			                lineNumber: this.scanner.lineNumber,
			                lineStart: this.scanner.lineStart,
			                start: start,
			                end: this.scanner.index
			            };
			        }
			        if (cp === 96) {
			            return {
			                type: 10 ,
			                value: '',
			                lineNumber: this.scanner.lineNumber,
			                lineStart: this.scanner.lineStart,
			                start: this.scanner.index,
			                end: this.scanner.index
			            };
			        }
			        if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) {
			            var start = this.scanner.index;
			            ++this.scanner.index;
			            while (!this.scanner.eof()) {
			                var ch = this.scanner.source.charCodeAt(this.scanner.index);
			                if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) {
			                    ++this.scanner.index;
			                }
			                else if (ch === 45) {
			                    ++this.scanner.index;
			                }
			                else {
			                    break;
			                }
			            }
			            var id = this.scanner.source.slice(start, this.scanner.index);
			            return {
			                type: 100 ,
			                value: id,
			                lineNumber: this.scanner.lineNumber,
			                lineStart: this.scanner.lineStart,
			                start: start,
			                end: this.scanner.index
			            };
			        }
			        return this.scanner.lex();
			    };
			    JSXParser.prototype.nextJSXToken = function () {
			        this.collectComments();
			        this.startMarker.index = this.scanner.index;
			        this.startMarker.line = this.scanner.lineNumber;
			        this.startMarker.column = this.scanner.index - this.scanner.lineStart;
			        var token = this.lexJSX();
			        this.lastMarker.index = this.scanner.index;
			        this.lastMarker.line = this.scanner.lineNumber;
			        this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
			        if (this.config.tokens) {
			            this.tokens.push(this.convertToken(token));
			        }
			        return token;
			    };
			    JSXParser.prototype.nextJSXText = function () {
			        this.startMarker.index = this.scanner.index;
			        this.startMarker.line = this.scanner.lineNumber;
			        this.startMarker.column = this.scanner.index - this.scanner.lineStart;
			        var start = this.scanner.index;
			        var text = '';
			        while (!this.scanner.eof()) {
			            var ch = this.scanner.source[this.scanner.index];
			            if (ch === '{' || ch === '<') {
			                break;
			            }
			            ++this.scanner.index;
			            text += ch;
			            if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
			                ++this.scanner.lineNumber;
			                if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') {
			                    ++this.scanner.index;
			                }
			                this.scanner.lineStart = this.scanner.index;
			            }
			        }
			        this.lastMarker.index = this.scanner.index;
			        this.lastMarker.line = this.scanner.lineNumber;
			        this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
			        var token = {
			            type: 101 ,
			            value: text,
			            lineNumber: this.scanner.lineNumber,
			            lineStart: this.scanner.lineStart,
			            start: start,
			            end: this.scanner.index
			        };
			        if ((text.length > 0) && this.config.tokens) {
			            this.tokens.push(this.convertToken(token));
			        }
			        return token;
			    };
			    JSXParser.prototype.peekJSXToken = function () {
			        var state = this.scanner.saveState();
			        this.scanner.scanComments();
			        var next = this.lexJSX();
			        this.scanner.restoreState(state);
			        return next;
			    };
			    JSXParser.prototype.expectJSX = function (value) {
			        var token = this.nextJSXToken();
			        if (token.type !== 7  || token.value !== value) {
			            this.throwUnexpectedToken(token);
			        }
			    };
			    JSXParser.prototype.matchJSX = function (value) {
			        var next = this.peekJSXToken();
			        return next.type === 7  && next.value === value;
			    };
			    JSXParser.prototype.parseJSXIdentifier = function () {
			        var node = this.createJSXNode();
			        var token = this.nextJSXToken();
			        if (token.type !== 100 ) {
			            this.throwUnexpectedToken(token);
			        }
			        return this.finalize(node, new JSXNode.JSXIdentifier(token.value));
			    };
			    JSXParser.prototype.parseJSXElementName = function () {
			        var node = this.createJSXNode();
			        var elementName = this.parseJSXIdentifier();
			        if (this.matchJSX(':')) {
			            var namespace = elementName;
			            this.expectJSX(':');
			            var name_1 = this.parseJSXIdentifier();
			            elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1));
			        }
			        else if (this.matchJSX('.')) {
			            while (this.matchJSX('.')) {
			                var object = elementName;
			                this.expectJSX('.');
			                var property = this.parseJSXIdentifier();
			                elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property));
			            }
			        }
			        return elementName;
			    };
			    JSXParser.prototype.parseJSXAttributeName = function () {
			        var node = this.createJSXNode();
			        var attributeName;
			        var identifier = this.parseJSXIdentifier();
			        if (this.matchJSX(':')) {
			            var namespace = identifier;
			            this.expectJSX(':');
			            var name_2 = this.parseJSXIdentifier();
			            attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2));
			        }
			        else {
			            attributeName = identifier;
			        }
			        return attributeName;
			    };
			    JSXParser.prototype.parseJSXStringLiteralAttribute = function () {
			        var node = this.createJSXNode();
			        var token = this.nextJSXToken();
			        if (token.type !== 8 ) {
			            this.throwUnexpectedToken(token);
			        }
			        var raw = this.getTokenRaw(token);
			        return this.finalize(node, new Node.Literal(token.value, raw));
			    };
			    JSXParser.prototype.parseJSXExpressionAttribute = function () {
			        var node = this.createJSXNode();
			        this.expectJSX('{');
			        this.finishJSX();
			        if (this.match('}')) {
			            this.tolerateError('JSX attributes must only be assigned a non-empty expression');
			        }
			        var expression = this.parseAssignmentExpression();
			        this.reenterJSX();
			        return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
			    };
			    JSXParser.prototype.parseJSXAttributeValue = function () {
			        return this.matchJSX('{') ? this.parseJSXExpressionAttribute() :
			            this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute();
			    };
			    JSXParser.prototype.parseJSXNameValueAttribute = function () {
			        var node = this.createJSXNode();
			        var name = this.parseJSXAttributeName();
			        var value = null;
			        if (this.matchJSX('=')) {
			            this.expectJSX('=');
			            value = this.parseJSXAttributeValue();
			        }
			        return this.finalize(node, new JSXNode.JSXAttribute(name, value));
			    };
			    JSXParser.prototype.parseJSXSpreadAttribute = function () {
			        var node = this.createJSXNode();
			        this.expectJSX('{');
			        this.expectJSX('...');
			        this.finishJSX();
			        var argument = this.parseAssignmentExpression();
			        this.reenterJSX();
			        return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument));
			    };
			    JSXParser.prototype.parseJSXAttributes = function () {
			        var attributes = [];
			        while (!this.matchJSX('/') && !this.matchJSX('>')) {
			            var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() :
			                this.parseJSXNameValueAttribute();
			            attributes.push(attribute);
			        }
			        return attributes;
			    };
			    JSXParser.prototype.parseJSXOpeningElement = function () {
			        var node = this.createJSXNode();
			        this.expectJSX('<');
			        var name = this.parseJSXElementName();
			        var attributes = this.parseJSXAttributes();
			        var selfClosing = this.matchJSX('/');
			        if (selfClosing) {
			            this.expectJSX('/');
			        }
			        this.expectJSX('>');
			        return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
			    };
			    JSXParser.prototype.parseJSXBoundaryElement = function () {
			        var node = this.createJSXNode();
			        this.expectJSX('<');
			        if (this.matchJSX('/')) {
			            this.expectJSX('/');
			            var name_3 = this.parseJSXElementName();
			            this.expectJSX('>');
			            return this.finalize(node, new JSXNode.JSXClosingElement(name_3));
			        }
			        var name = this.parseJSXElementName();
			        var attributes = this.parseJSXAttributes();
			        var selfClosing = this.matchJSX('/');
			        if (selfClosing) {
			            this.expectJSX('/');
			        }
			        this.expectJSX('>');
			        return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
			    };
			    JSXParser.prototype.parseJSXEmptyExpression = function () {
			        var node = this.createJSXChildNode();
			        this.collectComments();
			        this.lastMarker.index = this.scanner.index;
			        this.lastMarker.line = this.scanner.lineNumber;
			        this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
			        return this.finalize(node, new JSXNode.JSXEmptyExpression());
			    };
			    JSXParser.prototype.parseJSXExpressionContainer = function () {
			        var node = this.createJSXNode();
			        this.expectJSX('{');
			        var expression;
			        if (this.matchJSX('}')) {
			            expression = this.parseJSXEmptyExpression();
			            this.expectJSX('}');
			        }
			        else {
			            this.finishJSX();
			            expression = this.parseAssignmentExpression();
			            this.reenterJSX();
			        }
			        return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
			    };
			    JSXParser.prototype.parseJSXChildren = function () {
			        var children = [];
			        while (!this.scanner.eof()) {
			            var node = this.createJSXChildNode();
			            var token = this.nextJSXText();
			            if (token.start < token.end) {
			                var raw = this.getTokenRaw(token);
			                var child = this.finalize(node, new JSXNode.JSXText(token.value, raw));
			                children.push(child);
			            }
			            if (this.scanner.source[this.scanner.index] === '{') {
			                var container = this.parseJSXExpressionContainer();
			                children.push(container);
			            }
			            else {
			                break;
			            }
			        }
			        return children;
			    };
			    JSXParser.prototype.parseComplexJSXElement = function (el) {
			        var stack = [];
			        while (!this.scanner.eof()) {
			            el.children = el.children.concat(this.parseJSXChildren());
			            var node = this.createJSXChildNode();
			            var element = this.parseJSXBoundaryElement();
			            if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) {
			                var opening = element;
			                if (opening.selfClosing) {
			                    var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null));
			                    el.children.push(child);
			                }
			                else {
			                    stack.push(el);
			                    el = { node: node, opening: opening, closing: null, children: [] };
			                }
			            }
			            if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) {
			                el.closing = element;
			                var open_1 = getQualifiedElementName(el.opening.name);
			                var close_1 = getQualifiedElementName(el.closing.name);
			                if (open_1 !== close_1) {
			                    this.tolerateError('Expected corresponding JSX closing tag for %0', open_1);
			                }
			                if (stack.length > 0) {
			                    var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing));
			                    el = stack[stack.length - 1];
			                    el.children.push(child);
			                    stack.pop();
			                }
			                else {
			                    break;
			                }
			            }
			        }
			        return el;
			    };
			    JSXParser.prototype.parseJSXElement = function () {
			        var node = this.createJSXNode();
			        var opening = this.parseJSXOpeningElement();
			        var children = [];
			        var closing = null;
			        if (!opening.selfClosing) {
			            var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children });
			            children = el.children;
			            closing = el.closing;
			        }
			        return this.finalize(node, new JSXNode.JSXElement(opening, children, closing));
			    };
			    JSXParser.prototype.parseJSXRoot = function () {
			        if (this.config.tokens) {
			            this.tokens.pop();
			        }
			        this.startJSX();
			        var element = this.parseJSXElement();
			        this.finishJSX();
			        return element;
			    };
			    JSXParser.prototype.isStartOfExpression = function () {
			        return _super.prototype.isStartOfExpression.call(this) || this.match('<');
			    };
			    return JSXParser;
			}(parser_1.Parser));
			exports$1.JSXParser = JSXParser;
		 },
		 function(module, exports$1) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			var Regex = {
			    NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
			    NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
			};
			exports$1.Character = {
			    fromCodePoint: function (cp) {
			        return (cp < 0x10000) ? String.fromCharCode(cp) :
			            String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
			                String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
			    },
			    isWhiteSpace: function (cp) {
			        return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) ||
			            (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0);
			    },
			    isLineTerminator: function (cp) {
			        return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029);
			    },
			    isIdentifierStart: function (cp) {
			        return (cp === 0x24) || (cp === 0x5F) ||
			            (cp >= 0x41 && cp <= 0x5A) ||
			            (cp >= 0x61 && cp <= 0x7A) ||
			            (cp === 0x5C) ||
			            ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports$1.Character.fromCodePoint(cp)));
			    },
			    isIdentifierPart: function (cp) {
			        return (cp === 0x24) || (cp === 0x5F) ||
			            (cp >= 0x41 && cp <= 0x5A) ||
			            (cp >= 0x61 && cp <= 0x7A) ||
			            (cp >= 0x30 && cp <= 0x39) ||
			            (cp === 0x5C) ||
			            ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports$1.Character.fromCodePoint(cp)));
			    },
			    isDecimalDigit: function (cp) {
			        return (cp >= 0x30 && cp <= 0x39);
			    },
			    isHexDigit: function (cp) {
			        return (cp >= 0x30 && cp <= 0x39) ||
			            (cp >= 0x41 && cp <= 0x46) ||
			            (cp >= 0x61 && cp <= 0x66);
			    },
			    isOctalDigit: function (cp) {
			        return (cp >= 0x30 && cp <= 0x37);
			    }
			};
		 },
		 function(module, exports$1, __webpack_require__) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			var jsx_syntax_1 = __webpack_require__(6);
			var JSXClosingElement = (function () {
			    function JSXClosingElement(name) {
			        this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
			        this.name = name;
			    }
			    return JSXClosingElement;
			}());
			exports$1.JSXClosingElement = JSXClosingElement;
			var JSXElement = (function () {
			    function JSXElement(openingElement, children, closingElement) {
			        this.type = jsx_syntax_1.JSXSyntax.JSXElement;
			        this.openingElement = openingElement;
			        this.children = children;
			        this.closingElement = closingElement;
			    }
			    return JSXElement;
			}());
			exports$1.JSXElement = JSXElement;
			var JSXEmptyExpression = (function () {
			    function JSXEmptyExpression() {
			        this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression;
			    }
			    return JSXEmptyExpression;
			}());
			exports$1.JSXEmptyExpression = JSXEmptyExpression;
			var JSXExpressionContainer = (function () {
			    function JSXExpressionContainer(expression) {
			        this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer;
			        this.expression = expression;
			    }
			    return JSXExpressionContainer;
			}());
			exports$1.JSXExpressionContainer = JSXExpressionContainer;
			var JSXIdentifier = (function () {
			    function JSXIdentifier(name) {
			        this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
			        this.name = name;
			    }
			    return JSXIdentifier;
			}());
			exports$1.JSXIdentifier = JSXIdentifier;
			var JSXMemberExpression = (function () {
			    function JSXMemberExpression(object, property) {
			        this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
			        this.object = object;
			        this.property = property;
			    }
			    return JSXMemberExpression;
			}());
			exports$1.JSXMemberExpression = JSXMemberExpression;
			var JSXAttribute = (function () {
			    function JSXAttribute(name, value) {
			        this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
			        this.name = name;
			        this.value = value;
			    }
			    return JSXAttribute;
			}());
			exports$1.JSXAttribute = JSXAttribute;
			var JSXNamespacedName = (function () {
			    function JSXNamespacedName(namespace, name) {
			        this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
			        this.namespace = namespace;
			        this.name = name;
			    }
			    return JSXNamespacedName;
			}());
			exports$1.JSXNamespacedName = JSXNamespacedName;
			var JSXOpeningElement = (function () {
			    function JSXOpeningElement(name, selfClosing, attributes) {
			        this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
			        this.name = name;
			        this.selfClosing = selfClosing;
			        this.attributes = attributes;
			    }
			    return JSXOpeningElement;
			}());
			exports$1.JSXOpeningElement = JSXOpeningElement;
			var JSXSpreadAttribute = (function () {
			    function JSXSpreadAttribute(argument) {
			        this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute;
			        this.argument = argument;
			    }
			    return JSXSpreadAttribute;
			}());
			exports$1.JSXSpreadAttribute = JSXSpreadAttribute;
			var JSXText = (function () {
			    function JSXText(value, raw) {
			        this.type = jsx_syntax_1.JSXSyntax.JSXText;
			        this.value = value;
			        this.raw = raw;
			    }
			    return JSXText;
			}());
			exports$1.JSXText = JSXText;
		 },
		 function(module, exports$1) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			exports$1.JSXSyntax = {
			    JSXAttribute: 'JSXAttribute',
			    JSXClosingElement: 'JSXClosingElement',
			    JSXElement: 'JSXElement',
			    JSXEmptyExpression: 'JSXEmptyExpression',
			    JSXExpressionContainer: 'JSXExpressionContainer',
			    JSXIdentifier: 'JSXIdentifier',
			    JSXMemberExpression: 'JSXMemberExpression',
			    JSXNamespacedName: 'JSXNamespacedName',
			    JSXOpeningElement: 'JSXOpeningElement',
			    JSXSpreadAttribute: 'JSXSpreadAttribute',
			    JSXText: 'JSXText'
			};
		 },
		 function(module, exports$1, __webpack_require__) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			var syntax_1 = __webpack_require__(2);
			var ArrayExpression = (function () {
			    function ArrayExpression(elements) {
			        this.type = syntax_1.Syntax.ArrayExpression;
			        this.elements = elements;
			    }
			    return ArrayExpression;
			}());
			exports$1.ArrayExpression = ArrayExpression;
			var ArrayPattern = (function () {
			    function ArrayPattern(elements) {
			        this.type = syntax_1.Syntax.ArrayPattern;
			        this.elements = elements;
			    }
			    return ArrayPattern;
			}());
			exports$1.ArrayPattern = ArrayPattern;
			var ArrowFunctionExpression = (function () {
			    function ArrowFunctionExpression(params, body, expression) {
			        this.type = syntax_1.Syntax.ArrowFunctionExpression;
			        this.id = null;
			        this.params = params;
			        this.body = body;
			        this.generator = false;
			        this.expression = expression;
			        this.async = false;
			    }
			    return ArrowFunctionExpression;
			}());
			exports$1.ArrowFunctionExpression = ArrowFunctionExpression;
			var AssignmentExpression = (function () {
			    function AssignmentExpression(operator, left, right) {
			        this.type = syntax_1.Syntax.AssignmentExpression;
			        this.operator = operator;
			        this.left = left;
			        this.right = right;
			    }
			    return AssignmentExpression;
			}());
			exports$1.AssignmentExpression = AssignmentExpression;
			var AssignmentPattern = (function () {
			    function AssignmentPattern(left, right) {
			        this.type = syntax_1.Syntax.AssignmentPattern;
			        this.left = left;
			        this.right = right;
			    }
			    return AssignmentPattern;
			}());
			exports$1.AssignmentPattern = AssignmentPattern;
			var AsyncArrowFunctionExpression = (function () {
			    function AsyncArrowFunctionExpression(params, body, expression) {
			        this.type = syntax_1.Syntax.ArrowFunctionExpression;
			        this.id = null;
			        this.params = params;
			        this.body = body;
			        this.generator = false;
			        this.expression = expression;
			        this.async = true;
			    }
			    return AsyncArrowFunctionExpression;
			}());
			exports$1.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression;
			var AsyncFunctionDeclaration = (function () {
			    function AsyncFunctionDeclaration(id, params, body) {
			        this.type = syntax_1.Syntax.FunctionDeclaration;
			        this.id = id;
			        this.params = params;
			        this.body = body;
			        this.generator = false;
			        this.expression = false;
			        this.async = true;
			    }
			    return AsyncFunctionDeclaration;
			}());
			exports$1.AsyncFunctionDeclaration = AsyncFunctionDeclaration;
			var AsyncFunctionExpression = (function () {
			    function AsyncFunctionExpression(id, params, body) {
			        this.type = syntax_1.Syntax.FunctionExpression;
			        this.id = id;
			        this.params = params;
			        this.body = body;
			        this.generator = false;
			        this.expression = false;
			        this.async = true;
			    }
			    return AsyncFunctionExpression;
			}());
			exports$1.AsyncFunctionExpression = AsyncFunctionExpression;
			var AwaitExpression = (function () {
			    function AwaitExpression(argument) {
			        this.type = syntax_1.Syntax.AwaitExpression;
			        this.argument = argument;
			    }
			    return AwaitExpression;
			}());
			exports$1.AwaitExpression = AwaitExpression;
			var BinaryExpression = (function () {
			    function BinaryExpression(operator, left, right) {
			        var logical = (operator === '||' || operator === '&&');
			        this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression;
			        this.operator = operator;
			        this.left = left;
			        this.right = right;
			    }
			    return BinaryExpression;
			}());
			exports$1.BinaryExpression = BinaryExpression;
			var BlockStatement = (function () {
			    function BlockStatement(body) {
			        this.type = syntax_1.Syntax.BlockStatement;
			        this.body = body;
			    }
			    return BlockStatement;
			}());
			exports$1.BlockStatement = BlockStatement;
			var BreakStatement = (function () {
			    function BreakStatement(label) {
			        this.type = syntax_1.Syntax.BreakStatement;
			        this.label = label;
			    }
			    return BreakStatement;
			}());
			exports$1.BreakStatement = BreakStatement;
			var CallExpression = (function () {
			    function CallExpression(callee, args) {
			        this.type = syntax_1.Syntax.CallExpression;
			        this.callee = callee;
			        this.arguments = args;
			    }
			    return CallExpression;
			}());
			exports$1.CallExpression = CallExpression;
			var CatchClause = (function () {
			    function CatchClause(param, body) {
			        this.type = syntax_1.Syntax.CatchClause;
			        this.param = param;
			        this.body = body;
			    }
			    return CatchClause;
			}());
			exports$1.CatchClause = CatchClause;
			var ClassBody = (function () {
			    function ClassBody(body) {
			        this.type = syntax_1.Syntax.ClassBody;
			        this.body = body;
			    }
			    return ClassBody;
			}());
			exports$1.ClassBody = ClassBody;
			var ClassDeclaration = (function () {
			    function ClassDeclaration(id, superClass, body) {
			        this.type = syntax_1.Syntax.ClassDeclaration;
			        this.id = id;
			        this.superClass = superClass;
			        this.body = body;
			    }
			    return ClassDeclaration;
			}());
			exports$1.ClassDeclaration = ClassDeclaration;
			var ClassExpression = (function () {
			    function ClassExpression(id, superClass, body) {
			        this.type = syntax_1.Syntax.ClassExpression;
			        this.id = id;
			        this.superClass = superClass;
			        this.body = body;
			    }
			    return ClassExpression;
			}());
			exports$1.ClassExpression = ClassExpression;
			var ComputedMemberExpression = (function () {
			    function ComputedMemberExpression(object, property) {
			        this.type = syntax_1.Syntax.MemberExpression;
			        this.computed = true;
			        this.object = object;
			        this.property = property;
			    }
			    return ComputedMemberExpression;
			}());
			exports$1.ComputedMemberExpression = ComputedMemberExpression;
			var ConditionalExpression = (function () {
			    function ConditionalExpression(test, consequent, alternate) {
			        this.type = syntax_1.Syntax.ConditionalExpression;
			        this.test = test;
			        this.consequent = consequent;
			        this.alternate = alternate;
			    }
			    return ConditionalExpression;
			}());
			exports$1.ConditionalExpression = ConditionalExpression;
			var ContinueStatement = (function () {
			    function ContinueStatement(label) {
			        this.type = syntax_1.Syntax.ContinueStatement;
			        this.label = label;
			    }
			    return ContinueStatement;
			}());
			exports$1.ContinueStatement = ContinueStatement;
			var DebuggerStatement = (function () {
			    function DebuggerStatement() {
			        this.type = syntax_1.Syntax.DebuggerStatement;
			    }
			    return DebuggerStatement;
			}());
			exports$1.DebuggerStatement = DebuggerStatement;
			var Directive = (function () {
			    function Directive(expression, directive) {
			        this.type = syntax_1.Syntax.ExpressionStatement;
			        this.expression = expression;
			        this.directive = directive;
			    }
			    return Directive;
			}());
			exports$1.Directive = Directive;
			var DoWhileStatement = (function () {
			    function DoWhileStatement(body, test) {
			        this.type = syntax_1.Syntax.DoWhileStatement;
			        this.body = body;
			        this.test = test;
			    }
			    return DoWhileStatement;
			}());
			exports$1.DoWhileStatement = DoWhileStatement;
			var EmptyStatement = (function () {
			    function EmptyStatement() {
			        this.type = syntax_1.Syntax.EmptyStatement;
			    }
			    return EmptyStatement;
			}());
			exports$1.EmptyStatement = EmptyStatement;
			var ExportAllDeclaration = (function () {
			    function ExportAllDeclaration(source) {
			        this.type = syntax_1.Syntax.ExportAllDeclaration;
			        this.source = source;
			    }
			    return ExportAllDeclaration;
			}());
			exports$1.ExportAllDeclaration = ExportAllDeclaration;
			var ExportDefaultDeclaration = (function () {
			    function ExportDefaultDeclaration(declaration) {
			        this.type = syntax_1.Syntax.ExportDefaultDeclaration;
			        this.declaration = declaration;
			    }
			    return ExportDefaultDeclaration;
			}());
			exports$1.ExportDefaultDeclaration = ExportDefaultDeclaration;
			var ExportNamedDeclaration = (function () {
			    function ExportNamedDeclaration(declaration, specifiers, source) {
			        this.type = syntax_1.Syntax.ExportNamedDeclaration;
			        this.declaration = declaration;
			        this.specifiers = specifiers;
			        this.source = source;
			    }
			    return ExportNamedDeclaration;
			}());
			exports$1.ExportNamedDeclaration = ExportNamedDeclaration;
			var ExportSpecifier = (function () {
			    function ExportSpecifier(local, exported) {
			        this.type = syntax_1.Syntax.ExportSpecifier;
			        this.exported = exported;
			        this.local = local;
			    }
			    return ExportSpecifier;
			}());
			exports$1.ExportSpecifier = ExportSpecifier;
			var ExpressionStatement = (function () {
			    function ExpressionStatement(expression) {
			        this.type = syntax_1.Syntax.ExpressionStatement;
			        this.expression = expression;
			    }
			    return ExpressionStatement;
			}());
			exports$1.ExpressionStatement = ExpressionStatement;
			var ForInStatement = (function () {
			    function ForInStatement(left, right, body) {
			        this.type = syntax_1.Syntax.ForInStatement;
			        this.left = left;
			        this.right = right;
			        this.body = body;
			        this.each = false;
			    }
			    return ForInStatement;
			}());
			exports$1.ForInStatement = ForInStatement;
			var ForOfStatement = (function () {
			    function ForOfStatement(left, right, body) {
			        this.type = syntax_1.Syntax.ForOfStatement;
			        this.left = left;
			        this.right = right;
			        this.body = body;
			    }
			    return ForOfStatement;
			}());
			exports$1.ForOfStatement = ForOfStatement;
			var ForStatement = (function () {
			    function ForStatement(init, test, update, body) {
			        this.type = syntax_1.Syntax.ForStatement;
			        this.init = init;
			        this.test = test;
			        this.update = update;
			        this.body = body;
			    }
			    return ForStatement;
			}());
			exports$1.ForStatement = ForStatement;
			var FunctionDeclaration = (function () {
			    function FunctionDeclaration(id, params, body, generator) {
			        this.type = syntax_1.Syntax.FunctionDeclaration;
			        this.id = id;
			        this.params = params;
			        this.body = body;
			        this.generator = generator;
			        this.expression = false;
			        this.async = false;
			    }
			    return FunctionDeclaration;
			}());
			exports$1.FunctionDeclaration = FunctionDeclaration;
			var FunctionExpression = (function () {
			    function FunctionExpression(id, params, body, generator) {
			        this.type = syntax_1.Syntax.FunctionExpression;
			        this.id = id;
			        this.params = params;
			        this.body = body;
			        this.generator = generator;
			        this.expression = false;
			        this.async = false;
			    }
			    return FunctionExpression;
			}());
			exports$1.FunctionExpression = FunctionExpression;
			var Identifier = (function () {
			    function Identifier(name) {
			        this.type = syntax_1.Syntax.Identifier;
			        this.name = name;
			    }
			    return Identifier;
			}());
			exports$1.Identifier = Identifier;
			var IfStatement = (function () {
			    function IfStatement(test, consequent, alternate) {
			        this.type = syntax_1.Syntax.IfStatement;
			        this.test = test;
			        this.consequent = consequent;
			        this.alternate = alternate;
			    }
			    return IfStatement;
			}());
			exports$1.IfStatement = IfStatement;
			var ImportDeclaration = (function () {
			    function ImportDeclaration(specifiers, source) {
			        this.type = syntax_1.Syntax.ImportDeclaration;
			        this.specifiers = specifiers;
			        this.source = source;
			    }
			    return ImportDeclaration;
			}());
			exports$1.ImportDeclaration = ImportDeclaration;
			var ImportDefaultSpecifier = (function () {
			    function ImportDefaultSpecifier(local) {
			        this.type = syntax_1.Syntax.ImportDefaultSpecifier;
			        this.local = local;
			    }
			    return ImportDefaultSpecifier;
			}());
			exports$1.ImportDefaultSpecifier = ImportDefaultSpecifier;
			var ImportNamespaceSpecifier = (function () {
			    function ImportNamespaceSpecifier(local) {
			        this.type = syntax_1.Syntax.ImportNamespaceSpecifier;
			        this.local = local;
			    }
			    return ImportNamespaceSpecifier;
			}());
			exports$1.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
			var ImportSpecifier = (function () {
			    function ImportSpecifier(local, imported) {
			        this.type = syntax_1.Syntax.ImportSpecifier;
			        this.local = local;
			        this.imported = imported;
			    }
			    return ImportSpecifier;
			}());
			exports$1.ImportSpecifier = ImportSpecifier;
			var LabeledStatement = (function () {
			    function LabeledStatement(label, body) {
			        this.type = syntax_1.Syntax.LabeledStatement;
			        this.label = label;
			        this.body = body;
			    }
			    return LabeledStatement;
			}());
			exports$1.LabeledStatement = LabeledStatement;
			var Literal = (function () {
			    function Literal(value, raw) {
			        this.type = syntax_1.Syntax.Literal;
			        this.value = value;
			        this.raw = raw;
			    }
			    return Literal;
			}());
			exports$1.Literal = Literal;
			var MetaProperty = (function () {
			    function MetaProperty(meta, property) {
			        this.type = syntax_1.Syntax.MetaProperty;
			        this.meta = meta;
			        this.property = property;
			    }
			    return MetaProperty;
			}());
			exports$1.MetaProperty = MetaProperty;
			var MethodDefinition = (function () {
			    function MethodDefinition(key, computed, value, kind, isStatic) {
			        this.type = syntax_1.Syntax.MethodDefinition;
			        this.key = key;
			        this.computed = computed;
			        this.value = value;
			        this.kind = kind;
			        this.static = isStatic;
			    }
			    return MethodDefinition;
			}());
			exports$1.MethodDefinition = MethodDefinition;
			var Module = (function () {
			    function Module(body) {
			        this.type = syntax_1.Syntax.Program;
			        this.body = body;
			        this.sourceType = 'module';
			    }
			    return Module;
			}());
			exports$1.Module = Module;
			var NewExpression = (function () {
			    function NewExpression(callee, args) {
			        this.type = syntax_1.Syntax.NewExpression;
			        this.callee = callee;
			        this.arguments = args;
			    }
			    return NewExpression;
			}());
			exports$1.NewExpression = NewExpression;
			var ObjectExpression = (function () {
			    function ObjectExpression(properties) {
			        this.type = syntax_1.Syntax.ObjectExpression;
			        this.properties = properties;
			    }
			    return ObjectExpression;
			}());
			exports$1.ObjectExpression = ObjectExpression;
			var ObjectPattern = (function () {
			    function ObjectPattern(properties) {
			        this.type = syntax_1.Syntax.ObjectPattern;
			        this.properties = properties;
			    }
			    return ObjectPattern;
			}());
			exports$1.ObjectPattern = ObjectPattern;
			var Property = (function () {
			    function Property(kind, key, computed, value, method, shorthand) {
			        this.type = syntax_1.Syntax.Property;
			        this.key = key;
			        this.computed = computed;
			        this.value = value;
			        this.kind = kind;
			        this.method = method;
			        this.shorthand = shorthand;
			    }
			    return Property;
			}());
			exports$1.Property = Property;
			var RegexLiteral = (function () {
			    function RegexLiteral(value, raw, pattern, flags) {
			        this.type = syntax_1.Syntax.Literal;
			        this.value = value;
			        this.raw = raw;
			        this.regex = { pattern: pattern, flags: flags };
			    }
			    return RegexLiteral;
			}());
			exports$1.RegexLiteral = RegexLiteral;
			var RestElement = (function () {
			    function RestElement(argument) {
			        this.type = syntax_1.Syntax.RestElement;
			        this.argument = argument;
			    }
			    return RestElement;
			}());
			exports$1.RestElement = RestElement;
			var ReturnStatement = (function () {
			    function ReturnStatement(argument) {
			        this.type = syntax_1.Syntax.ReturnStatement;
			        this.argument = argument;
			    }
			    return ReturnStatement;
			}());
			exports$1.ReturnStatement = ReturnStatement;
			var Script = (function () {
			    function Script(body) {
			        this.type = syntax_1.Syntax.Program;
			        this.body = body;
			        this.sourceType = 'script';
			    }
			    return Script;
			}());
			exports$1.Script = Script;
			var SequenceExpression = (function () {
			    function SequenceExpression(expressions) {
			        this.type = syntax_1.Syntax.SequenceExpression;
			        this.expressions = expressions;
			    }
			    return SequenceExpression;
			}());
			exports$1.SequenceExpression = SequenceExpression;
			var SpreadElement = (function () {
			    function SpreadElement(argument) {
			        this.type = syntax_1.Syntax.SpreadElement;
			        this.argument = argument;
			    }
			    return SpreadElement;
			}());
			exports$1.SpreadElement = SpreadElement;
			var StaticMemberExpression = (function () {
			    function StaticMemberExpression(object, property) {
			        this.type = syntax_1.Syntax.MemberExpression;
			        this.computed = false;
			        this.object = object;
			        this.property = property;
			    }
			    return StaticMemberExpression;
			}());
			exports$1.StaticMemberExpression = StaticMemberExpression;
			var Super = (function () {
			    function Super() {
			        this.type = syntax_1.Syntax.Super;
			    }
			    return Super;
			}());
			exports$1.Super = Super;
			var SwitchCase = (function () {
			    function SwitchCase(test, consequent) {
			        this.type = syntax_1.Syntax.SwitchCase;
			        this.test = test;
			        this.consequent = consequent;
			    }
			    return SwitchCase;
			}());
			exports$1.SwitchCase = SwitchCase;
			var SwitchStatement = (function () {
			    function SwitchStatement(discriminant, cases) {
			        this.type = syntax_1.Syntax.SwitchStatement;
			        this.discriminant = discriminant;
			        this.cases = cases;
			    }
			    return SwitchStatement;
			}());
			exports$1.SwitchStatement = SwitchStatement;
			var TaggedTemplateExpression = (function () {
			    function TaggedTemplateExpression(tag, quasi) {
			        this.type = syntax_1.Syntax.TaggedTemplateExpression;
			        this.tag = tag;
			        this.quasi = quasi;
			    }
			    return TaggedTemplateExpression;
			}());
			exports$1.TaggedTemplateExpression = TaggedTemplateExpression;
			var TemplateElement = (function () {
			    function TemplateElement(value, tail) {
			        this.type = syntax_1.Syntax.TemplateElement;
			        this.value = value;
			        this.tail = tail;
			    }
			    return TemplateElement;
			}());
			exports$1.TemplateElement = TemplateElement;
			var TemplateLiteral = (function () {
			    function TemplateLiteral(quasis, expressions) {
			        this.type = syntax_1.Syntax.TemplateLiteral;
			        this.quasis = quasis;
			        this.expressions = expressions;
			    }
			    return TemplateLiteral;
			}());
			exports$1.TemplateLiteral = TemplateLiteral;
			var ThisExpression = (function () {
			    function ThisExpression() {
			        this.type = syntax_1.Syntax.ThisExpression;
			    }
			    return ThisExpression;
			}());
			exports$1.ThisExpression = ThisExpression;
			var ThrowStatement = (function () {
			    function ThrowStatement(argument) {
			        this.type = syntax_1.Syntax.ThrowStatement;
			        this.argument = argument;
			    }
			    return ThrowStatement;
			}());
			exports$1.ThrowStatement = ThrowStatement;
			var TryStatement = (function () {
			    function TryStatement(block, handler, finalizer) {
			        this.type = syntax_1.Syntax.TryStatement;
			        this.block = block;
			        this.handler = handler;
			        this.finalizer = finalizer;
			    }
			    return TryStatement;
			}());
			exports$1.TryStatement = TryStatement;
			var UnaryExpression = (function () {
			    function UnaryExpression(operator, argument) {
			        this.type = syntax_1.Syntax.UnaryExpression;
			        this.operator = operator;
			        this.argument = argument;
			        this.prefix = true;
			    }
			    return UnaryExpression;
			}());
			exports$1.UnaryExpression = UnaryExpression;
			var UpdateExpression = (function () {
			    function UpdateExpression(operator, argument, prefix) {
			        this.type = syntax_1.Syntax.UpdateExpression;
			        this.operator = operator;
			        this.argument = argument;
			        this.prefix = prefix;
			    }
			    return UpdateExpression;
			}());
			exports$1.UpdateExpression = UpdateExpression;
			var VariableDeclaration = (function () {
			    function VariableDeclaration(declarations, kind) {
			        this.type = syntax_1.Syntax.VariableDeclaration;
			        this.declarations = declarations;
			        this.kind = kind;
			    }
			    return VariableDeclaration;
			}());
			exports$1.VariableDeclaration = VariableDeclaration;
			var VariableDeclarator = (function () {
			    function VariableDeclarator(id, init) {
			        this.type = syntax_1.Syntax.VariableDeclarator;
			        this.id = id;
			        this.init = init;
			    }
			    return VariableDeclarator;
			}());
			exports$1.VariableDeclarator = VariableDeclarator;
			var WhileStatement = (function () {
			    function WhileStatement(test, body) {
			        this.type = syntax_1.Syntax.WhileStatement;
			        this.test = test;
			        this.body = body;
			    }
			    return WhileStatement;
			}());
			exports$1.WhileStatement = WhileStatement;
			var WithStatement = (function () {
			    function WithStatement(object, body) {
			        this.type = syntax_1.Syntax.WithStatement;
			        this.object = object;
			        this.body = body;
			    }
			    return WithStatement;
			}());
			exports$1.WithStatement = WithStatement;
			var YieldExpression = (function () {
			    function YieldExpression(argument, delegate) {
			        this.type = syntax_1.Syntax.YieldExpression;
			        this.argument = argument;
			        this.delegate = delegate;
			    }
			    return YieldExpression;
			}());
			exports$1.YieldExpression = YieldExpression;
		 },
		 function(module, exports$1, __webpack_require__) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			var assert_1 = __webpack_require__(9);
			var error_handler_1 = __webpack_require__(10);
			var messages_1 = __webpack_require__(11);
			var Node = __webpack_require__(7);
			var scanner_1 = __webpack_require__(12);
			var syntax_1 = __webpack_require__(2);
			var token_1 = __webpack_require__(13);
			var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder';
			var Parser = (function () {
			    function Parser(code, options, delegate) {
			        if (options === void 0) { options = {}; }
			        this.config = {
			            range: (typeof options.range === 'boolean') && options.range,
			            loc: (typeof options.loc === 'boolean') && options.loc,
			            source: null,
			            tokens: (typeof options.tokens === 'boolean') && options.tokens,
			            comment: (typeof options.comment === 'boolean') && options.comment,
			            tolerant: (typeof options.tolerant === 'boolean') && options.tolerant
			        };
			        if (this.config.loc && options.source && options.source !== null) {
			            this.config.source = String(options.source);
			        }
			        this.delegate = delegate;
			        this.errorHandler = new error_handler_1.ErrorHandler();
			        this.errorHandler.tolerant = this.config.tolerant;
			        this.scanner = new scanner_1.Scanner(code, this.errorHandler);
			        this.scanner.trackComment = this.config.comment;
			        this.operatorPrecedence = {
			            ')': 0,
			            ';': 0,
			            ',': 0,
			            '=': 0,
			            ']': 0,
			            '||': 1,
			            '&&': 2,
			            '|': 3,
			            '^': 4,
			            '&': 5,
			            '==': 6,
			            '!=': 6,
			            '===': 6,
			            '!==': 6,
			            '<': 7,
			            '>': 7,
			            '<=': 7,
			            '>=': 7,
			            '<<': 8,
			            '>>': 8,
			            '>>>': 8,
			            '+': 9,
			            '-': 9,
			            '*': 11,
			            '/': 11,
			            '%': 11
			        };
			        this.lookahead = {
			            type: 2 ,
			            value: '',
			            lineNumber: this.scanner.lineNumber,
			            lineStart: 0,
			            start: 0,
			            end: 0
			        };
			        this.hasLineTerminator = false;
			        this.context = {
			            isModule: false,
			            await: false,
			            allowIn: true,
			            allowStrictDirective: true,
			            allowYield: true,
			            firstCoverInitializedNameError: null,
			            isAssignmentTarget: false,
			            isBindingElement: false,
			            inFunctionBody: false,
			            inIteration: false,
			            inSwitch: false,
			            labelSet: {},
			            strict: false
			        };
			        this.tokens = [];
			        this.startMarker = {
			            index: 0,
			            line: this.scanner.lineNumber,
			            column: 0
			        };
			        this.lastMarker = {
			            index: 0,
			            line: this.scanner.lineNumber,
			            column: 0
			        };
			        this.nextToken();
			        this.lastMarker = {
			            index: this.scanner.index,
			            line: this.scanner.lineNumber,
			            column: this.scanner.index - this.scanner.lineStart
			        };
			    }
			    Parser.prototype.throwError = function (messageFormat) {
			        var args = Array.prototype.slice.call(arguments, 1);
			        var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
			            assert_1.assert(idx < args.length, 'Message reference must be in range');
			            return args[idx];
			        });
			        var index = this.lastMarker.index;
			        var line = this.lastMarker.line;
			        var column = this.lastMarker.column + 1;
			        throw this.errorHandler.createError(index, line, column, msg);
			    };
			    Parser.prototype.tolerateError = function (messageFormat) {
			        var args = Array.prototype.slice.call(arguments, 1);
			        var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
			            assert_1.assert(idx < args.length, 'Message reference must be in range');
			            return args[idx];
			        });
			        var index = this.lastMarker.index;
			        var line = this.scanner.lineNumber;
			        var column = this.lastMarker.column + 1;
			        this.errorHandler.tolerateError(index, line, column, msg);
			    };
			    Parser.prototype.unexpectedTokenError = function (token, message) {
			        var msg = message || messages_1.Messages.UnexpectedToken;
			        var value;
			        if (token) {
			            if (!message) {
			                msg = (token.type === 2 ) ? messages_1.Messages.UnexpectedEOS :
			                    (token.type === 3 ) ? messages_1.Messages.UnexpectedIdentifier :
			                        (token.type === 6 ) ? messages_1.Messages.UnexpectedNumber :
			                            (token.type === 8 ) ? messages_1.Messages.UnexpectedString :
			                                (token.type === 10 ) ? messages_1.Messages.UnexpectedTemplate :
			                                    messages_1.Messages.UnexpectedToken;
			                if (token.type === 4 ) {
			                    if (this.scanner.isFutureReservedWord(token.value)) {
			                        msg = messages_1.Messages.UnexpectedReserved;
			                    }
			                    else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) {
			                        msg = messages_1.Messages.StrictReservedWord;
			                    }
			                }
			            }
			            value = token.value;
			        }
			        else {
			            value = 'ILLEGAL';
			        }
			        msg = msg.replace('%0', value);
			        if (token && typeof token.lineNumber === 'number') {
			            var index = token.start;
			            var line = token.lineNumber;
			            var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column;
			            var column = token.start - lastMarkerLineStart + 1;
			            return this.errorHandler.createError(index, line, column, msg);
			        }
			        else {
			            var index = this.lastMarker.index;
			            var line = this.lastMarker.line;
			            var column = this.lastMarker.column + 1;
			            return this.errorHandler.createError(index, line, column, msg);
			        }
			    };
			    Parser.prototype.throwUnexpectedToken = function (token, message) {
			        throw this.unexpectedTokenError(token, message);
			    };
			    Parser.prototype.tolerateUnexpectedToken = function (token, message) {
			        this.errorHandler.tolerate(this.unexpectedTokenError(token, message));
			    };
			    Parser.prototype.collectComments = function () {
			        if (!this.config.comment) {
			            this.scanner.scanComments();
			        }
			        else {
			            var comments = this.scanner.scanComments();
			            if (comments.length > 0 && this.delegate) {
			                for (var i = 0; i < comments.length; ++i) {
			                    var e = comments[i];
			                    var node = void 0;
			                    node = {
			                        type: e.multiLine ? 'BlockComment' : 'LineComment',
			                        value: this.scanner.source.slice(e.slice[0], e.slice[1])
			                    };
			                    if (this.config.range) {
			                        node.range = e.range;
			                    }
			                    if (this.config.loc) {
			                        node.loc = e.loc;
			                    }
			                    var metadata = {
			                        start: {
			                            line: e.loc.start.line,
			                            column: e.loc.start.column,
			                            offset: e.range[0]
			                        },
			                        end: {
			                            line: e.loc.end.line,
			                            column: e.loc.end.column,
			                            offset: e.range[1]
			                        }
			                    };
			                    this.delegate(node, metadata);
			                }
			            }
			        }
			    };
			    Parser.prototype.getTokenRaw = function (token) {
			        return this.scanner.source.slice(token.start, token.end);
			    };
			    Parser.prototype.convertToken = function (token) {
			        var t = {
			            type: token_1.TokenName[token.type],
			            value: this.getTokenRaw(token)
			        };
			        if (this.config.range) {
			            t.range = [token.start, token.end];
			        }
			        if (this.config.loc) {
			            t.loc = {
			                start: {
			                    line: this.startMarker.line,
			                    column: this.startMarker.column
			                },
			                end: {
			                    line: this.scanner.lineNumber,
			                    column: this.scanner.index - this.scanner.lineStart
			                }
			            };
			        }
			        if (token.type === 9 ) {
			            var pattern = token.pattern;
			            var flags = token.flags;
			            t.regex = { pattern: pattern, flags: flags };
			        }
			        return t;
			    };
			    Parser.prototype.nextToken = function () {
			        var token = this.lookahead;
			        this.lastMarker.index = this.scanner.index;
			        this.lastMarker.line = this.scanner.lineNumber;
			        this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
			        this.collectComments();
			        if (this.scanner.index !== this.startMarker.index) {
			            this.startMarker.index = this.scanner.index;
			            this.startMarker.line = this.scanner.lineNumber;
			            this.startMarker.column = this.scanner.index - this.scanner.lineStart;
			        }
			        var next = this.scanner.lex();
			        this.hasLineTerminator = (token.lineNumber !== next.lineNumber);
			        if (next && this.context.strict && next.type === 3 ) {
			            if (this.scanner.isStrictModeReservedWord(next.value)) {
			                next.type = 4 ;
			            }
			        }
			        this.lookahead = next;
			        if (this.config.tokens && next.type !== 2 ) {
			            this.tokens.push(this.convertToken(next));
			        }
			        return token;
			    };
			    Parser.prototype.nextRegexToken = function () {
			        this.collectComments();
			        var token = this.scanner.scanRegExp();
			        if (this.config.tokens) {
			            this.tokens.pop();
			            this.tokens.push(this.convertToken(token));
			        }
			        this.lookahead = token;
			        this.nextToken();
			        return token;
			    };
			    Parser.prototype.createNode = function () {
			        return {
			            index: this.startMarker.index,
			            line: this.startMarker.line,
			            column: this.startMarker.column
			        };
			    };
			    Parser.prototype.startNode = function (token, lastLineStart) {
			        if (lastLineStart === void 0) { lastLineStart = 0; }
			        var column = token.start - token.lineStart;
			        var line = token.lineNumber;
			        if (column < 0) {
			            column += lastLineStart;
			            line--;
			        }
			        return {
			            index: token.start,
			            line: line,
			            column: column
			        };
			    };
			    Parser.prototype.finalize = function (marker, node) {
			        if (this.config.range) {
			            node.range = [marker.index, this.lastMarker.index];
			        }
			        if (this.config.loc) {
			            node.loc = {
			                start: {
			                    line: marker.line,
			                    column: marker.column,
			                },
			                end: {
			                    line: this.lastMarker.line,
			                    column: this.lastMarker.column
			                }
			            };
			            if (this.config.source) {
			                node.loc.source = this.config.source;
			            }
			        }
			        if (this.delegate) {
			            var metadata = {
			                start: {
			                    line: marker.line,
			                    column: marker.column,
			                    offset: marker.index
			                },
			                end: {
			                    line: this.lastMarker.line,
			                    column: this.lastMarker.column,
			                    offset: this.lastMarker.index
			                }
			            };
			            this.delegate(node, metadata);
			        }
			        return node;
			    };
			    Parser.prototype.expect = function (value) {
			        var token = this.nextToken();
			        if (token.type !== 7  || token.value !== value) {
			            this.throwUnexpectedToken(token);
			        }
			    };
			    Parser.prototype.expectCommaSeparator = function () {
			        if (this.config.tolerant) {
			            var token = this.lookahead;
			            if (token.type === 7  && token.value === ',') {
			                this.nextToken();
			            }
			            else if (token.type === 7  && token.value === ';') {
			                this.nextToken();
			                this.tolerateUnexpectedToken(token);
			            }
			            else {
			                this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken);
			            }
			        }
			        else {
			            this.expect(',');
			        }
			    };
			    Parser.prototype.expectKeyword = function (keyword) {
			        var token = this.nextToken();
			        if (token.type !== 4  || token.value !== keyword) {
			            this.throwUnexpectedToken(token);
			        }
			    };
			    Parser.prototype.match = function (value) {
			        return this.lookahead.type === 7  && this.lookahead.value === value;
			    };
			    Parser.prototype.matchKeyword = function (keyword) {
			        return this.lookahead.type === 4  && this.lookahead.value === keyword;
			    };
			    Parser.prototype.matchContextualKeyword = function (keyword) {
			        return this.lookahead.type === 3  && this.lookahead.value === keyword;
			    };
			    Parser.prototype.matchAssign = function () {
			        if (this.lookahead.type !== 7 ) {
			            return false;
			        }
			        var op = this.lookahead.value;
			        return op === '=' ||
			            op === '*=' ||
			            op === '**=' ||
			            op === '/=' ||
			            op === '%=' ||
			            op === '+=' ||
			            op === '-=' ||
			            op === '<<=' ||
			            op === '>>=' ||
			            op === '>>>=' ||
			            op === '&=' ||
			            op === '^=' ||
			            op === '|=';
			    };
			    Parser.prototype.isolateCoverGrammar = function (parseFunction) {
			        var previousIsBindingElement = this.context.isBindingElement;
			        var previousIsAssignmentTarget = this.context.isAssignmentTarget;
			        var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
			        this.context.isBindingElement = true;
			        this.context.isAssignmentTarget = true;
			        this.context.firstCoverInitializedNameError = null;
			        var result = parseFunction.call(this);
			        if (this.context.firstCoverInitializedNameError !== null) {
			            this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
			        }
			        this.context.isBindingElement = previousIsBindingElement;
			        this.context.isAssignmentTarget = previousIsAssignmentTarget;
			        this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError;
			        return result;
			    };
			    Parser.prototype.inheritCoverGrammar = function (parseFunction) {
			        var previousIsBindingElement = this.context.isBindingElement;
			        var previousIsAssignmentTarget = this.context.isAssignmentTarget;
			        var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
			        this.context.isBindingElement = true;
			        this.context.isAssignmentTarget = true;
			        this.context.firstCoverInitializedNameError = null;
			        var result = parseFunction.call(this);
			        this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement;
			        this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget;
			        this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError;
			        return result;
			    };
			    Parser.prototype.consumeSemicolon = function () {
			        if (this.match(';')) {
			            this.nextToken();
			        }
			        else if (!this.hasLineTerminator) {
			            if (this.lookahead.type !== 2  && !this.match('}')) {
			                this.throwUnexpectedToken(this.lookahead);
			            }
			            this.lastMarker.index = this.startMarker.index;
			            this.lastMarker.line = this.startMarker.line;
			            this.lastMarker.column = this.startMarker.column;
			        }
			    };
			    Parser.prototype.parsePrimaryExpression = function () {
			        var node = this.createNode();
			        var expr;
			        var token, raw;
			        switch (this.lookahead.type) {
			            case 3 :
			                if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') {
			                    this.tolerateUnexpectedToken(this.lookahead);
			                }
			                expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value));
			                break;
			            case 6 :
			            case 8 :
			                if (this.context.strict && this.lookahead.octal) {
			                    this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral);
			                }
			                this.context.isAssignmentTarget = false;
			                this.context.isBindingElement = false;
			                token = this.nextToken();
			                raw = this.getTokenRaw(token);
			                expr = this.finalize(node, new Node.Literal(token.value, raw));
			                break;
			            case 1 :
			                this.context.isAssignmentTarget = false;
			                this.context.isBindingElement = false;
			                token = this.nextToken();
			                raw = this.getTokenRaw(token);
			                expr = this.finalize(node, new Node.Literal(token.value === 'true', raw));
			                break;
			            case 5 :
			                this.context.isAssignmentTarget = false;
			                this.context.isBindingElement = false;
			                token = this.nextToken();
			                raw = this.getTokenRaw(token);
			                expr = this.finalize(node, new Node.Literal(null, raw));
			                break;
			            case 10 :
			                expr = this.parseTemplateLiteral();
			                break;
			            case 7 :
			                switch (this.lookahead.value) {
			                    case '(':
			                        this.context.isBindingElement = false;
			                        expr = this.inheritCoverGrammar(this.parseGroupExpression);
			                        break;
			                    case '[':
			                        expr = this.inheritCoverGrammar(this.parseArrayInitializer);
			                        break;
			                    case '{':
			                        expr = this.inheritCoverGrammar(this.parseObjectInitializer);
			                        break;
			                    case '/':
			                    case '/=':
			                        this.context.isAssignmentTarget = false;
			                        this.context.isBindingElement = false;
			                        this.scanner.index = this.startMarker.index;
			                        token = this.nextRegexToken();
			                        raw = this.getTokenRaw(token);
			                        expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags));
			                        break;
			                    default:
			                        expr = this.throwUnexpectedToken(this.nextToken());
			                }
			                break;
			            case 4 :
			                if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) {
			                    expr = this.parseIdentifierName();
			                }
			                else if (!this.context.strict && this.matchKeyword('let')) {
			                    expr = this.finalize(node, new Node.Identifier(this.nextToken().value));
			                }
			                else {
			                    this.context.isAssignmentTarget = false;
			                    this.context.isBindingElement = false;
			                    if (this.matchKeyword('function')) {
			                        expr = this.parseFunctionExpression();
			                    }
			                    else if (this.matchKeyword('this')) {
			                        this.nextToken();
			                        expr = this.finalize(node, new Node.ThisExpression());
			                    }
			                    else if (this.matchKeyword('class')) {
			                        expr = this.parseClassExpression();
			                    }
			                    else {
			                        expr = this.throwUnexpectedToken(this.nextToken());
			                    }
			                }
			                break;
			            default:
			                expr = this.throwUnexpectedToken(this.nextToken());
			        }
			        return expr;
			    };
			    Parser.prototype.parseSpreadElement = function () {
			        var node = this.createNode();
			        this.expect('...');
			        var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
			        return this.finalize(node, new Node.SpreadElement(arg));
			    };
			    Parser.prototype.parseArrayInitializer = function () {
			        var node = this.createNode();
			        var elements = [];
			        this.expect('[');
			        while (!this.match(']')) {
			            if (this.match(',')) {
			                this.nextToken();
			                elements.push(null);
			            }
			            else if (this.match('...')) {
			                var element = this.parseSpreadElement();
			                if (!this.match(']')) {
			                    this.context.isAssignmentTarget = false;
			                    this.context.isBindingElement = false;
			                    this.expect(',');
			                }
			                elements.push(element);
			            }
			            else {
			                elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
			                if (!this.match(']')) {
			                    this.expect(',');
			                }
			            }
			        }
			        this.expect(']');
			        return this.finalize(node, new Node.ArrayExpression(elements));
			    };
			    Parser.prototype.parsePropertyMethod = function (params) {
			        this.context.isAssignmentTarget = false;
			        this.context.isBindingElement = false;
			        var previousStrict = this.context.strict;
			        var previousAllowStrictDirective = this.context.allowStrictDirective;
			        this.context.allowStrictDirective = params.simple;
			        var body = this.isolateCoverGrammar(this.parseFunctionSourceElements);
			        if (this.context.strict && params.firstRestricted) {
			            this.tolerateUnexpectedToken(params.firstRestricted, params.message);
			        }
			        if (this.context.strict && params.stricted) {
			            this.tolerateUnexpectedToken(params.stricted, params.message);
			        }
			        this.context.strict = previousStrict;
			        this.context.allowStrictDirective = previousAllowStrictDirective;
			        return body;
			    };
			    Parser.prototype.parsePropertyMethodFunction = function () {
			        var isGenerator = false;
			        var node = this.createNode();
			        var previousAllowYield = this.context.allowYield;
			        this.context.allowYield = true;
			        var params = this.parseFormalParameters();
			        var method = this.parsePropertyMethod(params);
			        this.context.allowYield = previousAllowYield;
			        return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
			    };
			    Parser.prototype.parsePropertyMethodAsyncFunction = function () {
			        var node = this.createNode();
			        var previousAllowYield = this.context.allowYield;
			        var previousAwait = this.context.await;
			        this.context.allowYield = false;
			        this.context.await = true;
			        var params = this.parseFormalParameters();
			        var method = this.parsePropertyMethod(params);
			        this.context.allowYield = previousAllowYield;
			        this.context.await = previousAwait;
			        return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method));
			    };
			    Parser.prototype.parseObjectPropertyKey = function () {
			        var node = this.createNode();
			        var token = this.nextToken();
			        var key;
			        switch (token.type) {
			            case 8 :
			            case 6 :
			                if (this.context.strict && token.octal) {
			                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral);
			                }
			                var raw = this.getTokenRaw(token);
			                key = this.finalize(node, new Node.Literal(token.value, raw));
			                break;
			            case 3 :
			            case 1 :
			            case 5 :
			            case 4 :
			                key = this.finalize(node, new Node.Identifier(token.value));
			                break;
			            case 7 :
			                if (token.value === '[') {
			                    key = this.isolateCoverGrammar(this.parseAssignmentExpression);
			                    this.expect(']');
			                }
			                else {
			                    key = this.throwUnexpectedToken(token);
			                }
			                break;
			            default:
			                key = this.throwUnexpectedToken(token);
			        }
			        return key;
			    };
			    Parser.prototype.isPropertyKey = function (key, value) {
			        return (key.type === syntax_1.Syntax.Identifier && key.name === value) ||
			            (key.type === syntax_1.Syntax.Literal && key.value === value);
			    };
			    Parser.prototype.parseObjectProperty = function (hasProto) {
			        var node = this.createNode();
			        var token = this.lookahead;
			        var kind;
			        var key = null;
			        var value = null;
			        var computed = false;
			        var method = false;
			        var shorthand = false;
			        var isAsync = false;
			        if (token.type === 3 ) {
			            var id = token.value;
			            this.nextToken();
			            computed = this.match('[');
			            isAsync = !this.hasLineTerminator && (id === 'async') &&
			                !this.match(':') && !this.match('(') && !this.match('*') && !this.match(',');
			            key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id));
			        }
			        else if (this.match('*')) {
			            this.nextToken();
			        }
			        else {
			            computed = this.match('[');
			            key = this.parseObjectPropertyKey();
			        }
			        var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
			        if (token.type === 3  && !isAsync && token.value === 'get' && lookaheadPropertyKey) {
			            kind = 'get';
			            computed = this.match('[');
			            key = this.parseObjectPropertyKey();
			            this.context.allowYield = false;
			            value = this.parseGetterMethod();
			        }
			        else if (token.type === 3  && !isAsync && token.value === 'set' && lookaheadPropertyKey) {
			            kind = 'set';
			            computed = this.match('[');
			            key = this.parseObjectPropertyKey();
			            value = this.parseSetterMethod();
			        }
			        else if (token.type === 7  && token.value === '*' && lookaheadPropertyKey) {
			            kind = 'init';
			            computed = this.match('[');
			            key = this.parseObjectPropertyKey();
			            value = this.parseGeneratorMethod();
			            method = true;
			        }
			        else {
			            if (!key) {
			                this.throwUnexpectedToken(this.lookahead);
			            }
			            kind = 'init';
			            if (this.match(':') && !isAsync) {
			                if (!computed && this.isPropertyKey(key, '__proto__')) {
			                    if (hasProto.value) {
			                        this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
			                    }
			                    hasProto.value = true;
			                }
			                this.nextToken();
			                value = this.inheritCoverGrammar(this.parseAssignmentExpression);
			            }
			            else if (this.match('(')) {
			                value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
			                method = true;
			            }
			            else if (token.type === 3 ) {
			                var id = this.finalize(node, new Node.Identifier(token.value));
			                if (this.match('=')) {
			                    this.context.firstCoverInitializedNameError = this.lookahead;
			                    this.nextToken();
			                    shorthand = true;
			                    var init = this.isolateCoverGrammar(this.parseAssignmentExpression);
			                    value = this.finalize(node, new Node.AssignmentPattern(id, init));
			                }
			                else {
			                    shorthand = true;
			                    value = id;
			                }
			            }
			            else {
			                this.throwUnexpectedToken(this.nextToken());
			            }
			        }
			        return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand));
			    };
			    Parser.prototype.parseObjectInitializer = function () {
			        var node = this.createNode();
			        this.expect('{');
			        var properties = [];
			        var hasProto = { value: false };
			        while (!this.match('}')) {
			            properties.push(this.parseObjectProperty(hasProto));
			            if (!this.match('}')) {
			                this.expectCommaSeparator();
			            }
			        }
			        this.expect('}');
			        return this.finalize(node, new Node.ObjectExpression(properties));
			    };
			    Parser.prototype.parseTemplateHead = function () {
			        assert_1.assert(this.lookahead.head, 'Template literal must start with a template head');
			        var node = this.createNode();
			        var token = this.nextToken();
			        var raw = token.value;
			        var cooked = token.cooked;
			        return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail));
			    };
			    Parser.prototype.parseTemplateElement = function () {
			        if (this.lookahead.type !== 10 ) {
			            this.throwUnexpectedToken();
			        }
			        var node = this.createNode();
			        var token = this.nextToken();
			        var raw = token.value;
			        var cooked = token.cooked;
			        return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail));
			    };
			    Parser.prototype.parseTemplateLiteral = function () {
			        var node = this.createNode();
			        var expressions = [];
			        var quasis = [];
			        var quasi = this.parseTemplateHead();
			        quasis.push(quasi);
			        while (!quasi.tail) {
			            expressions.push(this.parseExpression());
			            quasi = this.parseTemplateElement();
			            quasis.push(quasi);
			        }
			        return this.finalize(node, new Node.TemplateLiteral(quasis, expressions));
			    };
			    Parser.prototype.reinterpretExpressionAsPattern = function (expr) {
			        switch (expr.type) {
			            case syntax_1.Syntax.Identifier:
			            case syntax_1.Syntax.MemberExpression:
			            case syntax_1.Syntax.RestElement:
			            case syntax_1.Syntax.AssignmentPattern:
			                break;
			            case syntax_1.Syntax.SpreadElement:
			                expr.type = syntax_1.Syntax.RestElement;
			                this.reinterpretExpressionAsPattern(expr.argument);
			                break;
			            case syntax_1.Syntax.ArrayExpression:
			                expr.type = syntax_1.Syntax.ArrayPattern;
			                for (var i = 0; i < expr.elements.length; i++) {
			                    if (expr.elements[i] !== null) {
			                        this.reinterpretExpressionAsPattern(expr.elements[i]);
			                    }
			                }
			                break;
			            case syntax_1.Syntax.ObjectExpression:
			                expr.type = syntax_1.Syntax.ObjectPattern;
			                for (var i = 0; i < expr.properties.length; i++) {
			                    this.reinterpretExpressionAsPattern(expr.properties[i].value);
			                }
			                break;
			            case syntax_1.Syntax.AssignmentExpression:
			                expr.type = syntax_1.Syntax.AssignmentPattern;
			                delete expr.operator;
			                this.reinterpretExpressionAsPattern(expr.left);
			                break;
			        }
			    };
			    Parser.prototype.parseGroupExpression = function () {
			        var expr;
			        this.expect('(');
			        if (this.match(')')) {
			            this.nextToken();
			            if (!this.match('=>')) {
			                this.expect('=>');
			            }
			            expr = {
			                type: ArrowParameterPlaceHolder,
			                params: [],
			                async: false
			            };
			        }
			        else {
			            var startToken = this.lookahead;
			            var params = [];
			            if (this.match('...')) {
			                expr = this.parseRestElement(params);
			                this.expect(')');
			                if (!this.match('=>')) {
			                    this.expect('=>');
			                }
			                expr = {
			                    type: ArrowParameterPlaceHolder,
			                    params: [expr],
			                    async: false
			                };
			            }
			            else {
			                var arrow = false;
			                this.context.isBindingElement = true;
			                expr = this.inheritCoverGrammar(this.parseAssignmentExpression);
			                if (this.match(',')) {
			                    var expressions = [];
			                    this.context.isAssignmentTarget = false;
			                    expressions.push(expr);
			                    while (this.lookahead.type !== 2 ) {
			                        if (!this.match(',')) {
			                            break;
			                        }
			                        this.nextToken();
			                        if (this.match(')')) {
			                            this.nextToken();
			                            for (var i = 0; i < expressions.length; i++) {
			                                this.reinterpretExpressionAsPattern(expressions[i]);
			                            }
			                            arrow = true;
			                            expr = {
			                                type: ArrowParameterPlaceHolder,
			                                params: expressions,
			                                async: false
			                            };
			                        }
			                        else if (this.match('...')) {
			                            if (!this.context.isBindingElement) {
			                                this.throwUnexpectedToken(this.lookahead);
			                            }
			                            expressions.push(this.parseRestElement(params));
			                            this.expect(')');
			                            if (!this.match('=>')) {
			                                this.expect('=>');
			                            }
			                            this.context.isBindingElement = false;
			                            for (var i = 0; i < expressions.length; i++) {
			                                this.reinterpretExpressionAsPattern(expressions[i]);
			                            }
			                            arrow = true;
			                            expr = {
			                                type: ArrowParameterPlaceHolder,
			                                params: expressions,
			                                async: false
			                            };
			                        }
			                        else {
			                            expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
			                        }
			                        if (arrow) {
			                            break;
			                        }
			                    }
			                    if (!arrow) {
			                        expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
			                    }
			                }
			                if (!arrow) {
			                    this.expect(')');
			                    if (this.match('=>')) {
			                        if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') {
			                            arrow = true;
			                            expr = {
			                                type: ArrowParameterPlaceHolder,
			                                params: [expr],
			                                async: false
			                            };
			                        }
			                        if (!arrow) {
			                            if (!this.context.isBindingElement) {
			                                this.throwUnexpectedToken(this.lookahead);
			                            }
			                            if (expr.type === syntax_1.Syntax.SequenceExpression) {
			                                for (var i = 0; i < expr.expressions.length; i++) {
			                                    this.reinterpretExpressionAsPattern(expr.expressions[i]);
			                                }
			                            }
			                            else {
			                                this.reinterpretExpressionAsPattern(expr);
			                            }
			                            var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]);
			                            expr = {
			                                type: ArrowParameterPlaceHolder,
			                                params: parameters,
			                                async: false
			                            };
			                        }
			                    }
			                    this.context.isBindingElement = false;
			                }
			            }
			        }
			        return expr;
			    };
			    Parser.prototype.parseArguments = function () {
			        this.expect('(');
			        var args = [];
			        if (!this.match(')')) {
			            while (true) {
			                var expr = this.match('...') ? this.parseSpreadElement() :
			                    this.isolateCoverGrammar(this.parseAssignmentExpression);
			                args.push(expr);
			                if (this.match(')')) {
			                    break;
			                }
			                this.expectCommaSeparator();
			                if (this.match(')')) {
			                    break;
			                }
			            }
			        }
			        this.expect(')');
			        return args;
			    };
			    Parser.prototype.isIdentifierName = function (token) {
			        return token.type === 3  ||
			            token.type === 4  ||
			            token.type === 1  ||
			            token.type === 5 ;
			    };
			    Parser.prototype.parseIdentifierName = function () {
			        var node = this.createNode();
			        var token = this.nextToken();
			        if (!this.isIdentifierName(token)) {
			            this.throwUnexpectedToken(token);
			        }
			        return this.finalize(node, new Node.Identifier(token.value));
			    };
			    Parser.prototype.parseNewExpression = function () {
			        var node = this.createNode();
			        var id = this.parseIdentifierName();
			        assert_1.assert(id.name === 'new', 'New expression must start with `new`');
			        var expr;
			        if (this.match('.')) {
			            this.nextToken();
			            if (this.lookahead.type === 3  && this.context.inFunctionBody && this.lookahead.value === 'target') {
			                var property = this.parseIdentifierName();
			                expr = new Node.MetaProperty(id, property);
			            }
			            else {
			                this.throwUnexpectedToken(this.lookahead);
			            }
			        }
			        else {
			            var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
			            var args = this.match('(') ? this.parseArguments() : [];
			            expr = new Node.NewExpression(callee, args);
			            this.context.isAssignmentTarget = false;
			            this.context.isBindingElement = false;
			        }
			        return this.finalize(node, expr);
			    };
			    Parser.prototype.parseAsyncArgument = function () {
			        var arg = this.parseAssignmentExpression();
			        this.context.firstCoverInitializedNameError = null;
			        return arg;
			    };
			    Parser.prototype.parseAsyncArguments = function () {
			        this.expect('(');
			        var args = [];
			        if (!this.match(')')) {
			            while (true) {
			                var expr = this.match('...') ? this.parseSpreadElement() :
			                    this.isolateCoverGrammar(this.parseAsyncArgument);
			                args.push(expr);
			                if (this.match(')')) {
			                    break;
			                }
			                this.expectCommaSeparator();
			                if (this.match(')')) {
			                    break;
			                }
			            }
			        }
			        this.expect(')');
			        return args;
			    };
			    Parser.prototype.parseLeftHandSideExpressionAllowCall = function () {
			        var startToken = this.lookahead;
			        var maybeAsync = this.matchContextualKeyword('async');
			        var previousAllowIn = this.context.allowIn;
			        this.context.allowIn = true;
			        var expr;
			        if (this.matchKeyword('super') && this.context.inFunctionBody) {
			            expr = this.createNode();
			            this.nextToken();
			            expr = this.finalize(expr, new Node.Super());
			            if (!this.match('(') && !this.match('.') && !this.match('[')) {
			                this.throwUnexpectedToken(this.lookahead);
			            }
			        }
			        else {
			            expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
			        }
			        while (true) {
			            if (this.match('.')) {
			                this.context.isBindingElement = false;
			                this.context.isAssignmentTarget = true;
			                this.expect('.');
			                var property = this.parseIdentifierName();
			                expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property));
			            }
			            else if (this.match('(')) {
			                var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber);
			                this.context.isBindingElement = false;
			                this.context.isAssignmentTarget = false;
			                var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments();
			                expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args));
			                if (asyncArrow && this.match('=>')) {
			                    for (var i = 0; i < args.length; ++i) {
			                        this.reinterpretExpressionAsPattern(args[i]);
			                    }
			                    expr = {
			                        type: ArrowParameterPlaceHolder,
			                        params: args,
			                        async: true
			                    };
			                }
			            }
			            else if (this.match('[')) {
			                this.context.isBindingElement = false;
			                this.context.isAssignmentTarget = true;
			                this.expect('[');
			                var property = this.isolateCoverGrammar(this.parseExpression);
			                this.expect(']');
			                expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property));
			            }
			            else if (this.lookahead.type === 10  && this.lookahead.head) {
			                var quasi = this.parseTemplateLiteral();
			                expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi));
			            }
			            else {
			                break;
			            }
			        }
			        this.context.allowIn = previousAllowIn;
			        return expr;
			    };
			    Parser.prototype.parseSuper = function () {
			        var node = this.createNode();
			        this.expectKeyword('super');
			        if (!this.match('[') && !this.match('.')) {
			            this.throwUnexpectedToken(this.lookahead);
			        }
			        return this.finalize(node, new Node.Super());
			    };
			    Parser.prototype.parseLeftHandSideExpression = function () {
			        assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.');
			        var node = this.startNode(this.lookahead);
			        var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() :
			            this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
			        while (true) {
			            if (this.match('[')) {
			                this.context.isBindingElement = false;
			                this.context.isAssignmentTarget = true;
			                this.expect('[');
			                var property = this.isolateCoverGrammar(this.parseExpression);
			                this.expect(']');
			                expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property));
			            }
			            else if (this.match('.')) {
			                this.context.isBindingElement = false;
			                this.context.isAssignmentTarget = true;
			                this.expect('.');
			                var property = this.parseIdentifierName();
			                expr = this.finalize(node, new Node.StaticMemberExpression(expr, property));
			            }
			            else if (this.lookahead.type === 10  && this.lookahead.head) {
			                var quasi = this.parseTemplateLiteral();
			                expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi));
			            }
			            else {
			                break;
			            }
			        }
			        return expr;
			    };
			    Parser.prototype.parseUpdateExpression = function () {
			        var expr;
			        var startToken = this.lookahead;
			        if (this.match('++') || this.match('--')) {
			            var node = this.startNode(startToken);
			            var token = this.nextToken();
			            expr = this.inheritCoverGrammar(this.parseUnaryExpression);
			            if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
			                this.tolerateError(messages_1.Messages.StrictLHSPrefix);
			            }
			            if (!this.context.isAssignmentTarget) {
			                this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
			            }
			            var prefix = true;
			            expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix));
			            this.context.isAssignmentTarget = false;
			            this.context.isBindingElement = false;
			        }
			        else {
			            expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
			            if (!this.hasLineTerminator && this.lookahead.type === 7 ) {
			                if (this.match('++') || this.match('--')) {
			                    if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
			                        this.tolerateError(messages_1.Messages.StrictLHSPostfix);
			                    }
			                    if (!this.context.isAssignmentTarget) {
			                        this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
			                    }
			                    this.context.isAssignmentTarget = false;
			                    this.context.isBindingElement = false;
			                    var operator = this.nextToken().value;
			                    var prefix = false;
			                    expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix));
			                }
			            }
			        }
			        return expr;
			    };
			    Parser.prototype.parseAwaitExpression = function () {
			        var node = this.createNode();
			        this.nextToken();
			        var argument = this.parseUnaryExpression();
			        return this.finalize(node, new Node.AwaitExpression(argument));
			    };
			    Parser.prototype.parseUnaryExpression = function () {
			        var expr;
			        if (this.match('+') || this.match('-') || this.match('~') || this.match('!') ||
			            this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) {
			            var node = this.startNode(this.lookahead);
			            var token = this.nextToken();
			            expr = this.inheritCoverGrammar(this.parseUnaryExpression);
			            expr = this.finalize(node, new Node.UnaryExpression(token.value, expr));
			            if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) {
			                this.tolerateError(messages_1.Messages.StrictDelete);
			            }
			            this.context.isAssignmentTarget = false;
			            this.context.isBindingElement = false;
			        }
			        else if (this.context.await && this.matchContextualKeyword('await')) {
			            expr = this.parseAwaitExpression();
			        }
			        else {
			            expr = this.parseUpdateExpression();
			        }
			        return expr;
			    };
			    Parser.prototype.parseExponentiationExpression = function () {
			        var startToken = this.lookahead;
			        var expr = this.inheritCoverGrammar(this.parseUnaryExpression);
			        if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) {
			            this.nextToken();
			            this.context.isAssignmentTarget = false;
			            this.context.isBindingElement = false;
			            var left = expr;
			            var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
			            expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right));
			        }
			        return expr;
			    };
			    Parser.prototype.binaryPrecedence = function (token) {
			        var op = token.value;
			        var precedence;
			        if (token.type === 7 ) {
			            precedence = this.operatorPrecedence[op] || 0;
			        }
			        else if (token.type === 4 ) {
			            precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0;
			        }
			        else {
			            precedence = 0;
			        }
			        return precedence;
			    };
			    Parser.prototype.parseBinaryExpression = function () {
			        var startToken = this.lookahead;
			        var expr = this.inheritCoverGrammar(this.parseExponentiationExpression);
			        var token = this.lookahead;
			        var prec = this.binaryPrecedence(token);
			        if (prec > 0) {
			            this.nextToken();
			            this.context.isAssignmentTarget = false;
			            this.context.isBindingElement = false;
			            var markers = [startToken, this.lookahead];
			            var left = expr;
			            var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
			            var stack = [left, token.value, right];
			            var precedences = [prec];
			            while (true) {
			                prec = this.binaryPrecedence(this.lookahead);
			                if (prec <= 0) {
			                    break;
			                }
			                while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) {
			                    right = stack.pop();
			                    var operator = stack.pop();
			                    precedences.pop();
			                    left = stack.pop();
			                    markers.pop();
			                    var node = this.startNode(markers[markers.length - 1]);
			                    stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right)));
			                }
			                stack.push(this.nextToken().value);
			                precedences.push(prec);
			                markers.push(this.lookahead);
			                stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
			            }
			            var i = stack.length - 1;
			            expr = stack[i];
			            var lastMarker = markers.pop();
			            while (i > 1) {
			                var marker = markers.pop();
			                var lastLineStart = lastMarker && lastMarker.lineStart;
			                var node = this.startNode(marker, lastLineStart);
			                var operator = stack[i - 1];
			                expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr));
			                i -= 2;
			                lastMarker = marker;
			            }
			        }
			        return expr;
			    };
			    Parser.prototype.parseConditionalExpression = function () {
			        var startToken = this.lookahead;
			        var expr = this.inheritCoverGrammar(this.parseBinaryExpression);
			        if (this.match('?')) {
			            this.nextToken();
			            var previousAllowIn = this.context.allowIn;
			            this.context.allowIn = true;
			            var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression);
			            this.context.allowIn = previousAllowIn;
			            this.expect(':');
			            var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression);
			            expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate));
			            this.context.isAssignmentTarget = false;
			            this.context.isBindingElement = false;
			        }
			        return expr;
			    };
			    Parser.prototype.checkPatternParam = function (options, param) {
			        switch (param.type) {
			            case syntax_1.Syntax.Identifier:
			                this.validateParam(options, param, param.name);
			                break;
			            case syntax_1.Syntax.RestElement:
			                this.checkPatternParam(options, param.argument);
			                break;
			            case syntax_1.Syntax.AssignmentPattern:
			                this.checkPatternParam(options, param.left);
			                break;
			            case syntax_1.Syntax.ArrayPattern:
			                for (var i = 0; i < param.elements.length; i++) {
			                    if (param.elements[i] !== null) {
			                        this.checkPatternParam(options, param.elements[i]);
			                    }
			                }
			                break;
			            case syntax_1.Syntax.ObjectPattern:
			                for (var i = 0; i < param.properties.length; i++) {
			                    this.checkPatternParam(options, param.properties[i].value);
			                }
			                break;
			        }
			        options.simple = options.simple && (param instanceof Node.Identifier);
			    };
			    Parser.prototype.reinterpretAsCoverFormalsList = function (expr) {
			        var params = [expr];
			        var options;
			        var asyncArrow = false;
			        switch (expr.type) {
			            case syntax_1.Syntax.Identifier:
			                break;
			            case ArrowParameterPlaceHolder:
			                params = expr.params;
			                asyncArrow = expr.async;
			                break;
			            default:
			                return null;
			        }
			        options = {
			            simple: true,
			            paramSet: {}
			        };
			        for (var i = 0; i < params.length; ++i) {
			            var param = params[i];
			            if (param.type === syntax_1.Syntax.AssignmentPattern) {
			                if (param.right.type === syntax_1.Syntax.YieldExpression) {
			                    if (param.right.argument) {
			                        this.throwUnexpectedToken(this.lookahead);
			                    }
			                    param.right.type = syntax_1.Syntax.Identifier;
			                    param.right.name = 'yield';
			                    delete param.right.argument;
			                    delete param.right.delegate;
			                }
			            }
			            else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') {
			                this.throwUnexpectedToken(this.lookahead);
			            }
			            this.checkPatternParam(options, param);
			            params[i] = param;
			        }
			        if (this.context.strict || !this.context.allowYield) {
			            for (var i = 0; i < params.length; ++i) {
			                var param = params[i];
			                if (param.type === syntax_1.Syntax.YieldExpression) {
			                    this.throwUnexpectedToken(this.lookahead);
			                }
			            }
			        }
			        if (options.message === messages_1.Messages.StrictParamDupe) {
			            var token = this.context.strict ? options.stricted : options.firstRestricted;
			            this.throwUnexpectedToken(token, options.message);
			        }
			        return {
			            simple: options.simple,
			            params: params,
			            stricted: options.stricted,
			            firstRestricted: options.firstRestricted,
			            message: options.message
			        };
			    };
			    Parser.prototype.parseAssignmentExpression = function () {
			        var expr;
			        if (!this.context.allowYield && this.matchKeyword('yield')) {
			            expr = this.parseYieldExpression();
			        }
			        else {
			            var startToken = this.lookahead;
			            var token = startToken;
			            expr = this.parseConditionalExpression();
			            if (token.type === 3  && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') {
			                if (this.lookahead.type === 3  || this.matchKeyword('yield')) {
			                    var arg = this.parsePrimaryExpression();
			                    this.reinterpretExpressionAsPattern(arg);
			                    expr = {
			                        type: ArrowParameterPlaceHolder,
			                        params: [arg],
			                        async: true
			                    };
			                }
			            }
			            if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) {
			                this.context.isAssignmentTarget = false;
			                this.context.isBindingElement = false;
			                var isAsync = expr.async;
			                var list = this.reinterpretAsCoverFormalsList(expr);
			                if (list) {
			                    if (this.hasLineTerminator) {
			                        this.tolerateUnexpectedToken(this.lookahead);
			                    }
			                    this.context.firstCoverInitializedNameError = null;
			                    var previousStrict = this.context.strict;
			                    var previousAllowStrictDirective = this.context.allowStrictDirective;
			                    this.context.allowStrictDirective = list.simple;
			                    var previousAllowYield = this.context.allowYield;
			                    var previousAwait = this.context.await;
			                    this.context.allowYield = true;
			                    this.context.await = isAsync;
			                    var node = this.startNode(startToken);
			                    this.expect('=>');
			                    var body = void 0;
			                    if (this.match('{')) {
			                        var previousAllowIn = this.context.allowIn;
			                        this.context.allowIn = true;
			                        body = this.parseFunctionSourceElements();
			                        this.context.allowIn = previousAllowIn;
			                    }
			                    else {
			                        body = this.isolateCoverGrammar(this.parseAssignmentExpression);
			                    }
			                    var expression = body.type !== syntax_1.Syntax.BlockStatement;
			                    if (this.context.strict && list.firstRestricted) {
			                        this.throwUnexpectedToken(list.firstRestricted, list.message);
			                    }
			                    if (this.context.strict && list.stricted) {
			                        this.tolerateUnexpectedToken(list.stricted, list.message);
			                    }
			                    expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) :
			                        this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression));
			                    this.context.strict = previousStrict;
			                    this.context.allowStrictDirective = previousAllowStrictDirective;
			                    this.context.allowYield = previousAllowYield;
			                    this.context.await = previousAwait;
			                }
			            }
			            else {
			                if (this.matchAssign()) {
			                    if (!this.context.isAssignmentTarget) {
			                        this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
			                    }
			                    if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) {
			                        var id = expr;
			                        if (this.scanner.isRestrictedWord(id.name)) {
			                            this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment);
			                        }
			                        if (this.scanner.isStrictModeReservedWord(id.name)) {
			                            this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
			                        }
			                    }
			                    if (!this.match('=')) {
			                        this.context.isAssignmentTarget = false;
			                        this.context.isBindingElement = false;
			                    }
			                    else {
			                        this.reinterpretExpressionAsPattern(expr);
			                    }
			                    token = this.nextToken();
			                    var operator = token.value;
			                    var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
			                    expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right));
			                    this.context.firstCoverInitializedNameError = null;
			                }
			            }
			        }
			        return expr;
			    };
			    Parser.prototype.parseExpression = function () {
			        var startToken = this.lookahead;
			        var expr = this.isolateCoverGrammar(this.parseAssignmentExpression);
			        if (this.match(',')) {
			            var expressions = [];
			            expressions.push(expr);
			            while (this.lookahead.type !== 2 ) {
			                if (!this.match(',')) {
			                    break;
			                }
			                this.nextToken();
			                expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
			            }
			            expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
			        }
			        return expr;
			    };
			    Parser.prototype.parseStatementListItem = function () {
			        var statement;
			        this.context.isAssignmentTarget = true;
			        this.context.isBindingElement = true;
			        if (this.lookahead.type === 4 ) {
			            switch (this.lookahead.value) {
			                case 'export':
			                    if (!this.context.isModule) {
			                        this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration);
			                    }
			                    statement = this.parseExportDeclaration();
			                    break;
			                case 'import':
			                    if (!this.context.isModule) {
			                        this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration);
			                    }
			                    statement = this.parseImportDeclaration();
			                    break;
			                case 'const':
			                    statement = this.parseLexicalDeclaration({ inFor: false });
			                    break;
			                case 'function':
			                    statement = this.parseFunctionDeclaration();
			                    break;
			                case 'class':
			                    statement = this.parseClassDeclaration();
			                    break;
			                case 'let':
			                    statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement();
			                    break;
			                default:
			                    statement = this.parseStatement();
			                    break;
			            }
			        }
			        else {
			            statement = this.parseStatement();
			        }
			        return statement;
			    };
			    Parser.prototype.parseBlock = function () {
			        var node = this.createNode();
			        this.expect('{');
			        var block = [];
			        while (true) {
			            if (this.match('}')) {
			                break;
			            }
			            block.push(this.parseStatementListItem());
			        }
			        this.expect('}');
			        return this.finalize(node, new Node.BlockStatement(block));
			    };
			    Parser.prototype.parseLexicalBinding = function (kind, options) {
			        var node = this.createNode();
			        var params = [];
			        var id = this.parsePattern(params, kind);
			        if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
			            if (this.scanner.isRestrictedWord(id.name)) {
			                this.tolerateError(messages_1.Messages.StrictVarName);
			            }
			        }
			        var init = null;
			        if (kind === 'const') {
			            if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) {
			                if (this.match('=')) {
			                    this.nextToken();
			                    init = this.isolateCoverGrammar(this.parseAssignmentExpression);
			                }
			                else {
			                    this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const');
			                }
			            }
			        }
			        else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) {
			            this.expect('=');
			            init = this.isolateCoverGrammar(this.parseAssignmentExpression);
			        }
			        return this.finalize(node, new Node.VariableDeclarator(id, init));
			    };
			    Parser.prototype.parseBindingList = function (kind, options) {
			        var list = [this.parseLexicalBinding(kind, options)];
			        while (this.match(',')) {
			            this.nextToken();
			            list.push(this.parseLexicalBinding(kind, options));
			        }
			        return list;
			    };
			    Parser.prototype.isLexicalDeclaration = function () {
			        var state = this.scanner.saveState();
			        this.scanner.scanComments();
			        var next = this.scanner.lex();
			        this.scanner.restoreState(state);
			        return (next.type === 3 ) ||
			            (next.type === 7  && next.value === '[') ||
			            (next.type === 7  && next.value === '{') ||
			            (next.type === 4  && next.value === 'let') ||
			            (next.type === 4  && next.value === 'yield');
			    };
			    Parser.prototype.parseLexicalDeclaration = function (options) {
			        var node = this.createNode();
			        var kind = this.nextToken().value;
			        assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
			        var declarations = this.parseBindingList(kind, options);
			        this.consumeSemicolon();
			        return this.finalize(node, new Node.VariableDeclaration(declarations, kind));
			    };
			    Parser.prototype.parseBindingRestElement = function (params, kind) {
			        var node = this.createNode();
			        this.expect('...');
			        var arg = this.parsePattern(params, kind);
			        return this.finalize(node, new Node.RestElement(arg));
			    };
			    Parser.prototype.parseArrayPattern = function (params, kind) {
			        var node = this.createNode();
			        this.expect('[');
			        var elements = [];
			        while (!this.match(']')) {
			            if (this.match(',')) {
			                this.nextToken();
			                elements.push(null);
			            }
			            else {
			                if (this.match('...')) {
			                    elements.push(this.parseBindingRestElement(params, kind));
			                    break;
			                }
			                else {
			                    elements.push(this.parsePatternWithDefault(params, kind));
			                }
			                if (!this.match(']')) {
			                    this.expect(',');
			                }
			            }
			        }
			        this.expect(']');
			        return this.finalize(node, new Node.ArrayPattern(elements));
			    };
			    Parser.prototype.parsePropertyPattern = function (params, kind) {
			        var node = this.createNode();
			        var computed = false;
			        var shorthand = false;
			        var method = false;
			        var key;
			        var value;
			        if (this.lookahead.type === 3 ) {
			            var keyToken = this.lookahead;
			            key = this.parseVariableIdentifier();
			            var init = this.finalize(node, new Node.Identifier(keyToken.value));
			            if (this.match('=')) {
			                params.push(keyToken);
			                shorthand = true;
			                this.nextToken();
			                var expr = this.parseAssignmentExpression();
			                value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr));
			            }
			            else if (!this.match(':')) {
			                params.push(keyToken);
			                shorthand = true;
			                value = init;
			            }
			            else {
			                this.expect(':');
			                value = this.parsePatternWithDefault(params, kind);
			            }
			        }
			        else {
			            computed = this.match('[');
			            key = this.parseObjectPropertyKey();
			            this.expect(':');
			            value = this.parsePatternWithDefault(params, kind);
			        }
			        return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand));
			    };
			    Parser.prototype.parseObjectPattern = function (params, kind) {
			        var node = this.createNode();
			        var properties = [];
			        this.expect('{');
			        while (!this.match('}')) {
			            properties.push(this.parsePropertyPattern(params, kind));
			            if (!this.match('}')) {
			                this.expect(',');
			            }
			        }
			        this.expect('}');
			        return this.finalize(node, new Node.ObjectPattern(properties));
			    };
			    Parser.prototype.parsePattern = function (params, kind) {
			        var pattern;
			        if (this.match('[')) {
			            pattern = this.parseArrayPattern(params, kind);
			        }
			        else if (this.match('{')) {
			            pattern = this.parseObjectPattern(params, kind);
			        }
			        else {
			            if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) {
			                this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding);
			            }
			            params.push(this.lookahead);
			            pattern = this.parseVariableIdentifier(kind);
			        }
			        return pattern;
			    };
			    Parser.prototype.parsePatternWithDefault = function (params, kind) {
			        var startToken = this.lookahead;
			        var pattern = this.parsePattern(params, kind);
			        if (this.match('=')) {
			            this.nextToken();
			            var previousAllowYield = this.context.allowYield;
			            this.context.allowYield = true;
			            var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
			            this.context.allowYield = previousAllowYield;
			            pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right));
			        }
			        return pattern;
			    };
			    Parser.prototype.parseVariableIdentifier = function (kind) {
			        var node = this.createNode();
			        var token = this.nextToken();
			        if (token.type === 4  && token.value === 'yield') {
			            if (this.context.strict) {
			                this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
			            }
			            else if (!this.context.allowYield) {
			                this.throwUnexpectedToken(token);
			            }
			        }
			        else if (token.type !== 3 ) {
			            if (this.context.strict && token.type === 4  && this.scanner.isStrictModeReservedWord(token.value)) {
			                this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
			            }
			            else {
			                if (this.context.strict || token.value !== 'let' || kind !== 'var') {
			                    this.throwUnexpectedToken(token);
			                }
			            }
			        }
			        else if ((this.context.isModule || this.context.await) && token.type === 3  && token.value === 'await') {
			            this.tolerateUnexpectedToken(token);
			        }
			        return this.finalize(node, new Node.Identifier(token.value));
			    };
			    Parser.prototype.parseVariableDeclaration = function (options) {
			        var node = this.createNode();
			        var params = [];
			        var id = this.parsePattern(params, 'var');
			        if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
			            if (this.scanner.isRestrictedWord(id.name)) {
			                this.tolerateError(messages_1.Messages.StrictVarName);
			            }
			        }
			        var init = null;
			        if (this.match('=')) {
			            this.nextToken();
			            init = this.isolateCoverGrammar(this.parseAssignmentExpression);
			        }
			        else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) {
			            this.expect('=');
			        }
			        return this.finalize(node, new Node.VariableDeclarator(id, init));
			    };
			    Parser.prototype.parseVariableDeclarationList = function (options) {
			        var opt = { inFor: options.inFor };
			        var list = [];
			        list.push(this.parseVariableDeclaration(opt));
			        while (this.match(',')) {
			            this.nextToken();
			            list.push(this.parseVariableDeclaration(opt));
			        }
			        return list;
			    };
			    Parser.prototype.parseVariableStatement = function () {
			        var node = this.createNode();
			        this.expectKeyword('var');
			        var declarations = this.parseVariableDeclarationList({ inFor: false });
			        this.consumeSemicolon();
			        return this.finalize(node, new Node.VariableDeclaration(declarations, 'var'));
			    };
			    Parser.prototype.parseEmptyStatement = function () {
			        var node = this.createNode();
			        this.expect(';');
			        return this.finalize(node, new Node.EmptyStatement());
			    };
			    Parser.prototype.parseExpressionStatement = function () {
			        var node = this.createNode();
			        var expr = this.parseExpression();
			        this.consumeSemicolon();
			        return this.finalize(node, new Node.ExpressionStatement(expr));
			    };
			    Parser.prototype.parseIfClause = function () {
			        if (this.context.strict && this.matchKeyword('function')) {
			            this.tolerateError(messages_1.Messages.StrictFunction);
			        }
			        return this.parseStatement();
			    };
			    Parser.prototype.parseIfStatement = function () {
			        var node = this.createNode();
			        var consequent;
			        var alternate = null;
			        this.expectKeyword('if');
			        this.expect('(');
			        var test = this.parseExpression();
			        if (!this.match(')') && this.config.tolerant) {
			            this.tolerateUnexpectedToken(this.nextToken());
			            consequent = this.finalize(this.createNode(), new Node.EmptyStatement());
			        }
			        else {
			            this.expect(')');
			            consequent = this.parseIfClause();
			            if (this.matchKeyword('else')) {
			                this.nextToken();
			                alternate = this.parseIfClause();
			            }
			        }
			        return this.finalize(node, new Node.IfStatement(test, consequent, alternate));
			    };
			    Parser.prototype.parseDoWhileStatement = function () {
			        var node = this.createNode();
			        this.expectKeyword('do');
			        var previousInIteration = this.context.inIteration;
			        this.context.inIteration = true;
			        var body = this.parseStatement();
			        this.context.inIteration = previousInIteration;
			        this.expectKeyword('while');
			        this.expect('(');
			        var test = this.parseExpression();
			        if (!this.match(')') && this.config.tolerant) {
			            this.tolerateUnexpectedToken(this.nextToken());
			        }
			        else {
			            this.expect(')');
			            if (this.match(';')) {
			                this.nextToken();
			            }
			        }
			        return this.finalize(node, new Node.DoWhileStatement(body, test));
			    };
			    Parser.prototype.parseWhileStatement = function () {
			        var node = this.createNode();
			        var body;
			        this.expectKeyword('while');
			        this.expect('(');
			        var test = this.parseExpression();
			        if (!this.match(')') && this.config.tolerant) {
			            this.tolerateUnexpectedToken(this.nextToken());
			            body = this.finalize(this.createNode(), new Node.EmptyStatement());
			        }
			        else {
			            this.expect(')');
			            var previousInIteration = this.context.inIteration;
			            this.context.inIteration = true;
			            body = this.parseStatement();
			            this.context.inIteration = previousInIteration;
			        }
			        return this.finalize(node, new Node.WhileStatement(test, body));
			    };
			    Parser.prototype.parseForStatement = function () {
			        var init = null;
			        var test = null;
			        var update = null;
			        var forIn = true;
			        var left, right;
			        var node = this.createNode();
			        this.expectKeyword('for');
			        this.expect('(');
			        if (this.match(';')) {
			            this.nextToken();
			        }
			        else {
			            if (this.matchKeyword('var')) {
			                init = this.createNode();
			                this.nextToken();
			                var previousAllowIn = this.context.allowIn;
			                this.context.allowIn = false;
			                var declarations = this.parseVariableDeclarationList({ inFor: true });
			                this.context.allowIn = previousAllowIn;
			                if (declarations.length === 1 && this.matchKeyword('in')) {
			                    var decl = declarations[0];
			                    if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) {
			                        this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in');
			                    }
			                    init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
			                    this.nextToken();
			                    left = init;
			                    right = this.parseExpression();
			                    init = null;
			                }
			                else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
			                    init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
			                    this.nextToken();
			                    left = init;
			                    right = this.parseAssignmentExpression();
			                    init = null;
			                    forIn = false;
			                }
			                else {
			                    init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
			                    this.expect(';');
			                }
			            }
			            else if (this.matchKeyword('const') || this.matchKeyword('let')) {
			                init = this.createNode();
			                var kind = this.nextToken().value;
			                if (!this.context.strict && this.lookahead.value === 'in') {
			                    init = this.finalize(init, new Node.Identifier(kind));
			                    this.nextToken();
			                    left = init;
			                    right = this.parseExpression();
			                    init = null;
			                }
			                else {
			                    var previousAllowIn = this.context.allowIn;
			                    this.context.allowIn = false;
			                    var declarations = this.parseBindingList(kind, { inFor: true });
			                    this.context.allowIn = previousAllowIn;
			                    if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) {
			                        init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
			                        this.nextToken();
			                        left = init;
			                        right = this.parseExpression();
			                        init = null;
			                    }
			                    else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
			                        init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
			                        this.nextToken();
			                        left = init;
			                        right = this.parseAssignmentExpression();
			                        init = null;
			                        forIn = false;
			                    }
			                    else {
			                        this.consumeSemicolon();
			                        init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
			                    }
			                }
			            }
			            else {
			                var initStartToken = this.lookahead;
			                var previousAllowIn = this.context.allowIn;
			                this.context.allowIn = false;
			                init = this.inheritCoverGrammar(this.parseAssignmentExpression);
			                this.context.allowIn = previousAllowIn;
			                if (this.matchKeyword('in')) {
			                    if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
			                        this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
			                    }
			                    this.nextToken();
			                    this.reinterpretExpressionAsPattern(init);
			                    left = init;
			                    right = this.parseExpression();
			                    init = null;
			                }
			                else if (this.matchContextualKeyword('of')) {
			                    if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
			                        this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
			                    }
			                    this.nextToken();
			                    this.reinterpretExpressionAsPattern(init);
			                    left = init;
			                    right = this.parseAssignmentExpression();
			                    init = null;
			                    forIn = false;
			                }
			                else {
			                    if (this.match(',')) {
			                        var initSeq = [init];
			                        while (this.match(',')) {
			                            this.nextToken();
			                            initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
			                        }
			                        init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq));
			                    }
			                    this.expect(';');
			                }
			            }
			        }
			        if (typeof left === 'undefined') {
			            if (!this.match(';')) {
			                test = this.parseExpression();
			            }
			            this.expect(';');
			            if (!this.match(')')) {
			                update = this.parseExpression();
			            }
			        }
			        var body;
			        if (!this.match(')') && this.config.tolerant) {
			            this.tolerateUnexpectedToken(this.nextToken());
			            body = this.finalize(this.createNode(), new Node.EmptyStatement());
			        }
			        else {
			            this.expect(')');
			            var previousInIteration = this.context.inIteration;
			            this.context.inIteration = true;
			            body = this.isolateCoverGrammar(this.parseStatement);
			            this.context.inIteration = previousInIteration;
			        }
			        return (typeof left === 'undefined') ?
			            this.finalize(node, new Node.ForStatement(init, test, update, body)) :
			            forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) :
			                this.finalize(node, new Node.ForOfStatement(left, right, body));
			    };
			    Parser.prototype.parseContinueStatement = function () {
			        var node = this.createNode();
			        this.expectKeyword('continue');
			        var label = null;
			        if (this.lookahead.type === 3  && !this.hasLineTerminator) {
			            var id = this.parseVariableIdentifier();
			            label = id;
			            var key = '$' + id.name;
			            if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
			                this.throwError(messages_1.Messages.UnknownLabel, id.name);
			            }
			        }
			        this.consumeSemicolon();
			        if (label === null && !this.context.inIteration) {
			            this.throwError(messages_1.Messages.IllegalContinue);
			        }
			        return this.finalize(node, new Node.ContinueStatement(label));
			    };
			    Parser.prototype.parseBreakStatement = function () {
			        var node = this.createNode();
			        this.expectKeyword('break');
			        var label = null;
			        if (this.lookahead.type === 3  && !this.hasLineTerminator) {
			            var id = this.parseVariableIdentifier();
			            var key = '$' + id.name;
			            if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
			                this.throwError(messages_1.Messages.UnknownLabel, id.name);
			            }
			            label = id;
			        }
			        this.consumeSemicolon();
			        if (label === null && !this.context.inIteration && !this.context.inSwitch) {
			            this.throwError(messages_1.Messages.IllegalBreak);
			        }
			        return this.finalize(node, new Node.BreakStatement(label));
			    };
			    Parser.prototype.parseReturnStatement = function () {
			        if (!this.context.inFunctionBody) {
			            this.tolerateError(messages_1.Messages.IllegalReturn);
			        }
			        var node = this.createNode();
			        this.expectKeyword('return');
			        var hasArgument = (!this.match(';') && !this.match('}') &&
			            !this.hasLineTerminator && this.lookahead.type !== 2 ) ||
			            this.lookahead.type === 8  ||
			            this.lookahead.type === 10 ;
			        var argument = hasArgument ? this.parseExpression() : null;
			        this.consumeSemicolon();
			        return this.finalize(node, new Node.ReturnStatement(argument));
			    };
			    Parser.prototype.parseWithStatement = function () {
			        if (this.context.strict) {
			            this.tolerateError(messages_1.Messages.StrictModeWith);
			        }
			        var node = this.createNode();
			        var body;
			        this.expectKeyword('with');
			        this.expect('(');
			        var object = this.parseExpression();
			        if (!this.match(')') && this.config.tolerant) {
			            this.tolerateUnexpectedToken(this.nextToken());
			            body = this.finalize(this.createNode(), new Node.EmptyStatement());
			        }
			        else {
			            this.expect(')');
			            body = this.parseStatement();
			        }
			        return this.finalize(node, new Node.WithStatement(object, body));
			    };
			    Parser.prototype.parseSwitchCase = function () {
			        var node = this.createNode();
			        var test;
			        if (this.matchKeyword('default')) {
			            this.nextToken();
			            test = null;
			        }
			        else {
			            this.expectKeyword('case');
			            test = this.parseExpression();
			        }
			        this.expect(':');
			        var consequent = [];
			        while (true) {
			            if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) {
			                break;
			            }
			            consequent.push(this.parseStatementListItem());
			        }
			        return this.finalize(node, new Node.SwitchCase(test, consequent));
			    };
			    Parser.prototype.parseSwitchStatement = function () {
			        var node = this.createNode();
			        this.expectKeyword('switch');
			        this.expect('(');
			        var discriminant = this.parseExpression();
			        this.expect(')');
			        var previousInSwitch = this.context.inSwitch;
			        this.context.inSwitch = true;
			        var cases = [];
			        var defaultFound = false;
			        this.expect('{');
			        while (true) {
			            if (this.match('}')) {
			                break;
			            }
			            var clause = this.parseSwitchCase();
			            if (clause.test === null) {
			                if (defaultFound) {
			                    this.throwError(messages_1.Messages.MultipleDefaultsInSwitch);
			                }
			                defaultFound = true;
			            }
			            cases.push(clause);
			        }
			        this.expect('}');
			        this.context.inSwitch = previousInSwitch;
			        return this.finalize(node, new Node.SwitchStatement(discriminant, cases));
			    };
			    Parser.prototype.parseLabelledStatement = function () {
			        var node = this.createNode();
			        var expr = this.parseExpression();
			        var statement;
			        if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) {
			            this.nextToken();
			            var id = expr;
			            var key = '$' + id.name;
			            if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
			                this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name);
			            }
			            this.context.labelSet[key] = true;
			            var body = void 0;
			            if (this.matchKeyword('class')) {
			                this.tolerateUnexpectedToken(this.lookahead);
			                body = this.parseClassDeclaration();
			            }
			            else if (this.matchKeyword('function')) {
			                var token = this.lookahead;
			                var declaration = this.parseFunctionDeclaration();
			                if (this.context.strict) {
			                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction);
			                }
			                else if (declaration.generator) {
			                    this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext);
			                }
			                body = declaration;
			            }
			            else {
			                body = this.parseStatement();
			            }
			            delete this.context.labelSet[key];
			            statement = new Node.LabeledStatement(id, body);
			        }
			        else {
			            this.consumeSemicolon();
			            statement = new Node.ExpressionStatement(expr);
			        }
			        return this.finalize(node, statement);
			    };
			    Parser.prototype.parseThrowStatement = function () {
			        var node = this.createNode();
			        this.expectKeyword('throw');
			        if (this.hasLineTerminator) {
			            this.throwError(messages_1.Messages.NewlineAfterThrow);
			        }
			        var argument = this.parseExpression();
			        this.consumeSemicolon();
			        return this.finalize(node, new Node.ThrowStatement(argument));
			    };
			    Parser.prototype.parseCatchClause = function () {
			        var node = this.createNode();
			        this.expectKeyword('catch');
			        this.expect('(');
			        if (this.match(')')) {
			            this.throwUnexpectedToken(this.lookahead);
			        }
			        var params = [];
			        var param = this.parsePattern(params);
			        var paramMap = {};
			        for (var i = 0; i < params.length; i++) {
			            var key = '$' + params[i].value;
			            if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
			                this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value);
			            }
			            paramMap[key] = true;
			        }
			        if (this.context.strict && param.type === syntax_1.Syntax.Identifier) {
			            if (this.scanner.isRestrictedWord(param.name)) {
			                this.tolerateError(messages_1.Messages.StrictCatchVariable);
			            }
			        }
			        this.expect(')');
			        var body = this.parseBlock();
			        return this.finalize(node, new Node.CatchClause(param, body));
			    };
			    Parser.prototype.parseFinallyClause = function () {
			        this.expectKeyword('finally');
			        return this.parseBlock();
			    };
			    Parser.prototype.parseTryStatement = function () {
			        var node = this.createNode();
			        this.expectKeyword('try');
			        var block = this.parseBlock();
			        var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null;
			        var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null;
			        if (!handler && !finalizer) {
			            this.throwError(messages_1.Messages.NoCatchOrFinally);
			        }
			        return this.finalize(node, new Node.TryStatement(block, handler, finalizer));
			    };
			    Parser.prototype.parseDebuggerStatement = function () {
			        var node = this.createNode();
			        this.expectKeyword('debugger');
			        this.consumeSemicolon();
			        return this.finalize(node, new Node.DebuggerStatement());
			    };
			    Parser.prototype.parseStatement = function () {
			        var statement;
			        switch (this.lookahead.type) {
			            case 1 :
			            case 5 :
			            case 6 :
			            case 8 :
			            case 10 :
			            case 9 :
			                statement = this.parseExpressionStatement();
			                break;
			            case 7 :
			                var value = this.lookahead.value;
			                if (value === '{') {
			                    statement = this.parseBlock();
			                }
			                else if (value === '(') {
			                    statement = this.parseExpressionStatement();
			                }
			                else if (value === ';') {
			                    statement = this.parseEmptyStatement();
			                }
			                else {
			                    statement = this.parseExpressionStatement();
			                }
			                break;
			            case 3 :
			                statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement();
			                break;
			            case 4 :
			                switch (this.lookahead.value) {
			                    case 'break':
			                        statement = this.parseBreakStatement();
			                        break;
			                    case 'continue':
			                        statement = this.parseContinueStatement();
			                        break;
			                    case 'debugger':
			                        statement = this.parseDebuggerStatement();
			                        break;
			                    case 'do':
			                        statement = this.parseDoWhileStatement();
			                        break;
			                    case 'for':
			                        statement = this.parseForStatement();
			                        break;
			                    case 'function':
			                        statement = this.parseFunctionDeclaration();
			                        break;
			                    case 'if':
			                        statement = this.parseIfStatement();
			                        break;
			                    case 'return':
			                        statement = this.parseReturnStatement();
			                        break;
			                    case 'switch':
			                        statement = this.parseSwitchStatement();
			                        break;
			                    case 'throw':
			                        statement = this.parseThrowStatement();
			                        break;
			                    case 'try':
			                        statement = this.parseTryStatement();
			                        break;
			                    case 'var':
			                        statement = this.parseVariableStatement();
			                        break;
			                    case 'while':
			                        statement = this.parseWhileStatement();
			                        break;
			                    case 'with':
			                        statement = this.parseWithStatement();
			                        break;
			                    default:
			                        statement = this.parseExpressionStatement();
			                        break;
			                }
			                break;
			            default:
			                statement = this.throwUnexpectedToken(this.lookahead);
			        }
			        return statement;
			    };
			    Parser.prototype.parseFunctionSourceElements = function () {
			        var node = this.createNode();
			        this.expect('{');
			        var body = this.parseDirectivePrologues();
			        var previousLabelSet = this.context.labelSet;
			        var previousInIteration = this.context.inIteration;
			        var previousInSwitch = this.context.inSwitch;
			        var previousInFunctionBody = this.context.inFunctionBody;
			        this.context.labelSet = {};
			        this.context.inIteration = false;
			        this.context.inSwitch = false;
			        this.context.inFunctionBody = true;
			        while (this.lookahead.type !== 2 ) {
			            if (this.match('}')) {
			                break;
			            }
			            body.push(this.parseStatementListItem());
			        }
			        this.expect('}');
			        this.context.labelSet = previousLabelSet;
			        this.context.inIteration = previousInIteration;
			        this.context.inSwitch = previousInSwitch;
			        this.context.inFunctionBody = previousInFunctionBody;
			        return this.finalize(node, new Node.BlockStatement(body));
			    };
			    Parser.prototype.validateParam = function (options, param, name) {
			        var key = '$' + name;
			        if (this.context.strict) {
			            if (this.scanner.isRestrictedWord(name)) {
			                options.stricted = param;
			                options.message = messages_1.Messages.StrictParamName;
			            }
			            if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
			                options.stricted = param;
			                options.message = messages_1.Messages.StrictParamDupe;
			            }
			        }
			        else if (!options.firstRestricted) {
			            if (this.scanner.isRestrictedWord(name)) {
			                options.firstRestricted = param;
			                options.message = messages_1.Messages.StrictParamName;
			            }
			            else if (this.scanner.isStrictModeReservedWord(name)) {
			                options.firstRestricted = param;
			                options.message = messages_1.Messages.StrictReservedWord;
			            }
			            else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
			                options.stricted = param;
			                options.message = messages_1.Messages.StrictParamDupe;
			            }
			        }
			        if (typeof Object.defineProperty === 'function') {
			            Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true });
			        }
			        else {
			            options.paramSet[key] = true;
			        }
			    };
			    Parser.prototype.parseRestElement = function (params) {
			        var node = this.createNode();
			        this.expect('...');
			        var arg = this.parsePattern(params);
			        if (this.match('=')) {
			            this.throwError(messages_1.Messages.DefaultRestParameter);
			        }
			        if (!this.match(')')) {
			            this.throwError(messages_1.Messages.ParameterAfterRestParameter);
			        }
			        return this.finalize(node, new Node.RestElement(arg));
			    };
			    Parser.prototype.parseFormalParameter = function (options) {
			        var params = [];
			        var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
			        for (var i = 0; i < params.length; i++) {
			            this.validateParam(options, params[i], params[i].value);
			        }
			        options.simple = options.simple && (param instanceof Node.Identifier);
			        options.params.push(param);
			    };
			    Parser.prototype.parseFormalParameters = function (firstRestricted) {
			        var options;
			        options = {
			            simple: true,
			            params: [],
			            firstRestricted: firstRestricted
			        };
			        this.expect('(');
			        if (!this.match(')')) {
			            options.paramSet = {};
			            while (this.lookahead.type !== 2 ) {
			                this.parseFormalParameter(options);
			                if (this.match(')')) {
			                    break;
			                }
			                this.expect(',');
			                if (this.match(')')) {
			                    break;
			                }
			            }
			        }
			        this.expect(')');
			        return {
			            simple: options.simple,
			            params: options.params,
			            stricted: options.stricted,
			            firstRestricted: options.firstRestricted,
			            message: options.message
			        };
			    };
			    Parser.prototype.matchAsyncFunction = function () {
			        var match = this.matchContextualKeyword('async');
			        if (match) {
			            var state = this.scanner.saveState();
			            this.scanner.scanComments();
			            var next = this.scanner.lex();
			            this.scanner.restoreState(state);
			            match = (state.lineNumber === next.lineNumber) && (next.type === 4 ) && (next.value === 'function');
			        }
			        return match;
			    };
			    Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) {
			        var node = this.createNode();
			        var isAsync = this.matchContextualKeyword('async');
			        if (isAsync) {
			            this.nextToken();
			        }
			        this.expectKeyword('function');
			        var isGenerator = isAsync ? false : this.match('*');
			        if (isGenerator) {
			            this.nextToken();
			        }
			        var message;
			        var id = null;
			        var firstRestricted = null;
			        if (!identifierIsOptional || !this.match('(')) {
			            var token = this.lookahead;
			            id = this.parseVariableIdentifier();
			            if (this.context.strict) {
			                if (this.scanner.isRestrictedWord(token.value)) {
			                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
			                }
			            }
			            else {
			                if (this.scanner.isRestrictedWord(token.value)) {
			                    firstRestricted = token;
			                    message = messages_1.Messages.StrictFunctionName;
			                }
			                else if (this.scanner.isStrictModeReservedWord(token.value)) {
			                    firstRestricted = token;
			                    message = messages_1.Messages.StrictReservedWord;
			                }
			            }
			        }
			        var previousAllowAwait = this.context.await;
			        var previousAllowYield = this.context.allowYield;
			        this.context.await = isAsync;
			        this.context.allowYield = !isGenerator;
			        var formalParameters = this.parseFormalParameters(firstRestricted);
			        var params = formalParameters.params;
			        var stricted = formalParameters.stricted;
			        firstRestricted = formalParameters.firstRestricted;
			        if (formalParameters.message) {
			            message = formalParameters.message;
			        }
			        var previousStrict = this.context.strict;
			        var previousAllowStrictDirective = this.context.allowStrictDirective;
			        this.context.allowStrictDirective = formalParameters.simple;
			        var body = this.parseFunctionSourceElements();
			        if (this.context.strict && firstRestricted) {
			            this.throwUnexpectedToken(firstRestricted, message);
			        }
			        if (this.context.strict && stricted) {
			            this.tolerateUnexpectedToken(stricted, message);
			        }
			        this.context.strict = previousStrict;
			        this.context.allowStrictDirective = previousAllowStrictDirective;
			        this.context.await = previousAllowAwait;
			        this.context.allowYield = previousAllowYield;
			        return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) :
			            this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator));
			    };
			    Parser.prototype.parseFunctionExpression = function () {
			        var node = this.createNode();
			        var isAsync = this.matchContextualKeyword('async');
			        if (isAsync) {
			            this.nextToken();
			        }
			        this.expectKeyword('function');
			        var isGenerator = isAsync ? false : this.match('*');
			        if (isGenerator) {
			            this.nextToken();
			        }
			        var message;
			        var id = null;
			        var firstRestricted;
			        var previousAllowAwait = this.context.await;
			        var previousAllowYield = this.context.allowYield;
			        this.context.await = isAsync;
			        this.context.allowYield = !isGenerator;
			        if (!this.match('(')) {
			            var token = this.lookahead;
			            id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier();
			            if (this.context.strict) {
			                if (this.scanner.isRestrictedWord(token.value)) {
			                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
			                }
			            }
			            else {
			                if (this.scanner.isRestrictedWord(token.value)) {
			                    firstRestricted = token;
			                    message = messages_1.Messages.StrictFunctionName;
			                }
			                else if (this.scanner.isStrictModeReservedWord(token.value)) {
			                    firstRestricted = token;
			                    message = messages_1.Messages.StrictReservedWord;
			                }
			            }
			        }
			        var formalParameters = this.parseFormalParameters(firstRestricted);
			        var params = formalParameters.params;
			        var stricted = formalParameters.stricted;
			        firstRestricted = formalParameters.firstRestricted;
			        if (formalParameters.message) {
			            message = formalParameters.message;
			        }
			        var previousStrict = this.context.strict;
			        var previousAllowStrictDirective = this.context.allowStrictDirective;
			        this.context.allowStrictDirective = formalParameters.simple;
			        var body = this.parseFunctionSourceElements();
			        if (this.context.strict && firstRestricted) {
			            this.throwUnexpectedToken(firstRestricted, message);
			        }
			        if (this.context.strict && stricted) {
			            this.tolerateUnexpectedToken(stricted, message);
			        }
			        this.context.strict = previousStrict;
			        this.context.allowStrictDirective = previousAllowStrictDirective;
			        this.context.await = previousAllowAwait;
			        this.context.allowYield = previousAllowYield;
			        return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) :
			            this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator));
			    };
			    Parser.prototype.parseDirective = function () {
			        var token = this.lookahead;
			        var node = this.createNode();
			        var expr = this.parseExpression();
			        var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null;
			        this.consumeSemicolon();
			        return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr));
			    };
			    Parser.prototype.parseDirectivePrologues = function () {
			        var firstRestricted = null;
			        var body = [];
			        while (true) {
			            var token = this.lookahead;
			            if (token.type !== 8 ) {
			                break;
			            }
			            var statement = this.parseDirective();
			            body.push(statement);
			            var directive = statement.directive;
			            if (typeof directive !== 'string') {
			                break;
			            }
			            if (directive === 'use strict') {
			                this.context.strict = true;
			                if (firstRestricted) {
			                    this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral);
			                }
			                if (!this.context.allowStrictDirective) {
			                    this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective);
			                }
			            }
			            else {
			                if (!firstRestricted && token.octal) {
			                    firstRestricted = token;
			                }
			            }
			        }
			        return body;
			    };
			    Parser.prototype.qualifiedPropertyName = function (token) {
			        switch (token.type) {
			            case 3 :
			            case 8 :
			            case 1 :
			            case 5 :
			            case 6 :
			            case 4 :
			                return true;
			            case 7 :
			                return token.value === '[';
			        }
			        return false;
			    };
			    Parser.prototype.parseGetterMethod = function () {
			        var node = this.createNode();
			        var isGenerator = false;
			        var previousAllowYield = this.context.allowYield;
			        this.context.allowYield = !isGenerator;
			        var formalParameters = this.parseFormalParameters();
			        if (formalParameters.params.length > 0) {
			            this.tolerateError(messages_1.Messages.BadGetterArity);
			        }
			        var method = this.parsePropertyMethod(formalParameters);
			        this.context.allowYield = previousAllowYield;
			        return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
			    };
			    Parser.prototype.parseSetterMethod = function () {
			        var node = this.createNode();
			        var isGenerator = false;
			        var previousAllowYield = this.context.allowYield;
			        this.context.allowYield = !isGenerator;
			        var formalParameters = this.parseFormalParameters();
			        if (formalParameters.params.length !== 1) {
			            this.tolerateError(messages_1.Messages.BadSetterArity);
			        }
			        else if (formalParameters.params[0] instanceof Node.RestElement) {
			            this.tolerateError(messages_1.Messages.BadSetterRestParameter);
			        }
			        var method = this.parsePropertyMethod(formalParameters);
			        this.context.allowYield = previousAllowYield;
			        return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
			    };
			    Parser.prototype.parseGeneratorMethod = function () {
			        var node = this.createNode();
			        var isGenerator = true;
			        var previousAllowYield = this.context.allowYield;
			        this.context.allowYield = true;
			        var params = this.parseFormalParameters();
			        this.context.allowYield = false;
			        var method = this.parsePropertyMethod(params);
			        this.context.allowYield = previousAllowYield;
			        return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
			    };
			    Parser.prototype.isStartOfExpression = function () {
			        var start = true;
			        var value = this.lookahead.value;
			        switch (this.lookahead.type) {
			            case 7 :
			                start = (value === '[') || (value === '(') || (value === '{') ||
			                    (value === '+') || (value === '-') ||
			                    (value === '!') || (value === '~') ||
			                    (value === '++') || (value === '--') ||
			                    (value === '/') || (value === '/=');
			                break;
			            case 4 :
			                start = (value === 'class') || (value === 'delete') ||
			                    (value === 'function') || (value === 'let') || (value === 'new') ||
			                    (value === 'super') || (value === 'this') || (value === 'typeof') ||
			                    (value === 'void') || (value === 'yield');
			                break;
			        }
			        return start;
			    };
			    Parser.prototype.parseYieldExpression = function () {
			        var node = this.createNode();
			        this.expectKeyword('yield');
			        var argument = null;
			        var delegate = false;
			        if (!this.hasLineTerminator) {
			            var previousAllowYield = this.context.allowYield;
			            this.context.allowYield = false;
			            delegate = this.match('*');
			            if (delegate) {
			                this.nextToken();
			                argument = this.parseAssignmentExpression();
			            }
			            else if (this.isStartOfExpression()) {
			                argument = this.parseAssignmentExpression();
			            }
			            this.context.allowYield = previousAllowYield;
			        }
			        return this.finalize(node, new Node.YieldExpression(argument, delegate));
			    };
			    Parser.prototype.parseClassElement = function (hasConstructor) {
			        var token = this.lookahead;
			        var node = this.createNode();
			        var kind = '';
			        var key = null;
			        var value = null;
			        var computed = false;
			        var method = false;
			        var isStatic = false;
			        var isAsync = false;
			        if (this.match('*')) {
			            this.nextToken();
			        }
			        else {
			            computed = this.match('[');
			            key = this.parseObjectPropertyKey();
			            var id = key;
			            if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) {
			                token = this.lookahead;
			                isStatic = true;
			                computed = this.match('[');
			                if (this.match('*')) {
			                    this.nextToken();
			                }
			                else {
			                    key = this.parseObjectPropertyKey();
			                }
			            }
			            if ((token.type === 3 ) && !this.hasLineTerminator && (token.value === 'async')) {
			                var punctuator = this.lookahead.value;
			                if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') {
			                    isAsync = true;
			                    token = this.lookahead;
			                    key = this.parseObjectPropertyKey();
			                    if (token.type === 3  && token.value === 'constructor') {
			                        this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync);
			                    }
			                }
			            }
			        }
			        var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
			        if (token.type === 3 ) {
			            if (token.value === 'get' && lookaheadPropertyKey) {
			                kind = 'get';
			                computed = this.match('[');
			                key = this.parseObjectPropertyKey();
			                this.context.allowYield = false;
			                value = this.parseGetterMethod();
			            }
			            else if (token.value === 'set' && lookaheadPropertyKey) {
			                kind = 'set';
			                computed = this.match('[');
			                key = this.parseObjectPropertyKey();
			                value = this.parseSetterMethod();
			            }
			        }
			        else if (token.type === 7  && token.value === '*' && lookaheadPropertyKey) {
			            kind = 'init';
			            computed = this.match('[');
			            key = this.parseObjectPropertyKey();
			            value = this.parseGeneratorMethod();
			            method = true;
			        }
			        if (!kind && key && this.match('(')) {
			            kind = 'init';
			            value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
			            method = true;
			        }
			        if (!kind) {
			            this.throwUnexpectedToken(this.lookahead);
			        }
			        if (kind === 'init') {
			            kind = 'method';
			        }
			        if (!computed) {
			            if (isStatic && this.isPropertyKey(key, 'prototype')) {
			                this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype);
			            }
			            if (!isStatic && this.isPropertyKey(key, 'constructor')) {
			                if (kind !== 'method' || !method || (value && value.generator)) {
			                    this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod);
			                }
			                if (hasConstructor.value) {
			                    this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor);
			                }
			                else {
			                    hasConstructor.value = true;
			                }
			                kind = 'constructor';
			            }
			        }
			        return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic));
			    };
			    Parser.prototype.parseClassElementList = function () {
			        var body = [];
			        var hasConstructor = { value: false };
			        this.expect('{');
			        while (!this.match('}')) {
			            if (this.match(';')) {
			                this.nextToken();
			            }
			            else {
			                body.push(this.parseClassElement(hasConstructor));
			            }
			        }
			        this.expect('}');
			        return body;
			    };
			    Parser.prototype.parseClassBody = function () {
			        var node = this.createNode();
			        var elementList = this.parseClassElementList();
			        return this.finalize(node, new Node.ClassBody(elementList));
			    };
			    Parser.prototype.parseClassDeclaration = function (identifierIsOptional) {
			        var node = this.createNode();
			        var previousStrict = this.context.strict;
			        this.context.strict = true;
			        this.expectKeyword('class');
			        var id = (identifierIsOptional && (this.lookahead.type !== 3 )) ? null : this.parseVariableIdentifier();
			        var superClass = null;
			        if (this.matchKeyword('extends')) {
			            this.nextToken();
			            superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
			        }
			        var classBody = this.parseClassBody();
			        this.context.strict = previousStrict;
			        return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody));
			    };
			    Parser.prototype.parseClassExpression = function () {
			        var node = this.createNode();
			        var previousStrict = this.context.strict;
			        this.context.strict = true;
			        this.expectKeyword('class');
			        var id = (this.lookahead.type === 3 ) ? this.parseVariableIdentifier() : null;
			        var superClass = null;
			        if (this.matchKeyword('extends')) {
			            this.nextToken();
			            superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
			        }
			        var classBody = this.parseClassBody();
			        this.context.strict = previousStrict;
			        return this.finalize(node, new Node.ClassExpression(id, superClass, classBody));
			    };
			    Parser.prototype.parseModule = function () {
			        this.context.strict = true;
			        this.context.isModule = true;
			        this.scanner.isModule = true;
			        var node = this.createNode();
			        var body = this.parseDirectivePrologues();
			        while (this.lookahead.type !== 2 ) {
			            body.push(this.parseStatementListItem());
			        }
			        return this.finalize(node, new Node.Module(body));
			    };
			    Parser.prototype.parseScript = function () {
			        var node = this.createNode();
			        var body = this.parseDirectivePrologues();
			        while (this.lookahead.type !== 2 ) {
			            body.push(this.parseStatementListItem());
			        }
			        return this.finalize(node, new Node.Script(body));
			    };
			    Parser.prototype.parseModuleSpecifier = function () {
			        var node = this.createNode();
			        if (this.lookahead.type !== 8 ) {
			            this.throwError(messages_1.Messages.InvalidModuleSpecifier);
			        }
			        var token = this.nextToken();
			        var raw = this.getTokenRaw(token);
			        return this.finalize(node, new Node.Literal(token.value, raw));
			    };
			    Parser.prototype.parseImportSpecifier = function () {
			        var node = this.createNode();
			        var imported;
			        var local;
			        if (this.lookahead.type === 3 ) {
			            imported = this.parseVariableIdentifier();
			            local = imported;
			            if (this.matchContextualKeyword('as')) {
			                this.nextToken();
			                local = this.parseVariableIdentifier();
			            }
			        }
			        else {
			            imported = this.parseIdentifierName();
			            local = imported;
			            if (this.matchContextualKeyword('as')) {
			                this.nextToken();
			                local = this.parseVariableIdentifier();
			            }
			            else {
			                this.throwUnexpectedToken(this.nextToken());
			            }
			        }
			        return this.finalize(node, new Node.ImportSpecifier(local, imported));
			    };
			    Parser.prototype.parseNamedImports = function () {
			        this.expect('{');
			        var specifiers = [];
			        while (!this.match('}')) {
			            specifiers.push(this.parseImportSpecifier());
			            if (!this.match('}')) {
			                this.expect(',');
			            }
			        }
			        this.expect('}');
			        return specifiers;
			    };
			    Parser.prototype.parseImportDefaultSpecifier = function () {
			        var node = this.createNode();
			        var local = this.parseIdentifierName();
			        return this.finalize(node, new Node.ImportDefaultSpecifier(local));
			    };
			    Parser.prototype.parseImportNamespaceSpecifier = function () {
			        var node = this.createNode();
			        this.expect('*');
			        if (!this.matchContextualKeyword('as')) {
			            this.throwError(messages_1.Messages.NoAsAfterImportNamespace);
			        }
			        this.nextToken();
			        var local = this.parseIdentifierName();
			        return this.finalize(node, new Node.ImportNamespaceSpecifier(local));
			    };
			    Parser.prototype.parseImportDeclaration = function () {
			        if (this.context.inFunctionBody) {
			            this.throwError(messages_1.Messages.IllegalImportDeclaration);
			        }
			        var node = this.createNode();
			        this.expectKeyword('import');
			        var src;
			        var specifiers = [];
			        if (this.lookahead.type === 8 ) {
			            src = this.parseModuleSpecifier();
			        }
			        else {
			            if (this.match('{')) {
			                specifiers = specifiers.concat(this.parseNamedImports());
			            }
			            else if (this.match('*')) {
			                specifiers.push(this.parseImportNamespaceSpecifier());
			            }
			            else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) {
			                specifiers.push(this.parseImportDefaultSpecifier());
			                if (this.match(',')) {
			                    this.nextToken();
			                    if (this.match('*')) {
			                        specifiers.push(this.parseImportNamespaceSpecifier());
			                    }
			                    else if (this.match('{')) {
			                        specifiers = specifiers.concat(this.parseNamedImports());
			                    }
			                    else {
			                        this.throwUnexpectedToken(this.lookahead);
			                    }
			                }
			            }
			            else {
			                this.throwUnexpectedToken(this.nextToken());
			            }
			            if (!this.matchContextualKeyword('from')) {
			                var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
			                this.throwError(message, this.lookahead.value);
			            }
			            this.nextToken();
			            src = this.parseModuleSpecifier();
			        }
			        this.consumeSemicolon();
			        return this.finalize(node, new Node.ImportDeclaration(specifiers, src));
			    };
			    Parser.prototype.parseExportSpecifier = function () {
			        var node = this.createNode();
			        var local = this.parseIdentifierName();
			        var exported = local;
			        if (this.matchContextualKeyword('as')) {
			            this.nextToken();
			            exported = this.parseIdentifierName();
			        }
			        return this.finalize(node, new Node.ExportSpecifier(local, exported));
			    };
			    Parser.prototype.parseExportDeclaration = function () {
			        if (this.context.inFunctionBody) {
			            this.throwError(messages_1.Messages.IllegalExportDeclaration);
			        }
			        var node = this.createNode();
			        this.expectKeyword('export');
			        var exportDeclaration;
			        if (this.matchKeyword('default')) {
			            this.nextToken();
			            if (this.matchKeyword('function')) {
			                var declaration = this.parseFunctionDeclaration(true);
			                exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
			            }
			            else if (this.matchKeyword('class')) {
			                var declaration = this.parseClassDeclaration(true);
			                exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
			            }
			            else if (this.matchContextualKeyword('async')) {
			                var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
			                exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
			            }
			            else {
			                if (this.matchContextualKeyword('from')) {
			                    this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value);
			                }
			                var declaration = this.match('{') ? this.parseObjectInitializer() :
			                    this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression();
			                this.consumeSemicolon();
			                exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
			            }
			        }
			        else if (this.match('*')) {
			            this.nextToken();
			            if (!this.matchContextualKeyword('from')) {
			                var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
			                this.throwError(message, this.lookahead.value);
			            }
			            this.nextToken();
			            var src = this.parseModuleSpecifier();
			            this.consumeSemicolon();
			            exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src));
			        }
			        else if (this.lookahead.type === 4 ) {
			            var declaration = void 0;
			            switch (this.lookahead.value) {
			                case 'let':
			                case 'const':
			                    declaration = this.parseLexicalDeclaration({ inFor: false });
			                    break;
			                case 'var':
			                case 'class':
			                case 'function':
			                    declaration = this.parseStatementListItem();
			                    break;
			                default:
			                    this.throwUnexpectedToken(this.lookahead);
			            }
			            exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
			        }
			        else if (this.matchAsyncFunction()) {
			            var declaration = this.parseFunctionDeclaration();
			            exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
			        }
			        else {
			            var specifiers = [];
			            var source = null;
			            var isExportFromIdentifier = false;
			            this.expect('{');
			            while (!this.match('}')) {
			                isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default');
			                specifiers.push(this.parseExportSpecifier());
			                if (!this.match('}')) {
			                    this.expect(',');
			                }
			            }
			            this.expect('}');
			            if (this.matchContextualKeyword('from')) {
			                this.nextToken();
			                source = this.parseModuleSpecifier();
			                this.consumeSemicolon();
			            }
			            else if (isExportFromIdentifier) {
			                var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
			                this.throwError(message, this.lookahead.value);
			            }
			            else {
			                this.consumeSemicolon();
			            }
			            exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source));
			        }
			        return exportDeclaration;
			    };
			    return Parser;
			}());
			exports$1.Parser = Parser;
		 },
		 function(module, exports$1) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			function assert(condition, message) {
			    if (!condition) {
			        throw new Error('ASSERT: ' + message);
			    }
			}
			exports$1.assert = assert;
		 },
		 function(module, exports$1) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			var ErrorHandler = (function () {
			    function ErrorHandler() {
			        this.errors = [];
			        this.tolerant = false;
			    }
			    ErrorHandler.prototype.recordError = function (error) {
			        this.errors.push(error);
			    };
			    ErrorHandler.prototype.tolerate = function (error) {
			        if (this.tolerant) {
			            this.recordError(error);
			        }
			        else {
			            throw error;
			        }
			    };
			    ErrorHandler.prototype.constructError = function (msg, column) {
			        var error = new Error(msg);
			        try {
			            throw error;
			        }
			        catch (base) {
			            if (Object.create && Object.defineProperty) {
			                error = Object.create(base);
			                Object.defineProperty(error, 'column', { value: column });
			            }
			        }
			        return error;
			    };
			    ErrorHandler.prototype.createError = function (index, line, col, description) {
			        var msg = 'Line ' + line + ': ' + description;
			        var error = this.constructError(msg, col);
			        error.index = index;
			        error.lineNumber = line;
			        error.description = description;
			        return error;
			    };
			    ErrorHandler.prototype.throwError = function (index, line, col, description) {
			        throw this.createError(index, line, col, description);
			    };
			    ErrorHandler.prototype.tolerateError = function (index, line, col, description) {
			        var error = this.createError(index, line, col, description);
			        if (this.tolerant) {
			            this.recordError(error);
			        }
			        else {
			            throw error;
			        }
			    };
			    return ErrorHandler;
			}());
			exports$1.ErrorHandler = ErrorHandler;
		 },
		 function(module, exports$1) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			exports$1.Messages = {
			    BadGetterArity: 'Getter must not have any formal parameters',
			    BadSetterArity: 'Setter must have exactly one formal parameter',
			    BadSetterRestParameter: 'Setter function argument must not be a rest parameter',
			    ConstructorIsAsync: 'Class constructor may not be an async method',
			    ConstructorSpecialMethod: 'Class constructor may not be an accessor',
			    DeclarationMissingInitializer: 'Missing initializer in %0 declaration',
			    DefaultRestParameter: 'Unexpected token =',
			    DuplicateBinding: 'Duplicate binding %0',
			    DuplicateConstructor: 'A class may only have one constructor',
			    DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
			    ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer',
			    GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts',
			    IllegalBreak: 'Illegal break statement',
			    IllegalContinue: 'Illegal continue statement',
			    IllegalExportDeclaration: 'Unexpected token',
			    IllegalImportDeclaration: 'Unexpected token',
			    IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list',
			    IllegalReturn: 'Illegal return statement',
			    InvalidEscapedReservedWord: 'Keyword must not contain escaped characters',
			    InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence',
			    InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
			    InvalidLHSInForIn: 'Invalid left-hand side in for-in',
			    InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
			    InvalidModuleSpecifier: 'Unexpected token',
			    InvalidRegExp: 'Invalid regular expression',
			    LetInLexicalBinding: 'let is disallowed as a lexically bound name',
			    MissingFromClause: 'Unexpected token',
			    MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
			    NewlineAfterThrow: 'Illegal newline after throw',
			    NoAsAfterImportNamespace: 'Unexpected token',
			    NoCatchOrFinally: 'Missing catch or finally after try',
			    ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
			    Redeclaration: '%0 \'%1\' has already been declared',
			    StaticPrototype: 'Classes may not have static property named prototype',
			    StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
			    StrictDelete: 'Delete of an unqualified identifier in strict mode.',
			    StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block',
			    StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
			    StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
			    StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
			    StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
			    StrictModeWith: 'Strict mode code may not include a with statement',
			    StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
			    StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
			    StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
			    StrictReservedWord: 'Use of future reserved word in strict mode',
			    StrictVarName: 'Variable name may not be eval or arguments in strict mode',
			    TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
			    UnexpectedEOS: 'Unexpected end of input',
			    UnexpectedIdentifier: 'Unexpected identifier',
			    UnexpectedNumber: 'Unexpected number',
			    UnexpectedReserved: 'Unexpected reserved word',
			    UnexpectedString: 'Unexpected string',
			    UnexpectedTemplate: 'Unexpected quasi %0',
			    UnexpectedToken: 'Unexpected token %0',
			    UnexpectedTokenIllegal: 'Unexpected token ILLEGAL',
			    UnknownLabel: 'Undefined label \'%0\'',
			    UnterminatedRegExp: 'Invalid regular expression: missing /'
			};
		 },
		 function(module, exports$1, __webpack_require__) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			var assert_1 = __webpack_require__(9);
			var character_1 = __webpack_require__(4);
			var messages_1 = __webpack_require__(11);
			function hexValue(ch) {
			    return '0123456789abcdef'.indexOf(ch.toLowerCase());
			}
			function octalValue(ch) {
			    return '01234567'.indexOf(ch);
			}
			var Scanner = (function () {
			    function Scanner(code, handler) {
			        this.source = code;
			        this.errorHandler = handler;
			        this.trackComment = false;
			        this.isModule = false;
			        this.length = code.length;
			        this.index = 0;
			        this.lineNumber = (code.length > 0) ? 1 : 0;
			        this.lineStart = 0;
			        this.curlyStack = [];
			    }
			    Scanner.prototype.saveState = function () {
			        return {
			            index: this.index,
			            lineNumber: this.lineNumber,
			            lineStart: this.lineStart
			        };
			    };
			    Scanner.prototype.restoreState = function (state) {
			        this.index = state.index;
			        this.lineNumber = state.lineNumber;
			        this.lineStart = state.lineStart;
			    };
			    Scanner.prototype.eof = function () {
			        return this.index >= this.length;
			    };
			    Scanner.prototype.throwUnexpectedToken = function (message) {
			        if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; }
			        return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
			    };
			    Scanner.prototype.tolerateUnexpectedToken = function (message) {
			        if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; }
			        this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
			    };
			    Scanner.prototype.skipSingleLineComment = function (offset) {
			        var comments = [];
			        var start, loc;
			        if (this.trackComment) {
			            comments = [];
			            start = this.index - offset;
			            loc = {
			                start: {
			                    line: this.lineNumber,
			                    column: this.index - this.lineStart - offset
			                },
			                end: {}
			            };
			        }
			        while (!this.eof()) {
			            var ch = this.source.charCodeAt(this.index);
			            ++this.index;
			            if (character_1.Character.isLineTerminator(ch)) {
			                if (this.trackComment) {
			                    loc.end = {
			                        line: this.lineNumber,
			                        column: this.index - this.lineStart - 1
			                    };
			                    var entry = {
			                        multiLine: false,
			                        slice: [start + offset, this.index - 1],
			                        range: [start, this.index - 1],
			                        loc: loc
			                    };
			                    comments.push(entry);
			                }
			                if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
			                    ++this.index;
			                }
			                ++this.lineNumber;
			                this.lineStart = this.index;
			                return comments;
			            }
			        }
			        if (this.trackComment) {
			            loc.end = {
			                line: this.lineNumber,
			                column: this.index - this.lineStart
			            };
			            var entry = {
			                multiLine: false,
			                slice: [start + offset, this.index],
			                range: [start, this.index],
			                loc: loc
			            };
			            comments.push(entry);
			        }
			        return comments;
			    };
			    Scanner.prototype.skipMultiLineComment = function () {
			        var comments = [];
			        var start, loc;
			        if (this.trackComment) {
			            comments = [];
			            start = this.index - 2;
			            loc = {
			                start: {
			                    line: this.lineNumber,
			                    column: this.index - this.lineStart - 2
			                },
			                end: {}
			            };
			        }
			        while (!this.eof()) {
			            var ch = this.source.charCodeAt(this.index);
			            if (character_1.Character.isLineTerminator(ch)) {
			                if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) {
			                    ++this.index;
			                }
			                ++this.lineNumber;
			                ++this.index;
			                this.lineStart = this.index;
			            }
			            else if (ch === 0x2A) {
			                if (this.source.charCodeAt(this.index + 1) === 0x2F) {
			                    this.index += 2;
			                    if (this.trackComment) {
			                        loc.end = {
			                            line: this.lineNumber,
			                            column: this.index - this.lineStart
			                        };
			                        var entry = {
			                            multiLine: true,
			                            slice: [start + 2, this.index - 2],
			                            range: [start, this.index],
			                            loc: loc
			                        };
			                        comments.push(entry);
			                    }
			                    return comments;
			                }
			                ++this.index;
			            }
			            else {
			                ++this.index;
			            }
			        }
			        if (this.trackComment) {
			            loc.end = {
			                line: this.lineNumber,
			                column: this.index - this.lineStart
			            };
			            var entry = {
			                multiLine: true,
			                slice: [start + 2, this.index],
			                range: [start, this.index],
			                loc: loc
			            };
			            comments.push(entry);
			        }
			        this.tolerateUnexpectedToken();
			        return comments;
			    };
			    Scanner.prototype.scanComments = function () {
			        var comments;
			        if (this.trackComment) {
			            comments = [];
			        }
			        var start = (this.index === 0);
			        while (!this.eof()) {
			            var ch = this.source.charCodeAt(this.index);
			            if (character_1.Character.isWhiteSpace(ch)) {
			                ++this.index;
			            }
			            else if (character_1.Character.isLineTerminator(ch)) {
			                ++this.index;
			                if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) {
			                    ++this.index;
			                }
			                ++this.lineNumber;
			                this.lineStart = this.index;
			                start = true;
			            }
			            else if (ch === 0x2F) {
			                ch = this.source.charCodeAt(this.index + 1);
			                if (ch === 0x2F) {
			                    this.index += 2;
			                    var comment = this.skipSingleLineComment(2);
			                    if (this.trackComment) {
			                        comments = comments.concat(comment);
			                    }
			                    start = true;
			                }
			                else if (ch === 0x2A) {
			                    this.index += 2;
			                    var comment = this.skipMultiLineComment();
			                    if (this.trackComment) {
			                        comments = comments.concat(comment);
			                    }
			                }
			                else {
			                    break;
			                }
			            }
			            else if (start && ch === 0x2D) {
			                if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) {
			                    this.index += 3;
			                    var comment = this.skipSingleLineComment(3);
			                    if (this.trackComment) {
			                        comments = comments.concat(comment);
			                    }
			                }
			                else {
			                    break;
			                }
			            }
			            else if (ch === 0x3C && !this.isModule) {
			                if (this.source.slice(this.index + 1, this.index + 4) === '!--') {
			                    this.index += 4;
			                    var comment = this.skipSingleLineComment(4);
			                    if (this.trackComment) {
			                        comments = comments.concat(comment);
			                    }
			                }
			                else {
			                    break;
			                }
			            }
			            else {
			                break;
			            }
			        }
			        return comments;
			    };
			    Scanner.prototype.isFutureReservedWord = function (id) {
			        switch (id) {
			            case 'enum':
			            case 'export':
			            case 'import':
			            case 'super':
			                return true;
			            default:
			                return false;
			        }
			    };
			    Scanner.prototype.isStrictModeReservedWord = function (id) {
			        switch (id) {
			            case 'implements':
			            case 'interface':
			            case 'package':
			            case 'private':
			            case 'protected':
			            case 'public':
			            case 'static':
			            case 'yield':
			            case 'let':
			                return true;
			            default:
			                return false;
			        }
			    };
			    Scanner.prototype.isRestrictedWord = function (id) {
			        return id === 'eval' || id === 'arguments';
			    };
			    Scanner.prototype.isKeyword = function (id) {
			        switch (id.length) {
			            case 2:
			                return (id === 'if') || (id === 'in') || (id === 'do');
			            case 3:
			                return (id === 'var') || (id === 'for') || (id === 'new') ||
			                    (id === 'try') || (id === 'let');
			            case 4:
			                return (id === 'this') || (id === 'else') || (id === 'case') ||
			                    (id === 'void') || (id === 'with') || (id === 'enum');
			            case 5:
			                return (id === 'while') || (id === 'break') || (id === 'catch') ||
			                    (id === 'throw') || (id === 'const') || (id === 'yield') ||
			                    (id === 'class') || (id === 'super');
			            case 6:
			                return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
			                    (id === 'switch') || (id === 'export') || (id === 'import');
			            case 7:
			                return (id === 'default') || (id === 'finally') || (id === 'extends');
			            case 8:
			                return (id === 'function') || (id === 'continue') || (id === 'debugger');
			            case 10:
			                return (id === 'instanceof');
			            default:
			                return false;
			        }
			    };
			    Scanner.prototype.codePointAt = function (i) {
			        var cp = this.source.charCodeAt(i);
			        if (cp >= 0xD800 && cp <= 0xDBFF) {
			            var second = this.source.charCodeAt(i + 1);
			            if (second >= 0xDC00 && second <= 0xDFFF) {
			                var first = cp;
			                cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
			            }
			        }
			        return cp;
			    };
			    Scanner.prototype.scanHexEscape = function (prefix) {
			        var len = (prefix === 'u') ? 4 : 2;
			        var code = 0;
			        for (var i = 0; i < len; ++i) {
			            if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
			                code = code * 16 + hexValue(this.source[this.index++]);
			            }
			            else {
			                return null;
			            }
			        }
			        return String.fromCharCode(code);
			    };
			    Scanner.prototype.scanUnicodeCodePointEscape = function () {
			        var ch = this.source[this.index];
			        var code = 0;
			        if (ch === '}') {
			            this.throwUnexpectedToken();
			        }
			        while (!this.eof()) {
			            ch = this.source[this.index++];
			            if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
			                break;
			            }
			            code = code * 16 + hexValue(ch);
			        }
			        if (code > 0x10FFFF || ch !== '}') {
			            this.throwUnexpectedToken();
			        }
			        return character_1.Character.fromCodePoint(code);
			    };
			    Scanner.prototype.getIdentifier = function () {
			        var start = this.index++;
			        while (!this.eof()) {
			            var ch = this.source.charCodeAt(this.index);
			            if (ch === 0x5C) {
			                this.index = start;
			                return this.getComplexIdentifier();
			            }
			            else if (ch >= 0xD800 && ch < 0xDFFF) {
			                this.index = start;
			                return this.getComplexIdentifier();
			            }
			            if (character_1.Character.isIdentifierPart(ch)) {
			                ++this.index;
			            }
			            else {
			                break;
			            }
			        }
			        return this.source.slice(start, this.index);
			    };
			    Scanner.prototype.getComplexIdentifier = function () {
			        var cp = this.codePointAt(this.index);
			        var id = character_1.Character.fromCodePoint(cp);
			        this.index += id.length;
			        var ch;
			        if (cp === 0x5C) {
			            if (this.source.charCodeAt(this.index) !== 0x75) {
			                this.throwUnexpectedToken();
			            }
			            ++this.index;
			            if (this.source[this.index] === '{') {
			                ++this.index;
			                ch = this.scanUnicodeCodePointEscape();
			            }
			            else {
			                ch = this.scanHexEscape('u');
			                if (ch === null || ch === '\\' || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) {
			                    this.throwUnexpectedToken();
			                }
			            }
			            id = ch;
			        }
			        while (!this.eof()) {
			            cp = this.codePointAt(this.index);
			            if (!character_1.Character.isIdentifierPart(cp)) {
			                break;
			            }
			            ch = character_1.Character.fromCodePoint(cp);
			            id += ch;
			            this.index += ch.length;
			            if (cp === 0x5C) {
			                id = id.substr(0, id.length - 1);
			                if (this.source.charCodeAt(this.index) !== 0x75) {
			                    this.throwUnexpectedToken();
			                }
			                ++this.index;
			                if (this.source[this.index] === '{') {
			                    ++this.index;
			                    ch = this.scanUnicodeCodePointEscape();
			                }
			                else {
			                    ch = this.scanHexEscape('u');
			                    if (ch === null || ch === '\\' || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
			                        this.throwUnexpectedToken();
			                    }
			                }
			                id += ch;
			            }
			        }
			        return id;
			    };
			    Scanner.prototype.octalToDecimal = function (ch) {
			        var octal = (ch !== '0');
			        var code = octalValue(ch);
			        if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
			            octal = true;
			            code = code * 8 + octalValue(this.source[this.index++]);
			            if ('0123'.indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
			                code = code * 8 + octalValue(this.source[this.index++]);
			            }
			        }
			        return {
			            code: code,
			            octal: octal
			        };
			    };
			    Scanner.prototype.scanIdentifier = function () {
			        var type;
			        var start = this.index;
			        var id = (this.source.charCodeAt(start) === 0x5C) ? this.getComplexIdentifier() : this.getIdentifier();
			        if (id.length === 1) {
			            type = 3 ;
			        }
			        else if (this.isKeyword(id)) {
			            type = 4 ;
			        }
			        else if (id === 'null') {
			            type = 5 ;
			        }
			        else if (id === 'true' || id === 'false') {
			            type = 1 ;
			        }
			        else {
			            type = 3 ;
			        }
			        if (type !== 3  && (start + id.length !== this.index)) {
			            var restore = this.index;
			            this.index = start;
			            this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord);
			            this.index = restore;
			        }
			        return {
			            type: type,
			            value: id,
			            lineNumber: this.lineNumber,
			            lineStart: this.lineStart,
			            start: start,
			            end: this.index
			        };
			    };
			    Scanner.prototype.scanPunctuator = function () {
			        var start = this.index;
			        var str = this.source[this.index];
			        switch (str) {
			            case '(':
			            case '{':
			                if (str === '{') {
			                    this.curlyStack.push('{');
			                }
			                ++this.index;
			                break;
			            case '.':
			                ++this.index;
			                if (this.source[this.index] === '.' && this.source[this.index + 1] === '.') {
			                    this.index += 2;
			                    str = '...';
			                }
			                break;
			            case '}':
			                ++this.index;
			                this.curlyStack.pop();
			                break;
			            case ')':
			            case ';':
			            case ',':
			            case '[':
			            case ']':
			            case ':':
			            case '?':
			            case '~':
			                ++this.index;
			                break;
			            default:
			                str = this.source.substr(this.index, 4);
			                if (str === '>>>=') {
			                    this.index += 4;
			                }
			                else {
			                    str = str.substr(0, 3);
			                    if (str === '===' || str === '!==' || str === '>>>' ||
			                        str === '<<=' || str === '>>=' || str === '**=') {
			                        this.index += 3;
			                    }
			                    else {
			                        str = str.substr(0, 2);
			                        if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
			                            str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
			                            str === '++' || str === '--' || str === '<<' || str === '>>' ||
			                            str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
			                            str === '<=' || str === '>=' || str === '=>' || str === '**') {
			                            this.index += 2;
			                        }
			                        else {
			                            str = this.source[this.index];
			                            if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
			                                ++this.index;
			                            }
			                        }
			                    }
			                }
			        }
			        if (this.index === start) {
			            this.throwUnexpectedToken();
			        }
			        return {
			            type: 7 ,
			            value: str,
			            lineNumber: this.lineNumber,
			            lineStart: this.lineStart,
			            start: start,
			            end: this.index
			        };
			    };
			    Scanner.prototype.scanHexLiteral = function (start) {
			        var num = '';
			        while (!this.eof()) {
			            if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
			                break;
			            }
			            num += this.source[this.index++];
			        }
			        if (num.length === 0) {
			            this.throwUnexpectedToken();
			        }
			        if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
			            this.throwUnexpectedToken();
			        }
			        return {
			            type: 6 ,
			            value: parseInt('0x' + num, 16),
			            lineNumber: this.lineNumber,
			            lineStart: this.lineStart,
			            start: start,
			            end: this.index
			        };
			    };
			    Scanner.prototype.scanBinaryLiteral = function (start) {
			        var num = '';
			        var ch;
			        while (!this.eof()) {
			            ch = this.source[this.index];
			            if (ch !== '0' && ch !== '1') {
			                break;
			            }
			            num += this.source[this.index++];
			        }
			        if (num.length === 0) {
			            this.throwUnexpectedToken();
			        }
			        if (!this.eof()) {
			            ch = this.source.charCodeAt(this.index);
			            if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) {
			                this.throwUnexpectedToken();
			            }
			        }
			        return {
			            type: 6 ,
			            value: parseInt(num, 2),
			            lineNumber: this.lineNumber,
			            lineStart: this.lineStart,
			            start: start,
			            end: this.index
			        };
			    };
			    Scanner.prototype.scanOctalLiteral = function (prefix, start) {
			        var num = '';
			        var octal = false;
			        if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
			            octal = true;
			            num = '0' + this.source[this.index++];
			        }
			        else {
			            ++this.index;
			        }
			        while (!this.eof()) {
			            if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
			                break;
			            }
			            num += this.source[this.index++];
			        }
			        if (!octal && num.length === 0) {
			            this.throwUnexpectedToken();
			        }
			        if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
			            this.throwUnexpectedToken();
			        }
			        return {
			            type: 6 ,
			            value: parseInt(num, 8),
			            octal: octal,
			            lineNumber: this.lineNumber,
			            lineStart: this.lineStart,
			            start: start,
			            end: this.index
			        };
			    };
			    Scanner.prototype.isImplicitOctalLiteral = function () {
			        for (var i = this.index + 1; i < this.length; ++i) {
			            var ch = this.source[i];
			            if (ch === '8' || ch === '9') {
			                return false;
			            }
			            if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
			                return true;
			            }
			        }
			        return true;
			    };
			    Scanner.prototype.scanNumericLiteral = function () {
			        var start = this.index;
			        var ch = this.source[start];
			        assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point');
			        var num = '';
			        if (ch !== '.') {
			            num = this.source[this.index++];
			            ch = this.source[this.index];
			            if (num === '0') {
			                if (ch === 'x' || ch === 'X') {
			                    ++this.index;
			                    return this.scanHexLiteral(start);
			                }
			                if (ch === 'b' || ch === 'B') {
			                    ++this.index;
			                    return this.scanBinaryLiteral(start);
			                }
			                if (ch === 'o' || ch === 'O') {
			                    return this.scanOctalLiteral(ch, start);
			                }
			                if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
			                    if (this.isImplicitOctalLiteral()) {
			                        return this.scanOctalLiteral(ch, start);
			                    }
			                }
			            }
			            while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
			                num += this.source[this.index++];
			            }
			            ch = this.source[this.index];
			        }
			        if (ch === '.') {
			            num += this.source[this.index++];
			            while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
			                num += this.source[this.index++];
			            }
			            ch = this.source[this.index];
			        }
			        if (ch === 'e' || ch === 'E') {
			            num += this.source[this.index++];
			            ch = this.source[this.index];
			            if (ch === '+' || ch === '-') {
			                num += this.source[this.index++];
			            }
			            if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
			                while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
			                    num += this.source[this.index++];
			                }
			            }
			            else {
			                this.throwUnexpectedToken();
			            }
			        }
			        if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
			            this.throwUnexpectedToken();
			        }
			        return {
			            type: 6 ,
			            value: parseFloat(num),
			            lineNumber: this.lineNumber,
			            lineStart: this.lineStart,
			            start: start,
			            end: this.index
			        };
			    };
			    Scanner.prototype.scanStringLiteral = function () {
			        var start = this.index;
			        var quote = this.source[start];
			        assert_1.assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote');
			        ++this.index;
			        var octal = false;
			        var str = '';
			        while (!this.eof()) {
			            var ch = this.source[this.index++];
			            if (ch === quote) {
			                quote = '';
			                break;
			            }
			            else if (ch === '\\') {
			                ch = this.source[this.index++];
			                if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
			                    switch (ch) {
			                        case 'u':
			                            if (this.source[this.index] === '{') {
			                                ++this.index;
			                                str += this.scanUnicodeCodePointEscape();
			                            }
			                            else {
			                                var unescaped_1 = this.scanHexEscape(ch);
			                                if (unescaped_1 === null) {
			                                    this.throwUnexpectedToken();
			                                }
			                                str += unescaped_1;
			                            }
			                            break;
			                        case 'x':
			                            var unescaped = this.scanHexEscape(ch);
			                            if (unescaped === null) {
			                                this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
			                            }
			                            str += unescaped;
			                            break;
			                        case 'n':
			                            str += '\n';
			                            break;
			                        case 'r':
			                            str += '\r';
			                            break;
			                        case 't':
			                            str += '\t';
			                            break;
			                        case 'b':
			                            str += '\b';
			                            break;
			                        case 'f':
			                            str += '\f';
			                            break;
			                        case 'v':
			                            str += '\x0B';
			                            break;
			                        case '8':
			                        case '9':
			                            str += ch;
			                            this.tolerateUnexpectedToken();
			                            break;
			                        default:
			                            if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
			                                var octToDec = this.octalToDecimal(ch);
			                                octal = octToDec.octal || octal;
			                                str += String.fromCharCode(octToDec.code);
			                            }
			                            else {
			                                str += ch;
			                            }
			                            break;
			                    }
			                }
			                else {
			                    ++this.lineNumber;
			                    if (ch === '\r' && this.source[this.index] === '\n') {
			                        ++this.index;
			                    }
			                    this.lineStart = this.index;
			                }
			            }
			            else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
			                break;
			            }
			            else {
			                str += ch;
			            }
			        }
			        if (quote !== '') {
			            this.index = start;
			            this.throwUnexpectedToken();
			        }
			        return {
			            type: 8 ,
			            value: str,
			            octal: octal,
			            lineNumber: this.lineNumber,
			            lineStart: this.lineStart,
			            start: start,
			            end: this.index
			        };
			    };
			    Scanner.prototype.scanTemplate = function () {
			        var cooked = '';
			        var terminated = false;
			        var start = this.index;
			        var head = (this.source[start] === '`');
			        var tail = false;
			        var rawOffset = 2;
			        ++this.index;
			        while (!this.eof()) {
			            var ch = this.source[this.index++];
			            if (ch === '`') {
			                rawOffset = 1;
			                tail = true;
			                terminated = true;
			                break;
			            }
			            else if (ch === '$') {
			                if (this.source[this.index] === '{') {
			                    this.curlyStack.push('${');
			                    ++this.index;
			                    terminated = true;
			                    break;
			                }
			                cooked += ch;
			            }
			            else if (ch === '\\') {
			                ch = this.source[this.index++];
			                if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
			                    switch (ch) {
			                        case 'n':
			                            cooked += '\n';
			                            break;
			                        case 'r':
			                            cooked += '\r';
			                            break;
			                        case 't':
			                            cooked += '\t';
			                            break;
			                        case 'u':
			                            if (this.source[this.index] === '{') {
			                                ++this.index;
			                                cooked += this.scanUnicodeCodePointEscape();
			                            }
			                            else {
			                                var restore = this.index;
			                                var unescaped_2 = this.scanHexEscape(ch);
			                                if (unescaped_2 !== null) {
			                                    cooked += unescaped_2;
			                                }
			                                else {
			                                    this.index = restore;
			                                    cooked += ch;
			                                }
			                            }
			                            break;
			                        case 'x':
			                            var unescaped = this.scanHexEscape(ch);
			                            if (unescaped === null) {
			                                this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
			                            }
			                            cooked += unescaped;
			                            break;
			                        case 'b':
			                            cooked += '\b';
			                            break;
			                        case 'f':
			                            cooked += '\f';
			                            break;
			                        case 'v':
			                            cooked += '\v';
			                            break;
			                        default:
			                            if (ch === '0') {
			                                if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
			                                    this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
			                                }
			                                cooked += '\0';
			                            }
			                            else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
			                                this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
			                            }
			                            else {
			                                cooked += ch;
			                            }
			                            break;
			                    }
			                }
			                else {
			                    ++this.lineNumber;
			                    if (ch === '\r' && this.source[this.index] === '\n') {
			                        ++this.index;
			                    }
			                    this.lineStart = this.index;
			                }
			            }
			            else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
			                ++this.lineNumber;
			                if (ch === '\r' && this.source[this.index] === '\n') {
			                    ++this.index;
			                }
			                this.lineStart = this.index;
			                cooked += '\n';
			            }
			            else {
			                cooked += ch;
			            }
			        }
			        if (!terminated) {
			            this.throwUnexpectedToken();
			        }
			        if (!head) {
			            this.curlyStack.pop();
			        }
			        return {
			            type: 10 ,
			            value: this.source.slice(start + 1, this.index - rawOffset),
			            cooked: cooked,
			            head: head,
			            tail: tail,
			            lineNumber: this.lineNumber,
			            lineStart: this.lineStart,
			            start: start,
			            end: this.index
			        };
			    };
			    Scanner.prototype.testRegExp = function (pattern, flags) {
			        var astralSubstitute = '\uFFFF';
			        var tmp = pattern;
			        var self = this;
			        if (flags.indexOf('u') >= 0) {
			            tmp = tmp
			                .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
			                var codePoint = parseInt($1 || $2, 16);
			                if (codePoint > 0x10FFFF) {
			                    self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
			                }
			                if (codePoint <= 0xFFFF) {
			                    return String.fromCharCode(codePoint);
			                }
			                return astralSubstitute;
			            })
			                .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute);
			        }
			        try {
			            RegExp(tmp);
			        }
			        catch (e) {
			            this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
			        }
			        try {
			            return new RegExp(pattern, flags);
			        }
			        catch (exception) {
			            return null;
			        }
			    };
			    Scanner.prototype.scanRegExpBody = function () {
			        var ch = this.source[this.index];
			        assert_1.assert(ch === '/', 'Regular expression literal must start with a slash');
			        var str = this.source[this.index++];
			        var classMarker = false;
			        var terminated = false;
			        while (!this.eof()) {
			            ch = this.source[this.index++];
			            str += ch;
			            if (ch === '\\') {
			                ch = this.source[this.index++];
			                if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
			                    this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
			                }
			                str += ch;
			            }
			            else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
			                this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
			            }
			            else if (classMarker) {
			                if (ch === ']') {
			                    classMarker = false;
			                }
			            }
			            else {
			                if (ch === '/') {
			                    terminated = true;
			                    break;
			                }
			                else if (ch === '[') {
			                    classMarker = true;
			                }
			            }
			        }
			        if (!terminated) {
			            this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
			        }
			        return str.substr(1, str.length - 2);
			    };
			    Scanner.prototype.scanRegExpFlags = function () {
			        var str = '';
			        var flags = '';
			        while (!this.eof()) {
			            var ch = this.source[this.index];
			            if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
			                break;
			            }
			            ++this.index;
			            if (ch === '\\' && !this.eof()) {
			                ch = this.source[this.index];
			                if (ch === 'u') {
			                    ++this.index;
			                    var restore = this.index;
			                    var char = this.scanHexEscape('u');
			                    if (char !== null) {
			                        flags += char;
			                        for (str += '\\u'; restore < this.index; ++restore) {
			                            str += this.source[restore];
			                        }
			                    }
			                    else {
			                        this.index = restore;
			                        flags += 'u';
			                        str += '\\u';
			                    }
			                    this.tolerateUnexpectedToken();
			                }
			                else {
			                    str += '\\';
			                    this.tolerateUnexpectedToken();
			                }
			            }
			            else {
			                flags += ch;
			                str += ch;
			            }
			        }
			        return flags;
			    };
			    Scanner.prototype.scanRegExp = function () {
			        var start = this.index;
			        var pattern = this.scanRegExpBody();
			        var flags = this.scanRegExpFlags();
			        var value = this.testRegExp(pattern, flags);
			        return {
			            type: 9 ,
			            value: '',
			            pattern: pattern,
			            flags: flags,
			            regex: value,
			            lineNumber: this.lineNumber,
			            lineStart: this.lineStart,
			            start: start,
			            end: this.index
			        };
			    };
			    Scanner.prototype.lex = function () {
			        if (this.eof()) {
			            return {
			                type: 2 ,
			                value: '',
			                lineNumber: this.lineNumber,
			                lineStart: this.lineStart,
			                start: this.index,
			                end: this.index
			            };
			        }
			        var cp = this.source.charCodeAt(this.index);
			        if (character_1.Character.isIdentifierStart(cp)) {
			            return this.scanIdentifier();
			        }
			        if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
			            return this.scanPunctuator();
			        }
			        if (cp === 0x27 || cp === 0x22) {
			            return this.scanStringLiteral();
			        }
			        if (cp === 0x2E) {
			            if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
			                return this.scanNumericLiteral();
			            }
			            return this.scanPunctuator();
			        }
			        if (character_1.Character.isDecimalDigit(cp)) {
			            return this.scanNumericLiteral();
			        }
			        if (cp === 0x60 || (cp === 0x7D && this.curlyStack[this.curlyStack.length - 1] === '${')) {
			            return this.scanTemplate();
			        }
			        if (cp >= 0xD800 && cp < 0xDFFF) {
			            if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) {
			                return this.scanIdentifier();
			            }
			        }
			        return this.scanPunctuator();
			    };
			    return Scanner;
			}());
			exports$1.Scanner = Scanner;
		 },
		 function(module, exports$1) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			exports$1.TokenName = {};
			exports$1.TokenName[1 ] = 'Boolean';
			exports$1.TokenName[2 ] = '<end>';
			exports$1.TokenName[3 ] = 'Identifier';
			exports$1.TokenName[4 ] = 'Keyword';
			exports$1.TokenName[5 ] = 'Null';
			exports$1.TokenName[6 ] = 'Numeric';
			exports$1.TokenName[7 ] = 'Punctuator';
			exports$1.TokenName[8 ] = 'String';
			exports$1.TokenName[9 ] = 'RegularExpression';
			exports$1.TokenName[10 ] = 'Template';
		 },
		 function(module, exports$1) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			exports$1.XHTMLEntities = {
			    quot: '\u0022',
			    amp: '\u0026',
			    apos: '\u0027',
			    gt: '\u003E',
			    nbsp: '\u00A0',
			    iexcl: '\u00A1',
			    cent: '\u00A2',
			    pound: '\u00A3',
			    curren: '\u00A4',
			    yen: '\u00A5',
			    brvbar: '\u00A6',
			    sect: '\u00A7',
			    uml: '\u00A8',
			    copy: '\u00A9',
			    ordf: '\u00AA',
			    laquo: '\u00AB',
			    not: '\u00AC',
			    shy: '\u00AD',
			    reg: '\u00AE',
			    macr: '\u00AF',
			    deg: '\u00B0',
			    plusmn: '\u00B1',
			    sup2: '\u00B2',
			    sup3: '\u00B3',
			    acute: '\u00B4',
			    micro: '\u00B5',
			    para: '\u00B6',
			    middot: '\u00B7',
			    cedil: '\u00B8',
			    sup1: '\u00B9',
			    ordm: '\u00BA',
			    raquo: '\u00BB',
			    frac14: '\u00BC',
			    frac12: '\u00BD',
			    frac34: '\u00BE',
			    iquest: '\u00BF',
			    Agrave: '\u00C0',
			    Aacute: '\u00C1',
			    Acirc: '\u00C2',
			    Atilde: '\u00C3',
			    Auml: '\u00C4',
			    Aring: '\u00C5',
			    AElig: '\u00C6',
			    Ccedil: '\u00C7',
			    Egrave: '\u00C8',
			    Eacute: '\u00C9',
			    Ecirc: '\u00CA',
			    Euml: '\u00CB',
			    Igrave: '\u00CC',
			    Iacute: '\u00CD',
			    Icirc: '\u00CE',
			    Iuml: '\u00CF',
			    ETH: '\u00D0',
			    Ntilde: '\u00D1',
			    Ograve: '\u00D2',
			    Oacute: '\u00D3',
			    Ocirc: '\u00D4',
			    Otilde: '\u00D5',
			    Ouml: '\u00D6',
			    times: '\u00D7',
			    Oslash: '\u00D8',
			    Ugrave: '\u00D9',
			    Uacute: '\u00DA',
			    Ucirc: '\u00DB',
			    Uuml: '\u00DC',
			    Yacute: '\u00DD',
			    THORN: '\u00DE',
			    szlig: '\u00DF',
			    agrave: '\u00E0',
			    aacute: '\u00E1',
			    acirc: '\u00E2',
			    atilde: '\u00E3',
			    auml: '\u00E4',
			    aring: '\u00E5',
			    aelig: '\u00E6',
			    ccedil: '\u00E7',
			    egrave: '\u00E8',
			    eacute: '\u00E9',
			    ecirc: '\u00EA',
			    euml: '\u00EB',
			    igrave: '\u00EC',
			    iacute: '\u00ED',
			    icirc: '\u00EE',
			    iuml: '\u00EF',
			    eth: '\u00F0',
			    ntilde: '\u00F1',
			    ograve: '\u00F2',
			    oacute: '\u00F3',
			    ocirc: '\u00F4',
			    otilde: '\u00F5',
			    ouml: '\u00F6',
			    divide: '\u00F7',
			    oslash: '\u00F8',
			    ugrave: '\u00F9',
			    uacute: '\u00FA',
			    ucirc: '\u00FB',
			    uuml: '\u00FC',
			    yacute: '\u00FD',
			    thorn: '\u00FE',
			    yuml: '\u00FF',
			    OElig: '\u0152',
			    oelig: '\u0153',
			    Scaron: '\u0160',
			    scaron: '\u0161',
			    Yuml: '\u0178',
			    fnof: '\u0192',
			    circ: '\u02C6',
			    tilde: '\u02DC',
			    Alpha: '\u0391',
			    Beta: '\u0392',
			    Gamma: '\u0393',
			    Delta: '\u0394',
			    Epsilon: '\u0395',
			    Zeta: '\u0396',
			    Eta: '\u0397',
			    Theta: '\u0398',
			    Iota: '\u0399',
			    Kappa: '\u039A',
			    Lambda: '\u039B',
			    Mu: '\u039C',
			    Nu: '\u039D',
			    Xi: '\u039E',
			    Omicron: '\u039F',
			    Pi: '\u03A0',
			    Rho: '\u03A1',
			    Sigma: '\u03A3',
			    Tau: '\u03A4',
			    Upsilon: '\u03A5',
			    Phi: '\u03A6',
			    Chi: '\u03A7',
			    Psi: '\u03A8',
			    Omega: '\u03A9',
			    alpha: '\u03B1',
			    beta: '\u03B2',
			    gamma: '\u03B3',
			    delta: '\u03B4',
			    epsilon: '\u03B5',
			    zeta: '\u03B6',
			    eta: '\u03B7',
			    theta: '\u03B8',
			    iota: '\u03B9',
			    kappa: '\u03BA',
			    lambda: '\u03BB',
			    mu: '\u03BC',
			    nu: '\u03BD',
			    xi: '\u03BE',
			    omicron: '\u03BF',
			    pi: '\u03C0',
			    rho: '\u03C1',
			    sigmaf: '\u03C2',
			    sigma: '\u03C3',
			    tau: '\u03C4',
			    upsilon: '\u03C5',
			    phi: '\u03C6',
			    chi: '\u03C7',
			    psi: '\u03C8',
			    omega: '\u03C9',
			    thetasym: '\u03D1',
			    upsih: '\u03D2',
			    piv: '\u03D6',
			    ensp: '\u2002',
			    emsp: '\u2003',
			    thinsp: '\u2009',
			    zwnj: '\u200C',
			    zwj: '\u200D',
			    lrm: '\u200E',
			    rlm: '\u200F',
			    ndash: '\u2013',
			    mdash: '\u2014',
			    lsquo: '\u2018',
			    rsquo: '\u2019',
			    sbquo: '\u201A',
			    ldquo: '\u201C',
			    rdquo: '\u201D',
			    bdquo: '\u201E',
			    dagger: '\u2020',
			    Dagger: '\u2021',
			    bull: '\u2022',
			    hellip: '\u2026',
			    permil: '\u2030',
			    prime: '\u2032',
			    Prime: '\u2033',
			    lsaquo: '\u2039',
			    rsaquo: '\u203A',
			    oline: '\u203E',
			    frasl: '\u2044',
			    euro: '\u20AC',
			    image: '\u2111',
			    weierp: '\u2118',
			    real: '\u211C',
			    trade: '\u2122',
			    alefsym: '\u2135',
			    larr: '\u2190',
			    uarr: '\u2191',
			    rarr: '\u2192',
			    darr: '\u2193',
			    harr: '\u2194',
			    crarr: '\u21B5',
			    lArr: '\u21D0',
			    uArr: '\u21D1',
			    rArr: '\u21D2',
			    dArr: '\u21D3',
			    hArr: '\u21D4',
			    forall: '\u2200',
			    part: '\u2202',
			    exist: '\u2203',
			    empty: '\u2205',
			    nabla: '\u2207',
			    isin: '\u2208',
			    notin: '\u2209',
			    ni: '\u220B',
			    prod: '\u220F',
			    sum: '\u2211',
			    minus: '\u2212',
			    lowast: '\u2217',
			    radic: '\u221A',
			    prop: '\u221D',
			    infin: '\u221E',
			    ang: '\u2220',
			    and: '\u2227',
			    or: '\u2228',
			    cap: '\u2229',
			    cup: '\u222A',
			    int: '\u222B',
			    there4: '\u2234',
			    sim: '\u223C',
			    cong: '\u2245',
			    asymp: '\u2248',
			    ne: '\u2260',
			    equiv: '\u2261',
			    le: '\u2264',
			    ge: '\u2265',
			    sub: '\u2282',
			    sup: '\u2283',
			    nsub: '\u2284',
			    sube: '\u2286',
			    supe: '\u2287',
			    oplus: '\u2295',
			    otimes: '\u2297',
			    perp: '\u22A5',
			    sdot: '\u22C5',
			    lceil: '\u2308',
			    rceil: '\u2309',
			    lfloor: '\u230A',
			    rfloor: '\u230B',
			    loz: '\u25CA',
			    spades: '\u2660',
			    clubs: '\u2663',
			    hearts: '\u2665',
			    diams: '\u2666',
			    lang: '\u27E8',
			    rang: '\u27E9'
			};
		 },
		 function(module, exports$1, __webpack_require__) {
			Object.defineProperty(exports$1, "__esModule", { value: true });
			var error_handler_1 = __webpack_require__(10);
			var scanner_1 = __webpack_require__(12);
			var token_1 = __webpack_require__(13);
			var Reader = (function () {
			    function Reader() {
			        this.values = [];
			        this.curly = this.paren = -1;
			    }
			    Reader.prototype.beforeFunctionExpression = function (t) {
			        return ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
			            'return', 'case', 'delete', 'throw', 'void',
			            '=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '>>=', '>>>=',
			            '&=', '|=', '^=', ',',
			            '+', '-', '*', '**', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
			            '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
			            '<=', '<', '>', '!=', '!=='].indexOf(t) >= 0;
			    };
			    Reader.prototype.isRegexStart = function () {
			        var previous = this.values[this.values.length - 1];
			        var regex = (previous !== null);
			        switch (previous) {
			            case 'this':
			            case ']':
			                regex = false;
			                break;
			            case ')':
			                var keyword = this.values[this.paren - 1];
			                regex = (keyword === 'if' || keyword === 'while' || keyword === 'for' || keyword === 'with');
			                break;
			            case '}':
			                regex = false;
			                if (this.values[this.curly - 3] === 'function') {
			                    var check = this.values[this.curly - 4];
			                    regex = check ? !this.beforeFunctionExpression(check) : false;
			                }
			                else if (this.values[this.curly - 4] === 'function') {
			                    var check = this.values[this.curly - 5];
			                    regex = check ? !this.beforeFunctionExpression(check) : true;
			                }
			                break;
			        }
			        return regex;
			    };
			    Reader.prototype.push = function (token) {
			        if (token.type === 7  || token.type === 4 ) {
			            if (token.value === '{') {
			                this.curly = this.values.length;
			            }
			            else if (token.value === '(') {
			                this.paren = this.values.length;
			            }
			            this.values.push(token.value);
			        }
			        else {
			            this.values.push(null);
			        }
			    };
			    return Reader;
			}());
			var Tokenizer = (function () {
			    function Tokenizer(code, config) {
			        this.errorHandler = new error_handler_1.ErrorHandler();
			        this.errorHandler.tolerant = config ? (typeof config.tolerant === 'boolean' && config.tolerant) : false;
			        this.scanner = new scanner_1.Scanner(code, this.errorHandler);
			        this.scanner.trackComment = config ? (typeof config.comment === 'boolean' && config.comment) : false;
			        this.trackRange = config ? (typeof config.range === 'boolean' && config.range) : false;
			        this.trackLoc = config ? (typeof config.loc === 'boolean' && config.loc) : false;
			        this.buffer = [];
			        this.reader = new Reader();
			    }
			    Tokenizer.prototype.errors = function () {
			        return this.errorHandler.errors;
			    };
			    Tokenizer.prototype.getNextToken = function () {
			        if (this.buffer.length === 0) {
			            var comments = this.scanner.scanComments();
			            if (this.scanner.trackComment) {
			                for (var i = 0; i < comments.length; ++i) {
			                    var e = comments[i];
			                    var value = this.scanner.source.slice(e.slice[0], e.slice[1]);
			                    var comment = {
			                        type: e.multiLine ? 'BlockComment' : 'LineComment',
			                        value: value
			                    };
			                    if (this.trackRange) {
			                        comment.range = e.range;
			                    }
			                    if (this.trackLoc) {
			                        comment.loc = e.loc;
			                    }
			                    this.buffer.push(comment);
			                }
			            }
			            if (!this.scanner.eof()) {
			                var loc = void 0;
			                if (this.trackLoc) {
			                    loc = {
			                        start: {
			                            line: this.scanner.lineNumber,
			                            column: this.scanner.index - this.scanner.lineStart
			                        },
			                        end: {}
			                    };
			                }
			                var startRegex = (this.scanner.source[this.scanner.index] === '/') && this.reader.isRegexStart();
			                var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex();
			                this.reader.push(token);
			                var entry = {
			                    type: token_1.TokenName[token.type],
			                    value: this.scanner.source.slice(token.start, token.end)
			                };
			                if (this.trackRange) {
			                    entry.range = [token.start, token.end];
			                }
			                if (this.trackLoc) {
			                    loc.end = {
			                        line: this.scanner.lineNumber,
			                        column: this.scanner.index - this.scanner.lineStart
			                    };
			                    entry.loc = loc;
			                }
			                if (token.type === 9 ) {
			                    var pattern = token.pattern;
			                    var flags = token.flags;
			                    entry.regex = { pattern: pattern, flags: flags };
			                }
			                this.buffer.push(entry);
			            }
			        }
			        return this.buffer.shift();
			    };
			    return Tokenizer;
			}());
			exports$1.Tokenizer = Tokenizer;
		 }
		 ])
		});
	} (esprima$2));
	return esprima$2.exports;
}

var main$1 = {};

/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var extendStatics = function(d, b) {
  extendStatics = Object.setPrototypeOf ||
      ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
      function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  return extendStatics(d, b);
};
function __extends(d, b) {
  if (typeof b !== "function" && b !== null)
      throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics(d, b);
  function __() { this.constructor = d; }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign$1 = function() {
  __assign$1 = Object.assign || function __assign(t) {
      for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];
          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
      }
      return t;
  };
  return __assign$1.apply(this, arguments);
};
function __rest(s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
      for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
          if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
              t[p[i]] = s[p[i]];
      }
  return t;
}
function __decorate(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
  return function (target, key) { decorator(target, key, paramIndex); }
}
function __esDecorate$1(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _, done = false;
  for (var i = decorators.length - 1; i >= 0; i--) {
      var context = {};
      for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
      for (var p in contextIn.access) context.access[p] = contextIn.access[p];
      context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
      var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
      if (kind === "accessor") {
          if (result === void 0) continue;
          if (result === null || typeof result !== "object") throw new TypeError("Object expected");
          if (_ = accept(result.get)) descriptor.get = _;
          if (_ = accept(result.set)) descriptor.set = _;
          if (_ = accept(result.init)) initializers.unshift(_);
      }
      else if (_ = accept(result)) {
          if (kind === "field") initializers.unshift(_);
          else descriptor[key] = _;
      }
  }
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
}function __runInitializers$1(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i = 0; i < initializers.length; i++) {
      value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
  }
  return useValue ? value : void 0;
}function __propKey(x) {
  return typeof x === "symbol" ? x : "".concat(x);
}function __setFunctionName$1(f, name, prefix) {
  if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
}function __metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  return new (P || (P = Promise))(function (resolve, reject) {
      function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
      function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
      function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
      step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  function verb(n) { return function (v) { return step([n, v]); }; }
  function step(op) {
      if (f) throw new TypeError("Generator is already executing.");
      while (g && (g = 0, op[0] && (_ = 0)), _) try {
          if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
          if (y = 0, t) op = [op[0] & 2, t.value];
          switch (op[0]) {
              case 0: case 1: t = op; break;
              case 4: _.label++; return { value: op[1], done: false };
              case 5: _.label++; y = op[1]; op = [0]; continue;
              case 7: op = _.ops.pop(); _.trys.pop(); continue;
              default:
                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                  if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                  if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                  if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                  if (t[2]) _.ops.pop();
                  _.trys.pop(); continue;
          }
          op = body.call(thisArg, _);
      } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
      if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  }
}
var __createBinding = Object.create ? (function(o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
  }
  Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  o[k2] = m[k];
});
function __exportStar(m, o) {
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}
function __values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  if (m) return m.call(o);
  if (o && typeof o.length === "number") return {
      next: function () {
          if (o && i >= o.length) o = void 0;
          return { value: o && o[i++], done: !o };
      }
  };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m) return o;
  var i = m.call(o), r, ar = [], e;
  try {
      while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  }
  catch (error) { e = { error: error }; }
  finally {
      try {
          if (r && !r.done && (m = i["return"])) m.call(i);
      }
      finally { if (e) throw e.error; }
  }
  return ar;
}
function __spread() {
  for (var ar = [], i = 0; i < arguments.length; i++)
      ar = ar.concat(__read(arguments[i]));
  return ar;
}
function __spreadArrays() {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  for (var r = Array(s), k = 0, i = 0; i < il; i++)
      for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
          r[k] = a[j];
  return r;
}
function __spreadArray(to, from, pack) {
  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
      if (ar || !(i in from)) {
          if (!ar) ar = Array.prototype.slice.call(from, 0, i);
          ar[i] = from[i];
      }
  }
  return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
  return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
  return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
  function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
  function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
  function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
  function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
  function fulfill(value) { resume("next", value); }
  function reject(value) { resume("throw", value); }
  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
  var i, p;
  return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
  function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
  if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
  return cooked;
}var __setModuleDefault = Object.create ? (function(o, v) {
  Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
  o["default"] = v;
};
var ownKeys = function(o) {
  ownKeys = Object.getOwnPropertyNames || function (o) {
    var ar = [];
    for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
    return ar;
  };
  return ownKeys(o);
};
function __importStar(mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  __setModuleDefault(result, mod);
  return result;
}
function __importDefault(mod) {
  return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
function __classPrivateFieldIn(state, receiver) {
  if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state === "function" ? receiver === state : state.has(receiver);
}
function __addDisposableResource(env, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
    var dispose, inner;
    if (async) {
      if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
    if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
    env.stack.push({ value: value, dispose: dispose, async: async });
  }
  else if (async) {
    env.stack.push({ async: true });
  }
  return value;
}
var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
  var e = new Error(message);
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
function __disposeResources(env) {
  function fail(e) {
    env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
    env.hasError = true;
  }
  var r, s = 0;
  function next() {
    while (r = env.stack.pop()) {
      try {
        if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
        if (r.dispose) {
          var result = r.dispose.call(r.value);
          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
        }
        else s |= 1;
      }
      catch (e) {
        fail(e);
      }
    }
    if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
    if (env.hasError) throw env.error;
  }
  return next();
}
function __rewriteRelativeImportExtension(path, preserveJsx) {
  if (typeof path === "string" && /^\.\.?\//.test(path)) {
      return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
          return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
      });
  }
  return path;
}
var tslib_es6 = {
  __extends,
  __assign: __assign$1,
  __rest,
  __decorate,
  __param,
  __esDecorate: __esDecorate$1,
  __runInitializers: __runInitializers$1,
  __propKey,
  __setFunctionName: __setFunctionName$1,
  __metadata,
  __awaiter,
  __generator,
  __createBinding,
  __exportStar,
  __values,
  __read,
  __spread,
  __spreadArrays,
  __spreadArray,
  __await,
  __asyncGenerator,
  __asyncDelegator,
  __asyncValues,
  __makeTemplateObject,
  __importStar,
  __importDefault,
  __classPrivateFieldGet,
  __classPrivateFieldSet,
  __classPrivateFieldIn,
  __addDisposableResource,
  __disposeResources,
  __rewriteRelativeImportExtension,
};

var tslib_es6$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	__addDisposableResource: __addDisposableResource,
	get __assign () { return __assign$1; },
	__asyncDelegator: __asyncDelegator,
	__asyncGenerator: __asyncGenerator,
	__asyncValues: __asyncValues,
	__await: __await,
	__awaiter: __awaiter,
	__classPrivateFieldGet: __classPrivateFieldGet,
	__classPrivateFieldIn: __classPrivateFieldIn,
	__classPrivateFieldSet: __classPrivateFieldSet,
	__createBinding: __createBinding,
	__decorate: __decorate,
	__disposeResources: __disposeResources,
	__esDecorate: __esDecorate$1,
	__exportStar: __exportStar,
	__extends: __extends,
	__generator: __generator,
	__importDefault: __importDefault,
	__importStar: __importStar,
	__makeTemplateObject: __makeTemplateObject,
	__metadata: __metadata,
	__param: __param,
	__propKey: __propKey,
	__read: __read,
	__rest: __rest,
	__rewriteRelativeImportExtension: __rewriteRelativeImportExtension,
	__runInitializers: __runInitializers$1,
	__setFunctionName: __setFunctionName$1,
	__spread: __spread,
	__spreadArray: __spreadArray,
	__spreadArrays: __spreadArrays,
	__values: __values,
	default: tslib_es6
});

var require$$0 = /*@__PURE__*/getAugmentedNamespace(tslib_es6$1);

var fork = {exports: {}};

var types$5 = {};

var hasRequiredTypes$1;

function requireTypes$1 () {
	if (hasRequiredTypes$1) return types$5;
	hasRequiredTypes$1 = 1;
	Object.defineProperty(types$5, "__esModule", { value: true });
	types$5.Def = void 0;
	var tslib_1 = require$$0;
	var Op = Object.prototype;
	var objToStr = Op.toString;
	var hasOwn = Op.hasOwnProperty;
	var BaseType =  (function () {
	    function BaseType() {
	    }
	    BaseType.prototype.assert = function (value, deep) {
	        if (!this.check(value, deep)) {
	            var str = shallowStringify(value);
	            throw new Error(str + " does not match type " + this);
	        }
	        return true;
	    };
	    BaseType.prototype.arrayOf = function () {
	        var elemType = this;
	        return new ArrayType(elemType);
	    };
	    return BaseType;
	}());
	var ArrayType =  (function (_super) {
	    tslib_1.__extends(ArrayType, _super);
	    function ArrayType(elemType) {
	        var _this = _super.call(this) || this;
	        _this.elemType = elemType;
	        _this.kind = "ArrayType";
	        return _this;
	    }
	    ArrayType.prototype.toString = function () {
	        return "[" + this.elemType + "]";
	    };
	    ArrayType.prototype.check = function (value, deep) {
	        var _this = this;
	        return Array.isArray(value) && value.every(function (elem) { return _this.elemType.check(elem, deep); });
	    };
	    return ArrayType;
	}(BaseType));
	var IdentityType =  (function (_super) {
	    tslib_1.__extends(IdentityType, _super);
	    function IdentityType(value) {
	        var _this = _super.call(this) || this;
	        _this.value = value;
	        _this.kind = "IdentityType";
	        return _this;
	    }
	    IdentityType.prototype.toString = function () {
	        return String(this.value);
	    };
	    IdentityType.prototype.check = function (value, deep) {
	        var result = value === this.value;
	        if (!result && typeof deep === "function") {
	            deep(this, value);
	        }
	        return result;
	    };
	    return IdentityType;
	}(BaseType));
	var ObjectType =  (function (_super) {
	    tslib_1.__extends(ObjectType, _super);
	    function ObjectType(fields) {
	        var _this = _super.call(this) || this;
	        _this.fields = fields;
	        _this.kind = "ObjectType";
	        return _this;
	    }
	    ObjectType.prototype.toString = function () {
	        return "{ " + this.fields.join(", ") + " }";
	    };
	    ObjectType.prototype.check = function (value, deep) {
	        return (objToStr.call(value) === objToStr.call({}) &&
	            this.fields.every(function (field) {
	                return field.type.check(value[field.name], deep);
	            }));
	    };
	    return ObjectType;
	}(BaseType));
	var OrType =  (function (_super) {
	    tslib_1.__extends(OrType, _super);
	    function OrType(types) {
	        var _this = _super.call(this) || this;
	        _this.types = types;
	        _this.kind = "OrType";
	        return _this;
	    }
	    OrType.prototype.toString = function () {
	        return this.types.join(" | ");
	    };
	    OrType.prototype.check = function (value, deep) {
	        return this.types.some(function (type) {
	            return type.check(value, deep);
	        });
	    };
	    return OrType;
	}(BaseType));
	var PredicateType =  (function (_super) {
	    tslib_1.__extends(PredicateType, _super);
	    function PredicateType(name, predicate) {
	        var _this = _super.call(this) || this;
	        _this.name = name;
	        _this.predicate = predicate;
	        _this.kind = "PredicateType";
	        return _this;
	    }
	    PredicateType.prototype.toString = function () {
	        return this.name;
	    };
	    PredicateType.prototype.check = function (value, deep) {
	        var result = this.predicate(value, deep);
	        if (!result && typeof deep === "function") {
	            deep(this, value);
	        }
	        return result;
	    };
	    return PredicateType;
	}(BaseType));
	var Def =  (function () {
	    function Def(type, typeName) {
	        this.type = type;
	        this.typeName = typeName;
	        this.baseNames = [];
	        this.ownFields = Object.create(null);
	        this.allSupertypes = Object.create(null);
	        this.supertypeList = [];
	        this.allFields = Object.create(null);
	        this.fieldNames = [];
	        this.finalized = false;
	        this.buildable = false;
	        this.buildParams = [];
	    }
	    Def.prototype.isSupertypeOf = function (that) {
	        if (that instanceof Def) {
	            if (this.finalized !== true ||
	                that.finalized !== true) {
	                throw new Error("");
	            }
	            return hasOwn.call(that.allSupertypes, this.typeName);
	        }
	        else {
	            throw new Error(that + " is not a Def");
	        }
	    };
	    Def.prototype.checkAllFields = function (value, deep) {
	        var allFields = this.allFields;
	        if (this.finalized !== true) {
	            throw new Error("" + this.typeName);
	        }
	        function checkFieldByName(name) {
	            var field = allFields[name];
	            var type = field.type;
	            var child = field.getValue(value);
	            return type.check(child, deep);
	        }
	        return value !== null &&
	            typeof value === "object" &&
	            Object.keys(allFields).every(checkFieldByName);
	    };
	    Def.prototype.bases = function () {
	        var supertypeNames = [];
	        for (var _i = 0; _i < arguments.length; _i++) {
	            supertypeNames[_i] = arguments[_i];
	        }
	        var bases = this.baseNames;
	        if (this.finalized) {
	            if (supertypeNames.length !== bases.length) {
	                throw new Error("");
	            }
	            for (var i = 0; i < supertypeNames.length; i++) {
	                if (supertypeNames[i] !== bases[i]) {
	                    throw new Error("");
	                }
	            }
	            return this;
	        }
	        supertypeNames.forEach(function (baseName) {
	            if (bases.indexOf(baseName) < 0) {
	                bases.push(baseName);
	            }
	        });
	        return this;
	    };
	    return Def;
	}());
	types$5.Def = Def;
	var Field =  (function () {
	    function Field(name, type, defaultFn, hidden) {
	        this.name = name;
	        this.type = type;
	        this.defaultFn = defaultFn;
	        this.hidden = !!hidden;
	    }
	    Field.prototype.toString = function () {
	        return JSON.stringify(this.name) + ": " + this.type;
	    };
	    Field.prototype.getValue = function (obj) {
	        var value = obj[this.name];
	        if (typeof value !== "undefined") {
	            return value;
	        }
	        if (typeof this.defaultFn === "function") {
	            value = this.defaultFn.call(obj);
	        }
	        return value;
	    };
	    return Field;
	}());
	function shallowStringify(value) {
	    if (Array.isArray(value)) {
	        return "[" + value.map(shallowStringify).join(", ") + "]";
	    }
	    if (value && typeof value === "object") {
	        return "{ " + Object.keys(value).map(function (key) {
	            return key + ": " + value[key];
	        }).join(", ") + " }";
	    }
	    return JSON.stringify(value);
	}
	function typesPlugin(_fork) {
	    var Type = {
	        or: function () {
	            var types = [];
	            for (var _i = 0; _i < arguments.length; _i++) {
	                types[_i] = arguments[_i];
	            }
	            return new OrType(types.map(function (type) { return Type.from(type); }));
	        },
	        from: function (value, name) {
	            if (value instanceof ArrayType ||
	                value instanceof IdentityType ||
	                value instanceof ObjectType ||
	                value instanceof OrType ||
	                value instanceof PredicateType) {
	                return value;
	            }
	            if (value instanceof Def) {
	                return value.type;
	            }
	            if (isArray.check(value)) {
	                if (value.length !== 1) {
	                    throw new Error("only one element type is permitted for typed arrays");
	                }
	                return new ArrayType(Type.from(value[0]));
	            }
	            if (isObject.check(value)) {
	                return new ObjectType(Object.keys(value).map(function (name) {
	                    return new Field(name, Type.from(value[name], name));
	                }));
	            }
	            if (typeof value === "function") {
	                var bicfIndex = builtInCtorFns.indexOf(value);
	                if (bicfIndex >= 0) {
	                    return builtInCtorTypes[bicfIndex];
	                }
	                if (typeof name !== "string") {
	                    throw new Error("missing name");
	                }
	                return new PredicateType(name, value);
	            }
	            return new IdentityType(value);
	        },
	        def: function (typeName) {
	            return hasOwn.call(defCache, typeName)
	                ? defCache[typeName]
	                : defCache[typeName] = new DefImpl(typeName);
	        },
	        hasDef: function (typeName) {
	            return hasOwn.call(defCache, typeName);
	        }
	    };
	    var builtInCtorFns = [];
	    var builtInCtorTypes = [];
	    function defBuiltInType(name, example) {
	        var objStr = objToStr.call(example);
	        var type = new PredicateType(name, function (value) { return objToStr.call(value) === objStr; });
	        if (example && typeof example.constructor === "function") {
	            builtInCtorFns.push(example.constructor);
	            builtInCtorTypes.push(type);
	        }
	        return type;
	    }
	    var isString = defBuiltInType("string", "truthy");
	    var isFunction = defBuiltInType("function", function () { });
	    var isArray = defBuiltInType("array", []);
	    var isObject = defBuiltInType("object", {});
	    var isRegExp = defBuiltInType("RegExp", /./);
	    var isDate = defBuiltInType("Date", new Date());
	    var isNumber = defBuiltInType("number", 3);
	    var isBoolean = defBuiltInType("boolean", true);
	    var isNull = defBuiltInType("null", null);
	    var isUndefined = defBuiltInType("undefined", undefined);
	    var builtInTypes = {
	        string: isString,
	        function: isFunction,
	        array: isArray,
	        object: isObject,
	        RegExp: isRegExp,
	        Date: isDate,
	        number: isNumber,
	        boolean: isBoolean,
	        null: isNull,
	        undefined: isUndefined,
	    };
	    var defCache = Object.create(null);
	    function defFromValue(value) {
	        if (value && typeof value === "object") {
	            var type = value.type;
	            if (typeof type === "string" &&
	                hasOwn.call(defCache, type)) {
	                var d = defCache[type];
	                if (d.finalized) {
	                    return d;
	                }
	            }
	        }
	        return null;
	    }
	    var DefImpl =  (function (_super) {
	        tslib_1.__extends(DefImpl, _super);
	        function DefImpl(typeName) {
	            var _this = _super.call(this, new PredicateType(typeName, function (value, deep) { return _this.check(value, deep); }), typeName) || this;
	            return _this;
	        }
	        DefImpl.prototype.check = function (value, deep) {
	            if (this.finalized !== true) {
	                throw new Error("prematurely checking unfinalized type " + this.typeName);
	            }
	            if (value === null || typeof value !== "object") {
	                return false;
	            }
	            var vDef = defFromValue(value);
	            if (!vDef) {
	                if (this.typeName === "SourceLocation" ||
	                    this.typeName === "Position") {
	                    return this.checkAllFields(value, deep);
	                }
	                return false;
	            }
	            if (deep && vDef === this) {
	                return this.checkAllFields(value, deep);
	            }
	            if (!this.isSupertypeOf(vDef)) {
	                return false;
	            }
	            if (!deep) {
	                return true;
	            }
	            return vDef.checkAllFields(value, deep)
	                && this.checkAllFields(value, false);
	        };
	        DefImpl.prototype.build = function () {
	            var _this = this;
	            var buildParams = [];
	            for (var _i = 0; _i < arguments.length; _i++) {
	                buildParams[_i] = arguments[_i];
	            }
	            this.buildParams = buildParams;
	            if (this.buildable) {
	                return this;
	            }
	            this.field("type", String, function () { return _this.typeName; });
	            this.buildable = true;
	            var addParam = function (built, param, arg, isArgAvailable) {
	                if (hasOwn.call(built, param))
	                    return;
	                var all = _this.allFields;
	                if (!hasOwn.call(all, param)) {
	                    throw new Error("" + param);
	                }
	                var field = all[param];
	                var type = field.type;
	                var value;
	                if (isArgAvailable) {
	                    value = arg;
	                }
	                else if (field.defaultFn) {
	                    value = field.defaultFn.call(built);
	                }
	                else {
	                    var message = "no value or default function given for field " +
	                        JSON.stringify(param) + " of " + _this.typeName + "(" +
	                        _this.buildParams.map(function (name) {
	                            return all[name];
	                        }).join(", ") + ")";
	                    throw new Error(message);
	                }
	                if (!type.check(value)) {
	                    throw new Error(shallowStringify(value) +
	                        " does not match field " + field +
	                        " of type " + _this.typeName);
	                }
	                built[param] = value;
	            };
	            var builder = function () {
	                var args = [];
	                for (var _i = 0; _i < arguments.length; _i++) {
	                    args[_i] = arguments[_i];
	                }
	                var argc = args.length;
	                if (!_this.finalized) {
	                    throw new Error("attempting to instantiate unfinalized type " +
	                        _this.typeName);
	                }
	                var built = Object.create(nodePrototype);
	                _this.buildParams.forEach(function (param, i) {
	                    if (i < argc) {
	                        addParam(built, param, args[i], true);
	                    }
	                    else {
	                        addParam(built, param, null, false);
	                    }
	                });
	                Object.keys(_this.allFields).forEach(function (param) {
	                    addParam(built, param, null, false);
	                });
	                if (built.type !== _this.typeName) {
	                    throw new Error("");
	                }
	                return built;
	            };
	            builder.from = function (obj) {
	                if (!_this.finalized) {
	                    throw new Error("attempting to instantiate unfinalized type " +
	                        _this.typeName);
	                }
	                var built = Object.create(nodePrototype);
	                Object.keys(_this.allFields).forEach(function (param) {
	                    if (hasOwn.call(obj, param)) {
	                        addParam(built, param, obj[param], true);
	                    }
	                    else {
	                        addParam(built, param, null, false);
	                    }
	                });
	                if (built.type !== _this.typeName) {
	                    throw new Error("");
	                }
	                return built;
	            };
	            Object.defineProperty(builders, getBuilderName(this.typeName), {
	                enumerable: true,
	                value: builder
	            });
	            return this;
	        };
	        DefImpl.prototype.field = function (name, type, defaultFn, hidden) {
	            if (this.finalized) {
	                console.error("Ignoring attempt to redefine field " +
	                    JSON.stringify(name) + " of finalized type " +
	                    JSON.stringify(this.typeName));
	                return this;
	            }
	            this.ownFields[name] = new Field(name, Type.from(type), defaultFn, hidden);
	            return this;
	        };
	        DefImpl.prototype.finalize = function () {
	            var _this = this;
	            if (!this.finalized) {
	                var allFields = this.allFields;
	                var allSupertypes = this.allSupertypes;
	                this.baseNames.forEach(function (name) {
	                    var def = defCache[name];
	                    if (def instanceof Def) {
	                        def.finalize();
	                        extend(allFields, def.allFields);
	                        extend(allSupertypes, def.allSupertypes);
	                    }
	                    else {
	                        var message = "unknown supertype name " +
	                            JSON.stringify(name) +
	                            " for subtype " +
	                            JSON.stringify(_this.typeName);
	                        throw new Error(message);
	                    }
	                });
	                extend(allFields, this.ownFields);
	                allSupertypes[this.typeName] = this;
	                this.fieldNames.length = 0;
	                for (var fieldName in allFields) {
	                    if (hasOwn.call(allFields, fieldName) &&
	                        !allFields[fieldName].hidden) {
	                        this.fieldNames.push(fieldName);
	                    }
	                }
	                Object.defineProperty(namedTypes, this.typeName, {
	                    enumerable: true,
	                    value: this.type
	                });
	                this.finalized = true;
	                populateSupertypeList(this.typeName, this.supertypeList);
	                if (this.buildable &&
	                    this.supertypeList.lastIndexOf("Expression") >= 0) {
	                    wrapExpressionBuilderWithStatement(this.typeName);
	                }
	            }
	        };
	        return DefImpl;
	    }(Def));
	    function getSupertypeNames(typeName) {
	        if (!hasOwn.call(defCache, typeName)) {
	            throw new Error("");
	        }
	        var d = defCache[typeName];
	        if (d.finalized !== true) {
	            throw new Error("");
	        }
	        return d.supertypeList.slice(1);
	    }
	    function computeSupertypeLookupTable(candidates) {
	        var table = {};
	        var typeNames = Object.keys(defCache);
	        var typeNameCount = typeNames.length;
	        for (var i = 0; i < typeNameCount; ++i) {
	            var typeName = typeNames[i];
	            var d = defCache[typeName];
	            if (d.finalized !== true) {
	                throw new Error("" + typeName);
	            }
	            for (var j = 0; j < d.supertypeList.length; ++j) {
	                var superTypeName = d.supertypeList[j];
	                if (hasOwn.call(candidates, superTypeName)) {
	                    table[typeName] = superTypeName;
	                    break;
	                }
	            }
	        }
	        return table;
	    }
	    var builders = Object.create(null);
	    var nodePrototype = {};
	    function defineMethod(name, func) {
	        var old = nodePrototype[name];
	        if (isUndefined.check(func)) {
	            delete nodePrototype[name];
	        }
	        else {
	            isFunction.assert(func);
	            Object.defineProperty(nodePrototype, name, {
	                enumerable: true,
	                configurable: true,
	                value: func
	            });
	        }
	        return old;
	    }
	    function getBuilderName(typeName) {
	        return typeName.replace(/^[A-Z]+/, function (upperCasePrefix) {
	            var len = upperCasePrefix.length;
	            switch (len) {
	                case 0: return "";
	                case 1: return upperCasePrefix.toLowerCase();
	                default:
	                    return upperCasePrefix.slice(0, len - 1).toLowerCase() +
	                        upperCasePrefix.charAt(len - 1);
	            }
	        });
	    }
	    function getStatementBuilderName(typeName) {
	        typeName = getBuilderName(typeName);
	        return typeName.replace(/(Expression)?$/, "Statement");
	    }
	    var namedTypes = {};
	    function getFieldNames(object) {
	        var d = defFromValue(object);
	        if (d) {
	            return d.fieldNames.slice(0);
	        }
	        if ("type" in object) {
	            throw new Error("did not recognize object of type " +
	                JSON.stringify(object.type));
	        }
	        return Object.keys(object);
	    }
	    function getFieldValue(object, fieldName) {
	        var d = defFromValue(object);
	        if (d) {
	            var field = d.allFields[fieldName];
	            if (field) {
	                return field.getValue(object);
	            }
	        }
	        return object && object[fieldName];
	    }
	    function eachField(object, callback, context) {
	        getFieldNames(object).forEach(function (name) {
	            callback.call(this, name, getFieldValue(object, name));
	        }, context);
	    }
	    function someField(object, callback, context) {
	        return getFieldNames(object).some(function (name) {
	            return callback.call(this, name, getFieldValue(object, name));
	        }, context);
	    }
	    function wrapExpressionBuilderWithStatement(typeName) {
	        var wrapperName = getStatementBuilderName(typeName);
	        if (builders[wrapperName])
	            return;
	        var wrapped = builders[getBuilderName(typeName)];
	        if (!wrapped)
	            return;
	        var builder = function () {
	            var args = [];
	            for (var _i = 0; _i < arguments.length; _i++) {
	                args[_i] = arguments[_i];
	            }
	            return builders.expressionStatement(wrapped.apply(builders, args));
	        };
	        builder.from = function () {
	            var args = [];
	            for (var _i = 0; _i < arguments.length; _i++) {
	                args[_i] = arguments[_i];
	            }
	            return builders.expressionStatement(wrapped.from.apply(builders, args));
	        };
	        builders[wrapperName] = builder;
	    }
	    function populateSupertypeList(typeName, list) {
	        list.length = 0;
	        list.push(typeName);
	        var lastSeen = Object.create(null);
	        for (var pos = 0; pos < list.length; ++pos) {
	            typeName = list[pos];
	            var d = defCache[typeName];
	            if (d.finalized !== true) {
	                throw new Error("");
	            }
	            if (hasOwn.call(lastSeen, typeName)) {
	                delete list[lastSeen[typeName]];
	            }
	            lastSeen[typeName] = pos;
	            list.push.apply(list, d.baseNames);
	        }
	        for (var to = 0, from = to, len = list.length; from < len; ++from) {
	            if (hasOwn.call(list, from)) {
	                list[to++] = list[from];
	            }
	        }
	        list.length = to;
	    }
	    function extend(into, from) {
	        Object.keys(from).forEach(function (name) {
	            into[name] = from[name];
	        });
	        return into;
	    }
	    function finalize() {
	        Object.keys(defCache).forEach(function (name) {
	            defCache[name].finalize();
	        });
	    }
	    return {
	        Type: Type,
	        builtInTypes: builtInTypes,
	        getSupertypeNames: getSupertypeNames,
	        computeSupertypeLookupTable: computeSupertypeLookupTable,
	        builders: builders,
	        defineMethod: defineMethod,
	        getBuilderName: getBuilderName,
	        getStatementBuilderName: getStatementBuilderName,
	        namedTypes: namedTypes,
	        getFieldNames: getFieldNames,
	        getFieldValue: getFieldValue,
	        eachField: eachField,
	        someField: someField,
	        finalize: finalize,
	    };
	}
	types$5.default = typesPlugin;
	return types$5;
}

var pathVisitor = {exports: {}};

var nodePath = {exports: {}};

var path = {exports: {}};

var hasRequiredPath;

function requirePath () {
	if (hasRequiredPath) return path.exports;
	hasRequiredPath = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var Op = Object.prototype;
		var hasOwn = Op.hasOwnProperty;
		function pathPlugin(fork) {
		    var types = fork.use(types_1.default);
		    var isArray = types.builtInTypes.array;
		    var isNumber = types.builtInTypes.number;
		    var Path = function Path(value, parentPath, name) {
		        if (!(this instanceof Path)) {
		            throw new Error("Path constructor cannot be invoked without 'new'");
		        }
		        if (parentPath) {
		            if (!(parentPath instanceof Path)) {
		                throw new Error("");
		            }
		        }
		        else {
		            parentPath = null;
		            name = null;
		        }
		        this.value = value;
		        this.parentPath = parentPath;
		        this.name = name;
		        this.__childCache = null;
		    };
		    var Pp = Path.prototype;
		    function getChildCache(path) {
		        return path.__childCache || (path.__childCache = Object.create(null));
		    }
		    function getChildPath(path, name) {
		        var cache = getChildCache(path);
		        var actualChildValue = path.getValueProperty(name);
		        var childPath = cache[name];
		        if (!hasOwn.call(cache, name) ||
		            childPath.value !== actualChildValue) {
		            childPath = cache[name] = new path.constructor(actualChildValue, path, name);
		        }
		        return childPath;
		    }
		    Pp.getValueProperty = function getValueProperty(name) {
		        return this.value[name];
		    };
		    Pp.get = function get() {
		        var names = [];
		        for (var _i = 0; _i < arguments.length; _i++) {
		            names[_i] = arguments[_i];
		        }
		        var path = this;
		        var count = names.length;
		        for (var i = 0; i < count; ++i) {
		            path = getChildPath(path, names[i]);
		        }
		        return path;
		    };
		    Pp.each = function each(callback, context) {
		        var childPaths = [];
		        var len = this.value.length;
		        var i = 0;
		        for (var i = 0; i < len; ++i) {
		            if (hasOwn.call(this.value, i)) {
		                childPaths[i] = this.get(i);
		            }
		        }
		        context = context || this;
		        for (i = 0; i < len; ++i) {
		            if (hasOwn.call(childPaths, i)) {
		                callback.call(context, childPaths[i]);
		            }
		        }
		    };
		    Pp.map = function map(callback, context) {
		        var result = [];
		        this.each(function (childPath) {
		            result.push(callback.call(this, childPath));
		        }, context);
		        return result;
		    };
		    Pp.filter = function filter(callback, context) {
		        var result = [];
		        this.each(function (childPath) {
		            if (callback.call(this, childPath)) {
		                result.push(childPath);
		            }
		        }, context);
		        return result;
		    };
		    function emptyMoves() { }
		    function getMoves(path, offset, start, end) {
		        isArray.assert(path.value);
		        if (offset === 0) {
		            return emptyMoves;
		        }
		        var length = path.value.length;
		        if (length < 1) {
		            return emptyMoves;
		        }
		        var argc = arguments.length;
		        if (argc === 2) {
		            start = 0;
		            end = length;
		        }
		        else if (argc === 3) {
		            start = Math.max(start, 0);
		            end = length;
		        }
		        else {
		            start = Math.max(start, 0);
		            end = Math.min(end, length);
		        }
		        isNumber.assert(start);
		        isNumber.assert(end);
		        var moves = Object.create(null);
		        var cache = getChildCache(path);
		        for (var i = start; i < end; ++i) {
		            if (hasOwn.call(path.value, i)) {
		                var childPath = path.get(i);
		                if (childPath.name !== i) {
		                    throw new Error("");
		                }
		                var newIndex = i + offset;
		                childPath.name = newIndex;
		                moves[newIndex] = childPath;
		                delete cache[i];
		            }
		        }
		        delete cache.length;
		        return function () {
		            for (var newIndex in moves) {
		                var childPath = moves[newIndex];
		                if (childPath.name !== +newIndex) {
		                    throw new Error("");
		                }
		                cache[newIndex] = childPath;
		                path.value[newIndex] = childPath.value;
		            }
		        };
		    }
		    Pp.shift = function shift() {
		        var move = getMoves(this, -1);
		        var result = this.value.shift();
		        move();
		        return result;
		    };
		    Pp.unshift = function unshift() {
		        var args = [];
		        for (var _i = 0; _i < arguments.length; _i++) {
		            args[_i] = arguments[_i];
		        }
		        var move = getMoves(this, args.length);
		        var result = this.value.unshift.apply(this.value, args);
		        move();
		        return result;
		    };
		    Pp.push = function push() {
		        var args = [];
		        for (var _i = 0; _i < arguments.length; _i++) {
		            args[_i] = arguments[_i];
		        }
		        isArray.assert(this.value);
		        delete getChildCache(this).length;
		        return this.value.push.apply(this.value, args);
		    };
		    Pp.pop = function pop() {
		        isArray.assert(this.value);
		        var cache = getChildCache(this);
		        delete cache[this.value.length - 1];
		        delete cache.length;
		        return this.value.pop();
		    };
		    Pp.insertAt = function insertAt(index) {
		        var argc = arguments.length;
		        var move = getMoves(this, argc - 1, index);
		        if (move === emptyMoves && argc <= 1) {
		            return this;
		        }
		        index = Math.max(index, 0);
		        for (var i = 1; i < argc; ++i) {
		            this.value[index + i - 1] = arguments[i];
		        }
		        move();
		        return this;
		    };
		    Pp.insertBefore = function insertBefore() {
		        var args = [];
		        for (var _i = 0; _i < arguments.length; _i++) {
		            args[_i] = arguments[_i];
		        }
		        var pp = this.parentPath;
		        var argc = args.length;
		        var insertAtArgs = [this.name];
		        for (var i = 0; i < argc; ++i) {
		            insertAtArgs.push(args[i]);
		        }
		        return pp.insertAt.apply(pp, insertAtArgs);
		    };
		    Pp.insertAfter = function insertAfter() {
		        var args = [];
		        for (var _i = 0; _i < arguments.length; _i++) {
		            args[_i] = arguments[_i];
		        }
		        var pp = this.parentPath;
		        var argc = args.length;
		        var insertAtArgs = [this.name + 1];
		        for (var i = 0; i < argc; ++i) {
		            insertAtArgs.push(args[i]);
		        }
		        return pp.insertAt.apply(pp, insertAtArgs);
		    };
		    function repairRelationshipWithParent(path) {
		        if (!(path instanceof Path)) {
		            throw new Error("");
		        }
		        var pp = path.parentPath;
		        if (!pp) {
		            return path;
		        }
		        var parentValue = pp.value;
		        var parentCache = getChildCache(pp);
		        if (parentValue[path.name] === path.value) {
		            parentCache[path.name] = path;
		        }
		        else if (isArray.check(parentValue)) {
		            var i = parentValue.indexOf(path.value);
		            if (i >= 0) {
		                parentCache[path.name = i] = path;
		            }
		        }
		        else {
		            parentValue[path.name] = path.value;
		            parentCache[path.name] = path;
		        }
		        if (parentValue[path.name] !== path.value) {
		            throw new Error("");
		        }
		        if (path.parentPath.get(path.name) !== path) {
		            throw new Error("");
		        }
		        return path;
		    }
		    Pp.replace = function replace(replacement) {
		        var results = [];
		        var parentValue = this.parentPath.value;
		        var parentCache = getChildCache(this.parentPath);
		        var count = arguments.length;
		        repairRelationshipWithParent(this);
		        if (isArray.check(parentValue)) {
		            var originalLength = parentValue.length;
		            var move = getMoves(this.parentPath, count - 1, this.name + 1);
		            var spliceArgs = [this.name, 1];
		            for (var i = 0; i < count; ++i) {
		                spliceArgs.push(arguments[i]);
		            }
		            var splicedOut = parentValue.splice.apply(parentValue, spliceArgs);
		            if (splicedOut[0] !== this.value) {
		                throw new Error("");
		            }
		            if (parentValue.length !== (originalLength - 1 + count)) {
		                throw new Error("");
		            }
		            move();
		            if (count === 0) {
		                delete this.value;
		                delete parentCache[this.name];
		                this.__childCache = null;
		            }
		            else {
		                if (parentValue[this.name] !== replacement) {
		                    throw new Error("");
		                }
		                if (this.value !== replacement) {
		                    this.value = replacement;
		                    this.__childCache = null;
		                }
		                for (i = 0; i < count; ++i) {
		                    results.push(this.parentPath.get(this.name + i));
		                }
		                if (results[0] !== this) {
		                    throw new Error("");
		                }
		            }
		        }
		        else if (count === 1) {
		            if (this.value !== replacement) {
		                this.__childCache = null;
		            }
		            this.value = parentValue[this.name] = replacement;
		            results.push(this);
		        }
		        else if (count === 0) {
		            delete parentValue[this.name];
		            delete this.value;
		            this.__childCache = null;
		        }
		        else {
		            throw new Error("Could not replace path");
		        }
		        return results;
		    };
		    return Path;
		}
		exports$1.default = pathPlugin;
		module.exports = exports$1["default"]; 
	} (path, path.exports));
	return path.exports;
}

var scope = {exports: {}};

var hasRequiredScope;

function requireScope () {
	if (hasRequiredScope) return scope.exports;
	hasRequiredScope = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var hasOwn = Object.prototype.hasOwnProperty;
		function scopePlugin(fork) {
		    var types = fork.use(types_1.default);
		    var Type = types.Type;
		    var namedTypes = types.namedTypes;
		    var Node = namedTypes.Node;
		    var Expression = namedTypes.Expression;
		    var isArray = types.builtInTypes.array;
		    var b = types.builders;
		    var Scope = function Scope(path, parentScope) {
		        if (!(this instanceof Scope)) {
		            throw new Error("Scope constructor cannot be invoked without 'new'");
		        }
		        ScopeType.assert(path.value);
		        var depth;
		        if (parentScope) {
		            if (!(parentScope instanceof Scope)) {
		                throw new Error("");
		            }
		            depth = parentScope.depth + 1;
		        }
		        else {
		            parentScope = null;
		            depth = 0;
		        }
		        Object.defineProperties(this, {
		            path: { value: path },
		            node: { value: path.value },
		            isGlobal: { value: !parentScope, enumerable: true },
		            depth: { value: depth },
		            parent: { value: parentScope },
		            bindings: { value: {} },
		            types: { value: {} },
		        });
		    };
		    var scopeTypes = [
		        namedTypes.Program,
		        namedTypes.Function,
		        namedTypes.CatchClause
		    ];
		    var ScopeType = Type.or.apply(Type, scopeTypes);
		    Scope.isEstablishedBy = function (node) {
		        return ScopeType.check(node);
		    };
		    var Sp = Scope.prototype;
		    Sp.didScan = false;
		    Sp.declares = function (name) {
		        this.scan();
		        return hasOwn.call(this.bindings, name);
		    };
		    Sp.declaresType = function (name) {
		        this.scan();
		        return hasOwn.call(this.types, name);
		    };
		    Sp.declareTemporary = function (prefix) {
		        if (prefix) {
		            if (!/^[a-z$_]/i.test(prefix)) {
		                throw new Error("");
		            }
		        }
		        else {
		            prefix = "t$";
		        }
		        prefix += this.depth.toString(36) + "$";
		        this.scan();
		        var index = 0;
		        while (this.declares(prefix + index)) {
		            ++index;
		        }
		        var name = prefix + index;
		        return this.bindings[name] = types.builders.identifier(name);
		    };
		    Sp.injectTemporary = function (identifier, init) {
		        identifier || (identifier = this.declareTemporary());
		        var bodyPath = this.path.get("body");
		        if (namedTypes.BlockStatement.check(bodyPath.value)) {
		            bodyPath = bodyPath.get("body");
		        }
		        bodyPath.unshift(b.variableDeclaration("var", [b.variableDeclarator(identifier, init || null)]));
		        return identifier;
		    };
		    Sp.scan = function (force) {
		        if (force || !this.didScan) {
		            for (var name in this.bindings) {
		                delete this.bindings[name];
		            }
		            scanScope(this.path, this.bindings, this.types);
		            this.didScan = true;
		        }
		    };
		    Sp.getBindings = function () {
		        this.scan();
		        return this.bindings;
		    };
		    Sp.getTypes = function () {
		        this.scan();
		        return this.types;
		    };
		    function scanScope(path, bindings, scopeTypes) {
		        var node = path.value;
		        ScopeType.assert(node);
		        if (namedTypes.CatchClause.check(node)) {
		            var param = path.get("param");
		            if (param.value) {
		                addPattern(param, bindings);
		            }
		        }
		        else {
		            recursiveScanScope(path, bindings, scopeTypes);
		        }
		    }
		    function recursiveScanScope(path, bindings, scopeTypes) {
		        var node = path.value;
		        if (path.parent &&
		            namedTypes.FunctionExpression.check(path.parent.node) &&
		            path.parent.node.id) {
		            addPattern(path.parent.get("id"), bindings);
		        }
		        if (!node) ;
		        else if (isArray.check(node)) {
		            path.each(function (childPath) {
		                recursiveScanChild(childPath, bindings, scopeTypes);
		            });
		        }
		        else if (namedTypes.Function.check(node)) {
		            path.get("params").each(function (paramPath) {
		                addPattern(paramPath, bindings);
		            });
		            recursiveScanChild(path.get("body"), bindings, scopeTypes);
		        }
		        else if ((namedTypes.TypeAlias && namedTypes.TypeAlias.check(node)) ||
		            (namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node)) ||
		            (namedTypes.TSTypeAliasDeclaration && namedTypes.TSTypeAliasDeclaration.check(node)) ||
		            (namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node))) {
		            addTypePattern(path.get("id"), scopeTypes);
		        }
		        else if (namedTypes.VariableDeclarator.check(node)) {
		            addPattern(path.get("id"), bindings);
		            recursiveScanChild(path.get("init"), bindings, scopeTypes);
		        }
		        else if (node.type === "ImportSpecifier" ||
		            node.type === "ImportNamespaceSpecifier" ||
		            node.type === "ImportDefaultSpecifier") {
		            addPattern(
		            path.get(node.local ? "local" :
		                node.name ? "name" : "id"), bindings);
		        }
		        else if (Node.check(node) && !Expression.check(node)) {
		            types.eachField(node, function (name, child) {
		                var childPath = path.get(name);
		                if (!pathHasValue(childPath, child)) {
		                    throw new Error("");
		                }
		                recursiveScanChild(childPath, bindings, scopeTypes);
		            });
		        }
		    }
		    function pathHasValue(path, value) {
		        if (path.value === value) {
		            return true;
		        }
		        if (Array.isArray(path.value) &&
		            path.value.length === 0 &&
		            Array.isArray(value) &&
		            value.length === 0) {
		            return true;
		        }
		        return false;
		    }
		    function recursiveScanChild(path, bindings, scopeTypes) {
		        var node = path.value;
		        if (!node || Expression.check(node)) ;
		        else if (namedTypes.FunctionDeclaration.check(node) &&
		            node.id !== null) {
		            addPattern(path.get("id"), bindings);
		        }
		        else if (namedTypes.ClassDeclaration &&
		            namedTypes.ClassDeclaration.check(node)) {
		            addPattern(path.get("id"), bindings);
		        }
		        else if (ScopeType.check(node)) {
		            if (namedTypes.CatchClause.check(node) &&
		                namedTypes.Identifier.check(node.param)) {
		                var catchParamName = node.param.name;
		                var hadBinding = hasOwn.call(bindings, catchParamName);
		                recursiveScanScope(path.get("body"), bindings, scopeTypes);
		                if (!hadBinding) {
		                    delete bindings[catchParamName];
		                }
		            }
		        }
		        else {
		            recursiveScanScope(path, bindings, scopeTypes);
		        }
		    }
		    function addPattern(patternPath, bindings) {
		        var pattern = patternPath.value;
		        namedTypes.Pattern.assert(pattern);
		        if (namedTypes.Identifier.check(pattern)) {
		            if (hasOwn.call(bindings, pattern.name)) {
		                bindings[pattern.name].push(patternPath);
		            }
		            else {
		                bindings[pattern.name] = [patternPath];
		            }
		        }
		        else if (namedTypes.AssignmentPattern &&
		            namedTypes.AssignmentPattern.check(pattern)) {
		            addPattern(patternPath.get('left'), bindings);
		        }
		        else if (namedTypes.ObjectPattern &&
		            namedTypes.ObjectPattern.check(pattern)) {
		            patternPath.get('properties').each(function (propertyPath) {
		                var property = propertyPath.value;
		                if (namedTypes.Pattern.check(property)) {
		                    addPattern(propertyPath, bindings);
		                }
		                else if (namedTypes.Property.check(property)) {
		                    addPattern(propertyPath.get('value'), bindings);
		                }
		                else if (namedTypes.SpreadProperty &&
		                    namedTypes.SpreadProperty.check(property)) {
		                    addPattern(propertyPath.get('argument'), bindings);
		                }
		            });
		        }
		        else if (namedTypes.ArrayPattern &&
		            namedTypes.ArrayPattern.check(pattern)) {
		            patternPath.get('elements').each(function (elementPath) {
		                var element = elementPath.value;
		                if (namedTypes.Pattern.check(element)) {
		                    addPattern(elementPath, bindings);
		                }
		                else if (namedTypes.SpreadElement &&
		                    namedTypes.SpreadElement.check(element)) {
		                    addPattern(elementPath.get("argument"), bindings);
		                }
		            });
		        }
		        else if (namedTypes.PropertyPattern &&
		            namedTypes.PropertyPattern.check(pattern)) {
		            addPattern(patternPath.get('pattern'), bindings);
		        }
		        else if ((namedTypes.SpreadElementPattern &&
		            namedTypes.SpreadElementPattern.check(pattern)) ||
		            (namedTypes.SpreadPropertyPattern &&
		                namedTypes.SpreadPropertyPattern.check(pattern))) {
		            addPattern(patternPath.get('argument'), bindings);
		        }
		    }
		    function addTypePattern(patternPath, types) {
		        var pattern = patternPath.value;
		        namedTypes.Pattern.assert(pattern);
		        if (namedTypes.Identifier.check(pattern)) {
		            if (hasOwn.call(types, pattern.name)) {
		                types[pattern.name].push(patternPath);
		            }
		            else {
		                types[pattern.name] = [patternPath];
		            }
		        }
		    }
		    Sp.lookup = function (name) {
		        for (var scope = this; scope; scope = scope.parent)
		            if (scope.declares(name))
		                break;
		        return scope;
		    };
		    Sp.lookupType = function (name) {
		        for (var scope = this; scope; scope = scope.parent)
		            if (scope.declaresType(name))
		                break;
		        return scope;
		    };
		    Sp.getGlobalScope = function () {
		        var scope = this;
		        while (!scope.isGlobal)
		            scope = scope.parent;
		        return scope;
		    };
		    return Scope;
		}
		exports$1.default = scopePlugin;
		module.exports = exports$1["default"]; 
	} (scope, scope.exports));
	return scope.exports;
}

var hasRequiredNodePath;

function requireNodePath () {
	if (hasRequiredNodePath) return nodePath.exports;
	hasRequiredNodePath = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var path_1 = tslib_1.__importDefault(requirePath());
		var scope_1 = tslib_1.__importDefault(requireScope());
		function nodePathPlugin(fork) {
		    var types = fork.use(types_1.default);
		    var n = types.namedTypes;
		    var b = types.builders;
		    var isNumber = types.builtInTypes.number;
		    var isArray = types.builtInTypes.array;
		    var Path = fork.use(path_1.default);
		    var Scope = fork.use(scope_1.default);
		    var NodePath = function NodePath(value, parentPath, name) {
		        if (!(this instanceof NodePath)) {
		            throw new Error("NodePath constructor cannot be invoked without 'new'");
		        }
		        Path.call(this, value, parentPath, name);
		    };
		    var NPp = NodePath.prototype = Object.create(Path.prototype, {
		        constructor: {
		            value: NodePath,
		            enumerable: false,
		            writable: true,
		            configurable: true
		        }
		    });
		    Object.defineProperties(NPp, {
		        node: {
		            get: function () {
		                Object.defineProperty(this, "node", {
		                    configurable: true,
		                    value: this._computeNode()
		                });
		                return this.node;
		            }
		        },
		        parent: {
		            get: function () {
		                Object.defineProperty(this, "parent", {
		                    configurable: true,
		                    value: this._computeParent()
		                });
		                return this.parent;
		            }
		        },
		        scope: {
		            get: function () {
		                Object.defineProperty(this, "scope", {
		                    configurable: true,
		                    value: this._computeScope()
		                });
		                return this.scope;
		            }
		        }
		    });
		    NPp.replace = function () {
		        delete this.node;
		        delete this.parent;
		        delete this.scope;
		        return Path.prototype.replace.apply(this, arguments);
		    };
		    NPp.prune = function () {
		        var remainingNodePath = this.parent;
		        this.replace();
		        return cleanUpNodesAfterPrune(remainingNodePath);
		    };
		    NPp._computeNode = function () {
		        var value = this.value;
		        if (n.Node.check(value)) {
		            return value;
		        }
		        var pp = this.parentPath;
		        return pp && pp.node || null;
		    };
		    NPp._computeParent = function () {
		        var value = this.value;
		        var pp = this.parentPath;
		        if (!n.Node.check(value)) {
		            while (pp && !n.Node.check(pp.value)) {
		                pp = pp.parentPath;
		            }
		            if (pp) {
		                pp = pp.parentPath;
		            }
		        }
		        while (pp && !n.Node.check(pp.value)) {
		            pp = pp.parentPath;
		        }
		        return pp || null;
		    };
		    NPp._computeScope = function () {
		        var value = this.value;
		        var pp = this.parentPath;
		        var scope = pp && pp.scope;
		        if (n.Node.check(value) &&
		            Scope.isEstablishedBy(value)) {
		            scope = new Scope(this, scope);
		        }
		        return scope || null;
		    };
		    NPp.getValueProperty = function (name) {
		        return types.getFieldValue(this.value, name);
		    };
		    NPp.needsParens = function (assumeExpressionContext) {
		        var pp = this.parentPath;
		        if (!pp) {
		            return false;
		        }
		        var node = this.value;
		        if (!n.Expression.check(node)) {
		            return false;
		        }
		        if (node.type === "Identifier") {
		            return false;
		        }
		        while (!n.Node.check(pp.value)) {
		            pp = pp.parentPath;
		            if (!pp) {
		                return false;
		            }
		        }
		        var parent = pp.value;
		        switch (node.type) {
		            case "UnaryExpression":
		            case "SpreadElement":
		            case "SpreadProperty":
		                return parent.type === "MemberExpression"
		                    && this.name === "object"
		                    && parent.object === node;
		            case "BinaryExpression":
		            case "LogicalExpression":
		                switch (parent.type) {
		                    case "CallExpression":
		                        return this.name === "callee"
		                            && parent.callee === node;
		                    case "UnaryExpression":
		                    case "SpreadElement":
		                    case "SpreadProperty":
		                        return true;
		                    case "MemberExpression":
		                        return this.name === "object"
		                            && parent.object === node;
		                    case "BinaryExpression":
		                    case "LogicalExpression": {
		                        var n_1 = node;
		                        var po = parent.operator;
		                        var pp_1 = PRECEDENCE[po];
		                        var no = n_1.operator;
		                        var np = PRECEDENCE[no];
		                        if (pp_1 > np) {
		                            return true;
		                        }
		                        if (pp_1 === np && this.name === "right") {
		                            if (parent.right !== n_1) {
		                                throw new Error("Nodes must be equal");
		                            }
		                            return true;
		                        }
		                    }
		                    default:
		                        return false;
		                }
		            case "SequenceExpression":
		                switch (parent.type) {
		                    case "ForStatement":
		                        return false;
		                    case "ExpressionStatement":
		                        return this.name !== "expression";
		                    default:
		                        return true;
		                }
		            case "YieldExpression":
		                switch (parent.type) {
		                    case "BinaryExpression":
		                    case "LogicalExpression":
		                    case "UnaryExpression":
		                    case "SpreadElement":
		                    case "SpreadProperty":
		                    case "CallExpression":
		                    case "MemberExpression":
		                    case "NewExpression":
		                    case "ConditionalExpression":
		                    case "YieldExpression":
		                        return true;
		                    default:
		                        return false;
		                }
		            case "Literal":
		                return parent.type === "MemberExpression"
		                    && isNumber.check(node.value)
		                    && this.name === "object"
		                    && parent.object === node;
		            case "AssignmentExpression":
		            case "ConditionalExpression":
		                switch (parent.type) {
		                    case "UnaryExpression":
		                    case "SpreadElement":
		                    case "SpreadProperty":
		                    case "BinaryExpression":
		                    case "LogicalExpression":
		                        return true;
		                    case "CallExpression":
		                        return this.name === "callee"
		                            && parent.callee === node;
		                    case "ConditionalExpression":
		                        return this.name === "test"
		                            && parent.test === node;
		                    case "MemberExpression":
		                        return this.name === "object"
		                            && parent.object === node;
		                    default:
		                        return false;
		                }
		            default:
		                if (parent.type === "NewExpression" &&
		                    this.name === "callee" &&
		                    parent.callee === node) {
		                    return containsCallExpression(node);
		                }
		        }
		        if (assumeExpressionContext !== true &&
		            !this.canBeFirstInStatement() &&
		            this.firstInStatement())
		            return true;
		        return false;
		    };
		    function isBinary(node) {
		        return n.BinaryExpression.check(node)
		            || n.LogicalExpression.check(node);
		    }
		    var PRECEDENCE = {};
		    [["||"],
		        ["&&"],
		        ["|"],
		        ["^"],
		        ["&"],
		        ["==", "===", "!=", "!=="],
		        ["<", ">", "<=", ">=", "in", "instanceof"],
		        [">>", "<<", ">>>"],
		        ["+", "-"],
		        ["*", "/", "%"]
		    ].forEach(function (tier, i) {
		        tier.forEach(function (op) {
		            PRECEDENCE[op] = i;
		        });
		    });
		    function containsCallExpression(node) {
		        if (n.CallExpression.check(node)) {
		            return true;
		        }
		        if (isArray.check(node)) {
		            return node.some(containsCallExpression);
		        }
		        if (n.Node.check(node)) {
		            return types.someField(node, function (_name, child) {
		                return containsCallExpression(child);
		            });
		        }
		        return false;
		    }
		    NPp.canBeFirstInStatement = function () {
		        var node = this.node;
		        return !n.FunctionExpression.check(node)
		            && !n.ObjectExpression.check(node);
		    };
		    NPp.firstInStatement = function () {
		        return firstInStatement(this);
		    };
		    function firstInStatement(path) {
		        for (var node, parent; path.parent; path = path.parent) {
		            node = path.node;
		            parent = path.parent.node;
		            if (n.BlockStatement.check(parent) &&
		                path.parent.name === "body" &&
		                path.name === 0) {
		                if (parent.body[0] !== node) {
		                    throw new Error("Nodes must be equal");
		                }
		                return true;
		            }
		            if (n.ExpressionStatement.check(parent) &&
		                path.name === "expression") {
		                if (parent.expression !== node) {
		                    throw new Error("Nodes must be equal");
		                }
		                return true;
		            }
		            if (n.SequenceExpression.check(parent) &&
		                path.parent.name === "expressions" &&
		                path.name === 0) {
		                if (parent.expressions[0] !== node) {
		                    throw new Error("Nodes must be equal");
		                }
		                continue;
		            }
		            if (n.CallExpression.check(parent) &&
		                path.name === "callee") {
		                if (parent.callee !== node) {
		                    throw new Error("Nodes must be equal");
		                }
		                continue;
		            }
		            if (n.MemberExpression.check(parent) &&
		                path.name === "object") {
		                if (parent.object !== node) {
		                    throw new Error("Nodes must be equal");
		                }
		                continue;
		            }
		            if (n.ConditionalExpression.check(parent) &&
		                path.name === "test") {
		                if (parent.test !== node) {
		                    throw new Error("Nodes must be equal");
		                }
		                continue;
		            }
		            if (isBinary(parent) &&
		                path.name === "left") {
		                if (parent.left !== node) {
		                    throw new Error("Nodes must be equal");
		                }
		                continue;
		            }
		            if (n.UnaryExpression.check(parent) &&
		                !parent.prefix &&
		                path.name === "argument") {
		                if (parent.argument !== node) {
		                    throw new Error("Nodes must be equal");
		                }
		                continue;
		            }
		            return false;
		        }
		        return true;
		    }
		    function cleanUpNodesAfterPrune(remainingNodePath) {
		        if (n.VariableDeclaration.check(remainingNodePath.node)) {
		            var declarations = remainingNodePath.get('declarations').value;
		            if (!declarations || declarations.length === 0) {
		                return remainingNodePath.prune();
		            }
		        }
		        else if (n.ExpressionStatement.check(remainingNodePath.node)) {
		            if (!remainingNodePath.get('expression').value) {
		                return remainingNodePath.prune();
		            }
		        }
		        else if (n.IfStatement.check(remainingNodePath.node)) {
		            cleanUpIfStatementAfterPrune(remainingNodePath);
		        }
		        return remainingNodePath;
		    }
		    function cleanUpIfStatementAfterPrune(ifStatement) {
		        var testExpression = ifStatement.get('test').value;
		        var alternate = ifStatement.get('alternate').value;
		        var consequent = ifStatement.get('consequent').value;
		        if (!consequent && !alternate) {
		            var testExpressionStatement = b.expressionStatement(testExpression);
		            ifStatement.replace(testExpressionStatement);
		        }
		        else if (!consequent && alternate) {
		            var negatedTestExpression = b.unaryExpression('!', testExpression, true);
		            if (n.UnaryExpression.check(testExpression) && testExpression.operator === '!') {
		                negatedTestExpression = testExpression.argument;
		            }
		            ifStatement.get("test").replace(negatedTestExpression);
		            ifStatement.get("consequent").replace(alternate);
		            ifStatement.get("alternate").replace();
		        }
		    }
		    return NodePath;
		}
		exports$1.default = nodePathPlugin;
		module.exports = exports$1["default"]; 
	} (nodePath, nodePath.exports));
	return nodePath.exports;
}

var hasRequiredPathVisitor;

function requirePathVisitor () {
	if (hasRequiredPathVisitor) return pathVisitor.exports;
	hasRequiredPathVisitor = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var node_path_1 = tslib_1.__importDefault(requireNodePath());
		var hasOwn = Object.prototype.hasOwnProperty;
		function pathVisitorPlugin(fork) {
		    var types = fork.use(types_1.default);
		    var NodePath = fork.use(node_path_1.default);
		    var isArray = types.builtInTypes.array;
		    var isObject = types.builtInTypes.object;
		    var isFunction = types.builtInTypes.function;
		    var undefined$1;
		    var PathVisitor = function PathVisitor() {
		        if (!(this instanceof PathVisitor)) {
		            throw new Error("PathVisitor constructor cannot be invoked without 'new'");
		        }
		        this._reusableContextStack = [];
		        this._methodNameTable = computeMethodNameTable(this);
		        this._shouldVisitComments =
		            hasOwn.call(this._methodNameTable, "Block") ||
		                hasOwn.call(this._methodNameTable, "Line");
		        this.Context = makeContextConstructor(this);
		        this._visiting = false;
		        this._changeReported = false;
		    };
		    function computeMethodNameTable(visitor) {
		        var typeNames = Object.create(null);
		        for (var methodName in visitor) {
		            if (/^visit[A-Z]/.test(methodName)) {
		                typeNames[methodName.slice("visit".length)] = true;
		            }
		        }
		        var supertypeTable = types.computeSupertypeLookupTable(typeNames);
		        var methodNameTable = Object.create(null);
		        var typeNameKeys = Object.keys(supertypeTable);
		        var typeNameCount = typeNameKeys.length;
		        for (var i = 0; i < typeNameCount; ++i) {
		            var typeName = typeNameKeys[i];
		            methodName = "visit" + supertypeTable[typeName];
		            if (isFunction.check(visitor[methodName])) {
		                methodNameTable[typeName] = methodName;
		            }
		        }
		        return methodNameTable;
		    }
		    PathVisitor.fromMethodsObject = function fromMethodsObject(methods) {
		        if (methods instanceof PathVisitor) {
		            return methods;
		        }
		        if (!isObject.check(methods)) {
		            return new PathVisitor;
		        }
		        var Visitor = function Visitor() {
		            if (!(this instanceof Visitor)) {
		                throw new Error("Visitor constructor cannot be invoked without 'new'");
		            }
		            PathVisitor.call(this);
		        };
		        var Vp = Visitor.prototype = Object.create(PVp);
		        Vp.constructor = Visitor;
		        extend(Vp, methods);
		        extend(Visitor, PathVisitor);
		        isFunction.assert(Visitor.fromMethodsObject);
		        isFunction.assert(Visitor.visit);
		        return new Visitor;
		    };
		    function extend(target, source) {
		        for (var property in source) {
		            if (hasOwn.call(source, property)) {
		                target[property] = source[property];
		            }
		        }
		        return target;
		    }
		    PathVisitor.visit = function visit(node, methods) {
		        return PathVisitor.fromMethodsObject(methods).visit(node);
		    };
		    var PVp = PathVisitor.prototype;
		    PVp.visit = function () {
		        if (this._visiting) {
		            throw new Error("Recursively calling visitor.visit(path) resets visitor state. " +
		                "Try this.visit(path) or this.traverse(path) instead.");
		        }
		        this._visiting = true;
		        this._changeReported = false;
		        this._abortRequested = false;
		        var argc = arguments.length;
		        var args = new Array(argc);
		        for (var i = 0; i < argc; ++i) {
		            args[i] = arguments[i];
		        }
		        if (!(args[0] instanceof NodePath)) {
		            args[0] = new NodePath({ root: args[0] }).get("root");
		        }
		        this.reset.apply(this, args);
		        var didNotThrow;
		        try {
		            var root = this.visitWithoutReset(args[0]);
		            didNotThrow = true;
		        }
		        finally {
		            this._visiting = false;
		            if (!didNotThrow && this._abortRequested) {
		                return args[0].value;
		            }
		        }
		        return root;
		    };
		    PVp.AbortRequest = function AbortRequest() { };
		    PVp.abort = function () {
		        var visitor = this;
		        visitor._abortRequested = true;
		        var request = new visitor.AbortRequest();
		        request.cancel = function () {
		            visitor._abortRequested = false;
		        };
		        throw request;
		    };
		    PVp.reset = function (_path ) {
		    };
		    PVp.visitWithoutReset = function (path) {
		        if (this instanceof this.Context) {
		            return this.visitor.visitWithoutReset(path);
		        }
		        if (!(path instanceof NodePath)) {
		            throw new Error("");
		        }
		        var value = path.value;
		        var methodName = value &&
		            typeof value === "object" &&
		            typeof value.type === "string" &&
		            this._methodNameTable[value.type];
		        if (methodName) {
		            var context = this.acquireContext(path);
		            try {
		                return context.invokeVisitorMethod(methodName);
		            }
		            finally {
		                this.releaseContext(context);
		            }
		        }
		        else {
		            return visitChildren(path, this);
		        }
		    };
		    function visitChildren(path, visitor) {
		        if (!(path instanceof NodePath)) {
		            throw new Error("");
		        }
		        if (!(visitor instanceof PathVisitor)) {
		            throw new Error("");
		        }
		        var value = path.value;
		        if (isArray.check(value)) {
		            path.each(visitor.visitWithoutReset, visitor);
		        }
		        else if (!isObject.check(value)) ;
		        else {
		            var childNames = types.getFieldNames(value);
		            if (visitor._shouldVisitComments &&
		                value.comments &&
		                childNames.indexOf("comments") < 0) {
		                childNames.push("comments");
		            }
		            var childCount = childNames.length;
		            var childPaths = [];
		            for (var i = 0; i < childCount; ++i) {
		                var childName = childNames[i];
		                if (!hasOwn.call(value, childName)) {
		                    value[childName] = types.getFieldValue(value, childName);
		                }
		                childPaths.push(path.get(childName));
		            }
		            for (var i = 0; i < childCount; ++i) {
		                visitor.visitWithoutReset(childPaths[i]);
		            }
		        }
		        return path.value;
		    }
		    PVp.acquireContext = function (path) {
		        if (this._reusableContextStack.length === 0) {
		            return new this.Context(path);
		        }
		        return this._reusableContextStack.pop().reset(path);
		    };
		    PVp.releaseContext = function (context) {
		        if (!(context instanceof this.Context)) {
		            throw new Error("");
		        }
		        this._reusableContextStack.push(context);
		        context.currentPath = null;
		    };
		    PVp.reportChanged = function () {
		        this._changeReported = true;
		    };
		    PVp.wasChangeReported = function () {
		        return this._changeReported;
		    };
		    function makeContextConstructor(visitor) {
		        function Context(path) {
		            if (!(this instanceof Context)) {
		                throw new Error("");
		            }
		            if (!(this instanceof PathVisitor)) {
		                throw new Error("");
		            }
		            if (!(path instanceof NodePath)) {
		                throw new Error("");
		            }
		            Object.defineProperty(this, "visitor", {
		                value: visitor,
		                writable: false,
		                enumerable: true,
		                configurable: false
		            });
		            this.currentPath = path;
		            this.needToCallTraverse = true;
		            Object.seal(this);
		        }
		        if (!(visitor instanceof PathVisitor)) {
		            throw new Error("");
		        }
		        var Cp = Context.prototype = Object.create(visitor);
		        Cp.constructor = Context;
		        extend(Cp, sharedContextProtoMethods);
		        return Context;
		    }
		    var sharedContextProtoMethods = Object.create(null);
		    sharedContextProtoMethods.reset =
		        function reset(path) {
		            if (!(this instanceof this.Context)) {
		                throw new Error("");
		            }
		            if (!(path instanceof NodePath)) {
		                throw new Error("");
		            }
		            this.currentPath = path;
		            this.needToCallTraverse = true;
		            return this;
		        };
		    sharedContextProtoMethods.invokeVisitorMethod =
		        function invokeVisitorMethod(methodName) {
		            if (!(this instanceof this.Context)) {
		                throw new Error("");
		            }
		            if (!(this.currentPath instanceof NodePath)) {
		                throw new Error("");
		            }
		            var result = this.visitor[methodName].call(this, this.currentPath);
		            if (result === false) {
		                this.needToCallTraverse = false;
		            }
		            else if (result !== undefined$1) {
		                this.currentPath = this.currentPath.replace(result)[0];
		                if (this.needToCallTraverse) {
		                    this.traverse(this.currentPath);
		                }
		            }
		            if (this.needToCallTraverse !== false) {
		                throw new Error("Must either call this.traverse or return false in " + methodName);
		            }
		            var path = this.currentPath;
		            return path && path.value;
		        };
		    sharedContextProtoMethods.traverse =
		        function traverse(path, newVisitor) {
		            if (!(this instanceof this.Context)) {
		                throw new Error("");
		            }
		            if (!(path instanceof NodePath)) {
		                throw new Error("");
		            }
		            if (!(this.currentPath instanceof NodePath)) {
		                throw new Error("");
		            }
		            this.needToCallTraverse = false;
		            return visitChildren(path, PathVisitor.fromMethodsObject(newVisitor || this.visitor));
		        };
		    sharedContextProtoMethods.visit =
		        function visit(path, newVisitor) {
		            if (!(this instanceof this.Context)) {
		                throw new Error("");
		            }
		            if (!(path instanceof NodePath)) {
		                throw new Error("");
		            }
		            if (!(this.currentPath instanceof NodePath)) {
		                throw new Error("");
		            }
		            this.needToCallTraverse = false;
		            return PathVisitor.fromMethodsObject(newVisitor || this.visitor).visitWithoutReset(path);
		        };
		    sharedContextProtoMethods.reportChanged = function reportChanged() {
		        this.visitor.reportChanged();
		    };
		    sharedContextProtoMethods.abort = function abort() {
		        this.needToCallTraverse = false;
		        this.visitor.abort();
		    };
		    return PathVisitor;
		}
		exports$1.default = pathVisitorPlugin;
		module.exports = exports$1["default"]; 
	} (pathVisitor, pathVisitor.exports));
	return pathVisitor.exports;
}

var equiv = {exports: {}};

var hasRequiredEquiv;

function requireEquiv () {
	if (hasRequiredEquiv) return equiv.exports;
	hasRequiredEquiv = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		function default_1(fork) {
		    var types = fork.use(types_1.default);
		    var getFieldNames = types.getFieldNames;
		    var getFieldValue = types.getFieldValue;
		    var isArray = types.builtInTypes.array;
		    var isObject = types.builtInTypes.object;
		    var isDate = types.builtInTypes.Date;
		    var isRegExp = types.builtInTypes.RegExp;
		    var hasOwn = Object.prototype.hasOwnProperty;
		    function astNodesAreEquivalent(a, b, problemPath) {
		        if (isArray.check(problemPath)) {
		            problemPath.length = 0;
		        }
		        else {
		            problemPath = null;
		        }
		        return areEquivalent(a, b, problemPath);
		    }
		    astNodesAreEquivalent.assert = function (a, b) {
		        var problemPath = [];
		        if (!astNodesAreEquivalent(a, b, problemPath)) {
		            if (problemPath.length === 0) {
		                if (a !== b) {
		                    throw new Error("Nodes must be equal");
		                }
		            }
		            else {
		                throw new Error("Nodes differ in the following path: " +
		                    problemPath.map(subscriptForProperty).join(""));
		            }
		        }
		    };
		    function subscriptForProperty(property) {
		        if (/[_$a-z][_$a-z0-9]*/i.test(property)) {
		            return "." + property;
		        }
		        return "[" + JSON.stringify(property) + "]";
		    }
		    function areEquivalent(a, b, problemPath) {
		        if (a === b) {
		            return true;
		        }
		        if (isArray.check(a)) {
		            return arraysAreEquivalent(a, b, problemPath);
		        }
		        if (isObject.check(a)) {
		            return objectsAreEquivalent(a, b, problemPath);
		        }
		        if (isDate.check(a)) {
		            return isDate.check(b) && (+a === +b);
		        }
		        if (isRegExp.check(a)) {
		            return isRegExp.check(b) && (a.source === b.source &&
		                a.global === b.global &&
		                a.multiline === b.multiline &&
		                a.ignoreCase === b.ignoreCase);
		        }
		        return a == b;
		    }
		    function arraysAreEquivalent(a, b, problemPath) {
		        isArray.assert(a);
		        var aLength = a.length;
		        if (!isArray.check(b) || b.length !== aLength) {
		            if (problemPath) {
		                problemPath.push("length");
		            }
		            return false;
		        }
		        for (var i = 0; i < aLength; ++i) {
		            if (problemPath) {
		                problemPath.push(i);
		            }
		            if (i in a !== i in b) {
		                return false;
		            }
		            if (!areEquivalent(a[i], b[i], problemPath)) {
		                return false;
		            }
		            if (problemPath) {
		                var problemPathTail = problemPath.pop();
		                if (problemPathTail !== i) {
		                    throw new Error("" + problemPathTail);
		                }
		            }
		        }
		        return true;
		    }
		    function objectsAreEquivalent(a, b, problemPath) {
		        isObject.assert(a);
		        if (!isObject.check(b)) {
		            return false;
		        }
		        if (a.type !== b.type) {
		            if (problemPath) {
		                problemPath.push("type");
		            }
		            return false;
		        }
		        var aNames = getFieldNames(a);
		        var aNameCount = aNames.length;
		        var bNames = getFieldNames(b);
		        var bNameCount = bNames.length;
		        if (aNameCount === bNameCount) {
		            for (var i = 0; i < aNameCount; ++i) {
		                var name = aNames[i];
		                var aChild = getFieldValue(a, name);
		                var bChild = getFieldValue(b, name);
		                if (problemPath) {
		                    problemPath.push(name);
		                }
		                if (!areEquivalent(aChild, bChild, problemPath)) {
		                    return false;
		                }
		                if (problemPath) {
		                    var problemPathTail = problemPath.pop();
		                    if (problemPathTail !== name) {
		                        throw new Error("" + problemPathTail);
		                    }
		                }
		            }
		            return true;
		        }
		        if (!problemPath) {
		            return false;
		        }
		        var seenNames = Object.create(null);
		        for (i = 0; i < aNameCount; ++i) {
		            seenNames[aNames[i]] = true;
		        }
		        for (i = 0; i < bNameCount; ++i) {
		            name = bNames[i];
		            if (!hasOwn.call(seenNames, name)) {
		                problemPath.push(name);
		                return false;
		            }
		            delete seenNames[name];
		        }
		        for (name in seenNames) {
		            problemPath.push(name);
		            break;
		        }
		        return false;
		    }
		    return astNodesAreEquivalent;
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (equiv, equiv.exports));
	return equiv.exports;
}

var hasRequiredFork;

function requireFork () {
	if (hasRequiredFork) return fork.exports;
	hasRequiredFork = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var path_visitor_1 = tslib_1.__importDefault(requirePathVisitor());
		var equiv_1 = tslib_1.__importDefault(requireEquiv());
		var path_1 = tslib_1.__importDefault(requirePath());
		var node_path_1 = tslib_1.__importDefault(requireNodePath());
		function default_1(defs) {
		    var fork = createFork();
		    var types = fork.use(types_1.default);
		    defs.forEach(fork.use);
		    types.finalize();
		    var PathVisitor = fork.use(path_visitor_1.default);
		    return {
		        Type: types.Type,
		        builtInTypes: types.builtInTypes,
		        namedTypes: types.namedTypes,
		        builders: types.builders,
		        defineMethod: types.defineMethod,
		        getFieldNames: types.getFieldNames,
		        getFieldValue: types.getFieldValue,
		        eachField: types.eachField,
		        someField: types.someField,
		        getSupertypeNames: types.getSupertypeNames,
		        getBuilderName: types.getBuilderName,
		        astNodesAreEquivalent: fork.use(equiv_1.default),
		        finalize: types.finalize,
		        Path: fork.use(path_1.default),
		        NodePath: fork.use(node_path_1.default),
		        PathVisitor: PathVisitor,
		        use: fork.use,
		        visit: PathVisitor.visit,
		    };
		}
		exports$1.default = default_1;
		function createFork() {
		    var used = [];
		    var usedResult = [];
		    function use(plugin) {
		        var idx = used.indexOf(plugin);
		        if (idx === -1) {
		            idx = used.length;
		            used.push(plugin);
		            usedResult[idx] = plugin(fork);
		        }
		        return usedResult[idx];
		    }
		    var fork = { use: use };
		    return fork;
		}
		module.exports = exports$1["default"]; 
	} (fork, fork.exports));
	return fork.exports;
}

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

var shared = {exports: {}};

var hasRequiredShared;

function requireShared () {
	if (hasRequiredShared) return shared.exports;
	hasRequiredShared = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		function default_1(fork) {
		    var types = fork.use(types_1.default);
		    var Type = types.Type;
		    var builtin = types.builtInTypes;
		    var isNumber = builtin.number;
		    function geq(than) {
		        return Type.from(function (value) { return isNumber.check(value) && value >= than; }, isNumber + " >= " + than);
		    }
		    var defaults = {
		        "null": function () { return null; },
		        "emptyArray": function () { return []; },
		        "false": function () { return false; },
		        "true": function () { return true; },
		        "undefined": function () { },
		        "use strict": function () { return "use strict"; }
		    };
		    var naiveIsPrimitive = Type.or(builtin.string, builtin.number, builtin.boolean, builtin.null, builtin.undefined);
		    var isPrimitive = Type.from(function (value) {
		        if (value === null)
		            return true;
		        var type = typeof value;
		        if (type === "object" ||
		            type === "function") {
		            return false;
		        }
		        return true;
		    }, naiveIsPrimitive.toString());
		    return {
		        geq: geq,
		        defaults: defaults,
		        isPrimitive: isPrimitive,
		    };
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (shared, shared.exports));
	return shared.exports;
}

var hasRequiredCore;

function requireCore () {
	if (hasRequiredCore) return core$1.exports;
	hasRequiredCore = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var shared_1 = tslib_1.__importDefault(requireShared());
		function default_1(fork) {
		    var types = fork.use(types_1.default);
		    var Type = types.Type;
		    var def = Type.def;
		    var or = Type.or;
		    var shared = fork.use(shared_1.default);
		    var defaults = shared.defaults;
		    var geq = shared.geq;
		    def("Printable")
		        .field("loc", or(def("SourceLocation"), null), defaults["null"], true);
		    def("Node")
		        .bases("Printable")
		        .field("type", String)
		        .field("comments", or([def("Comment")], null), defaults["null"], true);
		    def("SourceLocation")
		        .field("start", def("Position"))
		        .field("end", def("Position"))
		        .field("source", or(String, null), defaults["null"]);
		    def("Position")
		        .field("line", geq(1))
		        .field("column", geq(0));
		    def("File")
		        .bases("Node")
		        .build("program", "name")
		        .field("program", def("Program"))
		        .field("name", or(String, null), defaults["null"]);
		    def("Program")
		        .bases("Node")
		        .build("body")
		        .field("body", [def("Statement")]);
		    def("Function")
		        .bases("Node")
		        .field("id", or(def("Identifier"), null), defaults["null"])
		        .field("params", [def("Pattern")])
		        .field("body", def("BlockStatement"))
		        .field("generator", Boolean, defaults["false"])
		        .field("async", Boolean, defaults["false"]);
		    def("Statement").bases("Node");
		    def("EmptyStatement").bases("Statement").build();
		    def("BlockStatement")
		        .bases("Statement")
		        .build("body")
		        .field("body", [def("Statement")]);
		    def("ExpressionStatement")
		        .bases("Statement")
		        .build("expression")
		        .field("expression", def("Expression"));
		    def("IfStatement")
		        .bases("Statement")
		        .build("test", "consequent", "alternate")
		        .field("test", def("Expression"))
		        .field("consequent", def("Statement"))
		        .field("alternate", or(def("Statement"), null), defaults["null"]);
		    def("LabeledStatement")
		        .bases("Statement")
		        .build("label", "body")
		        .field("label", def("Identifier"))
		        .field("body", def("Statement"));
		    def("BreakStatement")
		        .bases("Statement")
		        .build("label")
		        .field("label", or(def("Identifier"), null), defaults["null"]);
		    def("ContinueStatement")
		        .bases("Statement")
		        .build("label")
		        .field("label", or(def("Identifier"), null), defaults["null"]);
		    def("WithStatement")
		        .bases("Statement")
		        .build("object", "body")
		        .field("object", def("Expression"))
		        .field("body", def("Statement"));
		    def("SwitchStatement")
		        .bases("Statement")
		        .build("discriminant", "cases", "lexical")
		        .field("discriminant", def("Expression"))
		        .field("cases", [def("SwitchCase")])
		        .field("lexical", Boolean, defaults["false"]);
		    def("ReturnStatement")
		        .bases("Statement")
		        .build("argument")
		        .field("argument", or(def("Expression"), null));
		    def("ThrowStatement")
		        .bases("Statement")
		        .build("argument")
		        .field("argument", def("Expression"));
		    def("TryStatement")
		        .bases("Statement")
		        .build("block", "handler", "finalizer")
		        .field("block", def("BlockStatement"))
		        .field("handler", or(def("CatchClause"), null), function () {
		        return this.handlers && this.handlers[0] || null;
		    })
		        .field("handlers", [def("CatchClause")], function () {
		        return this.handler ? [this.handler] : [];
		    }, true)
		        .field("guardedHandlers", [def("CatchClause")], defaults.emptyArray)
		        .field("finalizer", or(def("BlockStatement"), null), defaults["null"]);
		    def("CatchClause")
		        .bases("Node")
		        .build("param", "guard", "body")
		        .field("param", or(def("Pattern"), null), defaults["null"])
		        .field("guard", or(def("Expression"), null), defaults["null"])
		        .field("body", def("BlockStatement"));
		    def("WhileStatement")
		        .bases("Statement")
		        .build("test", "body")
		        .field("test", def("Expression"))
		        .field("body", def("Statement"));
		    def("DoWhileStatement")
		        .bases("Statement")
		        .build("body", "test")
		        .field("body", def("Statement"))
		        .field("test", def("Expression"));
		    def("ForStatement")
		        .bases("Statement")
		        .build("init", "test", "update", "body")
		        .field("init", or(def("VariableDeclaration"), def("Expression"), null))
		        .field("test", or(def("Expression"), null))
		        .field("update", or(def("Expression"), null))
		        .field("body", def("Statement"));
		    def("ForInStatement")
		        .bases("Statement")
		        .build("left", "right", "body")
		        .field("left", or(def("VariableDeclaration"), def("Expression")))
		        .field("right", def("Expression"))
		        .field("body", def("Statement"));
		    def("DebuggerStatement").bases("Statement").build();
		    def("Declaration").bases("Statement");
		    def("FunctionDeclaration")
		        .bases("Function", "Declaration")
		        .build("id", "params", "body")
		        .field("id", def("Identifier"));
		    def("FunctionExpression")
		        .bases("Function", "Expression")
		        .build("id", "params", "body");
		    def("VariableDeclaration")
		        .bases("Declaration")
		        .build("kind", "declarations")
		        .field("kind", or("var", "let", "const"))
		        .field("declarations", [def("VariableDeclarator")]);
		    def("VariableDeclarator")
		        .bases("Node")
		        .build("id", "init")
		        .field("id", def("Pattern"))
		        .field("init", or(def("Expression"), null), defaults["null"]);
		    def("Expression").bases("Node");
		    def("ThisExpression").bases("Expression").build();
		    def("ArrayExpression")
		        .bases("Expression")
		        .build("elements")
		        .field("elements", [or(def("Expression"), null)]);
		    def("ObjectExpression")
		        .bases("Expression")
		        .build("properties")
		        .field("properties", [def("Property")]);
		    def("Property")
		        .bases("Node")
		        .build("kind", "key", "value")
		        .field("kind", or("init", "get", "set"))
		        .field("key", or(def("Literal"), def("Identifier")))
		        .field("value", def("Expression"));
		    def("SequenceExpression")
		        .bases("Expression")
		        .build("expressions")
		        .field("expressions", [def("Expression")]);
		    var UnaryOperator = or("-", "+", "!", "~", "typeof", "void", "delete");
		    def("UnaryExpression")
		        .bases("Expression")
		        .build("operator", "argument", "prefix")
		        .field("operator", UnaryOperator)
		        .field("argument", def("Expression"))
		        .field("prefix", Boolean, defaults["true"]);
		    var BinaryOperator = or("==", "!=", "===", "!==", "<", "<=", ">", ">=", "<<", ">>", ">>>", "+", "-", "*", "/", "%", "**", "&",
		    "|", "^", "in", "instanceof");
		    def("BinaryExpression")
		        .bases("Expression")
		        .build("operator", "left", "right")
		        .field("operator", BinaryOperator)
		        .field("left", def("Expression"))
		        .field("right", def("Expression"));
		    var AssignmentOperator = or("=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&=");
		    def("AssignmentExpression")
		        .bases("Expression")
		        .build("operator", "left", "right")
		        .field("operator", AssignmentOperator)
		        .field("left", or(def("Pattern"), def("MemberExpression")))
		        .field("right", def("Expression"));
		    var UpdateOperator = or("++", "--");
		    def("UpdateExpression")
		        .bases("Expression")
		        .build("operator", "argument", "prefix")
		        .field("operator", UpdateOperator)
		        .field("argument", def("Expression"))
		        .field("prefix", Boolean);
		    var LogicalOperator = or("||", "&&");
		    def("LogicalExpression")
		        .bases("Expression")
		        .build("operator", "left", "right")
		        .field("operator", LogicalOperator)
		        .field("left", def("Expression"))
		        .field("right", def("Expression"));
		    def("ConditionalExpression")
		        .bases("Expression")
		        .build("test", "consequent", "alternate")
		        .field("test", def("Expression"))
		        .field("consequent", def("Expression"))
		        .field("alternate", def("Expression"));
		    def("NewExpression")
		        .bases("Expression")
		        .build("callee", "arguments")
		        .field("callee", def("Expression"))
		        .field("arguments", [def("Expression")]);
		    def("CallExpression")
		        .bases("Expression")
		        .build("callee", "arguments")
		        .field("callee", def("Expression"))
		        .field("arguments", [def("Expression")]);
		    def("MemberExpression")
		        .bases("Expression")
		        .build("object", "property", "computed")
		        .field("object", def("Expression"))
		        .field("property", or(def("Identifier"), def("Expression")))
		        .field("computed", Boolean, function () {
		        var type = this.property.type;
		        if (type === 'Literal' ||
		            type === 'MemberExpression' ||
		            type === 'BinaryExpression') {
		            return true;
		        }
		        return false;
		    });
		    def("Pattern").bases("Node");
		    def("SwitchCase")
		        .bases("Node")
		        .build("test", "consequent")
		        .field("test", or(def("Expression"), null))
		        .field("consequent", [def("Statement")]);
		    def("Identifier")
		        .bases("Expression", "Pattern")
		        .build("name")
		        .field("name", String)
		        .field("optional", Boolean, defaults["false"]);
		    def("Literal")
		        .bases("Expression")
		        .build("value")
		        .field("value", or(String, Boolean, null, Number, RegExp))
		        .field("regex", or({
		        pattern: String,
		        flags: String
		    }, null), function () {
		        if (this.value instanceof RegExp) {
		            var flags = "";
		            if (this.value.ignoreCase)
		                flags += "i";
		            if (this.value.multiline)
		                flags += "m";
		            if (this.value.global)
		                flags += "g";
		            return {
		                pattern: this.value.source,
		                flags: flags
		            };
		        }
		        return null;
		    });
		    def("Comment")
		        .bases("Printable")
		        .field("value", String)
		        .field("leading", Boolean, defaults["true"])
		        .field("trailing", Boolean, defaults["false"]);
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (core$1, core$1.exports));
	return core$1.exports;
}

var es6 = {exports: {}};

var hasRequiredEs6;

function requireEs6 () {
	if (hasRequiredEs6) return es6.exports;
	hasRequiredEs6 = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var core_1 = tslib_1.__importDefault(requireCore());
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var shared_1 = tslib_1.__importDefault(requireShared());
		function default_1(fork) {
		    fork.use(core_1.default);
		    var types = fork.use(types_1.default);
		    var def = types.Type.def;
		    var or = types.Type.or;
		    var defaults = fork.use(shared_1.default).defaults;
		    def("Function")
		        .field("generator", Boolean, defaults["false"])
		        .field("expression", Boolean, defaults["false"])
		        .field("defaults", [or(def("Expression"), null)], defaults.emptyArray)
		        .field("rest", or(def("Identifier"), null), defaults["null"]);
		    def("RestElement")
		        .bases("Pattern")
		        .build("argument")
		        .field("argument", def("Pattern"))
		        .field("typeAnnotation",
		    or(def("TypeAnnotation"), def("TSTypeAnnotation"), null), defaults["null"]);
		    def("SpreadElementPattern")
		        .bases("Pattern")
		        .build("argument")
		        .field("argument", def("Pattern"));
		    def("FunctionDeclaration")
		        .build("id", "params", "body", "generator", "expression");
		    def("FunctionExpression")
		        .build("id", "params", "body", "generator", "expression");
		    def("ArrowFunctionExpression")
		        .bases("Function", "Expression")
		        .build("params", "body", "expression")
		        .field("id", null, defaults["null"])
		        .field("body", or(def("BlockStatement"), def("Expression")))
		        .field("generator", false, defaults["false"]);
		    def("ForOfStatement")
		        .bases("Statement")
		        .build("left", "right", "body")
		        .field("left", or(def("VariableDeclaration"), def("Pattern")))
		        .field("right", def("Expression"))
		        .field("body", def("Statement"));
		    def("YieldExpression")
		        .bases("Expression")
		        .build("argument", "delegate")
		        .field("argument", or(def("Expression"), null))
		        .field("delegate", Boolean, defaults["false"]);
		    def("GeneratorExpression")
		        .bases("Expression")
		        .build("body", "blocks", "filter")
		        .field("body", def("Expression"))
		        .field("blocks", [def("ComprehensionBlock")])
		        .field("filter", or(def("Expression"), null));
		    def("ComprehensionExpression")
		        .bases("Expression")
		        .build("body", "blocks", "filter")
		        .field("body", def("Expression"))
		        .field("blocks", [def("ComprehensionBlock")])
		        .field("filter", or(def("Expression"), null));
		    def("ComprehensionBlock")
		        .bases("Node")
		        .build("left", "right", "each")
		        .field("left", def("Pattern"))
		        .field("right", def("Expression"))
		        .field("each", Boolean);
		    def("Property")
		        .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
		        .field("value", or(def("Expression"), def("Pattern")))
		        .field("method", Boolean, defaults["false"])
		        .field("shorthand", Boolean, defaults["false"])
		        .field("computed", Boolean, defaults["false"]);
		    def("ObjectProperty")
		        .field("shorthand", Boolean, defaults["false"]);
		    def("PropertyPattern")
		        .bases("Pattern")
		        .build("key", "pattern")
		        .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
		        .field("pattern", def("Pattern"))
		        .field("computed", Boolean, defaults["false"]);
		    def("ObjectPattern")
		        .bases("Pattern")
		        .build("properties")
		        .field("properties", [or(def("PropertyPattern"), def("Property"))]);
		    def("ArrayPattern")
		        .bases("Pattern")
		        .build("elements")
		        .field("elements", [or(def("Pattern"), null)]);
		    def("MethodDefinition")
		        .bases("Declaration")
		        .build("kind", "key", "value", "static")
		        .field("kind", or("constructor", "method", "get", "set"))
		        .field("key", def("Expression"))
		        .field("value", def("Function"))
		        .field("computed", Boolean, defaults["false"])
		        .field("static", Boolean, defaults["false"]);
		    def("SpreadElement")
		        .bases("Node")
		        .build("argument")
		        .field("argument", def("Expression"));
		    def("ArrayExpression")
		        .field("elements", [or(def("Expression"), def("SpreadElement"), def("RestElement"), null)]);
		    def("NewExpression")
		        .field("arguments", [or(def("Expression"), def("SpreadElement"))]);
		    def("CallExpression")
		        .field("arguments", [or(def("Expression"), def("SpreadElement"))]);
		    def("AssignmentPattern")
		        .bases("Pattern")
		        .build("left", "right")
		        .field("left", def("Pattern"))
		        .field("right", def("Expression"));
		    var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"));
		    def("ClassProperty")
		        .bases("Declaration")
		        .build("key")
		        .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
		        .field("computed", Boolean, defaults["false"]);
		    def("ClassPropertyDefinition")
		        .bases("Declaration")
		        .build("definition")
		        .field("definition", ClassBodyElement);
		    def("ClassBody")
		        .bases("Declaration")
		        .build("body")
		        .field("body", [ClassBodyElement]);
		    def("ClassDeclaration")
		        .bases("Declaration")
		        .build("id", "body", "superClass")
		        .field("id", or(def("Identifier"), null))
		        .field("body", def("ClassBody"))
		        .field("superClass", or(def("Expression"), null), defaults["null"]);
		    def("ClassExpression")
		        .bases("Expression")
		        .build("id", "body", "superClass")
		        .field("id", or(def("Identifier"), null), defaults["null"])
		        .field("body", def("ClassBody"))
		        .field("superClass", or(def("Expression"), null), defaults["null"]);
		    def("Specifier").bases("Node");
		    def("ModuleSpecifier")
		        .bases("Specifier")
		        .field("local", or(def("Identifier"), null), defaults["null"])
		        .field("id", or(def("Identifier"), null), defaults["null"])
		        .field("name", or(def("Identifier"), null), defaults["null"]);
		    def("ImportSpecifier")
		        .bases("ModuleSpecifier")
		        .build("id", "name");
		    def("ImportNamespaceSpecifier")
		        .bases("ModuleSpecifier")
		        .build("id");
		    def("ImportDefaultSpecifier")
		        .bases("ModuleSpecifier")
		        .build("id");
		    def("ImportDeclaration")
		        .bases("Declaration")
		        .build("specifiers", "source", "importKind")
		        .field("specifiers", [or(def("ImportSpecifier"), def("ImportNamespaceSpecifier"), def("ImportDefaultSpecifier"))], defaults.emptyArray)
		        .field("source", def("Literal"))
		        .field("importKind", or("value", "type"), function () {
		        return "value";
		    });
		    def("TaggedTemplateExpression")
		        .bases("Expression")
		        .build("tag", "quasi")
		        .field("tag", def("Expression"))
		        .field("quasi", def("TemplateLiteral"));
		    def("TemplateLiteral")
		        .bases("Expression")
		        .build("quasis", "expressions")
		        .field("quasis", [def("TemplateElement")])
		        .field("expressions", [def("Expression")]);
		    def("TemplateElement")
		        .bases("Node")
		        .build("value", "tail")
		        .field("value", { "cooked": String, "raw": String })
		        .field("tail", Boolean);
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (es6, es6.exports));
	return es6.exports;
}

var es7 = {exports: {}};

var hasRequiredEs7;

function requireEs7 () {
	if (hasRequiredEs7) return es7.exports;
	hasRequiredEs7 = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var es6_1 = tslib_1.__importDefault(requireEs6());
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var shared_1 = tslib_1.__importDefault(requireShared());
		function default_1(fork) {
		    fork.use(es6_1.default);
		    var types = fork.use(types_1.default);
		    var def = types.Type.def;
		    var or = types.Type.or;
		    var defaults = fork.use(shared_1.default).defaults;
		    def("Function")
		        .field("async", Boolean, defaults["false"]);
		    def("SpreadProperty")
		        .bases("Node")
		        .build("argument")
		        .field("argument", def("Expression"));
		    def("ObjectExpression")
		        .field("properties", [or(def("Property"), def("SpreadProperty"), def("SpreadElement"))]);
		    def("SpreadPropertyPattern")
		        .bases("Pattern")
		        .build("argument")
		        .field("argument", def("Pattern"));
		    def("ObjectPattern")
		        .field("properties", [or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"))]);
		    def("AwaitExpression")
		        .bases("Expression")
		        .build("argument", "all")
		        .field("argument", or(def("Expression"), null))
		        .field("all", Boolean, defaults["false"]);
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (es7, es7.exports));
	return es7.exports;
}

var es2020 = {exports: {}};

var hasRequiredEs2020;

function requireEs2020 () {
	if (hasRequiredEs2020) return es2020.exports;
	hasRequiredEs2020 = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var es7_1 = tslib_1.__importDefault(requireEs7());
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		function default_1(fork) {
		    fork.use(es7_1.default);
		    var types = fork.use(types_1.default);
		    var def = types.Type.def;
		    def("ImportExpression")
		        .bases("Expression")
		        .build("source")
		        .field("source", def("Expression"));
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (es2020, es2020.exports));
	return es2020.exports;
}

var jsx = {exports: {}};

var hasRequiredJsx;

function requireJsx () {
	if (hasRequiredJsx) return jsx.exports;
	hasRequiredJsx = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var es7_1 = tslib_1.__importDefault(requireEs7());
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var shared_1 = tslib_1.__importDefault(requireShared());
		function default_1(fork) {
		    fork.use(es7_1.default);
		    var types = fork.use(types_1.default);
		    var def = types.Type.def;
		    var or = types.Type.or;
		    var defaults = fork.use(shared_1.default).defaults;
		    def("JSXAttribute")
		        .bases("Node")
		        .build("name", "value")
		        .field("name", or(def("JSXIdentifier"), def("JSXNamespacedName")))
		        .field("value", or(def("Literal"),
		    def("JSXExpressionContainer"),
		    null
		    ), defaults["null"]);
		    def("JSXIdentifier")
		        .bases("Identifier")
		        .build("name")
		        .field("name", String);
		    def("JSXNamespacedName")
		        .bases("Node")
		        .build("namespace", "name")
		        .field("namespace", def("JSXIdentifier"))
		        .field("name", def("JSXIdentifier"));
		    def("JSXMemberExpression")
		        .bases("MemberExpression")
		        .build("object", "property")
		        .field("object", or(def("JSXIdentifier"), def("JSXMemberExpression")))
		        .field("property", def("JSXIdentifier"))
		        .field("computed", Boolean, defaults.false);
		    var JSXElementName = or(def("JSXIdentifier"), def("JSXNamespacedName"), def("JSXMemberExpression"));
		    def("JSXSpreadAttribute")
		        .bases("Node")
		        .build("argument")
		        .field("argument", def("Expression"));
		    var JSXAttributes = [or(def("JSXAttribute"), def("JSXSpreadAttribute"))];
		    def("JSXExpressionContainer")
		        .bases("Expression")
		        .build("expression")
		        .field("expression", def("Expression"));
		    def("JSXElement")
		        .bases("Expression")
		        .build("openingElement", "closingElement", "children")
		        .field("openingElement", def("JSXOpeningElement"))
		        .field("closingElement", or(def("JSXClosingElement"), null), defaults["null"])
		        .field("children", [or(def("JSXElement"), def("JSXExpressionContainer"), def("JSXFragment"), def("JSXText"), def("Literal")
		        )], defaults.emptyArray)
		        .field("name", JSXElementName, function () {
		        return this.openingElement.name;
		    }, true)
		        .field("selfClosing", Boolean, function () {
		        return this.openingElement.selfClosing;
		    }, true)
		        .field("attributes", JSXAttributes, function () {
		        return this.openingElement.attributes;
		    }, true);
		    def("JSXOpeningElement")
		        .bases("Node")
		        .build("name", "attributes", "selfClosing")
		        .field("name", JSXElementName)
		        .field("attributes", JSXAttributes, defaults.emptyArray)
		        .field("selfClosing", Boolean, defaults["false"]);
		    def("JSXClosingElement")
		        .bases("Node")
		        .build("name")
		        .field("name", JSXElementName);
		    def("JSXFragment")
		        .bases("Expression")
		        .build("openingElement", "closingElement", "children")
		        .field("openingElement", def("JSXOpeningFragment"))
		        .field("closingElement", def("JSXClosingFragment"))
		        .field("children", [or(def("JSXElement"), def("JSXExpressionContainer"), def("JSXFragment"), def("JSXText"), def("Literal")
		        )], defaults.emptyArray);
		    def("JSXOpeningFragment")
		        .bases("Node")
		        .build();
		    def("JSXClosingFragment")
		        .bases("Node")
		        .build();
		    def("JSXText")
		        .bases("Literal")
		        .build("value")
		        .field("value", String);
		    def("JSXEmptyExpression").bases("Expression").build();
		    def("JSXSpreadChild")
		        .bases("Expression")
		        .build("expression")
		        .field("expression", def("Expression"));
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (jsx, jsx.exports));
	return jsx.exports;
}

var flow = {exports: {}};

var typeAnnotations = {exports: {}};

var hasRequiredTypeAnnotations;

function requireTypeAnnotations () {
	if (hasRequiredTypeAnnotations) return typeAnnotations.exports;
	hasRequiredTypeAnnotations = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var shared_1 = tslib_1.__importDefault(requireShared());
		function default_1(fork) {
		    var types = fork.use(types_1.default);
		    var def = types.Type.def;
		    var or = types.Type.or;
		    var defaults = fork.use(shared_1.default).defaults;
		    var TypeAnnotation = or(def("TypeAnnotation"), def("TSTypeAnnotation"), null);
		    var TypeParamDecl = or(def("TypeParameterDeclaration"), def("TSTypeParameterDeclaration"), null);
		    def("Identifier")
		        .field("typeAnnotation", TypeAnnotation, defaults["null"]);
		    def("ObjectPattern")
		        .field("typeAnnotation", TypeAnnotation, defaults["null"]);
		    def("Function")
		        .field("returnType", TypeAnnotation, defaults["null"])
		        .field("typeParameters", TypeParamDecl, defaults["null"]);
		    def("ClassProperty")
		        .build("key", "value", "typeAnnotation", "static")
		        .field("value", or(def("Expression"), null))
		        .field("static", Boolean, defaults["false"])
		        .field("typeAnnotation", TypeAnnotation, defaults["null"]);
		    ["ClassDeclaration",
		        "ClassExpression",
		    ].forEach(function (typeName) {
		        def(typeName)
		            .field("typeParameters", TypeParamDecl, defaults["null"])
		            .field("superTypeParameters", or(def("TypeParameterInstantiation"), def("TSTypeParameterInstantiation"), null), defaults["null"])
		            .field("implements", or([def("ClassImplements")], [def("TSExpressionWithTypeArguments")]), defaults.emptyArray);
		    });
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (typeAnnotations, typeAnnotations.exports));
	return typeAnnotations.exports;
}

var hasRequiredFlow;

function requireFlow () {
	if (hasRequiredFlow) return flow.exports;
	hasRequiredFlow = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var es7_1 = tslib_1.__importDefault(requireEs7());
		var type_annotations_1 = tslib_1.__importDefault(requireTypeAnnotations());
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var shared_1 = tslib_1.__importDefault(requireShared());
		function default_1(fork) {
		    fork.use(es7_1.default);
		    fork.use(type_annotations_1.default);
		    var types = fork.use(types_1.default);
		    var def = types.Type.def;
		    var or = types.Type.or;
		    var defaults = fork.use(shared_1.default).defaults;
		    def("Flow").bases("Node");
		    def("FlowType").bases("Flow");
		    def("AnyTypeAnnotation")
		        .bases("FlowType")
		        .build();
		    def("EmptyTypeAnnotation")
		        .bases("FlowType")
		        .build();
		    def("MixedTypeAnnotation")
		        .bases("FlowType")
		        .build();
		    def("VoidTypeAnnotation")
		        .bases("FlowType")
		        .build();
		    def("NumberTypeAnnotation")
		        .bases("FlowType")
		        .build();
		    def("NumberLiteralTypeAnnotation")
		        .bases("FlowType")
		        .build("value", "raw")
		        .field("value", Number)
		        .field("raw", String);
		    def("NumericLiteralTypeAnnotation")
		        .bases("FlowType")
		        .build("value", "raw")
		        .field("value", Number)
		        .field("raw", String);
		    def("StringTypeAnnotation")
		        .bases("FlowType")
		        .build();
		    def("StringLiteralTypeAnnotation")
		        .bases("FlowType")
		        .build("value", "raw")
		        .field("value", String)
		        .field("raw", String);
		    def("BooleanTypeAnnotation")
		        .bases("FlowType")
		        .build();
		    def("BooleanLiteralTypeAnnotation")
		        .bases("FlowType")
		        .build("value", "raw")
		        .field("value", Boolean)
		        .field("raw", String);
		    def("TypeAnnotation")
		        .bases("Node")
		        .build("typeAnnotation")
		        .field("typeAnnotation", def("FlowType"));
		    def("NullableTypeAnnotation")
		        .bases("FlowType")
		        .build("typeAnnotation")
		        .field("typeAnnotation", def("FlowType"));
		    def("NullLiteralTypeAnnotation")
		        .bases("FlowType")
		        .build();
		    def("NullTypeAnnotation")
		        .bases("FlowType")
		        .build();
		    def("ThisTypeAnnotation")
		        .bases("FlowType")
		        .build();
		    def("ExistsTypeAnnotation")
		        .bases("FlowType")
		        .build();
		    def("ExistentialTypeParam")
		        .bases("FlowType")
		        .build();
		    def("FunctionTypeAnnotation")
		        .bases("FlowType")
		        .build("params", "returnType", "rest", "typeParameters")
		        .field("params", [def("FunctionTypeParam")])
		        .field("returnType", def("FlowType"))
		        .field("rest", or(def("FunctionTypeParam"), null))
		        .field("typeParameters", or(def("TypeParameterDeclaration"), null));
		    def("FunctionTypeParam")
		        .bases("Node")
		        .build("name", "typeAnnotation", "optional")
		        .field("name", def("Identifier"))
		        .field("typeAnnotation", def("FlowType"))
		        .field("optional", Boolean);
		    def("ArrayTypeAnnotation")
		        .bases("FlowType")
		        .build("elementType")
		        .field("elementType", def("FlowType"));
		    def("ObjectTypeAnnotation")
		        .bases("FlowType")
		        .build("properties", "indexers", "callProperties")
		        .field("properties", [
		        or(def("ObjectTypeProperty"), def("ObjectTypeSpreadProperty"))
		    ])
		        .field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray)
		        .field("callProperties", [def("ObjectTypeCallProperty")], defaults.emptyArray)
		        .field("inexact", or(Boolean, void 0), defaults["undefined"])
		        .field("exact", Boolean, defaults["false"])
		        .field("internalSlots", [def("ObjectTypeInternalSlot")], defaults.emptyArray);
		    def("Variance")
		        .bases("Node")
		        .build("kind")
		        .field("kind", or("plus", "minus"));
		    var LegacyVariance = or(def("Variance"), "plus", "minus", null);
		    def("ObjectTypeProperty")
		        .bases("Node")
		        .build("key", "value", "optional")
		        .field("key", or(def("Literal"), def("Identifier")))
		        .field("value", def("FlowType"))
		        .field("optional", Boolean)
		        .field("variance", LegacyVariance, defaults["null"]);
		    def("ObjectTypeIndexer")
		        .bases("Node")
		        .build("id", "key", "value")
		        .field("id", def("Identifier"))
		        .field("key", def("FlowType"))
		        .field("value", def("FlowType"))
		        .field("variance", LegacyVariance, defaults["null"]);
		    def("ObjectTypeCallProperty")
		        .bases("Node")
		        .build("value")
		        .field("value", def("FunctionTypeAnnotation"))
		        .field("static", Boolean, defaults["false"]);
		    def("QualifiedTypeIdentifier")
		        .bases("Node")
		        .build("qualification", "id")
		        .field("qualification", or(def("Identifier"), def("QualifiedTypeIdentifier")))
		        .field("id", def("Identifier"));
		    def("GenericTypeAnnotation")
		        .bases("FlowType")
		        .build("id", "typeParameters")
		        .field("id", or(def("Identifier"), def("QualifiedTypeIdentifier")))
		        .field("typeParameters", or(def("TypeParameterInstantiation"), null));
		    def("MemberTypeAnnotation")
		        .bases("FlowType")
		        .build("object", "property")
		        .field("object", def("Identifier"))
		        .field("property", or(def("MemberTypeAnnotation"), def("GenericTypeAnnotation")));
		    def("UnionTypeAnnotation")
		        .bases("FlowType")
		        .build("types")
		        .field("types", [def("FlowType")]);
		    def("IntersectionTypeAnnotation")
		        .bases("FlowType")
		        .build("types")
		        .field("types", [def("FlowType")]);
		    def("TypeofTypeAnnotation")
		        .bases("FlowType")
		        .build("argument")
		        .field("argument", def("FlowType"));
		    def("ObjectTypeSpreadProperty")
		        .bases("Node")
		        .build("argument")
		        .field("argument", def("FlowType"));
		    def("ObjectTypeInternalSlot")
		        .bases("Node")
		        .build("id", "value", "optional", "static", "method")
		        .field("id", def("Identifier"))
		        .field("value", def("FlowType"))
		        .field("optional", Boolean)
		        .field("static", Boolean)
		        .field("method", Boolean);
		    def("TypeParameterDeclaration")
		        .bases("Node")
		        .build("params")
		        .field("params", [def("TypeParameter")]);
		    def("TypeParameterInstantiation")
		        .bases("Node")
		        .build("params")
		        .field("params", [def("FlowType")]);
		    def("TypeParameter")
		        .bases("FlowType")
		        .build("name", "variance", "bound")
		        .field("name", String)
		        .field("variance", LegacyVariance, defaults["null"])
		        .field("bound", or(def("TypeAnnotation"), null), defaults["null"]);
		    def("ClassProperty")
		        .field("variance", LegacyVariance, defaults["null"]);
		    def("ClassImplements")
		        .bases("Node")
		        .build("id")
		        .field("id", def("Identifier"))
		        .field("superClass", or(def("Expression"), null), defaults["null"])
		        .field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]);
		    def("InterfaceTypeAnnotation")
		        .bases("FlowType")
		        .build("body", "extends")
		        .field("body", def("ObjectTypeAnnotation"))
		        .field("extends", or([def("InterfaceExtends")], null), defaults["null"]);
		    def("InterfaceDeclaration")
		        .bases("Declaration")
		        .build("id", "body", "extends")
		        .field("id", def("Identifier"))
		        .field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"])
		        .field("body", def("ObjectTypeAnnotation"))
		        .field("extends", [def("InterfaceExtends")]);
		    def("DeclareInterface")
		        .bases("InterfaceDeclaration")
		        .build("id", "body", "extends");
		    def("InterfaceExtends")
		        .bases("Node")
		        .build("id")
		        .field("id", def("Identifier"))
		        .field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]);
		    def("TypeAlias")
		        .bases("Declaration")
		        .build("id", "typeParameters", "right")
		        .field("id", def("Identifier"))
		        .field("typeParameters", or(def("TypeParameterDeclaration"), null))
		        .field("right", def("FlowType"));
		    def("OpaqueType")
		        .bases("Declaration")
		        .build("id", "typeParameters", "impltype", "supertype")
		        .field("id", def("Identifier"))
		        .field("typeParameters", or(def("TypeParameterDeclaration"), null))
		        .field("impltype", def("FlowType"))
		        .field("supertype", def("FlowType"));
		    def("DeclareTypeAlias")
		        .bases("TypeAlias")
		        .build("id", "typeParameters", "right");
		    def("DeclareOpaqueType")
		        .bases("TypeAlias")
		        .build("id", "typeParameters", "supertype");
		    def("TypeCastExpression")
		        .bases("Expression")
		        .build("expression", "typeAnnotation")
		        .field("expression", def("Expression"))
		        .field("typeAnnotation", def("TypeAnnotation"));
		    def("TupleTypeAnnotation")
		        .bases("FlowType")
		        .build("types")
		        .field("types", [def("FlowType")]);
		    def("DeclareVariable")
		        .bases("Statement")
		        .build("id")
		        .field("id", def("Identifier"));
		    def("DeclareFunction")
		        .bases("Statement")
		        .build("id")
		        .field("id", def("Identifier"));
		    def("DeclareClass")
		        .bases("InterfaceDeclaration")
		        .build("id");
		    def("DeclareModule")
		        .bases("Statement")
		        .build("id", "body")
		        .field("id", or(def("Identifier"), def("Literal")))
		        .field("body", def("BlockStatement"));
		    def("DeclareModuleExports")
		        .bases("Statement")
		        .build("typeAnnotation")
		        .field("typeAnnotation", def("TypeAnnotation"));
		    def("DeclareExportDeclaration")
		        .bases("Declaration")
		        .build("default", "declaration", "specifiers", "source")
		        .field("default", Boolean)
		        .field("declaration", or(def("DeclareVariable"), def("DeclareFunction"), def("DeclareClass"), def("FlowType"),
		    null))
		        .field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray)
		        .field("source", or(def("Literal"), null), defaults["null"]);
		    def("DeclareExportAllDeclaration")
		        .bases("Declaration")
		        .build("source")
		        .field("source", or(def("Literal"), null), defaults["null"]);
		    def("FlowPredicate").bases("Flow");
		    def("InferredPredicate")
		        .bases("FlowPredicate")
		        .build();
		    def("DeclaredPredicate")
		        .bases("FlowPredicate")
		        .build("value")
		        .field("value", def("Expression"));
		    def("CallExpression")
		        .field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]);
		    def("NewExpression")
		        .field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]);
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (flow, flow.exports));
	return flow.exports;
}

var esprima = {exports: {}};

var hasRequiredEsprima;

function requireEsprima () {
	if (hasRequiredEsprima) return esprima.exports;
	hasRequiredEsprima = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var es7_1 = tslib_1.__importDefault(requireEs7());
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var shared_1 = tslib_1.__importDefault(requireShared());
		function default_1(fork) {
		    fork.use(es7_1.default);
		    var types = fork.use(types_1.default);
		    var defaults = fork.use(shared_1.default).defaults;
		    var def = types.Type.def;
		    var or = types.Type.or;
		    def("VariableDeclaration")
		        .field("declarations", [or(def("VariableDeclarator"), def("Identifier")
		        )]);
		    def("Property")
		        .field("value", or(def("Expression"), def("Pattern")
		    ));
		    def("ArrayPattern")
		        .field("elements", [or(def("Pattern"), def("SpreadElement"), null)]);
		    def("ObjectPattern")
		        .field("properties", [or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"), def("SpreadProperty")
		        )]);
		    def("ExportSpecifier")
		        .bases("ModuleSpecifier")
		        .build("id", "name");
		    def("ExportBatchSpecifier")
		        .bases("Specifier")
		        .build();
		    def("ExportDeclaration")
		        .bases("Declaration")
		        .build("default", "declaration", "specifiers", "source")
		        .field("default", Boolean)
		        .field("declaration", or(def("Declaration"), def("Expression"),
		    null))
		        .field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray)
		        .field("source", or(def("Literal"), null), defaults["null"]);
		    def("Block")
		        .bases("Comment")
		        .build("value",  "leading", "trailing");
		    def("Line")
		        .bases("Comment")
		        .build("value",  "leading", "trailing");
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (esprima, esprima.exports));
	return esprima.exports;
}

var babel = {exports: {}};

var babelCore = {exports: {}};

var hasRequiredBabelCore;

function requireBabelCore () {
	if (hasRequiredBabelCore) return babelCore.exports;
	hasRequiredBabelCore = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var shared_1 = tslib_1.__importDefault(requireShared());
		var es7_1 = tslib_1.__importDefault(requireEs7());
		function default_1(fork) {
		    fork.use(es7_1.default);
		    var types = fork.use(types_1.default);
		    var defaults = fork.use(shared_1.default).defaults;
		    var def = types.Type.def;
		    var or = types.Type.or;
		    def("Noop")
		        .bases("Statement")
		        .build();
		    def("DoExpression")
		        .bases("Expression")
		        .build("body")
		        .field("body", [def("Statement")]);
		    def("Super")
		        .bases("Expression")
		        .build();
		    def("BindExpression")
		        .bases("Expression")
		        .build("object", "callee")
		        .field("object", or(def("Expression"), null))
		        .field("callee", def("Expression"));
		    def("Decorator")
		        .bases("Node")
		        .build("expression")
		        .field("expression", def("Expression"));
		    def("Property")
		        .field("decorators", or([def("Decorator")], null), defaults["null"]);
		    def("MethodDefinition")
		        .field("decorators", or([def("Decorator")], null), defaults["null"]);
		    def("MetaProperty")
		        .bases("Expression")
		        .build("meta", "property")
		        .field("meta", def("Identifier"))
		        .field("property", def("Identifier"));
		    def("ParenthesizedExpression")
		        .bases("Expression")
		        .build("expression")
		        .field("expression", def("Expression"));
		    def("ImportSpecifier")
		        .bases("ModuleSpecifier")
		        .build("imported", "local")
		        .field("imported", def("Identifier"));
		    def("ImportDefaultSpecifier")
		        .bases("ModuleSpecifier")
		        .build("local");
		    def("ImportNamespaceSpecifier")
		        .bases("ModuleSpecifier")
		        .build("local");
		    def("ExportDefaultDeclaration")
		        .bases("Declaration")
		        .build("declaration")
		        .field("declaration", or(def("Declaration"), def("Expression")));
		    def("ExportNamedDeclaration")
		        .bases("Declaration")
		        .build("declaration", "specifiers", "source")
		        .field("declaration", or(def("Declaration"), null))
		        .field("specifiers", [def("ExportSpecifier")], defaults.emptyArray)
		        .field("source", or(def("Literal"), null), defaults["null"]);
		    def("ExportSpecifier")
		        .bases("ModuleSpecifier")
		        .build("local", "exported")
		        .field("exported", def("Identifier"));
		    def("ExportNamespaceSpecifier")
		        .bases("Specifier")
		        .build("exported")
		        .field("exported", def("Identifier"));
		    def("ExportDefaultSpecifier")
		        .bases("Specifier")
		        .build("exported")
		        .field("exported", def("Identifier"));
		    def("ExportAllDeclaration")
		        .bases("Declaration")
		        .build("exported", "source")
		        .field("exported", or(def("Identifier"), null))
		        .field("source", def("Literal"));
		    def("CommentBlock")
		        .bases("Comment")
		        .build("value",  "leading", "trailing");
		    def("CommentLine")
		        .bases("Comment")
		        .build("value",  "leading", "trailing");
		    def("Directive")
		        .bases("Node")
		        .build("value")
		        .field("value", def("DirectiveLiteral"));
		    def("DirectiveLiteral")
		        .bases("Node", "Expression")
		        .build("value")
		        .field("value", String, defaults["use strict"]);
		    def("InterpreterDirective")
		        .bases("Node")
		        .build("value")
		        .field("value", String);
		    def("BlockStatement")
		        .bases("Statement")
		        .build("body")
		        .field("body", [def("Statement")])
		        .field("directives", [def("Directive")], defaults.emptyArray);
		    def("Program")
		        .bases("Node")
		        .build("body")
		        .field("body", [def("Statement")])
		        .field("directives", [def("Directive")], defaults.emptyArray)
		        .field("interpreter", or(def("InterpreterDirective"), null), defaults["null"]);
		    def("StringLiteral")
		        .bases("Literal")
		        .build("value")
		        .field("value", String);
		    def("NumericLiteral")
		        .bases("Literal")
		        .build("value")
		        .field("value", Number)
		        .field("raw", or(String, null), defaults["null"])
		        .field("extra", {
		        rawValue: Number,
		        raw: String
		    }, function getDefault() {
		        return {
		            rawValue: this.value,
		            raw: this.value + ""
		        };
		    });
		    def("BigIntLiteral")
		        .bases("Literal")
		        .build("value")
		        .field("value", or(String, Number))
		        .field("extra", {
		        rawValue: String,
		        raw: String
		    }, function getDefault() {
		        return {
		            rawValue: String(this.value),
		            raw: this.value + "n"
		        };
		    });
		    def("NullLiteral")
		        .bases("Literal")
		        .build()
		        .field("value", null, defaults["null"]);
		    def("BooleanLiteral")
		        .bases("Literal")
		        .build("value")
		        .field("value", Boolean);
		    def("RegExpLiteral")
		        .bases("Literal")
		        .build("pattern", "flags")
		        .field("pattern", String)
		        .field("flags", String)
		        .field("value", RegExp, function () {
		        return new RegExp(this.pattern, this.flags);
		    });
		    var ObjectExpressionProperty = or(def("Property"), def("ObjectMethod"), def("ObjectProperty"), def("SpreadProperty"), def("SpreadElement"));
		    def("ObjectExpression")
		        .bases("Expression")
		        .build("properties")
		        .field("properties", [ObjectExpressionProperty]);
		    def("ObjectMethod")
		        .bases("Node", "Function")
		        .build("kind", "key", "params", "body", "computed")
		        .field("kind", or("method", "get", "set"))
		        .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
		        .field("params", [def("Pattern")])
		        .field("body", def("BlockStatement"))
		        .field("computed", Boolean, defaults["false"])
		        .field("generator", Boolean, defaults["false"])
		        .field("async", Boolean, defaults["false"])
		        .field("accessibility",
		    or(def("Literal"), null), defaults["null"])
		        .field("decorators", or([def("Decorator")], null), defaults["null"]);
		    def("ObjectProperty")
		        .bases("Node")
		        .build("key", "value")
		        .field("key", or(def("Literal"), def("Identifier"), def("Expression")))
		        .field("value", or(def("Expression"), def("Pattern")))
		        .field("accessibility",
		    or(def("Literal"), null), defaults["null"])
		        .field("computed", Boolean, defaults["false"]);
		    var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("ClassPrivateProperty"), def("ClassMethod"), def("ClassPrivateMethod"));
		    def("ClassBody")
		        .bases("Declaration")
		        .build("body")
		        .field("body", [ClassBodyElement]);
		    def("ClassMethod")
		        .bases("Declaration", "Function")
		        .build("kind", "key", "params", "body", "computed", "static")
		        .field("key", or(def("Literal"), def("Identifier"), def("Expression")));
		    def("ClassPrivateMethod")
		        .bases("Declaration", "Function")
		        .build("key", "params", "body", "kind", "computed", "static")
		        .field("key", def("PrivateName"));
		    ["ClassMethod",
		        "ClassPrivateMethod",
		    ].forEach(function (typeName) {
		        def(typeName)
		            .field("kind", or("get", "set", "method", "constructor"), function () { return "method"; })
		            .field("body", def("BlockStatement"))
		            .field("computed", Boolean, defaults["false"])
		            .field("static", or(Boolean, null), defaults["null"])
		            .field("abstract", or(Boolean, null), defaults["null"])
		            .field("access", or("public", "private", "protected", null), defaults["null"])
		            .field("accessibility", or("public", "private", "protected", null), defaults["null"])
		            .field("decorators", or([def("Decorator")], null), defaults["null"])
		            .field("optional", or(Boolean, null), defaults["null"]);
		    });
		    def("ClassPrivateProperty")
		        .bases("ClassProperty")
		        .build("key", "value")
		        .field("key", def("PrivateName"))
		        .field("value", or(def("Expression"), null), defaults["null"]);
		    def("PrivateName")
		        .bases("Expression", "Pattern")
		        .build("id")
		        .field("id", def("Identifier"));
		    var ObjectPatternProperty = or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"), def("SpreadProperty"),
		    def("ObjectProperty"),
		    def("RestProperty")
		    );
		    def("ObjectPattern")
		        .bases("Pattern")
		        .build("properties")
		        .field("properties", [ObjectPatternProperty])
		        .field("decorators", or([def("Decorator")], null), defaults["null"]);
		    def("SpreadProperty")
		        .bases("Node")
		        .build("argument")
		        .field("argument", def("Expression"));
		    def("RestProperty")
		        .bases("Node")
		        .build("argument")
		        .field("argument", def("Expression"));
		    def("ForAwaitStatement")
		        .bases("Statement")
		        .build("left", "right", "body")
		        .field("left", or(def("VariableDeclaration"), def("Expression")))
		        .field("right", def("Expression"))
		        .field("body", def("Statement"));
		    def("Import")
		        .bases("Expression")
		        .build();
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (babelCore, babelCore.exports));
	return babelCore.exports;
}

var hasRequiredBabel;

function requireBabel () {
	if (hasRequiredBabel) return babel.exports;
	hasRequiredBabel = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var babel_core_1 = tslib_1.__importDefault(requireBabelCore());
		var flow_1 = tslib_1.__importDefault(requireFlow());
		function default_1(fork) {
		    fork.use(babel_core_1.default);
		    fork.use(flow_1.default);
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (babel, babel.exports));
	return babel.exports;
}

var typescript = {exports: {}};

var hasRequiredTypescript;

function requireTypescript () {
	if (hasRequiredTypescript) return typescript.exports;
	hasRequiredTypescript = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var babel_core_1 = tslib_1.__importDefault(requireBabelCore());
		var type_annotations_1 = tslib_1.__importDefault(requireTypeAnnotations());
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var shared_1 = tslib_1.__importDefault(requireShared());
		function default_1(fork) {
		    fork.use(babel_core_1.default);
		    fork.use(type_annotations_1.default);
		    var types = fork.use(types_1.default);
		    var n = types.namedTypes;
		    var def = types.Type.def;
		    var or = types.Type.or;
		    var defaults = fork.use(shared_1.default).defaults;
		    var StringLiteral = types.Type.from(function (value, deep) {
		        if (n.StringLiteral &&
		            n.StringLiteral.check(value, deep)) {
		            return true;
		        }
		        if (n.Literal &&
		            n.Literal.check(value, deep) &&
		            typeof value.value === "string") {
		            return true;
		        }
		        return false;
		    }, "StringLiteral");
		    def("TSType")
		        .bases("Node");
		    var TSEntityName = or(def("Identifier"), def("TSQualifiedName"));
		    def("TSTypeReference")
		        .bases("TSType", "TSHasOptionalTypeParameterInstantiation")
		        .build("typeName", "typeParameters")
		        .field("typeName", TSEntityName);
		    def("TSHasOptionalTypeParameterInstantiation")
		        .field("typeParameters", or(def("TSTypeParameterInstantiation"), null), defaults["null"]);
		    def("TSHasOptionalTypeParameters")
		        .field("typeParameters", or(def("TSTypeParameterDeclaration"), null, void 0), defaults["null"]);
		    def("TSHasOptionalTypeAnnotation")
		        .field("typeAnnotation", or(def("TSTypeAnnotation"), null), defaults["null"]);
		    def("TSQualifiedName")
		        .bases("Node")
		        .build("left", "right")
		        .field("left", TSEntityName)
		        .field("right", TSEntityName);
		    def("TSAsExpression")
		        .bases("Expression", "Pattern")
		        .build("expression", "typeAnnotation")
		        .field("expression", def("Expression"))
		        .field("typeAnnotation", def("TSType"))
		        .field("extra", or({ parenthesized: Boolean }, null), defaults["null"]);
		    def("TSNonNullExpression")
		        .bases("Expression", "Pattern")
		        .build("expression")
		        .field("expression", def("Expression"));
		    [
		        "TSAnyKeyword",
		        "TSBigIntKeyword",
		        "TSBooleanKeyword",
		        "TSNeverKeyword",
		        "TSNullKeyword",
		        "TSNumberKeyword",
		        "TSObjectKeyword",
		        "TSStringKeyword",
		        "TSSymbolKeyword",
		        "TSUndefinedKeyword",
		        "TSUnknownKeyword",
		        "TSVoidKeyword",
		        "TSThisType",
		    ].forEach(function (keywordType) {
		        def(keywordType)
		            .bases("TSType")
		            .build();
		    });
		    def("TSArrayType")
		        .bases("TSType")
		        .build("elementType")
		        .field("elementType", def("TSType"));
		    def("TSLiteralType")
		        .bases("TSType")
		        .build("literal")
		        .field("literal", or(def("NumericLiteral"), def("StringLiteral"), def("BooleanLiteral"), def("TemplateLiteral"), def("UnaryExpression")));
		    ["TSUnionType",
		        "TSIntersectionType",
		    ].forEach(function (typeName) {
		        def(typeName)
		            .bases("TSType")
		            .build("types")
		            .field("types", [def("TSType")]);
		    });
		    def("TSConditionalType")
		        .bases("TSType")
		        .build("checkType", "extendsType", "trueType", "falseType")
		        .field("checkType", def("TSType"))
		        .field("extendsType", def("TSType"))
		        .field("trueType", def("TSType"))
		        .field("falseType", def("TSType"));
		    def("TSInferType")
		        .bases("TSType")
		        .build("typeParameter")
		        .field("typeParameter", def("TSTypeParameter"));
		    def("TSParenthesizedType")
		        .bases("TSType")
		        .build("typeAnnotation")
		        .field("typeAnnotation", def("TSType"));
		    var ParametersType = [or(def("Identifier"), def("RestElement"), def("ArrayPattern"), def("ObjectPattern"))];
		    ["TSFunctionType",
		        "TSConstructorType",
		    ].forEach(function (typeName) {
		        def(typeName)
		            .bases("TSType", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation")
		            .build("parameters")
		            .field("parameters", ParametersType);
		    });
		    def("TSDeclareFunction")
		        .bases("Declaration", "TSHasOptionalTypeParameters")
		        .build("id", "params", "returnType")
		        .field("declare", Boolean, defaults["false"])
		        .field("async", Boolean, defaults["false"])
		        .field("generator", Boolean, defaults["false"])
		        .field("id", or(def("Identifier"), null), defaults["null"])
		        .field("params", [def("Pattern")])
		        .field("returnType", or(def("TSTypeAnnotation"), def("Noop"),
		    null), defaults["null"]);
		    def("TSDeclareMethod")
		        .bases("Declaration", "TSHasOptionalTypeParameters")
		        .build("key", "params", "returnType")
		        .field("async", Boolean, defaults["false"])
		        .field("generator", Boolean, defaults["false"])
		        .field("params", [def("Pattern")])
		        .field("abstract", Boolean, defaults["false"])
		        .field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"])
		        .field("static", Boolean, defaults["false"])
		        .field("computed", Boolean, defaults["false"])
		        .field("optional", Boolean, defaults["false"])
		        .field("key", or(def("Identifier"), def("StringLiteral"), def("NumericLiteral"),
		    def("Expression")))
		        .field("kind", or("get", "set", "method", "constructor"), function getDefault() { return "method"; })
		        .field("access",
		    or("public", "private", "protected", void 0), defaults["undefined"])
		        .field("decorators", or([def("Decorator")], null), defaults["null"])
		        .field("returnType", or(def("TSTypeAnnotation"), def("Noop"),
		    null), defaults["null"]);
		    def("TSMappedType")
		        .bases("TSType")
		        .build("typeParameter", "typeAnnotation")
		        .field("readonly", or(Boolean, "+", "-"), defaults["false"])
		        .field("typeParameter", def("TSTypeParameter"))
		        .field("optional", or(Boolean, "+", "-"), defaults["false"])
		        .field("typeAnnotation", or(def("TSType"), null), defaults["null"]);
		    def("TSTupleType")
		        .bases("TSType")
		        .build("elementTypes")
		        .field("elementTypes", [or(def("TSType"), def("TSNamedTupleMember"))]);
		    def("TSNamedTupleMember")
		        .bases("TSType")
		        .build("label", "elementType", "optional")
		        .field("label", def("Identifier"))
		        .field("optional", Boolean, defaults["false"])
		        .field("elementType", def("TSType"));
		    def("TSRestType")
		        .bases("TSType")
		        .build("typeAnnotation")
		        .field("typeAnnotation", def("TSType"));
		    def("TSOptionalType")
		        .bases("TSType")
		        .build("typeAnnotation")
		        .field("typeAnnotation", def("TSType"));
		    def("TSIndexedAccessType")
		        .bases("TSType")
		        .build("objectType", "indexType")
		        .field("objectType", def("TSType"))
		        .field("indexType", def("TSType"));
		    def("TSTypeOperator")
		        .bases("TSType")
		        .build("operator")
		        .field("operator", String)
		        .field("typeAnnotation", def("TSType"));
		    def("TSTypeAnnotation")
		        .bases("Node")
		        .build("typeAnnotation")
		        .field("typeAnnotation", or(def("TSType"), def("TSTypeAnnotation")));
		    def("TSIndexSignature")
		        .bases("Declaration", "TSHasOptionalTypeAnnotation")
		        .build("parameters", "typeAnnotation")
		        .field("parameters", [def("Identifier")])
		        .field("readonly", Boolean, defaults["false"]);
		    def("TSPropertySignature")
		        .bases("Declaration", "TSHasOptionalTypeAnnotation")
		        .build("key", "typeAnnotation", "optional")
		        .field("key", def("Expression"))
		        .field("computed", Boolean, defaults["false"])
		        .field("readonly", Boolean, defaults["false"])
		        .field("optional", Boolean, defaults["false"])
		        .field("initializer", or(def("Expression"), null), defaults["null"]);
		    def("TSMethodSignature")
		        .bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation")
		        .build("key", "parameters", "typeAnnotation")
		        .field("key", def("Expression"))
		        .field("computed", Boolean, defaults["false"])
		        .field("optional", Boolean, defaults["false"])
		        .field("parameters", ParametersType);
		    def("TSTypePredicate")
		        .bases("TSTypeAnnotation", "TSType")
		        .build("parameterName", "typeAnnotation", "asserts")
		        .field("parameterName", or(def("Identifier"), def("TSThisType")))
		        .field("typeAnnotation", or(def("TSTypeAnnotation"), null), defaults["null"])
		        .field("asserts", Boolean, defaults["false"]);
		    ["TSCallSignatureDeclaration",
		        "TSConstructSignatureDeclaration",
		    ].forEach(function (typeName) {
		        def(typeName)
		            .bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation")
		            .build("parameters", "typeAnnotation")
		            .field("parameters", ParametersType);
		    });
		    def("TSEnumMember")
		        .bases("Node")
		        .build("id", "initializer")
		        .field("id", or(def("Identifier"), StringLiteral))
		        .field("initializer", or(def("Expression"), null), defaults["null"]);
		    def("TSTypeQuery")
		        .bases("TSType")
		        .build("exprName")
		        .field("exprName", or(TSEntityName, def("TSImportType")));
		    var TSTypeMember = or(def("TSCallSignatureDeclaration"), def("TSConstructSignatureDeclaration"), def("TSIndexSignature"), def("TSMethodSignature"), def("TSPropertySignature"));
		    def("TSTypeLiteral")
		        .bases("TSType")
		        .build("members")
		        .field("members", [TSTypeMember]);
		    def("TSTypeParameter")
		        .bases("Identifier")
		        .build("name", "constraint", "default")
		        .field("name", String)
		        .field("constraint", or(def("TSType"), void 0), defaults["undefined"])
		        .field("default", or(def("TSType"), void 0), defaults["undefined"]);
		    def("TSTypeAssertion")
		        .bases("Expression", "Pattern")
		        .build("typeAnnotation", "expression")
		        .field("typeAnnotation", def("TSType"))
		        .field("expression", def("Expression"))
		        .field("extra", or({ parenthesized: Boolean }, null), defaults["null"]);
		    def("TSTypeParameterDeclaration")
		        .bases("Declaration")
		        .build("params")
		        .field("params", [def("TSTypeParameter")]);
		    def("TSTypeParameterInstantiation")
		        .bases("Node")
		        .build("params")
		        .field("params", [def("TSType")]);
		    def("TSEnumDeclaration")
		        .bases("Declaration")
		        .build("id", "members")
		        .field("id", def("Identifier"))
		        .field("const", Boolean, defaults["false"])
		        .field("declare", Boolean, defaults["false"])
		        .field("members", [def("TSEnumMember")])
		        .field("initializer", or(def("Expression"), null), defaults["null"]);
		    def("TSTypeAliasDeclaration")
		        .bases("Declaration", "TSHasOptionalTypeParameters")
		        .build("id", "typeAnnotation")
		        .field("id", def("Identifier"))
		        .field("declare", Boolean, defaults["false"])
		        .field("typeAnnotation", def("TSType"));
		    def("TSModuleBlock")
		        .bases("Node")
		        .build("body")
		        .field("body", [def("Statement")]);
		    def("TSModuleDeclaration")
		        .bases("Declaration")
		        .build("id", "body")
		        .field("id", or(StringLiteral, TSEntityName))
		        .field("declare", Boolean, defaults["false"])
		        .field("global", Boolean, defaults["false"])
		        .field("body", or(def("TSModuleBlock"), def("TSModuleDeclaration"), null), defaults["null"]);
		    def("TSImportType")
		        .bases("TSType", "TSHasOptionalTypeParameterInstantiation")
		        .build("argument", "qualifier", "typeParameters")
		        .field("argument", StringLiteral)
		        .field("qualifier", or(TSEntityName, void 0), defaults["undefined"]);
		    def("TSImportEqualsDeclaration")
		        .bases("Declaration")
		        .build("id", "moduleReference")
		        .field("id", def("Identifier"))
		        .field("isExport", Boolean, defaults["false"])
		        .field("moduleReference", or(TSEntityName, def("TSExternalModuleReference")));
		    def("TSExternalModuleReference")
		        .bases("Declaration")
		        .build("expression")
		        .field("expression", StringLiteral);
		    def("TSExportAssignment")
		        .bases("Statement")
		        .build("expression")
		        .field("expression", def("Expression"));
		    def("TSNamespaceExportDeclaration")
		        .bases("Declaration")
		        .build("id")
		        .field("id", def("Identifier"));
		    def("TSInterfaceBody")
		        .bases("Node")
		        .build("body")
		        .field("body", [TSTypeMember]);
		    def("TSExpressionWithTypeArguments")
		        .bases("TSType", "TSHasOptionalTypeParameterInstantiation")
		        .build("expression", "typeParameters")
		        .field("expression", TSEntityName);
		    def("TSInterfaceDeclaration")
		        .bases("Declaration", "TSHasOptionalTypeParameters")
		        .build("id", "body")
		        .field("id", TSEntityName)
		        .field("declare", Boolean, defaults["false"])
		        .field("extends", or([def("TSExpressionWithTypeArguments")], null), defaults["null"])
		        .field("body", def("TSInterfaceBody"));
		    def("TSParameterProperty")
		        .bases("Pattern")
		        .build("parameter")
		        .field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"])
		        .field("readonly", Boolean, defaults["false"])
		        .field("parameter", or(def("Identifier"), def("AssignmentPattern")));
		    def("ClassProperty")
		        .field("access",
		    or("public", "private", "protected", void 0), defaults["undefined"]);
		    def("ClassBody")
		        .field("body", [or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("ClassPrivateProperty"), def("ClassMethod"), def("ClassPrivateMethod"),
		        def("TSDeclareMethod"), TSTypeMember)]);
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (typescript, typescript.exports));
	return typescript.exports;
}

var esProposals = {exports: {}};

var hasRequiredEsProposals;

function requireEsProposals () {
	if (hasRequiredEsProposals) return esProposals.exports;
	hasRequiredEsProposals = 1;
	(function (module, exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		var tslib_1 = require$$0;
		var types_1 = tslib_1.__importDefault(requireTypes$1());
		var shared_1 = tslib_1.__importDefault(requireShared());
		var core_1 = tslib_1.__importDefault(requireCore());
		function default_1(fork) {
		    fork.use(core_1.default);
		    var types = fork.use(types_1.default);
		    var Type = types.Type;
		    var def = types.Type.def;
		    var or = Type.or;
		    var shared = fork.use(shared_1.default);
		    var defaults = shared.defaults;
		    def("OptionalMemberExpression")
		        .bases("MemberExpression")
		        .build("object", "property", "computed", "optional")
		        .field("optional", Boolean, defaults["true"]);
		    def("OptionalCallExpression")
		        .bases("CallExpression")
		        .build("callee", "arguments", "optional")
		        .field("optional", Boolean, defaults["true"]);
		    var LogicalOperator = or("||", "&&", "??");
		    def("LogicalExpression")
		        .field("operator", LogicalOperator);
		}
		exports$1.default = default_1;
		module.exports = exports$1["default"]; 
	} (esProposals, esProposals.exports));
	return esProposals.exports;
}

var namedTypes = {};

var hasRequiredNamedTypes;

function requireNamedTypes () {
	if (hasRequiredNamedTypes) return namedTypes;
	hasRequiredNamedTypes = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.namedTypes = void 0;
		(function (namedTypes) {
		})(exports$1.namedTypes || (exports$1.namedTypes = {})); 
	} (namedTypes));
	return namedTypes;
}

var hasRequiredMain;

function requireMain () {
	if (hasRequiredMain) return main$1;
	hasRequiredMain = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.visit = exports$1.use = exports$1.Type = exports$1.someField = exports$1.PathVisitor = exports$1.Path = exports$1.NodePath = exports$1.namedTypes = exports$1.getSupertypeNames = exports$1.getFieldValue = exports$1.getFieldNames = exports$1.getBuilderName = exports$1.finalize = exports$1.eachField = exports$1.defineMethod = exports$1.builtInTypes = exports$1.builders = exports$1.astNodesAreEquivalent = void 0;
		var tslib_1 = require$$0;
		var fork_1 = tslib_1.__importDefault(requireFork());
		var core_1 = tslib_1.__importDefault(requireCore());
		var es6_1 = tslib_1.__importDefault(requireEs6());
		var es7_1 = tslib_1.__importDefault(requireEs7());
		var es2020_1 = tslib_1.__importDefault(requireEs2020());
		var jsx_1 = tslib_1.__importDefault(requireJsx());
		var flow_1 = tslib_1.__importDefault(requireFlow());
		var esprima_1 = tslib_1.__importDefault(requireEsprima());
		var babel_1 = tslib_1.__importDefault(requireBabel());
		var typescript_1 = tslib_1.__importDefault(requireTypescript());
		var es_proposals_1 = tslib_1.__importDefault(requireEsProposals());
		var namedTypes_1 = requireNamedTypes();
		Object.defineProperty(exports$1, "namedTypes", { enumerable: true, get: function () { return namedTypes_1.namedTypes; } });
		var _a = fork_1.default([
		    core_1.default,
		    es6_1.default,
		    es7_1.default,
		    es2020_1.default,
		    jsx_1.default,
		    flow_1.default,
		    esprima_1.default,
		    babel_1.default,
		    typescript_1.default,
		    es_proposals_1.default,
		]), astNodesAreEquivalent = _a.astNodesAreEquivalent, builders = _a.builders, builtInTypes = _a.builtInTypes, defineMethod = _a.defineMethod, eachField = _a.eachField, finalize = _a.finalize, getBuilderName = _a.getBuilderName, getFieldNames = _a.getFieldNames, getFieldValue = _a.getFieldValue, getSupertypeNames = _a.getSupertypeNames, n = _a.namedTypes, NodePath = _a.NodePath, Path = _a.Path, PathVisitor = _a.PathVisitor, someField = _a.someField, Type = _a.Type, use = _a.use, visit = _a.visit;
		exports$1.astNodesAreEquivalent = astNodesAreEquivalent;
		exports$1.builders = builders;
		exports$1.builtInTypes = builtInTypes;
		exports$1.defineMethod = defineMethod;
		exports$1.eachField = eachField;
		exports$1.finalize = finalize;
		exports$1.getBuilderName = getBuilderName;
		exports$1.getFieldNames = getFieldNames;
		exports$1.getFieldValue = getFieldValue;
		exports$1.getSupertypeNames = getSupertypeNames;
		exports$1.NodePath = NodePath;
		exports$1.Path = Path;
		exports$1.PathVisitor = PathVisitor;
		exports$1.someField = someField;
		exports$1.Type = Type;
		exports$1.use = use;
		exports$1.visit = visit;
		Object.assign(namedTypes_1.namedTypes, n); 
	} (main$1));
	return main$1;
}

var hasRequiredDegenerator;

function requireDegenerator () {
	if (hasRequiredDegenerator) return degenerator;
	hasRequiredDegenerator = 1;
	Object.defineProperty(degenerator, "__esModule", { value: true });
	degenerator.degenerator = void 0;
	const util_1 = require$$0$2;
	const escodegen_1 = requireEscodegen();
	const esprima_1 = requireEsprima$1();
	const ast_types_1 = requireMain();
	function degenerator$1(code, _names) {
	    if (!Array.isArray(_names)) {
	        throw new TypeError('an array of async function "names" is required');
	    }
	    const names = _names.slice(0);
	    const ast = (0, esprima_1.parseScript)(code);
	    let lastNamesLength = 0;
	    do {
	        lastNamesLength = names.length;
	        (0, ast_types_1.visit)(ast, {
	            visitVariableDeclaration(path) {
	                if (path.node.declarations) {
	                    for (let i = 0; i < path.node.declarations.length; i++) {
	                        const declaration = path.node.declarations[i];
	                        if (ast_types_1.namedTypes.VariableDeclarator.check(declaration) &&
	                            ast_types_1.namedTypes.Identifier.check(declaration.init) &&
	                            ast_types_1.namedTypes.Identifier.check(declaration.id) &&
	                            checkName(declaration.init.name, names) &&
	                            !checkName(declaration.id.name, names)) {
	                            names.push(declaration.id.name);
	                        }
	                    }
	                }
	                return false;
	            },
	            visitAssignmentExpression(path) {
	                if (ast_types_1.namedTypes.Identifier.check(path.node.left) &&
	                    ast_types_1.namedTypes.Identifier.check(path.node.right) &&
	                    checkName(path.node.right.name, names) &&
	                    !checkName(path.node.left.name, names)) {
	                    names.push(path.node.left.name);
	                }
	                return false;
	            },
	            visitFunction(path) {
	                if (path.node.id) {
	                    let shouldDegenerate = false;
	                    (0, ast_types_1.visit)(path.node, {
	                        visitCallExpression(path) {
	                            if (checkNames(path.node, names)) {
	                                shouldDegenerate = true;
	                            }
	                            return false;
	                        },
	                    });
	                    if (!shouldDegenerate) {
	                        return false;
	                    }
	                    path.node.async = true;
	                    if (!checkName(path.node.id.name, names)) {
	                        names.push(path.node.id.name);
	                    }
	                }
	                this.traverse(path);
	            },
	        });
	    } while (lastNamesLength !== names.length);
	    (0, ast_types_1.visit)(ast, {
	        visitCallExpression(path) {
	            if (checkNames(path.node, names)) {
	                const delegate = false;
	                const { name, parent: { node: pNode }, } = path;
	                const expr = ast_types_1.builders.awaitExpression(path.node, delegate);
	                if (ast_types_1.namedTypes.CallExpression.check(pNode)) {
	                    pNode.arguments[name] = expr;
	                }
	                else {
	                    pNode[name] = expr;
	                }
	            }
	            this.traverse(path);
	        },
	    });
	    return (0, escodegen_1.generate)(ast);
	}
	degenerator.degenerator = degenerator$1;
	function checkNames({ callee }, names) {
	    let name;
	    if (ast_types_1.namedTypes.Identifier.check(callee)) {
	        name = callee.name;
	    }
	    else if (ast_types_1.namedTypes.MemberExpression.check(callee)) {
	        if (ast_types_1.namedTypes.Identifier.check(callee.object) &&
	            ast_types_1.namedTypes.Identifier.check(callee.property)) {
	            name = `${callee.object.name}.${callee.property.name}`;
	        }
	        else {
	            return false;
	        }
	    }
	    else if (ast_types_1.namedTypes.FunctionExpression.check(callee)) {
	        if (callee.id) {
	            name = callee.id.name;
	        }
	        else {
	            return false;
	        }
	    }
	    else {
	        throw new Error(`Don't know how to get name for: ${callee.type}`);
	    }
	    return checkName(name, names);
	}
	function checkName(name, names) {
	    for (let i = 0; i < names.length; i++) {
	        const n = names[i];
	        if (util_1.types.isRegExp(n)) {
	            if (n.test(name)) {
	                return true;
	            }
	        }
	        else if (name === n) {
	            return true;
	        }
	    }
	    return false;
	}
	return degenerator;
}

var compile = {};

var hasRequiredCompile;

function requireCompile () {
	if (hasRequiredCompile) return compile;
	hasRequiredCompile = 1;
	Object.defineProperty(compile, "__esModule", { value: true });
	compile.compile = void 0;
	const util_1 = require$$0$2;
	const degenerator_1 = requireDegenerator();
	function compile$1(qjs, code, returnName, options = {}) {
	    const compiled = (0, degenerator_1.degenerator)(code, options.names ?? []);
	    const vm = qjs.newContext();
	    if (options.sandbox) {
	        for (const [name, value] of Object.entries(options.sandbox)) {
	            if (typeof value !== 'function') {
	                throw new Error(`Expected a "function" for sandbox property \`${name}\`, but got "${typeof value}"`);
	            }
	            const fnHandle = vm.newFunction(name, (...args) => {
	                const result = value(...args.map((arg) => quickJSHandleToHost(vm, arg)));
	                vm.runtime.executePendingJobs();
	                return hostToQuickJSHandle(vm, result);
	            });
	            fnHandle.consume((handle) => vm.setProp(vm.global, name, handle));
	        }
	    }
	    const fnResult = vm.evalCode(`${compiled};${returnName}`, options.filename);
	    const fn = vm.unwrapResult(fnResult);
	    const t = vm.typeof(fn);
	    if (t !== 'function') {
	        throw new Error(`Expected a "function" named \`${returnName}\` to be defined, but got "${t}"`);
	    }
	    const r = async function (...args) {
	        let promiseHandle;
	        let resolvedHandle;
	        try {
	            const result = vm.callFunction(fn, vm.undefined, ...args.map((arg) => hostToQuickJSHandle(vm, arg)));
	            promiseHandle = vm.unwrapResult(result);
	            const resolvedResultP = vm.resolvePromise(promiseHandle);
	            vm.runtime.executePendingJobs();
	            const resolvedResult = await resolvedResultP;
	            resolvedHandle = vm.unwrapResult(resolvedResult);
	            return quickJSHandleToHost(vm, resolvedHandle);
	        }
	        catch (err) {
	            if (err && typeof err === 'object' && 'cause' in err && err.cause) {
	                if (typeof err.cause === 'object' &&
	                    'stack' in err.cause &&
	                    'name' in err.cause &&
	                    'message' in err.cause &&
	                    typeof err.cause.stack === 'string' &&
	                    typeof err.cause.name === 'string' &&
	                    typeof err.cause.message === 'string') {
	                    err.cause.stack = `${err.cause.name}: ${err.cause.message}\n${err.cause.stack}`;
	                }
	                throw err.cause;
	            }
	            throw err;
	        }
	        finally {
	            promiseHandle?.dispose();
	            resolvedHandle?.dispose();
	        }
	    };
	    Object.defineProperty(r, 'toString', {
	        value: () => compiled,
	        enumerable: false,
	    });
	    return r;
	}
	compile.compile = compile$1;
	function quickJSHandleToHost(vm, val) {
	    return vm.dump(val);
	}
	function hostToQuickJSHandle(vm, val) {
	    if (typeof val === 'undefined') {
	        return vm.undefined;
	    }
	    else if (val === null) {
	        return vm.null;
	    }
	    else if (typeof val === 'string') {
	        return vm.newString(val);
	    }
	    else if (typeof val === 'number') {
	        return vm.newNumber(val);
	    }
	    else if (typeof val === 'bigint') {
	        return vm.newBigInt(val);
	    }
	    else if (typeof val === 'boolean') {
	        return val ? vm.true : vm.false;
	    }
	    else if (util_1.types.isPromise(val)) {
	        const promise = vm.newPromise();
	        promise.settled.then(vm.runtime.executePendingJobs);
	        val.then((r) => {
	            promise.resolve(hostToQuickJSHandle(vm, r));
	        }, (err) => {
	            promise.reject(hostToQuickJSHandle(vm, err));
	        });
	        return promise.handle;
	    }
	    else if (util_1.types.isNativeError(val)) {
	        return vm.newError(val);
	    }
	    throw new Error(`Unsupported value: ${val}`);
	}
	return compile;
}

var hasRequiredDist$4;

function requireDist$4 () {
	if (hasRequiredDist$4) return dist$1;
	hasRequiredDist$4 = 1;
	(function (exports$1) {
		var __createBinding = (dist$1 && dist$1.__createBinding) || (Object.create ? (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    var desc = Object.getOwnPropertyDescriptor(m, k);
		    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
		      desc = { enumerable: true, get: function() { return m[k]; } };
		    }
		    Object.defineProperty(o, k2, desc);
		}) : (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    o[k2] = m[k];
		}));
		var __exportStar = (dist$1 && dist$1.__exportStar) || function(m, exports$1) {
		    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		__exportStar(requireDegenerator(), exports$1);
		__exportStar(requireCompile(), exports$1); 
	} (dist$1));
	return dist$1;
}

var dateRange = {};

var hasRequiredDateRange;

function requireDateRange () {
	if (hasRequiredDateRange) return dateRange;
	hasRequiredDateRange = 1;
	Object.defineProperty(dateRange, "__esModule", { value: true });
	function dateRange$1() {
	    return false;
	}
	dateRange.default = dateRange$1;
	return dateRange;
}

var dnsDomainIs = {};

var hasRequiredDnsDomainIs;

function requireDnsDomainIs () {
	if (hasRequiredDnsDomainIs) return dnsDomainIs;
	hasRequiredDnsDomainIs = 1;
	Object.defineProperty(dnsDomainIs, "__esModule", { value: true });
	function dnsDomainIs$1(host, domain) {
	    host = String(host);
	    domain = String(domain);
	    return host.substr(domain.length * -1) === domain;
	}
	dnsDomainIs.default = dnsDomainIs$1;
	return dnsDomainIs;
}

var dnsDomainLevels = {};

var hasRequiredDnsDomainLevels;

function requireDnsDomainLevels () {
	if (hasRequiredDnsDomainLevels) return dnsDomainLevels;
	hasRequiredDnsDomainLevels = 1;
	Object.defineProperty(dnsDomainLevels, "__esModule", { value: true });
	function dnsDomainLevels$1(host) {
	    const match = String(host).match(/\./g);
	    let levels = 0;
	    if (match) {
	        levels = match.length;
	    }
	    return levels;
	}
	dnsDomainLevels.default = dnsDomainLevels$1;
	return dnsDomainLevels;
}

var dnsResolve = {};

var util = {};

var hasRequiredUtil;

function requireUtil () {
	if (hasRequiredUtil) return util;
	hasRequiredUtil = 1;
	Object.defineProperty(util, "__esModule", { value: true });
	util.isGMT = util.dnsLookup = void 0;
	const dns_1 = require$$3$3;
	function dnsLookup(host, opts) {
	    return new Promise((resolve, reject) => {
	        (0, dns_1.lookup)(host, opts, (err, res) => {
	            if (err) {
	                reject(err);
	            }
	            else {
	                resolve(res);
	            }
	        });
	    });
	}
	util.dnsLookup = dnsLookup;
	function isGMT(v) {
	    return v === 'GMT';
	}
	util.isGMT = isGMT;
	return util;
}

var hasRequiredDnsResolve;

function requireDnsResolve () {
	if (hasRequiredDnsResolve) return dnsResolve;
	hasRequiredDnsResolve = 1;
	Object.defineProperty(dnsResolve, "__esModule", { value: true });
	const util_1 = requireUtil();
	async function dnsResolve$1(host) {
	    const family = 4;
	    try {
	        const r = await (0, util_1.dnsLookup)(host, { family });
	        if (typeof r === 'string') {
	            return r;
	        }
	    }
	    catch (err) {
	    }
	    return null;
	}
	dnsResolve.default = dnsResolve$1;
	return dnsResolve;
}

var isInNet = {};

var netmask = {};

var hasRequiredNetmask;

function requireNetmask () {
	if (hasRequiredNetmask) return netmask;
	hasRequiredNetmask = 1;
	(function() {
	  var Netmask, atob, chr, chr0, chrA, chra, ip2long, long2ip;
	  long2ip = function(long) {
	    var a, b, c, d;
	    a = (long & (0xff << 24)) >>> 24;
	    b = (long & (0xff << 16)) >>> 16;
	    c = (long & (0xff << 8)) >>> 8;
	    d = long & 0xff;
	    return [a, b, c, d].join('.');
	  };
	  ip2long = function(ip) {
	    var b, c, i, j, n, ref;
	    b = [];
	    for (i = j = 0; j <= 3; i = ++j) {
	      if (ip.length === 0) {
	        break;
	      }
	      if (i > 0) {
	        if (ip[0] !== '.') {
	          throw new Error('Invalid IP');
	        }
	        ip = ip.substring(1);
	      }
	      ref = atob(ip), n = ref[0], c = ref[1];
	      ip = ip.substring(c);
	      b.push(n);
	    }
	    if (ip.length !== 0) {
	      throw new Error('Invalid IP');
	    }
	    switch (b.length) {
	      case 1:
	        if (b[0] > 0xFFFFFFFF) {
	          throw new Error('Invalid IP');
	        }
	        return b[0] >>> 0;
	      case 2:
	        if (b[0] > 0xFF || b[1] > 0xFFFFFF) {
	          throw new Error('Invalid IP');
	        }
	        return (b[0] << 24 | b[1]) >>> 0;
	      case 3:
	        if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFFFF) {
	          throw new Error('Invalid IP');
	        }
	        return (b[0] << 24 | b[1] << 16 | b[2]) >>> 0;
	      case 4:
	        if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFF || b[3] > 0xFF) {
	          throw new Error('Invalid IP');
	        }
	        return (b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3]) >>> 0;
	      default:
	        throw new Error('Invalid IP');
	    }
	  };
	  chr = function(b) {
	    return b.charCodeAt(0);
	  };
	  chr0 = chr('0');
	  chra = chr('a');
	  chrA = chr('A');
	  atob = function(s) {
	    var base, dmax, i, n, start;
	    n = 0;
	    base = 10;
	    dmax = '9';
	    i = 0;
	    if (s.length > 1 && s[i] === '0') {
	      if (s[i + 1] === 'x' || s[i + 1] === 'X') {
	        i += 2;
	        base = 16;
	      } else if ('0' <= s[i + 1] && s[i + 1] <= '9') {
	        i++;
	        base = 8;
	        dmax = '7';
	      }
	    }
	    start = i;
	    while (i < s.length) {
	      if ('0' <= s[i] && s[i] <= dmax) {
	        n = (n * base + (chr(s[i]) - chr0)) >>> 0;
	      } else if (base === 16) {
	        if ('a' <= s[i] && s[i] <= 'f') {
	          n = (n * base + (10 + chr(s[i]) - chra)) >>> 0;
	        } else if ('A' <= s[i] && s[i] <= 'F') {
	          n = (n * base + (10 + chr(s[i]) - chrA)) >>> 0;
	        } else {
	          break;
	        }
	      } else {
	        break;
	      }
	      if (n > 0xFFFFFFFF) {
	        throw new Error('too large');
	      }
	      i++;
	    }
	    if (i === start) {
	      throw new Error('empty octet');
	    }
	    return [n, i];
	  };
	  Netmask = (function() {
	    function Netmask(net, mask) {
	      var i, j, ref;
	      if (typeof net !== 'string') {
	        throw new Error("Missing `net' parameter");
	      }
	      if (!mask) {
	        ref = net.split('/', 2), net = ref[0], mask = ref[1];
	      }
	      if (!mask) {
	        mask = 32;
	      }
	      if (typeof mask === 'string' && mask.indexOf('.') > -1) {
	        try {
	          this.maskLong = ip2long(mask);
	        } catch (error1) {
	          throw new Error("Invalid mask: " + mask);
	        }
	        for (i = j = 32; j >= 0; i = --j) {
	          if (this.maskLong === (0xffffffff << (32 - i)) >>> 0) {
	            this.bitmask = i;
	            break;
	          }
	        }
	      } else if (mask || mask === 0) {
	        this.bitmask = parseInt(mask, 10);
	        this.maskLong = 0;
	        if (this.bitmask > 0) {
	          this.maskLong = (0xffffffff << (32 - this.bitmask)) >>> 0;
	        }
	      } else {
	        throw new Error("Invalid mask: empty");
	      }
	      try {
	        this.netLong = (ip2long(net) & this.maskLong) >>> 0;
	      } catch (error1) {
	        throw new Error("Invalid net address: " + net);
	      }
	      if (!(this.bitmask <= 32)) {
	        throw new Error("Invalid mask for ip4: " + mask);
	      }
	      this.size = Math.pow(2, 32 - this.bitmask);
	      this.base = long2ip(this.netLong);
	      this.mask = long2ip(this.maskLong);
	      this.hostmask = long2ip(~this.maskLong);
	      this.first = this.bitmask <= 30 ? long2ip(this.netLong + 1) : this.base;
	      this.last = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 2) : long2ip(this.netLong + this.size - 1);
	      this.broadcast = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 1) : void 0;
	    }
	    Netmask.prototype.contains = function(ip) {
	      if (typeof ip === 'string' && (ip.indexOf('/') > 0 || ip.split('.').length !== 4)) {
	        ip = new Netmask(ip);
	      }
	      if (ip instanceof Netmask) {
	        return this.contains(ip.base) && this.contains(ip.broadcast || ip.last);
	      } else {
	        return (ip2long(ip) & this.maskLong) >>> 0 === (this.netLong & this.maskLong) >>> 0;
	      }
	    };
	    Netmask.prototype.next = function(count) {
	      if (count == null) {
	        count = 1;
	      }
	      return new Netmask(long2ip(this.netLong + (this.size * count)), this.mask);
	    };
	    Netmask.prototype.forEach = function(fn) {
	      var index, lastLong, long;
	      long = ip2long(this.first);
	      lastLong = ip2long(this.last);
	      index = 0;
	      while (long <= lastLong) {
	        fn(long2ip(long), long, index);
	        index++;
	        long++;
	      }
	    };
	    Netmask.prototype.toString = function() {
	      return this.base + "/" + this.bitmask;
	    };
	    return Netmask;
	  })();
	  netmask.ip2long = ip2long;
	  netmask.long2ip = long2ip;
	  netmask.Netmask = Netmask;
	}).call(netmask);
	return netmask;
}

var hasRequiredIsInNet;

function requireIsInNet () {
	if (hasRequiredIsInNet) return isInNet;
	hasRequiredIsInNet = 1;
	Object.defineProperty(isInNet, "__esModule", { value: true });
	const netmask_1 = requireNetmask();
	const util_1 = requireUtil();
	async function isInNet$1(host, pattern, mask) {
	    const family = 4;
	    try {
	        const ip = await (0, util_1.dnsLookup)(host, { family });
	        if (typeof ip === 'string') {
	            const netmask = new netmask_1.Netmask(pattern, mask);
	            return netmask.contains(ip);
	        }
	    }
	    catch (err) {
	    }
	    return false;
	}
	isInNet.default = isInNet$1;
	return isInNet;
}

var isPlainHostName = {};

var hasRequiredIsPlainHostName;

function requireIsPlainHostName () {
	if (hasRequiredIsPlainHostName) return isPlainHostName;
	hasRequiredIsPlainHostName = 1;
	Object.defineProperty(isPlainHostName, "__esModule", { value: true });
	function isPlainHostName$1(host) {
	    return !/\./.test(host);
	}
	isPlainHostName.default = isPlainHostName$1;
	return isPlainHostName;
}

var isResolvable = {};

var hasRequiredIsResolvable;

function requireIsResolvable () {
	if (hasRequiredIsResolvable) return isResolvable;
	hasRequiredIsResolvable = 1;
	Object.defineProperty(isResolvable, "__esModule", { value: true });
	const util_1 = requireUtil();
	async function isResolvable$1(host) {
	    const family = 4;
	    try {
	        if (await (0, util_1.dnsLookup)(host, { family })) {
	            return true;
	        }
	    }
	    catch (err) {
	    }
	    return false;
	}
	isResolvable.default = isResolvable$1;
	return isResolvable;
}

var localHostOrDomainIs = {};

var hasRequiredLocalHostOrDomainIs;

function requireLocalHostOrDomainIs () {
	if (hasRequiredLocalHostOrDomainIs) return localHostOrDomainIs;
	hasRequiredLocalHostOrDomainIs = 1;
	Object.defineProperty(localHostOrDomainIs, "__esModule", { value: true });
	function localHostOrDomainIs$1(host, hostdom) {
	    const parts = host.split('.');
	    const domparts = hostdom.split('.');
	    let matches = true;
	    for (let i = 0; i < parts.length; i++) {
	        if (parts[i] !== domparts[i]) {
	            matches = false;
	            break;
	        }
	    }
	    return matches;
	}
	localHostOrDomainIs.default = localHostOrDomainIs$1;
	return localHostOrDomainIs;
}

var myIpAddress = {};

var ip = {};

var hasRequiredIp;

function requireIp () {
	if (hasRequiredIp) return ip;
	hasRequiredIp = 1;
	(function (exports$1) {
		var __importDefault = (ip && ip.__importDefault) || function (mod) {
		    return (mod && mod.__esModule) ? mod : { "default": mod };
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.ip = void 0;
		const os_1 = __importDefault(require$$0$1);
		exports$1.ip = {
		    address() {
		        const interfaces = os_1.default.networkInterfaces();
		        const family = normalizeFamily();
		        const all = Object.values(interfaces).map((addrs = []) => {
		            const addresses = addrs.filter((details) => {
		                const detailsFamily = normalizeFamily(details.family);
		                if (detailsFamily !== family || exports$1.ip.isLoopback(details.address)) {
		                    return false;
		                }
		                return true;
		            });
		            return addresses.length ? addresses[0].address : undefined;
		        }).filter(Boolean);
		        return !all.length ? exports$1.ip.loopback(family) : all[0];
		    },
		    isLoopback(addr) {
		        return /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/
		            .test(addr)
		            || /^fe80::1$/.test(addr)
		            || /^::1$/.test(addr)
		            || /^::$/.test(addr);
		    },
		    loopback(family) {
		        family = normalizeFamily(family);
		        if (family !== 'ipv4' && family !== 'ipv6') {
		            throw new Error('family must be ipv4 or ipv6');
		        }
		        return family === 'ipv4' ? '127.0.0.1' : 'fe80::1';
		    }
		};
		function normalizeFamily(family) {
		    if (family === 4) {
		        return 'ipv4';
		    }
		    if (family === 6) {
		        return 'ipv6';
		    }
		    return family ? family.toLowerCase() : 'ipv4';
		} 
	} (ip));
	return ip;
}

var hasRequiredMyIpAddress;

function requireMyIpAddress () {
	if (hasRequiredMyIpAddress) return myIpAddress;
	hasRequiredMyIpAddress = 1;
	var __importDefault = (myIpAddress && myIpAddress.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(myIpAddress, "__esModule", { value: true });
	const ip_1 = requireIp();
	const net_1 = __importDefault(require$$0$7);
	async function myIpAddress$1() {
	    return new Promise((resolve, reject) => {
	        const socket = net_1.default.connect({ host: '8.8.8.8', port: 53 });
	        const onError = () => {
	            resolve(ip_1.ip.address());
	        };
	        socket.once('error', onError);
	        socket.once('connect', () => {
	            socket.removeListener('error', onError);
	            const addr = socket.address();
	            socket.destroy();
	            if (typeof addr === 'string') {
	                resolve(addr);
	            }
	            else if (addr.address) {
	                resolve(addr.address);
	            }
	            else {
	                reject(new Error('Expected a `string`'));
	            }
	        });
	    });
	}
	myIpAddress.default = myIpAddress$1;
	return myIpAddress;
}

var shExpMatch = {};

var hasRequiredShExpMatch;

function requireShExpMatch () {
	if (hasRequiredShExpMatch) return shExpMatch;
	hasRequiredShExpMatch = 1;
	Object.defineProperty(shExpMatch, "__esModule", { value: true });
	function shExpMatch$1(str, shexp) {
	    const re = toRegExp(shexp);
	    return re.test(str);
	}
	shExpMatch.default = shExpMatch$1;
	function toRegExp(str) {
	    str = String(str)
	        .replace(/\./g, '\\.')
	        .replace(/\?/g, '.')
	        .replace(/\*/g, '.*');
	    return new RegExp(`^${str}$`);
	}
	return shExpMatch;
}

var timeRange = {};

var hasRequiredTimeRange;

function requireTimeRange () {
	if (hasRequiredTimeRange) return timeRange;
	hasRequiredTimeRange = 1;
	Object.defineProperty(timeRange, "__esModule", { value: true });
	function timeRange$1() {
	    const args = Array.prototype.slice.call(arguments);
	    const lastArg = args.pop();
	    const useGMTzone = lastArg === 'GMT';
	    const currentDate = new Date();
	    if (!useGMTzone) {
	        args.push(lastArg);
	    }
	    let result = false;
	    const noOfArgs = args.length;
	    const numericArgs = args.map((n) => parseInt(n, 10));
	    if (noOfArgs === 1) {
	        result = getCurrentHour(useGMTzone, currentDate) === numericArgs[0];
	    }
	    else if (noOfArgs === 2) {
	        const currentHour = getCurrentHour(useGMTzone, currentDate);
	        result = numericArgs[0] <= currentHour && currentHour < numericArgs[1];
	    }
	    else if (noOfArgs === 4) {
	        result = valueInRange(secondsElapsedToday(numericArgs[0], numericArgs[1], 0), secondsElapsedToday(getCurrentHour(useGMTzone, currentDate), getCurrentMinute(useGMTzone, currentDate), 0), secondsElapsedToday(numericArgs[2], numericArgs[3], 59));
	    }
	    else if (noOfArgs === 6) {
	        result = valueInRange(secondsElapsedToday(numericArgs[0], numericArgs[1], numericArgs[2]), secondsElapsedToday(getCurrentHour(useGMTzone, currentDate), getCurrentMinute(useGMTzone, currentDate), getCurrentSecond(useGMTzone, currentDate)), secondsElapsedToday(numericArgs[3], numericArgs[4], numericArgs[5]));
	    }
	    return result;
	}
	timeRange.default = timeRange$1;
	function secondsElapsedToday(hh, mm, ss) {
	    return hh * 3600 + mm * 60 + ss;
	}
	function getCurrentHour(gmt, currentDate) {
	    return gmt ? currentDate.getUTCHours() : currentDate.getHours();
	}
	function getCurrentMinute(gmt, currentDate) {
	    return gmt ? currentDate.getUTCMinutes() : currentDate.getMinutes();
	}
	function getCurrentSecond(gmt, currentDate) {
	    return gmt ? currentDate.getUTCSeconds() : currentDate.getSeconds();
	}
	function valueInRange(start, value, finish) {
	    return start <= value && value <= finish;
	}
	return timeRange;
}

var weekdayRange = {};

var hasRequiredWeekdayRange;

function requireWeekdayRange () {
	if (hasRequiredWeekdayRange) return weekdayRange;
	hasRequiredWeekdayRange = 1;
	Object.defineProperty(weekdayRange, "__esModule", { value: true });
	const util_1 = requireUtil();
	const weekdays = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
	function weekdayRange$1(wd1, wd2, gmt) {
	    let useGMTzone = false;
	    let wd1Index = -1;
	    let wd2Index = -1;
	    let wd2IsGmt = false;
	    if ((0, util_1.isGMT)(gmt)) {
	        useGMTzone = true;
	    }
	    else if ((0, util_1.isGMT)(wd2)) {
	        useGMTzone = true;
	        wd2IsGmt = true;
	    }
	    wd1Index = weekdays.indexOf(wd1);
	    if (!wd2IsGmt && isWeekday(wd2)) {
	        wd2Index = weekdays.indexOf(wd2);
	    }
	    const todaysDay = getTodaysDay(useGMTzone);
	    let result;
	    if (wd2Index < 0) {
	        result = todaysDay === wd1Index;
	    }
	    else if (wd1Index <= wd2Index) {
	        result = valueInRange(wd1Index, todaysDay, wd2Index);
	    }
	    else {
	        result =
	            valueInRange(wd1Index, todaysDay, 6) ||
	                valueInRange(0, todaysDay, wd2Index);
	    }
	    return result;
	}
	weekdayRange.default = weekdayRange$1;
	function getTodaysDay(gmt) {
	    return gmt ? new Date().getUTCDay() : new Date().getDay();
	}
	function valueInRange(start, value, finish) {
	    return start <= value && value <= finish;
	}
	function isWeekday(v) {
	    if (!v)
	        return false;
	    return weekdays.includes(v);
	}
	return weekdayRange;
}

var hasRequiredDist$3;

function requireDist$3 () {
	if (hasRequiredDist$3) return dist$2;
	hasRequiredDist$3 = 1;
	(function (exports$1) {
		var __importDefault = (dist$2 && dist$2.__importDefault) || function (mod) {
		    return (mod && mod.__esModule) ? mod : { "default": mod };
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.sandbox = exports$1.createPacResolver = void 0;
		const degenerator_1 = requireDist$4();
		const dateRange_1 = __importDefault(requireDateRange());
		const dnsDomainIs_1 = __importDefault(requireDnsDomainIs());
		const dnsDomainLevels_1 = __importDefault(requireDnsDomainLevels());
		const dnsResolve_1 = __importDefault(requireDnsResolve());
		const isInNet_1 = __importDefault(requireIsInNet());
		const isPlainHostName_1 = __importDefault(requireIsPlainHostName());
		const isResolvable_1 = __importDefault(requireIsResolvable());
		const localHostOrDomainIs_1 = __importDefault(requireLocalHostOrDomainIs());
		const myIpAddress_1 = __importDefault(requireMyIpAddress());
		const shExpMatch_1 = __importDefault(requireShExpMatch());
		const timeRange_1 = __importDefault(requireTimeRange());
		const weekdayRange_1 = __importDefault(requireWeekdayRange());
		function createPacResolver(qjs, _str, _opts = {}) {
		    const str = Buffer.isBuffer(_str) ? _str.toString('utf8') : _str;
		    const context = {
		        ...exports$1.sandbox,
		        ..._opts.sandbox,
		    };
		    const names = Object.keys(context).filter((k) => isAsyncFunction(context[k]));
		    const opts = {
		        filename: 'proxy.pac',
		        names,
		        ..._opts,
		        sandbox: context,
		    };
		    const resolver = (0, degenerator_1.compile)(qjs, str, 'FindProxyForURL', opts);
		    function FindProxyForURL(url, _host) {
		        const urlObj = typeof url === 'string' ? new URL(url) : url;
		        const host = _host || urlObj.hostname;
		        if (!host) {
		            throw new TypeError('Could not determine `host`');
		        }
		        return resolver(urlObj.href, host);
		    }
		    Object.defineProperty(FindProxyForURL, 'toString', {
		        value: () => resolver.toString(),
		        enumerable: false,
		    });
		    return FindProxyForURL;
		}
		exports$1.createPacResolver = createPacResolver;
		exports$1.sandbox = Object.freeze({
		    alert: (message = '') => console.log('%s', message),
		    dateRange: dateRange_1.default,
		    dnsDomainIs: dnsDomainIs_1.default,
		    dnsDomainLevels: dnsDomainLevels_1.default,
		    dnsResolve: dnsResolve_1.default,
		    isInNet: isInNet_1.default,
		    isPlainHostName: isPlainHostName_1.default,
		    isResolvable: isResolvable_1.default,
		    localHostOrDomainIs: localHostOrDomainIs_1.default,
		    myIpAddress: myIpAddress_1.default,
		    shExpMatch: shExpMatch_1.default,
		    timeRange: timeRange_1.default,
		    weekdayRange: weekdayRange_1.default,
		});
		function isAsyncFunction(v) {
		    if (typeof v !== 'function')
		        return false;
		    if (v.constructor.name === 'AsyncFunction')
		        return true;
		    if (String(v).indexOf('__awaiter(') !== -1)
		        return true;
		    return Boolean(v.async);
		} 
	} (dist$2));
	return dist$2;
}

var dist = {};

var variants = {};

var esmHelpers = {};

var hasRequiredEsmHelpers;

function requireEsmHelpers () {
	if (hasRequiredEsmHelpers) return esmHelpers;
	hasRequiredEsmHelpers = 1;
	Object.defineProperty(esmHelpers, "__esModule", { value: true });
	esmHelpers.unwrapJavascript = esmHelpers.unwrapTypescript = void 0;
	function fakeUnwrapDefault(mod) {
	    return mod.default;
	}
	function actualUnwrapDefault(mod) {
	    const maybeUnwrap = mod.default;
	    return maybeUnwrap ?? mod;
	}
	esmHelpers.unwrapTypescript = actualUnwrapDefault;
	esmHelpers.unwrapJavascript = fakeUnwrapDefault;
	return esmHelpers;
}

var module$1 = {};

var debug = {};

var hasRequiredDebug;

function requireDebug () {
	if (hasRequiredDebug) return debug;
	hasRequiredDebug = 1;
	(function (exports$1) {
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.debugLog = exports$1.QTS_DEBUG = void 0;
		exports$1.QTS_DEBUG = Boolean(typeof process === "object" && process.env.QTS_DEBUG);
		exports$1.debugLog = exports$1.QTS_DEBUG ? console.log.bind(console) : () => { }; 
	} (debug));
	return debug;
}

var errors = {};

var hasRequiredErrors;

function requireErrors () {
	if (hasRequiredErrors) return errors;
	hasRequiredErrors = 1;
	Object.defineProperty(errors, "__esModule", { value: true });
	errors.QuickJSMemoryLeakDetected = errors.QuickJSAsyncifySuspended = errors.QuickJSAsyncifyError = errors.QuickJSNotImplemented = errors.QuickJSUseAfterFree = errors.QuickJSWrongOwner = errors.QuickJSUnwrapError = void 0;
	class QuickJSUnwrapError extends Error {
	    constructor(cause, context) {
	        super(String(cause));
	        this.cause = cause;
	        this.context = context;
	        this.name = "QuickJSUnwrapError";
	    }
	}
	errors.QuickJSUnwrapError = QuickJSUnwrapError;
	class QuickJSWrongOwner extends Error {
	    constructor() {
	        super(...arguments);
	        this.name = "QuickJSWrongOwner";
	    }
	}
	errors.QuickJSWrongOwner = QuickJSWrongOwner;
	class QuickJSUseAfterFree extends Error {
	    constructor() {
	        super(...arguments);
	        this.name = "QuickJSUseAfterFree";
	    }
	}
	errors.QuickJSUseAfterFree = QuickJSUseAfterFree;
	class QuickJSNotImplemented extends Error {
	    constructor() {
	        super(...arguments);
	        this.name = "QuickJSNotImplemented";
	    }
	}
	errors.QuickJSNotImplemented = QuickJSNotImplemented;
	class QuickJSAsyncifyError extends Error {
	    constructor() {
	        super(...arguments);
	        this.name = "QuickJSAsyncifyError";
	    }
	}
	errors.QuickJSAsyncifyError = QuickJSAsyncifyError;
	class QuickJSAsyncifySuspended extends Error {
	    constructor() {
	        super(...arguments);
	        this.name = "QuickJSAsyncifySuspended";
	    }
	}
	errors.QuickJSAsyncifySuspended = QuickJSAsyncifySuspended;
	class QuickJSMemoryLeakDetected extends Error {
	    constructor() {
	        super(...arguments);
	        this.name = "QuickJSMemoryLeakDetected";
	    }
	}
	errors.QuickJSMemoryLeakDetected = QuickJSMemoryLeakDetected;
	return errors;
}

var lifetime = {};

var asyncifyHelpers = {};

var hasRequiredAsyncifyHelpers;

function requireAsyncifyHelpers () {
	if (hasRequiredAsyncifyHelpers) return asyncifyHelpers;
	hasRequiredAsyncifyHelpers = 1;
	Object.defineProperty(asyncifyHelpers, "__esModule", { value: true });
	asyncifyHelpers.awaitEachYieldedPromise = asyncifyHelpers.maybeAsync = asyncifyHelpers.maybeAsyncFn = void 0;
	function* awaitYield(value) {
	    return (yield value);
	}
	function awaitYieldOf(generator) {
	    return awaitYield(awaitEachYieldedPromise(generator));
	}
	const AwaitYield = awaitYield;
	AwaitYield.of = awaitYieldOf;
	function maybeAsyncFn(that, fn) {
	    return (...args) => {
	        const generator = fn.call(that, AwaitYield, ...args);
	        return awaitEachYieldedPromise(generator);
	    };
	}
	asyncifyHelpers.maybeAsyncFn = maybeAsyncFn;
	function maybeAsync(that, startGenerator) {
	    const generator = startGenerator.call(that, AwaitYield);
	    return awaitEachYieldedPromise(generator);
	}
	asyncifyHelpers.maybeAsync = maybeAsync;
	function awaitEachYieldedPromise(gen) {
	    function handleNextStep(step) {
	        if (step.done) {
	            return step.value;
	        }
	        if (step.value instanceof Promise) {
	            return step.value.then((value) => handleNextStep(gen.next(value)), (error) => handleNextStep(gen.throw(error)));
	        }
	        return handleNextStep(gen.next(step.value));
	    }
	    return handleNextStep(gen.next());
	}
	asyncifyHelpers.awaitEachYieldedPromise = awaitEachYieldedPromise;
	return asyncifyHelpers;
}

var hasRequiredLifetime;

function requireLifetime () {
	if (hasRequiredLifetime) return lifetime;
	hasRequiredLifetime = 1;
	Object.defineProperty(lifetime, "__esModule", { value: true });
	lifetime.Scope = lifetime.WeakLifetime = lifetime.StaticLifetime = lifetime.Lifetime = void 0;
	const asyncify_helpers_1 = /*@__PURE__*/ requireAsyncifyHelpers();
	const debug_1 = /*@__PURE__*/ requireDebug();
	const errors_1 = /*@__PURE__*/ requireErrors();
	class Lifetime {
	    constructor(_value, copier, disposer, _owner) {
	        this._value = _value;
	        this.copier = copier;
	        this.disposer = disposer;
	        this._owner = _owner;
	        this._alive = true;
	        this._constructorStack = debug_1.QTS_DEBUG ? new Error("Lifetime constructed").stack : undefined;
	    }
	    get alive() {
	        return this._alive;
	    }
	    get value() {
	        this.assertAlive();
	        return this._value;
	    }
	    get owner() {
	        return this._owner;
	    }
	    get dupable() {
	        return !!this.copier;
	    }
	    dup() {
	        this.assertAlive();
	        if (!this.copier) {
	            throw new Error("Non-dupable lifetime");
	        }
	        return new Lifetime(this.copier(this._value), this.copier, this.disposer, this._owner);
	    }
	    consume(map) {
	        this.assertAlive();
	        const result = map(this);
	        this.dispose();
	        return result;
	    }
	    dispose() {
	        this.assertAlive();
	        if (this.disposer) {
	            this.disposer(this._value);
	        }
	        this._alive = false;
	    }
	    assertAlive() {
	        if (!this.alive) {
	            if (this._constructorStack) {
	                throw new errors_1.QuickJSUseAfterFree(`Lifetime not alive\n${this._constructorStack}\nLifetime used`);
	            }
	            throw new errors_1.QuickJSUseAfterFree("Lifetime not alive");
	        }
	    }
	}
	lifetime.Lifetime = Lifetime;
	class StaticLifetime extends Lifetime {
	    constructor(value, owner) {
	        super(value, undefined, undefined, owner);
	    }
	    get dupable() {
	        return true;
	    }
	    dup() {
	        return this;
	    }
	    dispose() { }
	}
	lifetime.StaticLifetime = StaticLifetime;
	class WeakLifetime extends Lifetime {
	    constructor(value, copier, disposer, owner) {
	        super(value, copier, disposer, owner);
	    }
	    dispose() {
	        this._alive = false;
	    }
	}
	lifetime.WeakLifetime = WeakLifetime;
	function scopeFinally(scope, blockError) {
	    let disposeError;
	    try {
	        scope.dispose();
	    }
	    catch (error) {
	        disposeError = error;
	    }
	    if (blockError && disposeError) {
	        Object.assign(blockError, {
	            message: `${blockError.message}\n Then, failed to dispose scope: ${disposeError.message}`,
	            disposeError,
	        });
	        throw blockError;
	    }
	    if (blockError || disposeError) {
	        throw blockError || disposeError;
	    }
	}
	class Scope {
	    constructor() {
	        this._disposables = new Lifetime(new Set());
	    }
	    static withScope(block) {
	        const scope = new Scope();
	        let blockError;
	        try {
	            return block(scope);
	        }
	        catch (error) {
	            blockError = error;
	            throw error;
	        }
	        finally {
	            scopeFinally(scope, blockError);
	        }
	    }
	    static withScopeMaybeAsync(_this, block) {
	        return (0, asyncify_helpers_1.maybeAsync)(undefined, function* (awaited) {
	            const scope = new Scope();
	            let blockError;
	            try {
	                return yield* awaited.of(block.call(_this, awaited, scope));
	            }
	            catch (error) {
	                blockError = error;
	                throw error;
	            }
	            finally {
	                scopeFinally(scope, blockError);
	            }
	        });
	    }
	    static async withScopeAsync(block) {
	        const scope = new Scope();
	        let blockError;
	        try {
	            return await block(scope);
	        }
	        catch (error) {
	            blockError = error;
	            throw error;
	        }
	        finally {
	            scopeFinally(scope, blockError);
	        }
	    }
	    manage(lifetime) {
	        this._disposables.value.add(lifetime);
	        return lifetime;
	    }
	    get alive() {
	        return this._disposables.alive;
	    }
	    dispose() {
	        const lifetimes = Array.from(this._disposables.value.values()).reverse();
	        for (const lifetime of lifetimes) {
	            if (lifetime.alive) {
	                lifetime.dispose();
	            }
	        }
	        this._disposables.dispose();
	    }
	}
	lifetime.Scope = Scope;
	return lifetime;
}

var runtime = {};

var context = {};

var deferredPromise = {};

var hasRequiredDeferredPromise;

function requireDeferredPromise () {
	if (hasRequiredDeferredPromise) return deferredPromise;
	hasRequiredDeferredPromise = 1;
	Object.defineProperty(deferredPromise, "__esModule", { value: true });
	deferredPromise.QuickJSDeferredPromise = void 0;
	class QuickJSDeferredPromise {
	    constructor(args) {
	        this.resolve = (value) => {
	            if (!this.resolveHandle.alive) {
	                return;
	            }
	            this.context
	                .unwrapResult(this.context.callFunction(this.resolveHandle, this.context.undefined, value || this.context.undefined))
	                .dispose();
	            this.disposeResolvers();
	            this.onSettled();
	        };
	        this.reject = (value) => {
	            if (!this.rejectHandle.alive) {
	                return;
	            }
	            this.context
	                .unwrapResult(this.context.callFunction(this.rejectHandle, this.context.undefined, value || this.context.undefined))
	                .dispose();
	            this.disposeResolvers();
	            this.onSettled();
	        };
	        this.dispose = () => {
	            if (this.handle.alive) {
	                this.handle.dispose();
	            }
	            this.disposeResolvers();
	        };
	        this.context = args.context;
	        this.owner = args.context.runtime;
	        this.handle = args.promiseHandle;
	        this.settled = new Promise((resolve) => {
	            this.onSettled = resolve;
	        });
	        this.resolveHandle = args.resolveHandle;
	        this.rejectHandle = args.rejectHandle;
	    }
	    get alive() {
	        return this.handle.alive || this.resolveHandle.alive || this.rejectHandle.alive;
	    }
	    disposeResolvers() {
	        if (this.resolveHandle.alive) {
	            this.resolveHandle.dispose();
	        }
	        if (this.rejectHandle.alive) {
	            this.rejectHandle.dispose();
	        }
	    }
	}
	deferredPromise.QuickJSDeferredPromise = QuickJSDeferredPromise;
	return deferredPromise;
}

var memory = {};

var hasRequiredMemory;

function requireMemory () {
	if (hasRequiredMemory) return memory;
	hasRequiredMemory = 1;
	Object.defineProperty(memory, "__esModule", { value: true });
	memory.ModuleMemory = void 0;
	const lifetime_1 = /*@__PURE__*/ requireLifetime();
	class ModuleMemory {
	    constructor(module) {
	        this.module = module;
	    }
	    toPointerArray(handleArray) {
	        const typedArray = new Int32Array(handleArray.map((handle) => handle.value));
	        const numBytes = typedArray.length * typedArray.BYTES_PER_ELEMENT;
	        const ptr = this.module._malloc(numBytes);
	        var heapBytes = new Uint8Array(this.module.HEAPU8.buffer, ptr, numBytes);
	        heapBytes.set(new Uint8Array(typedArray.buffer));
	        return new lifetime_1.Lifetime(ptr, undefined, (ptr) => this.module._free(ptr));
	    }
	    newMutablePointerArray(length) {
	        const zeros = new Int32Array(new Array(length).fill(0));
	        const numBytes = zeros.length * zeros.BYTES_PER_ELEMENT;
	        const ptr = this.module._malloc(numBytes);
	        const typedArray = new Int32Array(this.module.HEAPU8.buffer, ptr, length);
	        typedArray.set(zeros);
	        return new lifetime_1.Lifetime({ typedArray, ptr }, undefined, (value) => this.module._free(value.ptr));
	    }
	    newHeapCharPointer(string) {
	        const numBytes = this.module.lengthBytesUTF8(string) + 1;
	        const ptr = this.module._malloc(numBytes);
	        this.module.stringToUTF8(string, ptr, numBytes);
	        return new lifetime_1.Lifetime(ptr, undefined, (value) => this.module._free(value));
	    }
	    consumeHeapCharPointer(ptr) {
	        const str = this.module.UTF8ToString(ptr);
	        this.module._free(ptr);
	        return str;
	    }
	}
	memory.ModuleMemory = ModuleMemory;
	return memory;
}

var types$4 = {};

var typesFfi = {};

var hasRequiredTypesFfi;

function requireTypesFfi () {
	if (hasRequiredTypesFfi) return typesFfi;
	hasRequiredTypesFfi = 1;
	Object.defineProperty(typesFfi, "__esModule", { value: true });
	typesFfi.EvalFlags = typesFfi.assertSync = void 0;
	function assertSync(fn) {
	    return function mustBeSync(...args) {
	        const result = fn(...args);
	        if (result && typeof result === "object" && result instanceof Promise) {
	            throw new Error("Function unexpectedly returned a Promise");
	        }
	        return result;
	    };
	}
	typesFfi.assertSync = assertSync;
	typesFfi.EvalFlags = {
	    JS_EVAL_TYPE_GLOBAL: 0 << 0,
	    JS_EVAL_TYPE_MODULE: 1 << 0,
	    JS_EVAL_TYPE_DIRECT: 2 << 0,
	    JS_EVAL_TYPE_INDIRECT: 3 << 0,
	    JS_EVAL_TYPE_MASK: 3 << 0,
	    JS_EVAL_FLAG_STRICT: 1 << 3,
	    JS_EVAL_FLAG_STRIP: 1 << 4,
	    JS_EVAL_FLAG_COMPILE_ONLY: 1 << 5,
	    JS_EVAL_FLAG_BACKTRACE_BARRIER: 1 << 6,
	};
	return typesFfi;
}

var hasRequiredTypes;

function requireTypes () {
	if (hasRequiredTypes) return types$4;
	hasRequiredTypes = 1;
	Object.defineProperty(types$4, "__esModule", { value: true });
	types$4.concat = types$4.evalOptionsToFlags = types$4.DefaultIntrinsics = void 0;
	const types_ffi_1 = /*@__PURE__*/ requireTypesFfi();
	types$4.DefaultIntrinsics = Symbol("DefaultIntrinsics");
	function evalOptionsToFlags(evalOptions) {
	    if (typeof evalOptions === "number") {
	        return evalOptions;
	    }
	    if (evalOptions === undefined) {
	        return 0;
	    }
	    const { type, strict, strip, compileOnly, backtraceBarrier } = evalOptions;
	    let flags = 0;
	    if (type === "global")
	        flags |= types_ffi_1.EvalFlags.JS_EVAL_TYPE_GLOBAL;
	    if (type === "module")
	        flags |= types_ffi_1.EvalFlags.JS_EVAL_TYPE_MODULE;
	    if (strict)
	        flags |= types_ffi_1.EvalFlags.JS_EVAL_FLAG_STRICT;
	    if (strip)
	        flags |= types_ffi_1.EvalFlags.JS_EVAL_FLAG_STRIP;
	    if (compileOnly)
	        flags |= types_ffi_1.EvalFlags.JS_EVAL_FLAG_COMPILE_ONLY;
	    if (backtraceBarrier)
	        flags |= types_ffi_1.EvalFlags.JS_EVAL_FLAG_BACKTRACE_BARRIER;
	    return flags;
	}
	types$4.evalOptionsToFlags = evalOptionsToFlags;
	function concat(...values) {
	    let result = [];
	    for (const value of values) {
	        if (value !== undefined) {
	            result = result.concat(value);
	        }
	    }
	    return result;
	}
	types$4.concat = concat;
	return types$4;
}

var hasRequiredContext;

function requireContext () {
	if (hasRequiredContext) return context;
	hasRequiredContext = 1;
	Object.defineProperty(context, "__esModule", { value: true });
	context.QuickJSContext = void 0;
	const debug_1 = /*@__PURE__*/ requireDebug();
	const deferred_promise_1 = /*@__PURE__*/ requireDeferredPromise();
	const errors_1 = /*@__PURE__*/ requireErrors();
	const lifetime_1 = /*@__PURE__*/ requireLifetime();
	const memory_1 = /*@__PURE__*/ requireMemory();
	const types_1 = /*@__PURE__*/ requireTypes();
	class ContextMemory extends memory_1.ModuleMemory {
	    constructor(args) {
	        super(args.module);
	        this.scope = new lifetime_1.Scope();
	        this.copyJSValue = (ptr) => {
	            return this.ffi.QTS_DupValuePointer(this.ctx.value, ptr);
	        };
	        this.freeJSValue = (ptr) => {
	            this.ffi.QTS_FreeValuePointer(this.ctx.value, ptr);
	        };
	        args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime));
	        this.owner = args.owner;
	        this.module = args.module;
	        this.ffi = args.ffi;
	        this.rt = args.rt;
	        this.ctx = this.scope.manage(args.ctx);
	    }
	    get alive() {
	        return this.scope.alive;
	    }
	    dispose() {
	        return this.scope.dispose();
	    }
	    manage(lifetime) {
	        return this.scope.manage(lifetime);
	    }
	    consumeJSCharPointer(ptr) {
	        const str = this.module.UTF8ToString(ptr);
	        this.ffi.QTS_FreeCString(this.ctx.value, ptr);
	        return str;
	    }
	    heapValueHandle(ptr) {
	        return new lifetime_1.Lifetime(ptr, this.copyJSValue, this.freeJSValue, this.owner);
	    }
	}
	class QuickJSContext {
	    constructor(args) {
	        this._undefined = undefined;
	        this._null = undefined;
	        this._false = undefined;
	        this._true = undefined;
	        this._global = undefined;
	        this._BigInt = undefined;
	        this.fnNextId = -32768;
	        this.fnMaps = new Map();
	        this.cToHostCallbacks = {
	            callFunction: (ctx, this_ptr, argc, argv, fn_id) => {
	                if (ctx !== this.ctx.value) {
	                    throw new Error("QuickJSContext instance received C -> JS call with mismatched ctx");
	                }
	                const fn = this.getFunction(fn_id);
	                if (!fn) {
	                    throw new Error(`QuickJSContext had no callback with id ${fn_id}`);
	                }
	                return lifetime_1.Scope.withScopeMaybeAsync(this, function* (awaited, scope) {
	                    const thisHandle = scope.manage(new lifetime_1.WeakLifetime(this_ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime));
	                    const argHandles = new Array(argc);
	                    for (let i = 0; i < argc; i++) {
	                        const ptr = this.ffi.QTS_ArgvGetJSValueConstPointer(argv, i);
	                        argHandles[i] = scope.manage(new lifetime_1.WeakLifetime(ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime));
	                    }
	                    try {
	                        const result = yield* awaited(fn.apply(thisHandle, argHandles));
	                        if (result) {
	                            if ("error" in result && result.error) {
	                                (0, debug_1.debugLog)("throw error", result.error);
	                                throw result.error;
	                            }
	                            const handle = scope.manage(result instanceof lifetime_1.Lifetime ? result : result.value);
	                            return this.ffi.QTS_DupValuePointer(this.ctx.value, handle.value);
	                        }
	                        return 0;
	                    }
	                    catch (error) {
	                        return this.errorToHandle(error).consume((errorHandle) => this.ffi.QTS_Throw(this.ctx.value, errorHandle.value));
	                    }
	                });
	            },
	        };
	        this.runtime = args.runtime;
	        this.module = args.module;
	        this.ffi = args.ffi;
	        this.rt = args.rt;
	        this.ctx = args.ctx;
	        this.memory = new ContextMemory({
	            ...args,
	            owner: this.runtime,
	        });
	        args.callbacks.setContextCallbacks(this.ctx.value, this.cToHostCallbacks);
	        this.dump = this.dump.bind(this);
	        this.getString = this.getString.bind(this);
	        this.getNumber = this.getNumber.bind(this);
	        this.resolvePromise = this.resolvePromise.bind(this);
	    }
	    get alive() {
	        return this.memory.alive;
	    }
	    dispose() {
	        this.memory.dispose();
	    }
	    get undefined() {
	        if (this._undefined) {
	            return this._undefined;
	        }
	        const ptr = this.ffi.QTS_GetUndefined();
	        return (this._undefined = new lifetime_1.StaticLifetime(ptr));
	    }
	    get null() {
	        if (this._null) {
	            return this._null;
	        }
	        const ptr = this.ffi.QTS_GetNull();
	        return (this._null = new lifetime_1.StaticLifetime(ptr));
	    }
	    get true() {
	        if (this._true) {
	            return this._true;
	        }
	        const ptr = this.ffi.QTS_GetTrue();
	        return (this._true = new lifetime_1.StaticLifetime(ptr));
	    }
	    get false() {
	        if (this._false) {
	            return this._false;
	        }
	        const ptr = this.ffi.QTS_GetFalse();
	        return (this._false = new lifetime_1.StaticLifetime(ptr));
	    }
	    get global() {
	        if (this._global) {
	            return this._global;
	        }
	        const ptr = this.ffi.QTS_GetGlobalObject(this.ctx.value);
	        this.memory.manage(this.memory.heapValueHandle(ptr));
	        this._global = new lifetime_1.StaticLifetime(ptr, this.runtime);
	        return this._global;
	    }
	    newNumber(num) {
	        return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value, num));
	    }
	    newString(str) {
	        const ptr = this.memory
	            .newHeapCharPointer(str)
	            .consume((charHandle) => this.ffi.QTS_NewString(this.ctx.value, charHandle.value));
	        return this.memory.heapValueHandle(ptr);
	    }
	    newUniqueSymbol(description) {
	        const key = (typeof description === "symbol" ? description.description : description) ?? "";
	        const ptr = this.memory
	            .newHeapCharPointer(key)
	            .consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value, 0));
	        return this.memory.heapValueHandle(ptr);
	    }
	    newSymbolFor(key) {
	        const description = (typeof key === "symbol" ? key.description : key) ?? "";
	        const ptr = this.memory
	            .newHeapCharPointer(description)
	            .consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value, 1));
	        return this.memory.heapValueHandle(ptr);
	    }
	    newBigInt(num) {
	        if (!this._BigInt) {
	            const bigIntHandle = this.getProp(this.global, "BigInt");
	            this.memory.manage(bigIntHandle);
	            this._BigInt = new lifetime_1.StaticLifetime(bigIntHandle.value, this.runtime);
	        }
	        const bigIntHandle = this._BigInt;
	        const asString = String(num);
	        return this.newString(asString).consume((handle) => this.unwrapResult(this.callFunction(bigIntHandle, this.undefined, handle)));
	    }
	    newObject(prototype) {
	        if (prototype) {
	            this.runtime.assertOwned(prototype);
	        }
	        const ptr = prototype
	            ? this.ffi.QTS_NewObjectProto(this.ctx.value, prototype.value)
	            : this.ffi.QTS_NewObject(this.ctx.value);
	        return this.memory.heapValueHandle(ptr);
	    }
	    newArray() {
	        const ptr = this.ffi.QTS_NewArray(this.ctx.value);
	        return this.memory.heapValueHandle(ptr);
	    }
	    newPromise(value) {
	        const deferredPromise = lifetime_1.Scope.withScope((scope) => {
	            const mutablePointerArray = scope.manage(this.memory.newMutablePointerArray(2));
	            const promisePtr = this.ffi.QTS_NewPromiseCapability(this.ctx.value, mutablePointerArray.value.ptr);
	            const promiseHandle = this.memory.heapValueHandle(promisePtr);
	            const [resolveHandle, rejectHandle] = Array.from(mutablePointerArray.value.typedArray).map((jsvaluePtr) => this.memory.heapValueHandle(jsvaluePtr));
	            return new deferred_promise_1.QuickJSDeferredPromise({
	                context: this,
	                promiseHandle,
	                resolveHandle,
	                rejectHandle,
	            });
	        });
	        if (value && typeof value === "function") {
	            value = new Promise(value);
	        }
	        if (value) {
	            Promise.resolve(value).then(deferredPromise.resolve, (error) => error instanceof lifetime_1.Lifetime
	                ? deferredPromise.reject(error)
	                : this.newError(error).consume(deferredPromise.reject));
	        }
	        return deferredPromise;
	    }
	    newFunction(name, fn) {
	        const fnId = ++this.fnNextId;
	        this.setFunction(fnId, fn);
	        return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value, fnId, name));
	    }
	    newError(error) {
	        const errorHandle = this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));
	        if (error && typeof error === "object") {
	            if (error.name !== undefined) {
	                this.newString(error.name).consume((handle) => this.setProp(errorHandle, "name", handle));
	            }
	            if (error.message !== undefined) {
	                this.newString(error.message).consume((handle) => this.setProp(errorHandle, "message", handle));
	            }
	        }
	        else if (typeof error === "string") {
	            this.newString(error).consume((handle) => this.setProp(errorHandle, "message", handle));
	        }
	        else if (error !== undefined) {
	            this.newString(String(error)).consume((handle) => this.setProp(errorHandle, "message", handle));
	        }
	        return errorHandle;
	    }
	    typeof(handle) {
	        this.runtime.assertOwned(handle);
	        return this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value, handle.value));
	    }
	    getNumber(handle) {
	        this.runtime.assertOwned(handle);
	        return this.ffi.QTS_GetFloat64(this.ctx.value, handle.value);
	    }
	    getString(handle) {
	        this.runtime.assertOwned(handle);
	        return this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value, handle.value));
	    }
	    getSymbol(handle) {
	        this.runtime.assertOwned(handle);
	        const key = this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value, handle.value));
	        const isGlobal = this.ffi.QTS_IsGlobalSymbol(this.ctx.value, handle.value);
	        return isGlobal ? Symbol.for(key) : Symbol(key);
	    }
	    getBigInt(handle) {
	        this.runtime.assertOwned(handle);
	        const asString = this.getString(handle);
	        return BigInt(asString);
	    }
	    resolvePromise(promiseLikeHandle) {
	        this.runtime.assertOwned(promiseLikeHandle);
	        const vmResolveResult = lifetime_1.Scope.withScope((scope) => {
	            const vmPromise = scope.manage(this.getProp(this.global, "Promise"));
	            const vmPromiseResolve = scope.manage(this.getProp(vmPromise, "resolve"));
	            return this.callFunction(vmPromiseResolve, vmPromise, promiseLikeHandle);
	        });
	        if (vmResolveResult.error) {
	            return Promise.resolve(vmResolveResult);
	        }
	        return new Promise((resolve) => {
	            lifetime_1.Scope.withScope((scope) => {
	                const resolveHandle = scope.manage(this.newFunction("resolve", (value) => {
	                    resolve({ value: value && value.dup() });
	                }));
	                const rejectHandle = scope.manage(this.newFunction("reject", (error) => {
	                    resolve({ error: error && error.dup() });
	                }));
	                const promiseHandle = scope.manage(vmResolveResult.value);
	                const promiseThenHandle = scope.manage(this.getProp(promiseHandle, "then"));
	                this.unwrapResult(this.callFunction(promiseThenHandle, promiseHandle, resolveHandle, rejectHandle)).dispose();
	            });
	        });
	    }
	    getProp(handle, key) {
	        this.runtime.assertOwned(handle);
	        const ptr = this.borrowPropertyKey(key).consume((quickJSKey) => this.ffi.QTS_GetProp(this.ctx.value, handle.value, quickJSKey.value));
	        const result = this.memory.heapValueHandle(ptr);
	        return result;
	    }
	    setProp(handle, key, value) {
	        this.runtime.assertOwned(handle);
	        this.borrowPropertyKey(key).consume((quickJSKey) => this.ffi.QTS_SetProp(this.ctx.value, handle.value, quickJSKey.value, value.value));
	    }
	    defineProp(handle, key, descriptor) {
	        this.runtime.assertOwned(handle);
	        lifetime_1.Scope.withScope((scope) => {
	            const quickJSKey = scope.manage(this.borrowPropertyKey(key));
	            const value = descriptor.value || this.undefined;
	            const configurable = Boolean(descriptor.configurable);
	            const enumerable = Boolean(descriptor.enumerable);
	            const hasValue = Boolean(descriptor.value);
	            const get = descriptor.get
	                ? scope.manage(this.newFunction(descriptor.get.name, descriptor.get))
	                : this.undefined;
	            const set = descriptor.set
	                ? scope.manage(this.newFunction(descriptor.set.name, descriptor.set))
	                : this.undefined;
	            this.ffi.QTS_DefineProp(this.ctx.value, handle.value, quickJSKey.value, value.value, get.value, set.value, configurable, enumerable, hasValue);
	        });
	    }
	    callFunction(func, thisVal, ...args) {
	        this.runtime.assertOwned(func);
	        const resultPtr = this.memory
	            .toPointerArray(args)
	            .consume((argsArrayPtr) => this.ffi.QTS_Call(this.ctx.value, func.value, thisVal.value, args.length, argsArrayPtr.value));
	        const errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
	        if (errorPtr) {
	            this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr);
	            return { error: this.memory.heapValueHandle(errorPtr) };
	        }
	        return { value: this.memory.heapValueHandle(resultPtr) };
	    }
	    evalCode(code, filename = "eval.js",
	    options) {
	        const detectModule = (options === undefined ? 1 : 0);
	        const flags = (0, types_1.evalOptionsToFlags)(options);
	        const resultPtr = this.memory
	            .newHeapCharPointer(code)
	            .consume((charHandle) => this.ffi.QTS_Eval(this.ctx.value, charHandle.value, filename, detectModule, flags));
	        const errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
	        if (errorPtr) {
	            this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr);
	            return { error: this.memory.heapValueHandle(errorPtr) };
	        }
	        return { value: this.memory.heapValueHandle(resultPtr) };
	    }
	    throw(error) {
	        return this.errorToHandle(error).consume((handle) => this.ffi.QTS_Throw(this.ctx.value, handle.value));
	    }
	    borrowPropertyKey(key) {
	        if (typeof key === "number") {
	            return this.newNumber(key);
	        }
	        if (typeof key === "string") {
	            return this.newString(key);
	        }
	        return new lifetime_1.StaticLifetime(key.value, this.runtime);
	    }
	    getMemory(rt) {
	        if (rt === this.rt.value) {
	            return this.memory;
	        }
	        else {
	            throw new Error("Private API. Cannot get memory from a different runtime");
	        }
	    }
	    dump(handle) {
	        this.runtime.assertOwned(handle);
	        const type = this.typeof(handle);
	        if (type === "string") {
	            return this.getString(handle);
	        }
	        else if (type === "number") {
	            return this.getNumber(handle);
	        }
	        else if (type === "bigint") {
	            return this.getBigInt(handle);
	        }
	        else if (type === "undefined") {
	            return undefined;
	        }
	        else if (type === "symbol") {
	            return this.getSymbol(handle);
	        }
	        const str = this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value, handle.value));
	        try {
	            return JSON.parse(str);
	        }
	        catch (err) {
	            return str;
	        }
	    }
	    unwrapResult(result) {
	        if (result.error) {
	            const context = "context" in result.error ? result.error.context : this;
	            const cause = result.error.consume((error) => this.dump(error));
	            if (cause && typeof cause === "object" && typeof cause.message === "string") {
	                const { message, name, stack } = cause;
	                const exception = new errors_1.QuickJSUnwrapError("");
	                const hostStack = exception.stack;
	                if (typeof name === "string") {
	                    exception.name = cause.name;
	                }
	                if (typeof stack === "string") {
	                    exception.stack = `${name}: ${message}\n${cause.stack}Host: ${hostStack}`;
	                }
	                Object.assign(exception, { cause, context, message });
	                throw exception;
	            }
	            throw new errors_1.QuickJSUnwrapError(cause, context);
	        }
	        return result.value;
	    }
	    getFunction(fn_id) {
	        const map_id = fn_id >> 8;
	        const fnMap = this.fnMaps.get(map_id);
	        if (!fnMap) {
	            return undefined;
	        }
	        return fnMap.get(fn_id);
	    }
	    setFunction(fn_id, handle) {
	        const map_id = fn_id >> 8;
	        let fnMap = this.fnMaps.get(map_id);
	        if (!fnMap) {
	            fnMap = new Map();
	            this.fnMaps.set(map_id, fnMap);
	        }
	        return fnMap.set(fn_id, handle);
	    }
	    errorToHandle(error) {
	        if (error instanceof lifetime_1.Lifetime) {
	            return error;
	        }
	        return this.newError(error);
	    }
	}
	context.QuickJSContext = QuickJSContext;
	return context;
}

var hasRequiredRuntime;

function requireRuntime () {
	if (hasRequiredRuntime) return runtime;
	hasRequiredRuntime = 1;
	Object.defineProperty(runtime, "__esModule", { value: true });
	runtime.QuickJSRuntime = void 0;
	const asyncify_helpers_1 = /*@__PURE__*/ requireAsyncifyHelpers();
	const context_1 = /*@__PURE__*/ requireContext();
	const debug_1 = /*@__PURE__*/ requireDebug();
	const errors_1 = /*@__PURE__*/ requireErrors();
	const lifetime_1 = /*@__PURE__*/ requireLifetime();
	const memory_1 = /*@__PURE__*/ requireMemory();
	const types_1 = /*@__PURE__*/ requireTypes();
	class QuickJSRuntime {
	    constructor(args) {
	        this.scope = new lifetime_1.Scope();
	        this.contextMap = new Map();
	        this.cToHostCallbacks = {
	            shouldInterrupt: (rt) => {
	                if (rt !== this.rt.value) {
	                    throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");
	                }
	                const fn = this.interruptHandler;
	                if (!fn) {
	                    throw new Error("QuickJSContext had no interrupt handler");
	                }
	                return fn(this) ? 1 : 0;
	            },
	            loadModuleSource: (0, asyncify_helpers_1.maybeAsyncFn)(this, function* (awaited, rt, ctx, moduleName) {
	                const moduleLoader = this.moduleLoader;
	                if (!moduleLoader) {
	                    throw new Error("Runtime has no module loader");
	                }
	                if (rt !== this.rt.value) {
	                    throw new Error("Runtime pointer mismatch");
	                }
	                const context = this.contextMap.get(ctx) ??
	                    this.newContext({
	                        contextPointer: ctx,
	                    });
	                try {
	                    const result = yield* awaited(moduleLoader(moduleName, context));
	                    if (typeof result === "object" && "error" in result && result.error) {
	                        (0, debug_1.debugLog)("cToHostLoadModule: loader returned error", result.error);
	                        throw result.error;
	                    }
	                    const moduleSource = typeof result === "string" ? result : "value" in result ? result.value : result;
	                    return this.memory.newHeapCharPointer(moduleSource).value;
	                }
	                catch (error) {
	                    (0, debug_1.debugLog)("cToHostLoadModule: caught error", error);
	                    context.throw(error);
	                    return 0;
	                }
	            }),
	            normalizeModule: (0, asyncify_helpers_1.maybeAsyncFn)(this, function* (awaited, rt, ctx, baseModuleName, moduleNameRequest) {
	                const moduleNormalizer = this.moduleNormalizer;
	                if (!moduleNormalizer) {
	                    throw new Error("Runtime has no module normalizer");
	                }
	                if (rt !== this.rt.value) {
	                    throw new Error("Runtime pointer mismatch");
	                }
	                const context = this.contextMap.get(ctx) ??
	                    this.newContext({
	                        contextPointer: ctx,
	                    });
	                try {
	                    const result = yield* awaited(moduleNormalizer(baseModuleName, moduleNameRequest, context));
	                    if (typeof result === "object" && "error" in result && result.error) {
	                        (0, debug_1.debugLog)("cToHostNormalizeModule: normalizer returned error", result.error);
	                        throw result.error;
	                    }
	                    const name = typeof result === "string" ? result : result.value;
	                    return context.getMemory(this.rt.value).newHeapCharPointer(name).value;
	                }
	                catch (error) {
	                    (0, debug_1.debugLog)("normalizeModule: caught error", error);
	                    context.throw(error);
	                    return 0;
	                }
	            }),
	        };
	        args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime));
	        this.module = args.module;
	        this.memory = new memory_1.ModuleMemory(this.module);
	        this.ffi = args.ffi;
	        this.rt = args.rt;
	        this.callbacks = args.callbacks;
	        this.scope.manage(this.rt);
	        this.callbacks.setRuntimeCallbacks(this.rt.value, this.cToHostCallbacks);
	        this.executePendingJobs = this.executePendingJobs.bind(this);
	    }
	    get alive() {
	        return this.scope.alive;
	    }
	    dispose() {
	        return this.scope.dispose();
	    }
	    newContext(options = {}) {
	        if (options.intrinsics && options.intrinsics !== types_1.DefaultIntrinsics) {
	            throw new Error("TODO: Custom intrinsics are not supported yet");
	        }
	        const ctx = new lifetime_1.Lifetime(options.contextPointer || this.ffi.QTS_NewContext(this.rt.value), undefined, (ctx_ptr) => {
	            this.contextMap.delete(ctx_ptr);
	            this.callbacks.deleteContext(ctx_ptr);
	            this.ffi.QTS_FreeContext(ctx_ptr);
	        });
	        const context = new context_1.QuickJSContext({
	            module: this.module,
	            ctx,
	            ffi: this.ffi,
	            rt: this.rt,
	            ownedLifetimes: options.ownedLifetimes,
	            runtime: this,
	            callbacks: this.callbacks,
	        });
	        this.contextMap.set(ctx.value, context);
	        return context;
	    }
	    setModuleLoader(moduleLoader, moduleNormalizer) {
	        this.moduleLoader = moduleLoader;
	        this.moduleNormalizer = moduleNormalizer;
	        this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value, this.moduleNormalizer ? 1 : 0);
	    }
	    removeModuleLoader() {
	        this.moduleLoader = undefined;
	        this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value);
	    }
	    hasPendingJob() {
	        return Boolean(this.ffi.QTS_IsJobPending(this.rt.value));
	    }
	    setInterruptHandler(cb) {
	        const prevInterruptHandler = this.interruptHandler;
	        this.interruptHandler = cb;
	        if (!prevInterruptHandler) {
	            this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value);
	        }
	    }
	    removeInterruptHandler() {
	        if (this.interruptHandler) {
	            this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value);
	            this.interruptHandler = undefined;
	        }
	    }
	    executePendingJobs(maxJobsToExecute = -1) {
	        const ctxPtrOut = this.memory.newMutablePointerArray(1);
	        const valuePtr = this.ffi.QTS_ExecutePendingJob(this.rt.value, maxJobsToExecute ?? -1, ctxPtrOut.value.ptr);
	        const ctxPtr = ctxPtrOut.value.typedArray[0];
	        ctxPtrOut.dispose();
	        if (ctxPtr === 0) {
	            this.ffi.QTS_FreeValuePointerRuntime(this.rt.value, valuePtr);
	            return { value: 0 };
	        }
	        const context = this.contextMap.get(ctxPtr) ??
	            this.newContext({
	                contextPointer: ctxPtr,
	            });
	        const resultValue = context.getMemory(this.rt.value).heapValueHandle(valuePtr);
	        const typeOfRet = context.typeof(resultValue);
	        if (typeOfRet === "number") {
	            const executedJobs = context.getNumber(resultValue);
	            resultValue.dispose();
	            return { value: executedJobs };
	        }
	        else {
	            const error = Object.assign(resultValue, { context });
	            return {
	                error,
	            };
	        }
	    }
	    setMemoryLimit(limitBytes) {
	        if (limitBytes < 0 && limitBytes !== -1) {
	            throw new Error("Cannot set memory limit to negative number. To unset, pass -1");
	        }
	        this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value, limitBytes);
	    }
	    computeMemoryUsage() {
	        const serviceContextMemory = this.getSystemContext().getMemory(this.rt.value);
	        return serviceContextMemory.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value, serviceContextMemory.ctx.value));
	    }
	    dumpMemoryUsage() {
	        return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value));
	    }
	    setMaxStackSize(stackSize) {
	        if (stackSize < 0) {
	            throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");
	        }
	        this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value, stackSize);
	    }
	    assertOwned(handle) {
	        if (handle.owner && handle.owner.rt !== this.rt) {
	            throw new errors_1.QuickJSWrongOwner(`Handle is not owned by this runtime: ${handle.owner.rt.value} != ${this.rt.value}`);
	        }
	    }
	    getSystemContext() {
	        if (!this.context) {
	            this.context = this.scope.manage(this.newContext());
	        }
	        return this.context;
	    }
	}
	runtime.QuickJSRuntime = QuickJSRuntime;
	return runtime;
}

var hasRequiredModule;

function requireModule () {
	if (hasRequiredModule) return module$1;
	hasRequiredModule = 1;
	Object.defineProperty(module$1, "__esModule", { value: true });
	module$1.QuickJSWASMModule = module$1.applyModuleEvalRuntimeOptions = module$1.applyBaseRuntimeOptions = module$1.QuickJSModuleCallbacks = void 0;
	const debug_1 = /*@__PURE__*/ requireDebug();
	const errors_1 = /*@__PURE__*/ requireErrors();
	const lifetime_1 = /*@__PURE__*/ requireLifetime();
	const runtime_1 = /*@__PURE__*/ requireRuntime();
	const types_1 = /*@__PURE__*/ requireTypes();
	class QuickJSEmscriptenModuleCallbacks {
	    constructor(args) {
	        this.callFunction = args.callFunction;
	        this.shouldInterrupt = args.shouldInterrupt;
	        this.loadModuleSource = args.loadModuleSource;
	        this.normalizeModule = args.normalizeModule;
	    }
	}
	class QuickJSModuleCallbacks {
	    constructor(module) {
	        this.contextCallbacks = new Map();
	        this.runtimeCallbacks = new Map();
	        this.suspendedCount = 0;
	        this.cToHostCallbacks = new QuickJSEmscriptenModuleCallbacks({
	            callFunction: (asyncify, ctx, this_ptr, argc, argv, fn_id) => this.handleAsyncify(asyncify, () => {
	                try {
	                    const vm = this.contextCallbacks.get(ctx);
	                    if (!vm) {
	                        throw new Error(`QuickJSContext(ctx = ${ctx}) not found for C function call "${fn_id}"`);
	                    }
	                    return vm.callFunction(ctx, this_ptr, argc, argv, fn_id);
	                }
	                catch (error) {
	                    console.error("[C to host error: returning null]", error);
	                    return 0;
	                }
	            }),
	            shouldInterrupt: (asyncify, rt) => this.handleAsyncify(asyncify, () => {
	                try {
	                    const vm = this.runtimeCallbacks.get(rt);
	                    if (!vm) {
	                        throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C interrupt`);
	                    }
	                    return vm.shouldInterrupt(rt);
	                }
	                catch (error) {
	                    console.error("[C to host interrupt: returning error]", error);
	                    return 1;
	                }
	            }),
	            loadModuleSource: (asyncify, rt, ctx, moduleName) => this.handleAsyncify(asyncify, () => {
	                try {
	                    const runtimeCallbacks = this.runtimeCallbacks.get(rt);
	                    if (!runtimeCallbacks) {
	                        throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
	                    }
	                    const loadModule = runtimeCallbacks.loadModuleSource;
	                    if (!loadModule) {
	                        throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
	                    }
	                    return loadModule(rt, ctx, moduleName);
	                }
	                catch (error) {
	                    console.error("[C to host module loader error: returning null]", error);
	                    return 0;
	                }
	            }),
	            normalizeModule: (asyncify, rt, ctx, moduleBaseName, moduleName) => this.handleAsyncify(asyncify, () => {
	                try {
	                    const runtimeCallbacks = this.runtimeCallbacks.get(rt);
	                    if (!runtimeCallbacks) {
	                        throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
	                    }
	                    const normalizeModule = runtimeCallbacks.normalizeModule;
	                    if (!normalizeModule) {
	                        throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
	                    }
	                    return normalizeModule(rt, ctx, moduleBaseName, moduleName);
	                }
	                catch (error) {
	                    console.error("[C to host module loader error: returning null]", error);
	                    return 0;
	                }
	            }),
	        });
	        this.module = module;
	        this.module.callbacks = this.cToHostCallbacks;
	    }
	    setRuntimeCallbacks(rt, callbacks) {
	        this.runtimeCallbacks.set(rt, callbacks);
	    }
	    deleteRuntime(rt) {
	        this.runtimeCallbacks.delete(rt);
	    }
	    setContextCallbacks(ctx, callbacks) {
	        this.contextCallbacks.set(ctx, callbacks);
	    }
	    deleteContext(ctx) {
	        this.contextCallbacks.delete(ctx);
	    }
	    handleAsyncify(asyncify, fn) {
	        if (asyncify) {
	            return asyncify.handleSleep((done) => {
	                try {
	                    const result = fn();
	                    if (!(result instanceof Promise)) {
	                        (0, debug_1.debugLog)("asyncify.handleSleep: not suspending:", result);
	                        done(result);
	                        return;
	                    }
	                    if (this.suspended) {
	                        throw new errors_1.QuickJSAsyncifyError(`Already suspended at: ${this.suspended.stack}\nAttempted to suspend at:`);
	                    }
	                    else {
	                        this.suspended = new errors_1.QuickJSAsyncifySuspended(`(${this.suspendedCount++})`);
	                        (0, debug_1.debugLog)("asyncify.handleSleep: suspending:", this.suspended);
	                    }
	                    result.then((resolvedResult) => {
	                        this.suspended = undefined;
	                        (0, debug_1.debugLog)("asyncify.handleSleep: resolved:", resolvedResult);
	                        done(resolvedResult);
	                    }, (error) => {
	                        (0, debug_1.debugLog)("asyncify.handleSleep: rejected:", error);
	                        console.error("QuickJS: cannot handle error in suspended function", error);
	                        this.suspended = undefined;
	                    });
	                }
	                catch (error) {
	                    (0, debug_1.debugLog)("asyncify.handleSleep: error:", error);
	                    this.suspended = undefined;
	                    throw error;
	                }
	            });
	        }
	        const value = fn();
	        if (value instanceof Promise) {
	            throw new Error("Promise return value not supported in non-asyncify context.");
	        }
	        return value;
	    }
	}
	module$1.QuickJSModuleCallbacks = QuickJSModuleCallbacks;
	function applyBaseRuntimeOptions(runtime, options) {
	    if (options.interruptHandler) {
	        runtime.setInterruptHandler(options.interruptHandler);
	    }
	    if (options.maxStackSizeBytes !== undefined) {
	        runtime.setMaxStackSize(options.maxStackSizeBytes);
	    }
	    if (options.memoryLimitBytes !== undefined) {
	        runtime.setMemoryLimit(options.memoryLimitBytes);
	    }
	}
	module$1.applyBaseRuntimeOptions = applyBaseRuntimeOptions;
	function applyModuleEvalRuntimeOptions(runtime, options) {
	    if (options.moduleLoader) {
	        runtime.setModuleLoader(options.moduleLoader);
	    }
	    if (options.shouldInterrupt) {
	        runtime.setInterruptHandler(options.shouldInterrupt);
	    }
	    if (options.memoryLimitBytes !== undefined) {
	        runtime.setMemoryLimit(options.memoryLimitBytes);
	    }
	    if (options.maxStackSizeBytes !== undefined) {
	        runtime.setMaxStackSize(options.maxStackSizeBytes);
	    }
	}
	module$1.applyModuleEvalRuntimeOptions = applyModuleEvalRuntimeOptions;
	class QuickJSWASMModule {
	    constructor(module, ffi) {
	        this.module = module;
	        this.ffi = ffi;
	        this.callbacks = new QuickJSModuleCallbacks(module);
	    }
	    newRuntime(options = {}) {
	        const rt = new lifetime_1.Lifetime(this.ffi.QTS_NewRuntime(), undefined, (rt_ptr) => {
	            this.callbacks.deleteRuntime(rt_ptr);
	            this.ffi.QTS_FreeRuntime(rt_ptr);
	        });
	        const runtime = new runtime_1.QuickJSRuntime({
	            module: this.module,
	            callbacks: this.callbacks,
	            ffi: this.ffi,
	            rt,
	        });
	        applyBaseRuntimeOptions(runtime, options);
	        if (options.moduleLoader) {
	            runtime.setModuleLoader(options.moduleLoader);
	        }
	        return runtime;
	    }
	    newContext(options = {}) {
	        const runtime = this.newRuntime();
	        const context = runtime.newContext({
	            ...options,
	            ownedLifetimes: (0, types_1.concat)(runtime, options.ownedLifetimes),
	        });
	        runtime.context = context;
	        return context;
	    }
	    evalCode(code, options = {}) {
	        return lifetime_1.Scope.withScope((scope) => {
	            const vm = scope.manage(this.newContext());
	            applyModuleEvalRuntimeOptions(vm.runtime, options);
	            const result = vm.evalCode(code, "eval.js");
	            if (options.memoryLimitBytes !== undefined) {
	                vm.runtime.setMemoryLimit(-1);
	            }
	            if (result.error) {
	                const error = vm.dump(scope.manage(result.error));
	                throw error;
	            }
	            const value = vm.dump(scope.manage(result.value));
	            return value;
	        });
	    }
	    getFFI() {
	        return this.ffi;
	    }
	}
	module$1.QuickJSWASMModule = QuickJSWASMModule;
	return module$1;
}

var moduleAsyncify = {};

var runtimeAsyncify = {};

var contextAsyncify = {};

var hasRequiredContextAsyncify;

function requireContextAsyncify () {
	if (hasRequiredContextAsyncify) return contextAsyncify;
	hasRequiredContextAsyncify = 1;
	Object.defineProperty(contextAsyncify, "__esModule", { value: true });
	contextAsyncify.QuickJSAsyncContext = void 0;
	const context_1 = /*@__PURE__*/ requireContext();
	const debug_1 = /*@__PURE__*/ requireDebug();
	const types_1 = /*@__PURE__*/ requireTypes();
	class QuickJSAsyncContext extends context_1.QuickJSContext {
	    async evalCodeAsync(code, filename = "eval.js",
	    options) {
	        const detectModule = (options === undefined ? 1 : 0);
	        const flags = (0, types_1.evalOptionsToFlags)(options);
	        let resultPtr = 0;
	        try {
	            resultPtr = await this.memory
	                .newHeapCharPointer(code)
	                .consume((charHandle) => this.ffi.QTS_Eval_MaybeAsync(this.ctx.value, charHandle.value, filename, detectModule, flags));
	        }
	        catch (error) {
	            (0, debug_1.debugLog)("QTS_Eval_MaybeAsync threw", error);
	            throw error;
	        }
	        const errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
	        if (errorPtr) {
	            this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr);
	            return { error: this.memory.heapValueHandle(errorPtr) };
	        }
	        return { value: this.memory.heapValueHandle(resultPtr) };
	    }
	    newAsyncifiedFunction(name, fn) {
	        return this.newFunction(name, fn);
	    }
	}
	contextAsyncify.QuickJSAsyncContext = QuickJSAsyncContext;
	return contextAsyncify;
}

var hasRequiredRuntimeAsyncify;

function requireRuntimeAsyncify () {
	if (hasRequiredRuntimeAsyncify) return runtimeAsyncify;
	hasRequiredRuntimeAsyncify = 1;
	Object.defineProperty(runtimeAsyncify, "__esModule", { value: true });
	runtimeAsyncify.QuickJSAsyncRuntime = void 0;
	const _1 = /*@__PURE__*/ requireDist$2();
	const context_asyncify_1 = /*@__PURE__*/ requireContextAsyncify();
	const runtime_1 = /*@__PURE__*/ requireRuntime();
	const types_1 = /*@__PURE__*/ requireTypes();
	class QuickJSAsyncRuntime extends runtime_1.QuickJSRuntime {
	    constructor(args) {
	        super(args);
	    }
	    newContext(options = {}) {
	        if (options.intrinsics && options.intrinsics !== types_1.DefaultIntrinsics) {
	            throw new Error("TODO: Custom intrinsics are not supported yet");
	        }
	        const ctx = new _1.Lifetime(this.ffi.QTS_NewContext(this.rt.value), undefined, (ctx_ptr) => {
	            this.contextMap.delete(ctx_ptr);
	            this.callbacks.deleteContext(ctx_ptr);
	            this.ffi.QTS_FreeContext(ctx_ptr);
	        });
	        const context = new context_asyncify_1.QuickJSAsyncContext({
	            module: this.module,
	            ctx,
	            ffi: this.ffi,
	            rt: this.rt,
	            ownedLifetimes: [],
	            runtime: this,
	            callbacks: this.callbacks,
	        });
	        this.contextMap.set(ctx.value, context);
	        return context;
	    }
	    setModuleLoader(moduleLoader, moduleNormalizer) {
	        super.setModuleLoader(moduleLoader, moduleNormalizer);
	    }
	    setMaxStackSize(stackSize) {
	        return super.setMaxStackSize(stackSize);
	    }
	}
	runtimeAsyncify.QuickJSAsyncRuntime = QuickJSAsyncRuntime;
	return runtimeAsyncify;
}

var hasRequiredModuleAsyncify;

function requireModuleAsyncify () {
	if (hasRequiredModuleAsyncify) return moduleAsyncify;
	hasRequiredModuleAsyncify = 1;
	Object.defineProperty(moduleAsyncify, "__esModule", { value: true });
	moduleAsyncify.QuickJSAsyncWASMModule = void 0;
	const errors_1 = /*@__PURE__*/ requireErrors();
	const lifetime_1 = /*@__PURE__*/ requireLifetime();
	const module_1 = /*@__PURE__*/ requireModule();
	const runtime_asyncify_1 = /*@__PURE__*/ requireRuntimeAsyncify();
	class QuickJSAsyncWASMModule extends module_1.QuickJSWASMModule {
	    constructor(module, ffi) {
	        super(module, ffi);
	        this.ffi = ffi;
	        this.module = module;
	    }
	    newRuntime(options = {}) {
	        const rt = new lifetime_1.Lifetime(this.ffi.QTS_NewRuntime(), undefined, (rt_ptr) => {
	            this.callbacks.deleteRuntime(rt_ptr);
	            this.ffi.QTS_FreeRuntime(rt_ptr);
	        });
	        const runtime = new runtime_asyncify_1.QuickJSAsyncRuntime({
	            module: this.module,
	            ffi: this.ffi,
	            rt,
	            callbacks: this.callbacks,
	        });
	        (0, module_1.applyBaseRuntimeOptions)(runtime, options);
	        if (options.moduleLoader) {
	            runtime.setModuleLoader(options.moduleLoader);
	        }
	        return runtime;
	    }
	    newContext(options = {}) {
	        const runtime = this.newRuntime();
	        const lifetimes = options.ownedLifetimes ? options.ownedLifetimes.concat([runtime]) : [runtime];
	        const context = runtime.newContext({ ...options, ownedLifetimes: lifetimes });
	        runtime.context = context;
	        return context;
	    }
	    evalCode() {
	        throw new errors_1.QuickJSNotImplemented("QuickJSWASMModuleAsyncify.evalCode: use evalCodeAsync instead");
	    }
	    evalCodeAsync(code, options) {
	        return lifetime_1.Scope.withScopeAsync(async (scope) => {
	            const vm = scope.manage(this.newContext());
	            (0, module_1.applyModuleEvalRuntimeOptions)(vm.runtime, options);
	            const result = await vm.evalCodeAsync(code, "eval.js");
	            if (options.memoryLimitBytes !== undefined) {
	                vm.runtime.setMemoryLimit(-1);
	            }
	            if (result.error) {
	                const error = vm.dump(scope.manage(result.error));
	                throw error;
	            }
	            const value = vm.dump(scope.manage(result.value));
	            return value;
	        });
	    }
	}
	moduleAsyncify.QuickJSAsyncWASMModule = QuickJSAsyncWASMModule;
	return moduleAsyncify;
}

var ffi_WASM_RELEASE_SYNC = {};

var hasRequiredFfi_WASM_RELEASE_SYNC;

function requireFfi_WASM_RELEASE_SYNC () {
	if (hasRequiredFfi_WASM_RELEASE_SYNC) return ffi_WASM_RELEASE_SYNC;
	hasRequiredFfi_WASM_RELEASE_SYNC = 1;
	Object.defineProperty(ffi_WASM_RELEASE_SYNC, "__esModule", { value: true });
	ffi_WASM_RELEASE_SYNC.QuickJSFFI = void 0;
	class QuickJSFFI {
	    constructor(module) {
	        this.module = module;
	        this.DEBUG = false;
	        this.QTS_Throw = this.module.cwrap("QTS_Throw", "number", ["number", "number"]);
	        this.QTS_NewError = this.module.cwrap("QTS_NewError", "number", ["number"]);
	        this.QTS_RuntimeSetMemoryLimit = this.module.cwrap("QTS_RuntimeSetMemoryLimit", null, ["number", "number"]);
	        this.QTS_RuntimeComputeMemoryUsage = this.module.cwrap("QTS_RuntimeComputeMemoryUsage", "number", ["number", "number"]);
	        this.QTS_RuntimeDumpMemoryUsage = this.module.cwrap("QTS_RuntimeDumpMemoryUsage", "number", ["number"]);
	        this.QTS_RecoverableLeakCheck = this.module.cwrap("QTS_RecoverableLeakCheck", "number", []);
	        this.QTS_BuildIsSanitizeLeak = this.module.cwrap("QTS_BuildIsSanitizeLeak", "number", []);
	        this.QTS_RuntimeSetMaxStackSize = this.module.cwrap("QTS_RuntimeSetMaxStackSize", null, ["number", "number"]);
	        this.QTS_GetUndefined = this.module.cwrap("QTS_GetUndefined", "number", []);
	        this.QTS_GetNull = this.module.cwrap("QTS_GetNull", "number", []);
	        this.QTS_GetFalse = this.module.cwrap("QTS_GetFalse", "number", []);
	        this.QTS_GetTrue = this.module.cwrap("QTS_GetTrue", "number", []);
	        this.QTS_NewRuntime = this.module.cwrap("QTS_NewRuntime", "number", []);
	        this.QTS_FreeRuntime = this.module.cwrap("QTS_FreeRuntime", null, ["number"]);
	        this.QTS_NewContext = this.module.cwrap("QTS_NewContext", "number", ["number"]);
	        this.QTS_FreeContext = this.module.cwrap("QTS_FreeContext", null, ["number"]);
	        this.QTS_FreeValuePointer = this.module.cwrap("QTS_FreeValuePointer", null, ["number", "number"]);
	        this.QTS_FreeValuePointerRuntime = this.module.cwrap("QTS_FreeValuePointerRuntime", null, ["number", "number"]);
	        this.QTS_FreeVoidPointer = this.module.cwrap("QTS_FreeVoidPointer", null, ["number", "number"]);
	        this.QTS_FreeCString = this.module.cwrap("QTS_FreeCString", null, ["number", "number"]);
	        this.QTS_DupValuePointer = this.module.cwrap("QTS_DupValuePointer", "number", ["number", "number"]);
	        this.QTS_NewObject = this.module.cwrap("QTS_NewObject", "number", ["number"]);
	        this.QTS_NewObjectProto = this.module.cwrap("QTS_NewObjectProto", "number", ["number", "number"]);
	        this.QTS_NewArray = this.module.cwrap("QTS_NewArray", "number", ["number"]);
	        this.QTS_NewFloat64 = this.module.cwrap("QTS_NewFloat64", "number", ["number", "number"]);
	        this.QTS_GetFloat64 = this.module.cwrap("QTS_GetFloat64", "number", ["number", "number"]);
	        this.QTS_NewString = this.module.cwrap("QTS_NewString", "number", ["number", "number"]);
	        this.QTS_GetString = this.module.cwrap("QTS_GetString", "number", ["number", "number"]);
	        this.QTS_NewSymbol = this.module.cwrap("QTS_NewSymbol", "number", ["number", "number", "number"]);
	        this.QTS_GetSymbolDescriptionOrKey = this.module.cwrap("QTS_GetSymbolDescriptionOrKey", "number", ["number", "number"]);
	        this.QTS_IsGlobalSymbol = this.module.cwrap("QTS_IsGlobalSymbol", "number", ["number", "number"]);
	        this.QTS_IsJobPending = this.module.cwrap("QTS_IsJobPending", "number", ["number"]);
	        this.QTS_ExecutePendingJob = this.module.cwrap("QTS_ExecutePendingJob", "number", ["number", "number", "number"]);
	        this.QTS_GetProp = this.module.cwrap("QTS_GetProp", "number", ["number", "number", "number"]);
	        this.QTS_SetProp = this.module.cwrap("QTS_SetProp", null, ["number", "number", "number", "number"]);
	        this.QTS_DefineProp = this.module.cwrap("QTS_DefineProp", null, ["number", "number", "number", "number", "number", "number", "boolean", "boolean", "boolean"]);
	        this.QTS_Call = this.module.cwrap("QTS_Call", "number", ["number", "number", "number", "number", "number"]);
	        this.QTS_ResolveException = this.module.cwrap("QTS_ResolveException", "number", ["number", "number"]);
	        this.QTS_Dump = this.module.cwrap("QTS_Dump", "number", ["number", "number"]);
	        this.QTS_Eval = this.module.cwrap("QTS_Eval", "number", ["number", "number", "string", "number", "number"]);
	        this.QTS_Typeof = this.module.cwrap("QTS_Typeof", "number", ["number", "number"]);
	        this.QTS_GetGlobalObject = this.module.cwrap("QTS_GetGlobalObject", "number", ["number"]);
	        this.QTS_NewPromiseCapability = this.module.cwrap("QTS_NewPromiseCapability", "number", ["number", "number"]);
	        this.QTS_TestStringArg = this.module.cwrap("QTS_TestStringArg", null, ["string"]);
	        this.QTS_BuildIsDebug = this.module.cwrap("QTS_BuildIsDebug", "number", []);
	        this.QTS_BuildIsAsyncify = this.module.cwrap("QTS_BuildIsAsyncify", "number", []);
	        this.QTS_NewFunction = this.module.cwrap("QTS_NewFunction", "number", ["number", "number", "string"]);
	        this.QTS_ArgvGetJSValueConstPointer = this.module.cwrap("QTS_ArgvGetJSValueConstPointer", "number", ["number", "number"]);
	        this.QTS_RuntimeEnableInterruptHandler = this.module.cwrap("QTS_RuntimeEnableInterruptHandler", null, ["number"]);
	        this.QTS_RuntimeDisableInterruptHandler = this.module.cwrap("QTS_RuntimeDisableInterruptHandler", null, ["number"]);
	        this.QTS_RuntimeEnableModuleLoader = this.module.cwrap("QTS_RuntimeEnableModuleLoader", null, ["number", "number"]);
	        this.QTS_RuntimeDisableModuleLoader = this.module.cwrap("QTS_RuntimeDisableModuleLoader", null, ["number"]);
	    }
	}
	ffi_WASM_RELEASE_SYNC.QuickJSFFI = QuickJSFFI;
	return ffi_WASM_RELEASE_SYNC;
}

var emscriptenModule_WASM_RELEASE_SYNC = {exports: {}};

var hasRequiredEmscriptenModule_WASM_RELEASE_SYNC;

function requireEmscriptenModule_WASM_RELEASE_SYNC () {
	if (hasRequiredEmscriptenModule_WASM_RELEASE_SYNC) return emscriptenModule_WASM_RELEASE_SYNC.exports;
	hasRequiredEmscriptenModule_WASM_RELEASE_SYNC = 1;
	(function (module, exports$1) {
		var QuickJSRaw = (() => {
		    var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
		    if (typeof __filename !== 'undefined')
		        _scriptDir = _scriptDir || __filename;
		    return (function (QuickJSRaw = {}) {
		        var a;
		        a || (a = typeof QuickJSRaw !== 'undefined' ? QuickJSRaw : {});
		        var m, n;
		        a.ready = new Promise(function (b, c) { m = b; n = c; });
		        var p = Object.assign({}, a), t = "./this.program", u = "object" == typeof window, v = "function" == typeof importScripts, w = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, x = "", y, z, A;
		        if (w) {
		            var fs = require$$0$3, B = require$$0$4;
		            x = v ? B.dirname(x) + "/" : __dirname + "/";
		            y = (b, c) => { var d = C(b); if (d)
		                return c ? d : d.toString(); b = b.startsWith("file://") ? new URL(b) : B.normalize(b); return fs.readFileSync(b, c ? void 0 : "utf8"); };
		            A = b => { b = y(b, true); b.buffer || (b = new Uint8Array(b)); return b; };
		            z = (b, c, d) => { var e = C(b); e && c(e); b = b.startsWith("file://") ? new URL(b) : B.normalize(b); fs.readFile(b, function (f, g) { f ? d(f) : c(g.buffer); }); };
		            !a.thisProgram && 1 < process.argv.length && (t = process.argv[1].replace(/\\/g, "/"));
		            process.argv.slice(2);
		            a.inspect = function () { return "[Emscripten Module object]"; };
		        }
		        else if (u || v)
		            v ? x = self.location.href : "undefined" != typeof document && document.currentScript && (x = document.currentScript.src), _scriptDir && (x = _scriptDir), 0 !== x.indexOf("blob:") ? x = x.substr(0, x.replace(/[?#].*/, "").lastIndexOf("/") + 1) : x = "", y = b => {
		                try {
		                    var c = new XMLHttpRequest;
		                    c.open("GET", b, !1);
		                    c.send(null);
		                    return c.responseText;
		                }
		                catch (f) {
		                    if (b = C(b)) {
		                        c = [];
		                        for (var d = 0; d < b.length; d++) {
		                            var e = b[d];
		                            255 < e && (e &= 255);
		                            c.push(String.fromCharCode(e));
		                        }
		                        return c.join("");
		                    }
		                    throw f;
		                }
		            }, v && (A = b => { try {
		                var c = new XMLHttpRequest;
		                c.open("GET", b, !1);
		                c.responseType = "arraybuffer";
		                c.send(null);
		                return new Uint8Array(c.response);
		            }
		            catch (d) {
		                if (b = C(b))
		                    return b;
		                throw d;
		            } }), z = (b, c, d) => { var e = new XMLHttpRequest; e.open("GET", b, true); e.responseType = "arraybuffer"; e.onload = () => { if (200 == e.status || 0 == e.status && e.response)
		                c(e.response);
		            else {
		                var f = C(b);
		                f ? c(f.buffer) : d();
		            } }; e.onerror = d; e.send(null); };
		        var aa = a.print || console.log.bind(console), D = a.printErr || console.warn.bind(console);
		        Object.assign(a, p);
		        p = null;
		        a.thisProgram && (t = a.thisProgram);
		        var E;
		        a.wasmBinary && (E = a.wasmBinary);
		        a.noExitRuntime || true;
		        "object" != typeof WebAssembly && F("no native wasm support detected");
		        var G, H = false, I, J, K, L;
		        function M() { var b = G.buffer; a.HEAP8 = I = new Int8Array(b); a.HEAP16 = new Int16Array(b); a.HEAP32 = K = new Int32Array(b); a.HEAPU8 = J = new Uint8Array(b); a.HEAPU16 = new Uint16Array(b); a.HEAPU32 = L = new Uint32Array(b); a.HEAPF32 = new Float32Array(b); a.HEAPF64 = new Float64Array(b); }
		        var ba = [], ca = [], da = [];
		        function ea() { var b = a.preRun.shift(); ba.unshift(b); }
		        var N = 0, P = null;
		        function F(b) { if (a.onAbort)
		            a.onAbort(b); b = "Aborted(" + b + ")"; D(b); H = true; b = new WebAssembly.RuntimeError(b + ". Build with -sASSERTIONS for more info."); n(b); throw b; }
		        var Q = "data:application/octet-stream;base64,", R;
		        R = "data:application/octet-stream;base64, ";
		        if (!R.startsWith(Q)) {
		            var fa = R;
		            R = a.locateFile ? a.locateFile(fa, x) : x + fa;
		        }
		        function ha(b) { try {
		            if (b == R && E)
		                return new Uint8Array(E);
		            var c = C(b);
		            if (c)
		                return c;
		            if (A)
		                return A(b);
		            throw "both async and sync fetching of the wasm failed";
		        }
		        catch (d) {
		            F(d);
		        } }
		        function ia(b) { if (!E && (u || v)) {
		            if ("function" == typeof fetch && !b.startsWith("file://"))
		                return fetch(b, { credentials: "same-origin" }).then(function (c) { if (!c.ok)
		                    throw "failed to load wasm binary file at '" + b + "'"; return c.arrayBuffer(); }).catch(function () { return ha(b); });
		            if (z)
		                return new Promise(function (c, d) { z(b, function (e) { c(new Uint8Array(e)); }, d); });
		        } return Promise.resolve().then(function () { return ha(b); }); }
		        function ja(b, c, d) { return ia(b).then(function (e) { return WebAssembly.instantiate(e, c); }).then(function (e) { return e; }).then(d, function (e) { D("failed to asynchronously prepare wasm: " + e); F(e); }); }
		        function ka(b, c) { var d = R; return E || "function" != typeof WebAssembly.instantiateStreaming || d.startsWith(Q) || d.startsWith("file://") || w || "function" != typeof fetch ? ja(d, b, c) : fetch(d, { credentials: "same-origin" }).then(function (e) { return WebAssembly.instantiateStreaming(e, b).then(c, function (f) { D("wasm streaming compile failed: " + f); D("falling back to ArrayBuffer instantiation"); return ja(d, b, c); }); }); }
		        function S(b) { for (; 0 < b.length;)
		            b.shift()(a); }
		        var la = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0;
		        function na(b, c, d) { var e = c + d; for (d = c; b[d] && !(d >= e);)
		            ++d; if (16 < d - c && b.buffer && la)
		            return la.decode(b.subarray(c, d)); for (e = ""; c < d;) {
		            var f = b[c++];
		            if (f & 128) {
		                var g = b[c++] & 63;
		                if (192 == (f & 224))
		                    e += String.fromCharCode((f & 31) << 6 | g);
		                else {
		                    var h = b[c++] & 63;
		                    f = 224 == (f & 240) ? (f & 15) << 12 | g << 6 | h : (f & 7) << 18 | g << 12 | h << 6 | b[c++] & 63;
		                    65536 > f ? e += String.fromCharCode(f) : (f -= 65536, e += String.fromCharCode(55296 | f >> 10, 56320 | f & 1023));
		                }
		            }
		            else
		                e += String.fromCharCode(f);
		        } return e; }
		        function T(b, c) { return b ? na(J, b, c) : ""; }
		        var oa = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], pa = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
		        function U(b) { for (var c = 0, d = 0; d < b.length; ++d) {
		            var e = b.charCodeAt(d);
		            127 >= e ? c++ : 2047 >= e ? c += 2 : 55296 <= e && 57343 >= e ? (c += 4, ++d) : c += 3;
		        } return c; }
		        function V(b, c, d) { var e = J; if (!(0 < d))
		            return 0; var f = c; d = c + d - 1; for (var g = 0; g < b.length; ++g) {
		            var h = b.charCodeAt(g);
		            if (55296 <= h && 57343 >= h) {
		                var k = b.charCodeAt(++g);
		                h = 65536 + ((h & 1023) << 10) | k & 1023;
		            }
		            if (127 >= h) {
		                if (c >= d)
		                    break;
		                e[c++] = h;
		            }
		            else {
		                if (2047 >= h) {
		                    if (c + 1 >= d)
		                        break;
		                    e[c++] = 192 | h >> 6;
		                }
		                else {
		                    if (65535 >= h) {
		                        if (c + 2 >= d)
		                            break;
		                        e[c++] = 224 | h >> 12;
		                    }
		                    else {
		                        if (c + 3 >= d)
		                            break;
		                        e[c++] = 240 | h >> 18;
		                        e[c++] = 128 | h >> 12 & 63;
		                    }
		                    e[c++] = 128 | h >> 6 & 63;
		                }
		                e[c++] = 128 | h & 63;
		            }
		        } e[c] = 0; return c - f; }
		        function qa(b) { var c = U(b) + 1, d = ra(c); d && V(b, d, c); return d; }
		        var W = {};
		        function sa() { if (!X) {
		            var b = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: ("object" == typeof navigator && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: t || "./this.program" }, c;
		            for (c in W)
		                void 0 === W[c] ? delete b[c] : b[c] = W[c];
		            var d = [];
		            for (c in b)
		                d.push(c + "=" + b[c]);
		            X = d;
		        } return X; }
		        var X, ta = [null, [], []];
		        function ua(b, c, d, e) { var f = { string: l => { var q = 0; if (null !== l && void 0 !== l && 0 !== l) {
		                q = U(l) + 1;
		                var ma = Y(q);
		                V(l, ma, q);
		                q = ma;
		            } return q; }, array: l => { var q = Y(l.length); I.set(l, q); return q; } }; b = a["_" + b]; var g = [], h = 0; if (e)
		            for (var k = 0; k < e.length; k++) {
		                var r = f[d[k]];
		                r ? (0 === h && (h = va()), g[k] = r(e[k])) : g[k] = e[k];
		            } d = b.apply(null, g); return d = function (l) { 0 !== h && wa(h); return "string" === c ? T(l) : "boolean" === c ? !!l : l; }(d); }
		        var xa = "function" == typeof atob ? atob : function (b) {
		            var c = "", d = 0;
		            b = b.replace(/[^A-Za-z0-9\+\/=]/g, "");
		            do {
		                var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
		                var f = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
		                var g = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
		                var h = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
		                e = e << 2 | f >> 4;
		                f = (f & 15) << 4 | g >> 2;
		                var k = (g & 3) << 6 | h;
		                c += String.fromCharCode(e);
		                64 !== g && (c += String.fromCharCode(f));
		                64 !== h && (c += String.fromCharCode(k));
		            } while (d < b.length);
		            return c;
		        };
		        function C(b) { if (b.startsWith(Q)) {
		            b = b.slice(Q.length);
		            if ("boolean" == typeof w && w) {
		                var c = Buffer.from(b, "base64");
		                c = new Uint8Array(c.buffer, c.byteOffset, c.byteLength);
		            }
		            else
		                try {
		                    var d = xa(b), e = new Uint8Array(d.length);
		                    for (b = 0; b < d.length; ++b)
		                        e[b] = d.charCodeAt(b);
		                    c = e;
		                }
		                catch (f) {
		                    throw Error("Converting base64 string to bytes failed.");
		                }
		            return c;
		        } }
		        var ya = { a: function (b, c, d, e) { F("Assertion failed: " + T(b) + ", at: " + [c ? T(c) : "unknown filename", d, e ? T(e) : "unknown function"]); }, l: function (b, c) {
		                b = new Date(1E3 * (L[b >> 2] + 4294967296 * K[b + 4 >> 2]));
		                K[c >> 2] = b.getSeconds();
		                K[c + 4 >> 2] = b.getMinutes();
		                K[c + 8 >> 2] = b.getHours();
		                K[c + 12 >> 2] = b.getDate();
		                K[c + 16 >> 2] = b.getMonth();
		                K[c + 20 >> 2] = b.getFullYear() - 1900;
		                K[c + 24 >> 2] = b.getDay();
		                var d = b.getFullYear();
		                K[c + 28 >> 2] = (0 !== d % 4 || 0 === d % 100 && 0 !== d % 400 ? pa : oa)[b.getMonth()] + b.getDate() - 1 | 0;
		                K[c + 36 >> 2] = -(60 * b.getTimezoneOffset());
		                d = (new Date(b.getFullYear(), 6, 1)).getTimezoneOffset();
		                var e = (new Date(b.getFullYear(), 0, 1)).getTimezoneOffset();
		                K[c + 32 >> 2] = (d != e && b.getTimezoneOffset() == Math.min(e, d)) | 0;
		            }, k: function (b, c, d) { function e(r) { return (r = r.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? r[1] : "GMT"; } var f = (new Date).getFullYear(), g = new Date(f, 0, 1), h = new Date(f, 6, 1); f = g.getTimezoneOffset(); var k = h.getTimezoneOffset(); L[b >> 2] = 60 * Math.max(f, k); K[c >> 2] = Number(f != k); b = e(g); c = e(h); b = qa(b); c = qa(c); k < f ? (L[d >> 2] = b, L[d + 4 >> 2] = c) : (L[d >> 2] = c, L[d + 4 >> 2] = b); }, b: function () { F(""); },
		            m: function () { return Date.now(); }, j: function (b) { var c = J.length; b >>>= 0; if (2147483648 < b)
		                return false; for (var d = 1; 4 >= d; d *= 2) {
		                var e = c * (1 + .2 / d);
		                e = Math.min(e, b + 100663296);
		                var f = Math, g = f.min;
		                e = Math.max(b, e);
		                e += (65536 - e % 65536) % 65536;
		                a: {
		                    var h = G.buffer;
		                    try {
		                        G.grow(g.call(f, 2147483648, e) - h.byteLength + 65535 >>> 16);
		                        M();
		                        var k = 1;
		                        break a;
		                    }
		                    catch (r) { }
		                    k = void 0;
		                }
		                if (k)
		                    return true;
		            } return false; }, e: function (b, c) {
		                var d = 0;
		                sa().forEach(function (e, f) {
		                    var g = c + d;
		                    f = L[b + 4 * f >> 2] = g;
		                    for (g = 0; g < e.length; ++g)
		                        I[f++ >> 0] = e.charCodeAt(g);
		                    I[f >> 0] = 0;
		                    d += e.length +
		                        1;
		                });
		                return 0;
		            }, f: function (b, c) { var d = sa(); L[b >> 2] = d.length; var e = 0; d.forEach(function (f) { e += f.length + 1; }); L[c >> 2] = e; return 0; }, d: function () { return 52; }, i: function () { return 70; }, c: function (b, c, d, e) { for (var f = 0, g = 0; g < d; g++) {
		                var h = L[c >> 2], k = L[c + 4 >> 2];
		                c += 8;
		                for (var r = 0; r < k; r++) {
		                    var l = J[h + r], q = ta[b];
		                    0 === l || 10 === l ? ((1 === b ? aa : D)(na(q, 0)), q.length = 0) : q.push(l);
		                }
		                f += k;
		            } L[e >> 2] = f; return 0; }, o: function (b, c, d, e, f) { return a.callbacks.callFunction(void 0, b, c, d, e, f); }, n: function (b) {
		                return a.callbacks.shouldInterrupt(void 0, b);
		            }, h: function (b, c, d) { d = T(d); return a.callbacks.loadModuleSource(void 0, b, c, d); }, g: function (b, c, d, e) { d = T(d); e = T(e); return a.callbacks.normalizeModule(void 0, b, c, d, e); } };
		        (function () { function b(d) { d = d.exports; a.asm = d; G = a.asm.p; M(); ca.unshift(a.asm.q); N--; a.monitorRunDependencies && a.monitorRunDependencies(N); if (0 == N && (P)) {
		            var e = P;
		            P = null;
		            e();
		        } return d; } var c = { a: ya }; N++; a.monitorRunDependencies && a.monitorRunDependencies(N); if (a.instantiateWasm)
		            try {
		                return a.instantiateWasm(c, b);
		            }
		            catch (d) {
		                D("Module.instantiateWasm callback failed with error: " + d), n(d);
		            } ka(c, function (d) { b(d.instance); }).catch(n); return {}; })();
		        var ra = a._malloc = function () { return (ra = a._malloc = a.asm.r).apply(null, arguments); };
		        a._QTS_Throw = function () { return (a._QTS_Throw = a.asm.s).apply(null, arguments); };
		        a._QTS_NewError = function () { return (a._QTS_NewError = a.asm.t).apply(null, arguments); };
		        a._QTS_RuntimeSetMemoryLimit = function () { return (a._QTS_RuntimeSetMemoryLimit = a.asm.u).apply(null, arguments); };
		        a._QTS_RuntimeComputeMemoryUsage = function () { return (a._QTS_RuntimeComputeMemoryUsage = a.asm.v).apply(null, arguments); };
		        a._QTS_RuntimeDumpMemoryUsage = function () { return (a._QTS_RuntimeDumpMemoryUsage = a.asm.w).apply(null, arguments); };
		        a._QTS_RecoverableLeakCheck = function () { return (a._QTS_RecoverableLeakCheck = a.asm.x).apply(null, arguments); };
		        a._QTS_BuildIsSanitizeLeak = function () { return (a._QTS_BuildIsSanitizeLeak = a.asm.y).apply(null, arguments); };
		        a._QTS_RuntimeSetMaxStackSize = function () { return (a._QTS_RuntimeSetMaxStackSize = a.asm.z).apply(null, arguments); };
		        a._QTS_GetUndefined = function () { return (a._QTS_GetUndefined = a.asm.A).apply(null, arguments); };
		        a._QTS_GetNull = function () { return (a._QTS_GetNull = a.asm.B).apply(null, arguments); };
		        a._QTS_GetFalse = function () { return (a._QTS_GetFalse = a.asm.C).apply(null, arguments); };
		        a._QTS_GetTrue = function () { return (a._QTS_GetTrue = a.asm.D).apply(null, arguments); };
		        a._QTS_NewRuntime = function () { return (a._QTS_NewRuntime = a.asm.E).apply(null, arguments); };
		        a._QTS_FreeRuntime = function () { return (a._QTS_FreeRuntime = a.asm.F).apply(null, arguments); };
		        a._QTS_NewContext = function () { return (a._QTS_NewContext = a.asm.G).apply(null, arguments); };
		        a._QTS_FreeContext = function () { return (a._QTS_FreeContext = a.asm.H).apply(null, arguments); };
		        a._QTS_FreeValuePointer = function () { return (a._QTS_FreeValuePointer = a.asm.I).apply(null, arguments); };
		        a._free = function () { return (a._free = a.asm.J).apply(null, arguments); };
		        a._QTS_FreeValuePointerRuntime = function () { return (a._QTS_FreeValuePointerRuntime = a.asm.K).apply(null, arguments); };
		        a._QTS_FreeVoidPointer = function () { return (a._QTS_FreeVoidPointer = a.asm.L).apply(null, arguments); };
		        a._QTS_FreeCString = function () { return (a._QTS_FreeCString = a.asm.M).apply(null, arguments); };
		        a._QTS_DupValuePointer = function () { return (a._QTS_DupValuePointer = a.asm.N).apply(null, arguments); };
		        a._QTS_NewObject = function () { return (a._QTS_NewObject = a.asm.O).apply(null, arguments); };
		        a._QTS_NewObjectProto = function () { return (a._QTS_NewObjectProto = a.asm.P).apply(null, arguments); };
		        a._QTS_NewArray = function () { return (a._QTS_NewArray = a.asm.Q).apply(null, arguments); };
		        a._QTS_NewFloat64 = function () { return (a._QTS_NewFloat64 = a.asm.R).apply(null, arguments); };
		        a._QTS_GetFloat64 = function () { return (a._QTS_GetFloat64 = a.asm.S).apply(null, arguments); };
		        a._QTS_NewString = function () { return (a._QTS_NewString = a.asm.T).apply(null, arguments); };
		        a._QTS_GetString = function () { return (a._QTS_GetString = a.asm.U).apply(null, arguments); };
		        a._QTS_NewSymbol = function () { return (a._QTS_NewSymbol = a.asm.V).apply(null, arguments); };
		        a._QTS_GetSymbolDescriptionOrKey = function () { return (a._QTS_GetSymbolDescriptionOrKey = a.asm.W).apply(null, arguments); };
		        a._QTS_IsGlobalSymbol = function () { return (a._QTS_IsGlobalSymbol = a.asm.X).apply(null, arguments); };
		        a._QTS_IsJobPending = function () { return (a._QTS_IsJobPending = a.asm.Y).apply(null, arguments); };
		        a._QTS_ExecutePendingJob = function () { return (a._QTS_ExecutePendingJob = a.asm.Z).apply(null, arguments); };
		        a._QTS_GetProp = function () { return (a._QTS_GetProp = a.asm._).apply(null, arguments); };
		        a._QTS_SetProp = function () { return (a._QTS_SetProp = a.asm.$).apply(null, arguments); };
		        a._QTS_DefineProp = function () { return (a._QTS_DefineProp = a.asm.aa).apply(null, arguments); };
		        a._QTS_Call = function () { return (a._QTS_Call = a.asm.ba).apply(null, arguments); };
		        a._QTS_ResolveException = function () { return (a._QTS_ResolveException = a.asm.ca).apply(null, arguments); };
		        a._QTS_Dump = function () { return (a._QTS_Dump = a.asm.da).apply(null, arguments); };
		        a._QTS_Eval = function () { return (a._QTS_Eval = a.asm.ea).apply(null, arguments); };
		        a._QTS_Typeof = function () { return (a._QTS_Typeof = a.asm.fa).apply(null, arguments); };
		        a._QTS_GetGlobalObject = function () { return (a._QTS_GetGlobalObject = a.asm.ga).apply(null, arguments); };
		        a._QTS_NewPromiseCapability = function () { return (a._QTS_NewPromiseCapability = a.asm.ha).apply(null, arguments); };
		        a._QTS_TestStringArg = function () { return (a._QTS_TestStringArg = a.asm.ia).apply(null, arguments); };
		        a._QTS_BuildIsDebug = function () { return (a._QTS_BuildIsDebug = a.asm.ja).apply(null, arguments); };
		        a._QTS_BuildIsAsyncify = function () { return (a._QTS_BuildIsAsyncify = a.asm.ka).apply(null, arguments); };
		        a._QTS_NewFunction = function () { return (a._QTS_NewFunction = a.asm.la).apply(null, arguments); };
		        a._QTS_ArgvGetJSValueConstPointer = function () { return (a._QTS_ArgvGetJSValueConstPointer = a.asm.ma).apply(null, arguments); };
		        a._QTS_RuntimeEnableInterruptHandler = function () { return (a._QTS_RuntimeEnableInterruptHandler = a.asm.na).apply(null, arguments); };
		        a._QTS_RuntimeDisableInterruptHandler = function () { return (a._QTS_RuntimeDisableInterruptHandler = a.asm.oa).apply(null, arguments); };
		        a._QTS_RuntimeEnableModuleLoader = function () { return (a._QTS_RuntimeEnableModuleLoader = a.asm.pa).apply(null, arguments); };
		        a._QTS_RuntimeDisableModuleLoader = function () { return (a._QTS_RuntimeDisableModuleLoader = a.asm.qa).apply(null, arguments); };
		        function va() { return (va = a.asm.sa).apply(null, arguments); }
		        function wa() { return (wa = a.asm.ta).apply(null, arguments); }
		        function Y() { return (Y = a.asm.ua).apply(null, arguments); }
		        a.___start_em_js = 74916;
		        a.___stop_em_js = 75818;
		        a.cwrap = function (b, c, d, e) { var f = !d || d.every(g => "number" === g || "boolean" === g); return "string" !== c && f && !e ? a["_" + b] : function () { return ua(b, c, d, arguments); }; };
		        a.UTF8ToString = T;
		        a.stringToUTF8 = function (b, c, d) { return V(b, c, d); };
		        a.lengthBytesUTF8 = U;
		        var Z;
		        P = function za() { Z || Aa(); Z || (P = za); };
		        function Aa() { function b() { if (!Z && (Z = true, a.calledRun = true, !H)) {
		            S(ca);
		            m(a);
		            if (a.onRuntimeInitialized)
		                a.onRuntimeInitialized();
		            if (a.postRun)
		                for ("function" == typeof a.postRun && (a.postRun = [a.postRun]); a.postRun.length;) {
		                    var c = a.postRun.shift();
		                    da.unshift(c);
		                }
		            S(da);
		        } } if (!(0 < N)) {
		            if (a.preRun)
		                for ("function" == typeof a.preRun && (a.preRun = [a.preRun]); a.preRun.length;)
		                    ea();
		            S(ba);
		            0 < N || (a.setStatus ? (a.setStatus("Running..."), setTimeout(function () { setTimeout(function () { a.setStatus(""); }, 1); b(); }, 1)) : b());
		        } }
		        if (a.preInit)
		            for ("function" == typeof a.preInit && (a.preInit = [a.preInit]); 0 < a.preInit.length;)
		                a.preInit.pop()();
		        Aa();
		        return QuickJSRaw.ready;
		    });
		})();
		module.exports = QuickJSRaw; 
	} (emscriptenModule_WASM_RELEASE_SYNC));
	return emscriptenModule_WASM_RELEASE_SYNC.exports;
}

var hasRequiredVariants;

function requireVariants () {
	if (hasRequiredVariants) return variants;
	hasRequiredVariants = 1;
	(function (exports$1) {
		var __createBinding = (variants && variants.__createBinding) || (Object.create ? (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    var desc = Object.getOwnPropertyDescriptor(m, k);
		    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
		      desc = { enumerable: true, get: function() { return m[k]; } };
		    }
		    Object.defineProperty(o, k2, desc);
		}) : (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    o[k2] = m[k];
		}));
		var __setModuleDefault = (variants && variants.__setModuleDefault) || (Object.create ? (function(o, v) {
		    Object.defineProperty(o, "default", { enumerable: true, value: v });
		}) : function(o, v) {
		    o["default"] = v;
		});
		var __importStar = (variants && variants.__importStar) || function (mod) {
		    if (mod && mod.__esModule) return mod;
		    var result = {};
		    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
		    __setModuleDefault(result, mod);
		    return result;
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.RELEASE_ASYNC = exports$1.DEBUG_ASYNC = exports$1.RELEASE_SYNC = exports$1.DEBUG_SYNC = exports$1.memoizePromiseFactory = exports$1.newQuickJSAsyncWASMModule = exports$1.newQuickJSWASMModule = void 0;
		const esmHelpers_1 = /*@__PURE__*/ requireEsmHelpers();
		async function newQuickJSWASMModule(
		variant = exports$1.RELEASE_SYNC) {
		    const [wasmModuleLoader, QuickJSFFI, { QuickJSWASMModule }] = await Promise.all([
		        variant.importModuleLoader(),
		        variant.importFFI(),
		        Promise.resolve().then(() => __importStar(/*@__PURE__*/ requireModule())).then(esmHelpers_1.unwrapTypescript),
		    ]);
		    const wasmModule = await wasmModuleLoader();
		    wasmModule.type = "sync";
		    const ffi = new QuickJSFFI(wasmModule);
		    return new QuickJSWASMModule(wasmModule, ffi);
		}
		exports$1.newQuickJSWASMModule = newQuickJSWASMModule;
		async function newQuickJSAsyncWASMModule(
		variant = exports$1.RELEASE_ASYNC) {
		    const [wasmModuleLoader, QuickJSAsyncFFI, { QuickJSAsyncWASMModule }] = await Promise.all([
		        variant.importModuleLoader(),
		        variant.importFFI(),
		        Promise.resolve().then(() => __importStar(/*@__PURE__*/ requireModuleAsyncify())).then(esmHelpers_1.unwrapTypescript),
		    ]);
		    const wasmModule = await wasmModuleLoader();
		    wasmModule.type = "async";
		    const ffi = new QuickJSAsyncFFI(wasmModule);
		    return new QuickJSAsyncWASMModule(wasmModule, ffi);
		}
		exports$1.newQuickJSAsyncWASMModule = newQuickJSAsyncWASMModule;
		function memoizePromiseFactory(fn) {
		    let promise;
		    return () => {
		        return (promise ?? (promise = fn()));
		    };
		}
		exports$1.memoizePromiseFactory = memoizePromiseFactory;
		exports$1.DEBUG_SYNC = {
		    type: "sync",
		    async importFFI() {
		        throw new Error("not implemented");
		    },
		    async importModuleLoader() {
		        throw new Error("not implemented");
		    },
		};
		exports$1.RELEASE_SYNC = {
		    type: "sync",
		    async importFFI() {
		        const mod = await Promise.resolve().then(() => __importStar(/*@__PURE__*/ requireFfi_WASM_RELEASE_SYNC()));
		        return (0, esmHelpers_1.unwrapTypescript)(mod).QuickJSFFI;
		    },
		    async importModuleLoader() {
		        const mod = await Promise.resolve().then(() => __importStar(/*@__PURE__*/ requireEmscriptenModule_WASM_RELEASE_SYNC()));
		        return (0, esmHelpers_1.unwrapJavascript)(mod);
		    },
		};
		exports$1.DEBUG_ASYNC = {
		    type: "async",
		    async importFFI() {
		        throw new Error("not implemented");
		    },
		    async importModuleLoader() {
		        throw new Error("not implemented");
		    },
		};
		exports$1.RELEASE_ASYNC = {
		    type: "async",
		    async importFFI() {
		        throw new Error("not implemented");
		    },
		    async importModuleLoader() {
		        throw new Error("not implemented");
		    },
		}; 
	} (variants));
	return variants;
}

var vmInterface = {};

var hasRequiredVmInterface;

function requireVmInterface () {
	if (hasRequiredVmInterface) return vmInterface;
	hasRequiredVmInterface = 1;
	Object.defineProperty(vmInterface, "__esModule", { value: true });
	vmInterface.isFail = vmInterface.isSuccess = void 0;
	function isSuccess(successOrFail) {
	    return "error" in successOrFail === false;
	}
	vmInterface.isSuccess = isSuccess;
	function isFail(successOrFail) {
	    return "error" in successOrFail === true;
	}
	vmInterface.isFail = isFail;
	return vmInterface;
}

var moduleTest = {};

var hasRequiredModuleTest;

function requireModuleTest () {
	if (hasRequiredModuleTest) return moduleTest;
	hasRequiredModuleTest = 1;
	Object.defineProperty(moduleTest, "__esModule", { value: true });
	moduleTest.TestQuickJSWASMModule = void 0;
	const errors_1 = /*@__PURE__*/ requireErrors();
	const lifetime_1 = /*@__PURE__*/ requireLifetime();
	class TestQuickJSWASMModule {
	    constructor(parent) {
	        this.parent = parent;
	        this.contexts = new Set();
	        this.runtimes = new Set();
	    }
	    newRuntime(options) {
	        const runtime = this.parent.newRuntime({
	            ...options,
	            ownedLifetimes: [
	                new lifetime_1.Lifetime(undefined, undefined, () => this.runtimes.delete(runtime)),
	                ...(options?.ownedLifetimes ?? []),
	            ],
	        });
	        this.runtimes.add(runtime);
	        return runtime;
	    }
	    newContext(options) {
	        const context = this.parent.newContext({
	            ...options,
	            ownedLifetimes: [
	                new lifetime_1.Lifetime(undefined, undefined, () => this.contexts.delete(context)),
	                ...(options?.ownedLifetimes ?? []),
	            ],
	        });
	        this.contexts.add(context);
	        return context;
	    }
	    evalCode(code, options) {
	        return this.parent.evalCode(code, options);
	    }
	    disposeAll() {
	        const allDisposables = [...this.contexts, ...this.runtimes];
	        this.runtimes.clear();
	        this.contexts.clear();
	        allDisposables.forEach((d) => {
	            if (d.alive) {
	                d.dispose();
	            }
	        });
	    }
	    assertNoMemoryAllocated() {
	        const leaksDetected = this.getFFI().QTS_RecoverableLeakCheck();
	        if (leaksDetected) {
	            throw new errors_1.QuickJSMemoryLeakDetected("Leak sanitizer detected un-freed memory");
	        }
	        if (this.contexts.size > 0) {
	            throw new errors_1.QuickJSMemoryLeakDetected(`${this.contexts.size} contexts leaked`);
	        }
	        if (this.runtimes.size > 0) {
	            throw new errors_1.QuickJSMemoryLeakDetected(`${this.runtimes.size} runtimes leaked`);
	        }
	    }
	    getFFI() {
	        return this.parent.getFFI();
	    }
	}
	moduleTest.TestQuickJSWASMModule = TestQuickJSWASMModule;
	return moduleTest;
}

var hasRequiredDist$2;

function requireDist$2 () {
	if (hasRequiredDist$2) return dist;
	hasRequiredDist$2 = 1;
	(function (exports$1) {
		var __createBinding = (dist && dist.__createBinding) || (Object.create ? (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    var desc = Object.getOwnPropertyDescriptor(m, k);
		    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
		      desc = { enumerable: true, get: function() { return m[k]; } };
		    }
		    Object.defineProperty(o, k2, desc);
		}) : (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    o[k2] = m[k];
		}));
		var __setModuleDefault = (dist && dist.__setModuleDefault) || (Object.create ? (function(o, v) {
		    Object.defineProperty(o, "default", { enumerable: true, value: v });
		}) : function(o, v) {
		    o["default"] = v;
		});
		var __exportStar = (dist && dist.__exportStar) || function(m, exports$1) {
		    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
		};
		var __importStar = (dist && dist.__importStar) || function (mod) {
		    if (mod && mod.__esModule) return mod;
		    var result = {};
		    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
		    __setModuleDefault(result, mod);
		    return result;
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.shouldInterruptAfterDeadline = exports$1.newAsyncContext = exports$1.newAsyncRuntime = exports$1.getQuickJSSync = exports$1.getQuickJS = exports$1.errors = exports$1.RELEASE_SYNC = exports$1.RELEASE_ASYNC = exports$1.DEBUG_SYNC = exports$1.DEBUG_ASYNC = exports$1.newQuickJSAsyncWASMModule = exports$1.newQuickJSWASMModule = void 0;
		const variants_1 = /*@__PURE__*/ requireVariants();
		Object.defineProperty(exports$1, "newQuickJSWASMModule", { enumerable: true, get: function () { return variants_1.newQuickJSWASMModule; } });
		Object.defineProperty(exports$1, "newQuickJSAsyncWASMModule", { enumerable: true, get: function () { return variants_1.newQuickJSAsyncWASMModule; } });
		Object.defineProperty(exports$1, "DEBUG_ASYNC", { enumerable: true, get: function () { return variants_1.DEBUG_ASYNC; } });
		Object.defineProperty(exports$1, "DEBUG_SYNC", { enumerable: true, get: function () { return variants_1.DEBUG_SYNC; } });
		Object.defineProperty(exports$1, "RELEASE_ASYNC", { enumerable: true, get: function () { return variants_1.RELEASE_ASYNC; } });
		Object.defineProperty(exports$1, "RELEASE_SYNC", { enumerable: true, get: function () { return variants_1.RELEASE_SYNC; } });
		__exportStar(/*@__PURE__*/ requireVmInterface(), exports$1);
		__exportStar(/*@__PURE__*/ requireLifetime(), exports$1);
		exports$1.errors = __importStar(/*@__PURE__*/ requireErrors());
		__exportStar(/*@__PURE__*/ requireDeferredPromise(), exports$1);
		__exportStar(/*@__PURE__*/ requireModuleTest(), exports$1);
		let singleton = undefined;
		let singletonPromise = undefined;
		async function getQuickJS() {
		    singletonPromise ?? (singletonPromise = (0, variants_1.newQuickJSWASMModule)().then((instance) => {
		        singleton = instance;
		        return instance;
		    }));
		    return await singletonPromise;
		}
		exports$1.getQuickJS = getQuickJS;
		function getQuickJSSync() {
		    if (!singleton) {
		        throw new Error("QuickJS not initialized. Await getQuickJS() at least once.");
		    }
		    return singleton;
		}
		exports$1.getQuickJSSync = getQuickJSSync;
		async function newAsyncRuntime(options) {
		    const module = await (0, variants_1.newQuickJSAsyncWASMModule)();
		    return module.newRuntime(options);
		}
		exports$1.newAsyncRuntime = newAsyncRuntime;
		async function newAsyncContext(options) {
		    const module = await (0, variants_1.newQuickJSAsyncWASMModule)();
		    return module.newContext(options);
		}
		exports$1.newAsyncContext = newAsyncContext;
		function shouldInterruptAfterDeadline(deadline) {
		    const deadlineAsNumber = typeof deadline === "number" ? deadline : deadline.getTime();
		    return function () {
		        return Date.now() > deadlineAsNumber;
		    };
		}
		exports$1.shouldInterruptAfterDeadline = shouldInterruptAfterDeadline; 
	} (dist));
	return dist;
}

var hasRequiredDist$1;

function requireDist$1 () {
	if (hasRequiredDist$1) return dist$6;
	hasRequiredDist$1 = 1;
	var __createBinding = (dist$6 && dist$6.__createBinding) || (Object.create ? (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    var desc = Object.getOwnPropertyDescriptor(m, k);
	    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
	      desc = { enumerable: true, get: function() { return m[k]; } };
	    }
	    Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
	    if (k2 === undefined) k2 = k;
	    o[k2] = m[k];
	}));
	var __setModuleDefault = (dist$6 && dist$6.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (dist$6 && dist$6.__importStar) || function (mod) {
	    if (mod && mod.__esModule) return mod;
	    var result = {};
	    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
	    __setModuleDefault(result, mod);
	    return result;
	};
	var __importDefault = (dist$6 && dist$6.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(dist$6, "__esModule", { value: true });
	dist$6.PacProxyAgent = void 0;
	const net = __importStar(require$$0$7);
	const tls = __importStar(require$$1$2);
	const crypto = __importStar(require$$2$1);
	const events_1 = require$$0$8;
	const debug_1 = __importDefault(requireSrc());
	const url_1 = require$$5;
	const agent_base_1 = requireDist$b();
	const get_uri_1 = requireDist$5();
	const pac_resolver_1 = requireDist$3();
	const quickjs_emscripten_1 = /*@__PURE__*/ requireDist$2();
	const debug = (0, debug_1.default)('pac-proxy-agent');
	const setServernameFromNonIpHost = (options) => {
	    if (options.servername === undefined &&
	        options.host &&
	        !net.isIP(options.host)) {
	        return {
	            ...options,
	            servername: options.host,
	        };
	    }
	    return options;
	};
	class PacProxyAgent extends agent_base_1.Agent {
	    constructor(uri, opts) {
	        super(opts);
	        this.clearResolverPromise = () => {
	            this.resolverPromise = undefined;
	        };
	        const uriStr = typeof uri === 'string' ? uri : uri.href;
	        this.uri = new url_1.URL(uriStr.replace(/^pac\+/i, ''));
	        debug('Creating PacProxyAgent with URI %o', this.uri.href);
	        this.opts = { ...opts };
	        this.cache = undefined;
	        this.resolver = undefined;
	        this.resolverHash = '';
	        this.resolverPromise = undefined;
	        if (!this.opts.filename) {
	            this.opts.filename = this.uri.href;
	        }
	    }
	    getResolver() {
	        if (!this.resolverPromise) {
	            this.resolverPromise = this.loadResolver();
	            this.resolverPromise.then(this.clearResolverPromise, this.clearResolverPromise);
	        }
	        return this.resolverPromise;
	    }
	    async loadResolver() {
	        try {
	            const [qjs, code] = await Promise.all([
	                (0, quickjs_emscripten_1.getQuickJS)(),
	                this.loadPacFile(),
	            ]);
	            const hash = crypto.createHash('sha1').update(code).digest('hex');
	            if (this.resolver && this.resolverHash === hash) {
	                debug('Same sha1 hash for code - contents have not changed, reusing previous proxy resolver');
	                return this.resolver;
	            }
	            debug('Creating new proxy resolver instance');
	            this.resolver = (0, pac_resolver_1.createPacResolver)(qjs, code, this.opts);
	            this.resolverHash = hash;
	            return this.resolver;
	        }
	        catch (err) {
	            if (this.resolver &&
	                err.code === 'ENOTMODIFIED') {
	                debug('Got ENOTMODIFIED response, reusing previous proxy resolver');
	                return this.resolver;
	            }
	            throw err;
	        }
	    }
	    async loadPacFile() {
	        debug('Loading PAC file: %o', this.uri);
	        const rs = await (0, get_uri_1.getUri)(this.uri, { ...this.opts, cache: this.cache });
	        debug('Got `Readable` instance for URI');
	        this.cache = rs;
	        const buf = await (0, agent_base_1.toBuffer)(rs);
	        debug('Read %o byte PAC file from URI', buf.length);
	        return buf.toString('utf8');
	    }
	    async connect(req, opts) {
	        const { secureEndpoint } = opts;
	        const isWebSocket = req.getHeader('upgrade') === 'websocket';
	        const resolver = await this.getResolver();
	        const protocol = secureEndpoint ? 'https:' : 'http:';
	        const host = opts.host && net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
	        const url = Object.assign(new url_1.URL(req.path, `${protocol}//${host}`), undefined );
	        debug('url: %s', url);
	        let result = await resolver(url);
	        if (!result) {
	            result = 'DIRECT';
	        }
	        const proxies = String(result)
	            .trim()
	            .split(/\s*;\s*/g)
	            .filter(Boolean);
	        if (this.opts.fallbackToDirect && !proxies.includes('DIRECT')) {
	            proxies.push('DIRECT');
	        }
	        for (const proxy of proxies) {
	            let agent = null;
	            let socket = null;
	            const [type, target] = proxy.split(/\s+/);
	            debug('Attempting to use proxy: %o', proxy);
	            if (type === 'DIRECT') {
	                if (secureEndpoint) {
	                    socket = tls.connect(setServernameFromNonIpHost(opts));
	                }
	                else {
	                    socket = net.connect(opts);
	                }
	            }
	            else if (type === 'SOCKS' || type === 'SOCKS5') {
	                const { SocksProxyAgent } = await Promise.resolve().then(() => __importStar(requireDist$8()));
	                agent = new SocksProxyAgent(`socks://${target}`, this.opts);
	            }
	            else if (type === 'SOCKS4') {
	                const { SocksProxyAgent } = await Promise.resolve().then(() => __importStar(requireDist$8()));
	                agent = new SocksProxyAgent(`socks4a://${target}`, this.opts);
	            }
	            else if (type === 'PROXY' ||
	                type === 'HTTP' ||
	                type === 'HTTPS') {
	                const proxyURL = `${type === 'HTTPS' ? 'https' : 'http'}://${target}`;
	                if (secureEndpoint || isWebSocket) {
	                    const { HttpsProxyAgent } = await Promise.resolve().then(() => __importStar(requireDist$9()));
	                    agent = new HttpsProxyAgent(proxyURL, this.opts);
	                }
	                else {
	                    const { HttpProxyAgent } = await Promise.resolve().then(() => __importStar(requireDist$a()));
	                    agent = new HttpProxyAgent(proxyURL, this.opts);
	                }
	            }
	            try {
	                if (socket) {
	                    await (0, events_1.once)(socket, 'connect');
	                    req.emit('proxy', { proxy, socket });
	                    return socket;
	                }
	                if (agent) {
	                    const s = await agent.connect(req, opts);
	                    if (!(s instanceof net.Socket)) {
	                        throw new Error('Expected a `net.Socket` to be returned from agent');
	                    }
	                    req.emit('proxy', { proxy, socket: s });
	                    return s;
	                }
	                throw new Error(`Could not determine proxy type for: ${proxy}`);
	            }
	            catch (err) {
	                debug('Got error for proxy %o: %o', proxy, err);
	                req.emit('proxy', { proxy, error: err });
	            }
	        }
	        throw new Error(`Failed to establish a socket connection to proxies: ${JSON.stringify(proxies)}`);
	    }
	}
	PacProxyAgent.protocols = [
	    'pac+data',
	    'pac+file',
	    'pac+ftp',
	    'pac+http',
	    'pac+https',
	];
	dist$6.PacProxyAgent = PacProxyAgent;
	return dist$6;
}

var hasRequiredDist;

function requireDist () {
	if (hasRequiredDist) return dist$b;
	hasRequiredDist = 1;
	(function (exports$1) {
		var __createBinding = (dist$b && dist$b.__createBinding) || (Object.create ? (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    var desc = Object.getOwnPropertyDescriptor(m, k);
		    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
		      desc = { enumerable: true, get: function() { return m[k]; } };
		    }
		    Object.defineProperty(o, k2, desc);
		}) : (function(o, m, k, k2) {
		    if (k2 === undefined) k2 = k;
		    o[k2] = m[k];
		}));
		var __setModuleDefault = (dist$b && dist$b.__setModuleDefault) || (Object.create ? (function(o, v) {
		    Object.defineProperty(o, "default", { enumerable: true, value: v });
		}) : function(o, v) {
		    o["default"] = v;
		});
		var __importStar = (dist$b && dist$b.__importStar) || function (mod) {
		    if (mod && mod.__esModule) return mod;
		    var result = {};
		    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
		    __setModuleDefault(result, mod);
		    return result;
		};
		var __importDefault = (dist$b && dist$b.__importDefault) || function (mod) {
		    return (mod && mod.__esModule) ? mod : { "default": mod };
		};
		Object.defineProperty(exports$1, "__esModule", { value: true });
		exports$1.ProxyAgent = exports$1.proxies = void 0;
		const http = __importStar(require$$0$6);
		const https = __importStar(require$$1$1);
		const url_1 = require$$5;
		const lru_cache_1 = __importDefault(/*@__PURE__*/ requireLruCache());
		const agent_base_1 = requireDist$b();
		const debug_1 = __importDefault(requireSrc());
		const proxy_from_env_1 = requireProxyFromEnv();
		const debug = (0, debug_1.default)('proxy-agent');
		const wellKnownAgents = {
		    http: async () => (await Promise.resolve().then(() => __importStar(requireDist$a()))).HttpProxyAgent,
		    https: async () => (await Promise.resolve().then(() => __importStar(requireDist$9()))).HttpsProxyAgent,
		    socks: async () => (await Promise.resolve().then(() => __importStar(requireDist$8()))).SocksProxyAgent,
		    pac: async () => (await Promise.resolve().then(() => __importStar(requireDist$1()))).PacProxyAgent,
		};
		exports$1.proxies = {
		    http: [wellKnownAgents.http, wellKnownAgents.https],
		    https: [wellKnownAgents.http, wellKnownAgents.https],
		    socks: [wellKnownAgents.socks, wellKnownAgents.socks],
		    socks4: [wellKnownAgents.socks, wellKnownAgents.socks],
		    socks4a: [wellKnownAgents.socks, wellKnownAgents.socks],
		    socks5: [wellKnownAgents.socks, wellKnownAgents.socks],
		    socks5h: [wellKnownAgents.socks, wellKnownAgents.socks],
		    'pac+data': [wellKnownAgents.pac, wellKnownAgents.pac],
		    'pac+file': [wellKnownAgents.pac, wellKnownAgents.pac],
		    'pac+ftp': [wellKnownAgents.pac, wellKnownAgents.pac],
		    'pac+http': [wellKnownAgents.pac, wellKnownAgents.pac],
		    'pac+https': [wellKnownAgents.pac, wellKnownAgents.pac],
		};
		function isValidProtocol(v) {
		    return Object.keys(exports$1.proxies).includes(v);
		}
		class ProxyAgent extends agent_base_1.Agent {
		    constructor(opts) {
		        super(opts);
		        this.cache = new lru_cache_1.default({
		            max: 20,
		            dispose: (agent) => agent.destroy(),
		        });
		        debug('Creating new ProxyAgent instance: %o', opts);
		        this.connectOpts = opts;
		        this.httpAgent = opts?.httpAgent || new http.Agent(opts);
		        this.httpsAgent =
		            opts?.httpsAgent || new https.Agent(opts);
		        this.getProxyForUrl = opts?.getProxyForUrl || proxy_from_env_1.getProxyForUrl;
		    }
		    async connect(req, opts) {
		        const { secureEndpoint } = opts;
		        const isWebSocket = req.getHeader('upgrade') === 'websocket';
		        const protocol = secureEndpoint
		            ? isWebSocket
		                ? 'wss:'
		                : 'https:'
		            : isWebSocket
		                ? 'ws:'
		                : 'http:';
		        const host = req.getHeader('host');
		        const url = new url_1.URL(req.path, `${protocol}//${host}`).href;
		        const proxy = await this.getProxyForUrl(url, req);
		        if (!proxy) {
		            debug('Proxy not enabled for URL: %o', url);
		            return secureEndpoint ? this.httpsAgent : this.httpAgent;
		        }
		        debug('Request URL: %o', url);
		        debug('Proxy URL: %o', proxy);
		        const cacheKey = `${protocol}+${proxy}`;
		        let agent = this.cache.get(cacheKey);
		        if (!agent) {
		            const proxyUrl = new url_1.URL(proxy);
		            const proxyProto = proxyUrl.protocol.replace(':', '');
		            if (!isValidProtocol(proxyProto)) {
		                throw new Error(`Unsupported protocol for proxy URL: ${proxy}`);
		            }
		            const ctor = await exports$1.proxies[proxyProto][secureEndpoint || isWebSocket ? 1 : 0]();
		            agent = new ctor(proxy, this.connectOpts);
		            this.cache.set(cacheKey, agent);
		        }
		        else {
		            debug('Cache hit for proxy URL: %o', proxy);
		        }
		        return agent;
		    }
		    destroy() {
		        for (const agent of this.cache.values()) {
		            agent.destroy();
		        }
		        super.destroy();
		    }
		}
		exports$1.ProxyAgent = ProxyAgent; 
	} (dist$b));
	return dist$b;
}

var distExports = requireDist();

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function httpRequest(url, method, response, keepAlive = true) {
    const options = {
        protocol: url.protocol,
        hostname: url.hostname,
        port: url.port,
        path: url.pathname + url.search,
        method,
        headers: keepAlive ? { Connection: 'keep-alive' } : undefined,
        auth: urlToHttpOptions(url).auth,
        agent: new distExports.ProxyAgent(),
    };
    const requestCallback = (res) => {
        if (res.statusCode &&
            res.statusCode >= 300 &&
            res.statusCode < 400 &&
            res.headers.location) {
            httpRequest(new URL$1(res.headers.location), method, response);
            res.resume();
        }
        else {
            response(res);
        }
    };
    const request = options.protocol === 'https:'
        ? https$1.request(options, requestCallback)
        : http$1.request(options, requestCallback);
    request.end();
    return request;
}
async function getJSON(url) {
    const text = await getText(url);
    try {
        return JSON.parse(text);
    }
    catch {
        throw new Error('Could not parse JSON from ' + url.toString());
    }
}
function getText(url) {
    return new Promise((resolve, reject) => {
        const request = httpRequest(url, 'GET', response => {
            let data = '';
            if (response.statusCode && response.statusCode >= 400) {
                return reject(new Error(`Got status code ${response.statusCode}`));
            }
            response.on('data', chunk => {
                data += chunk;
            });
            response.on('end', () => {
                try {
                    return resolve(String(data));
                }
                catch {
                    return reject(new Error(`Failed to read text response from ${url}`));
                }
            });
        }, false);
        request.on('error', err => {
            reject(err);
        });
    });
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function folder$3(platform) {
    switch (platform) {
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            return 'linux64';
        case BrowserPlatform.MAC_ARM:
            return 'mac-arm64';
        case BrowserPlatform.MAC:
            return 'mac-x64';
        case BrowserPlatform.WIN32:
            return 'win32';
        case BrowserPlatform.WIN64:
            return 'win64';
    }
}
function resolveDownloadUrl$4(platform, buildId, baseUrl = 'https://storage.googleapis.com/chrome-for-testing-public') {
    return `${baseUrl}/${resolveDownloadPath$4(platform, buildId).join('/')}`;
}
function resolveDownloadPath$4(platform, buildId) {
    return [buildId, folder$3(platform), `chrome-${folder$3(platform)}.zip`];
}
function relativeExecutablePath$4(platform, _buildId) {
    switch (platform) {
        case BrowserPlatform.MAC:
        case BrowserPlatform.MAC_ARM:
            return path$1.join('chrome-' + folder$3(platform), 'Google Chrome for Testing.app', 'Contents', 'MacOS', 'Google Chrome for Testing');
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            return path$1.join('chrome-linux64', 'chrome');
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
            return path$1.join('chrome-' + folder$3(platform), 'chrome.exe');
    }
}
let baseVersionUrl$1 = 'https://googlechromelabs.github.io/chrome-for-testing';
async function getLastKnownGoodReleaseForChannel(channel) {
    const data = (await getJSON(new URL(`${baseVersionUrl$1}/last-known-good-versions.json`)));
    for (const channel of Object.keys(data.channels)) {
        data.channels[channel.toLowerCase()] = data.channels[channel];
        delete data.channels[channel];
    }
    return data.channels[channel];
}
async function getLastKnownGoodReleaseForMilestone(milestone) {
    const data = (await getJSON(new URL(`${baseVersionUrl$1}/latest-versions-per-milestone.json`)));
    return data.milestones[milestone];
}
async function getLastKnownGoodReleaseForBuild(
buildPrefix) {
    const data = (await getJSON(new URL(`${baseVersionUrl$1}/latest-patch-versions-per-build.json`)));
    return data.builds[buildPrefix];
}
async function resolveBuildId$3(channel) {
    if (Object.values(ChromeReleaseChannel).includes(channel)) {
        return (await getLastKnownGoodReleaseForChannel(channel)).version;
    }
    if (channel.match(/^\d+$/)) {
        return (await getLastKnownGoodReleaseForMilestone(channel))?.version;
    }
    if (channel.match(/^\d+\.\d+\.\d+$/)) {
        return (await getLastKnownGoodReleaseForBuild(channel))?.version;
    }
    return;
}
const WINDOWS_ENV_PARAM_NAMES = [
    'PROGRAMFILES',
    'ProgramW6432',
    'ProgramFiles(x86)',
    'LOCALAPPDATA',
];
function getChromeWindowsLocation(channel, locationsPrefixes) {
    if (locationsPrefixes.size === 0) {
        throw new Error('Non of the common Windows Env variables were set');
    }
    let suffix;
    switch (channel) {
        case ChromeReleaseChannel.STABLE:
            suffix = 'Google\\Chrome\\Application\\chrome.exe';
            break;
        case ChromeReleaseChannel.BETA:
            suffix = 'Google\\Chrome Beta\\Application\\chrome.exe';
            break;
        case ChromeReleaseChannel.CANARY:
            suffix = 'Google\\Chrome SxS\\Application\\chrome.exe';
            break;
        case ChromeReleaseChannel.DEV:
            suffix = 'Google\\Chrome Dev\\Application\\chrome.exe';
            break;
    }
    return [...locationsPrefixes.values()].map(l => {
        return path$1.win32.join(l, suffix);
    });
}
function getWslVariable(variable) {
    try {
        const result = execSync(`cmd.exe /c echo %${variable.toLocaleUpperCase()}%`, {
            stdio: ['ignore', 'pipe', 'ignore'],
            encoding: 'utf-8',
        }).trim();
        if (result) {
            return result;
        }
    }
    catch { }
    return;
}
function getWslLocation(channel) {
    const wslVersion = execSync('wslinfo --version', {
        stdio: ['ignore', 'pipe', 'ignore'],
        encoding: 'utf-8',
    }).trim();
    if (!wslVersion) {
        throw new Error('Not in WSL or unsupported version of WSL.');
    }
    const wslPrefixes = new Set();
    for (const name of WINDOWS_ENV_PARAM_NAMES) {
        const wslPrefix = getWslVariable(name);
        if (wslPrefix) {
            wslPrefixes.add(wslPrefix);
        }
    }
    const windowsPath = getChromeWindowsLocation(channel, wslPrefixes);
    return windowsPath.map(path => {
        return execSync(`wslpath "${path}"`).toString().trim();
    });
}
function getChromeLinuxOrWslLocation(channel) {
    const locations = [];
    switch (channel) {
        case ChromeReleaseChannel.STABLE:
            locations.push('/opt/google/chrome/chrome');
            break;
        case ChromeReleaseChannel.BETA:
            locations.push('/opt/google/chrome-beta/chrome');
            break;
        case ChromeReleaseChannel.CANARY:
            locations.push('/opt/google/chrome-canary/chrome');
            break;
        case ChromeReleaseChannel.DEV:
            locations.push('/opt/google/chrome-unstable/chrome');
            break;
    }
    try {
        const wslPath = getWslLocation(channel);
        if (wslPath) {
            locations.push(...wslPath);
        }
    }
    catch {
    }
    return locations;
}
function resolveSystemExecutablePaths$1(platform, channel) {
    switch (platform) {
        case BrowserPlatform.WIN64:
        case BrowserPlatform.WIN32:
            const prefixLocation = new Set(WINDOWS_ENV_PARAM_NAMES.map(name => {
                return process.env[name];
            }).filter((l) => {
                return !!l;
            }));
            prefixLocation.add('C:\\Program Files');
            prefixLocation.add('C:\\Program Files (x86)');
            prefixLocation.add('D:\\Program Files');
            prefixLocation.add('D:\\Program Files (x86)');
            return getChromeWindowsLocation(channel, prefixLocation);
        case BrowserPlatform.MAC_ARM:
        case BrowserPlatform.MAC:
            switch (channel) {
                case ChromeReleaseChannel.STABLE:
                    return [
                        '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
                    ];
                case ChromeReleaseChannel.BETA:
                    return [
                        '/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta',
                    ];
                case ChromeReleaseChannel.CANARY:
                    return [
                        '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
                    ];
                case ChromeReleaseChannel.DEV:
                    return [
                        '/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev',
                    ];
            }
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            return getChromeLinuxOrWslLocation(channel);
    }
}
function resolveDefaultUserDataDir$1(platform, channel) {
    switch (platform) {
        case BrowserPlatform.WIN64:
        case BrowserPlatform.WIN32:
            switch (channel) {
                case ChromeReleaseChannel.STABLE:
                    return path$1.join(getLocalAppDataWin(), 'Google', 'Chrome', 'User Data');
                case ChromeReleaseChannel.BETA:
                    return path$1.join(getLocalAppDataWin(), 'Google', 'Chrome Beta', 'User Data');
                case ChromeReleaseChannel.CANARY:
                    return path$1.join(getLocalAppDataWin(), 'Google', 'Chrome SxS', 'User Data');
                case ChromeReleaseChannel.DEV:
                    return path$1.join(getLocalAppDataWin(), 'Google', 'Chrome Dev', 'User Data');
            }
        case BrowserPlatform.MAC_ARM:
        case BrowserPlatform.MAC:
            switch (channel) {
                case ChromeReleaseChannel.STABLE:
                    return path$1.join(getBaseUserDataDirPathMac(), 'Chrome');
                case ChromeReleaseChannel.BETA:
                    return path$1.join(getBaseUserDataDirPathMac(), 'Chrome Beta');
                case ChromeReleaseChannel.DEV:
                    return path$1.join(getBaseUserDataDirPathMac(), 'Chrome Dev');
                case ChromeReleaseChannel.CANARY:
                    return path$1.join(getBaseUserDataDirPathMac(), 'Chrome Canary');
            }
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            switch (channel) {
                case ChromeReleaseChannel.STABLE:
                    return path$1.join(getConfigHomeLinux(), 'google-chrome');
                case ChromeReleaseChannel.BETA:
                    return path$1.join(getConfigHomeLinux(), 'google-chrome-beta');
                case ChromeReleaseChannel.CANARY:
                    return path$1.join(getConfigHomeLinux(), 'google-chrome-canary');
                case ChromeReleaseChannel.DEV:
                    return path$1.join(getConfigHomeLinux(), 'google-chrome-unstable');
            }
    }
}
function getLocalAppDataWin() {
    return (process.env['LOCALAPPDATA'] || path$1.join(os.homedir(), 'AppData', 'Local'));
}
function getConfigHomeLinux() {
    return (process.env['CHROME_CONFIG_HOME'] ||
        process.env['XDG_CONFIG_HOME'] ||
        path$1.join(os.homedir(), '.config'));
}
function getBaseUserDataDirPathMac() {
    return path$1.join(os.homedir(), 'Library', 'Application Support', 'Google');
}
function compareVersions$2(a, b) {
    if (!semver.valid(a)) {
        throw new Error(`Version ${a} is not a valid semver version`);
    }
    if (!semver.valid(b)) {
        throw new Error(`Version ${b} is not a valid semver version`);
    }
    if (semver.gt(a, b)) {
        return 1;
    }
    else if (semver.lt(a, b)) {
        return -1;
    }
    else {
        return 0;
    }
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function folder$2(platform) {
    switch (platform) {
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            return 'linux64';
        case BrowserPlatform.MAC_ARM:
            return 'mac-arm64';
        case BrowserPlatform.MAC:
            return 'mac-x64';
        case BrowserPlatform.WIN32:
            return 'win32';
        case BrowserPlatform.WIN64:
            return 'win64';
    }
}
function resolveDownloadUrl$3(platform, buildId, baseUrl = 'https://storage.googleapis.com/chrome-for-testing-public') {
    return `${baseUrl}/${resolveDownloadPath$3(platform, buildId).join('/')}`;
}
function resolveDownloadPath$3(platform, buildId) {
    return [
        buildId,
        folder$2(platform),
        `chrome-headless-shell-${folder$2(platform)}.zip`,
    ];
}
function relativeExecutablePath$3(platform, _buildId) {
    switch (platform) {
        case BrowserPlatform.MAC:
        case BrowserPlatform.MAC_ARM:
            return path$1.join('chrome-headless-shell-' + folder$2(platform), 'chrome-headless-shell');
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            return path$1.join('chrome-headless-shell-linux64', 'chrome-headless-shell');
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
            return path$1.join('chrome-headless-shell-' + folder$2(platform), 'chrome-headless-shell.exe');
    }
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function folder$1(platform) {
    switch (platform) {
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            return 'linux64';
        case BrowserPlatform.MAC_ARM:
            return 'mac-arm64';
        case BrowserPlatform.MAC:
            return 'mac-x64';
        case BrowserPlatform.WIN32:
            return 'win32';
        case BrowserPlatform.WIN64:
            return 'win64';
    }
}
function resolveDownloadUrl$2(platform, buildId, baseUrl = 'https://storage.googleapis.com/chrome-for-testing-public') {
    return `${baseUrl}/${resolveDownloadPath$2(platform, buildId).join('/')}`;
}
function resolveDownloadPath$2(platform, buildId) {
    return [buildId, folder$1(platform), `chromedriver-${folder$1(platform)}.zip`];
}
function relativeExecutablePath$2(platform, _buildId) {
    switch (platform) {
        case BrowserPlatform.MAC:
        case BrowserPlatform.MAC_ARM:
            return path$1.join('chromedriver-' + folder$1(platform), 'chromedriver');
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            return path$1.join('chromedriver-linux64', 'chromedriver');
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
            return path$1.join('chromedriver-' + folder$1(platform), 'chromedriver.exe');
    }
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function archive$1(platform, buildId) {
    switch (platform) {
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            return 'chrome-linux';
        case BrowserPlatform.MAC_ARM:
        case BrowserPlatform.MAC:
            return 'chrome-mac';
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
            return parseInt(buildId, 10) > 591479 ? 'chrome-win' : 'chrome-win32';
    }
}
function folder(platform) {
    switch (platform) {
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            return 'Linux_x64';
        case BrowserPlatform.MAC_ARM:
            return 'Mac_Arm';
        case BrowserPlatform.MAC:
            return 'Mac';
        case BrowserPlatform.WIN32:
            return 'Win';
        case BrowserPlatform.WIN64:
            return 'Win_x64';
    }
}
function resolveDownloadUrl$1(platform, buildId, baseUrl = 'https://storage.googleapis.com/chromium-browser-snapshots') {
    return `${baseUrl}/${resolveDownloadPath$1(platform, buildId).join('/')}`;
}
function resolveDownloadPath$1(platform, buildId) {
    return [folder(platform), buildId, `${archive$1(platform, buildId)}.zip`];
}
function relativeExecutablePath$1(platform, _buildId) {
    switch (platform) {
        case BrowserPlatform.MAC:
        case BrowserPlatform.MAC_ARM:
            return path$1.join('chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium');
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            return path$1.join('chrome-linux', 'chrome');
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
            return path$1.join('chrome-win', 'chrome.exe');
    }
}
async function resolveBuildId$2(platform) {
    return await getText(new URL(`https://storage.googleapis.com/chromium-browser-snapshots/${folder(platform)}/LAST_CHANGE`));
}
function compareVersions$1(a, b) {
    return Number(a) - Number(b);
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function getFormat$1(buildId) {
    const majorVersion = Number(buildId.split('.').shift());
    return majorVersion >= 135 ? 'xz' : 'bz2';
}
function archiveNightly(platform, buildId) {
    switch (platform) {
        case BrowserPlatform.LINUX:
            return `firefox-${buildId}.en-US.linux-x86_64.tar.${getFormat$1(buildId)}`;
        case BrowserPlatform.LINUX_ARM:
            return `firefox-${buildId}.en-US.linux-aarch64.tar.${getFormat$1(buildId)}`;
        case BrowserPlatform.MAC_ARM:
        case BrowserPlatform.MAC:
            return `firefox-${buildId}.en-US.mac.dmg`;
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
            return `firefox-${buildId}.en-US.${platform}.zip`;
    }
}
function archive(platform, buildId) {
    switch (platform) {
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
            return `firefox-${buildId}.tar.${getFormat$1(buildId)}`;
        case BrowserPlatform.MAC_ARM:
        case BrowserPlatform.MAC:
            return `Firefox ${buildId}.dmg`;
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
            return `Firefox Setup ${buildId}.exe`;
    }
}
function platformName(platform) {
    switch (platform) {
        case BrowserPlatform.LINUX:
            return `linux-x86_64`;
        case BrowserPlatform.LINUX_ARM:
            return `linux-aarch64`;
        case BrowserPlatform.MAC_ARM:
        case BrowserPlatform.MAC:
            return `mac`;
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
            return platform;
    }
}
function parseBuildId(buildId) {
    for (const value of Object.values(FirefoxChannel)) {
        if (buildId.startsWith(value + '_')) {
            buildId = buildId.substring(value.length + 1);
            return [value, buildId];
        }
    }
    return [FirefoxChannel.NIGHTLY, buildId];
}
function resolveDownloadUrl(platform, buildId, baseUrl) {
    const [channel] = parseBuildId(buildId);
    switch (channel) {
        case FirefoxChannel.NIGHTLY:
            baseUrl ??=
                'https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central';
            break;
        case FirefoxChannel.DEVEDITION:
            baseUrl ??= 'https://archive.mozilla.org/pub/devedition/releases';
            break;
        case FirefoxChannel.BETA:
        case FirefoxChannel.STABLE:
        case FirefoxChannel.ESR:
            baseUrl ??= 'https://archive.mozilla.org/pub/firefox/releases';
            break;
    }
    return `${baseUrl}/${resolveDownloadPath(platform, buildId).join('/')}`;
}
function resolveDownloadPath(platform, buildId) {
    const [channel, resolvedBuildId] = parseBuildId(buildId);
    switch (channel) {
        case FirefoxChannel.NIGHTLY:
            return [archiveNightly(platform, resolvedBuildId)];
        case FirefoxChannel.DEVEDITION:
        case FirefoxChannel.BETA:
        case FirefoxChannel.STABLE:
        case FirefoxChannel.ESR:
            return [
                resolvedBuildId,
                platformName(platform),
                'en-US',
                archive(platform, resolvedBuildId),
            ];
    }
}
function relativeExecutablePath(platform, buildId) {
    const [channel] = parseBuildId(buildId);
    switch (channel) {
        case FirefoxChannel.NIGHTLY:
            switch (platform) {
                case BrowserPlatform.MAC_ARM:
                case BrowserPlatform.MAC:
                    return path$1.join('Firefox Nightly.app', 'Contents', 'MacOS', 'firefox');
                case BrowserPlatform.LINUX_ARM:
                case BrowserPlatform.LINUX:
                    return path$1.join('firefox', 'firefox');
                case BrowserPlatform.WIN32:
                case BrowserPlatform.WIN64:
                    return path$1.join('firefox', 'firefox.exe');
            }
        case FirefoxChannel.BETA:
        case FirefoxChannel.DEVEDITION:
        case FirefoxChannel.ESR:
        case FirefoxChannel.STABLE:
            switch (platform) {
                case BrowserPlatform.MAC_ARM:
                case BrowserPlatform.MAC:
                    return path$1.join('Firefox.app', 'Contents', 'MacOS', 'firefox');
                case BrowserPlatform.LINUX_ARM:
                case BrowserPlatform.LINUX:
                    return path$1.join('firefox', 'firefox');
                case BrowserPlatform.WIN32:
                case BrowserPlatform.WIN64:
                    return path$1.join('core', 'firefox.exe');
            }
    }
}
var FirefoxChannel;
(function (FirefoxChannel) {
    FirefoxChannel["STABLE"] = "stable";
    FirefoxChannel["ESR"] = "esr";
    FirefoxChannel["DEVEDITION"] = "devedition";
    FirefoxChannel["BETA"] = "beta";
    FirefoxChannel["NIGHTLY"] = "nightly";
})(FirefoxChannel || (FirefoxChannel = {}));
let baseVersionUrl = 'https://product-details.mozilla.org/1.0';
async function resolveBuildId$1(channel = FirefoxChannel.NIGHTLY) {
    const channelToVersionKey = {
        [FirefoxChannel.ESR]: 'FIREFOX_ESR',
        [FirefoxChannel.STABLE]: 'LATEST_FIREFOX_VERSION',
        [FirefoxChannel.DEVEDITION]: 'FIREFOX_DEVEDITION',
        [FirefoxChannel.BETA]: 'FIREFOX_DEVEDITION',
        [FirefoxChannel.NIGHTLY]: 'FIREFOX_NIGHTLY',
    };
    const versions = (await getJSON(new URL(`${baseVersionUrl}/firefox_versions.json`)));
    const version = versions[channelToVersionKey[channel]];
    if (!version) {
        throw new Error(`Channel ${channel} is not found.`);
    }
    return channel + '_' + version;
}
async function createProfile$1(options) {
    if (!fs.existsSync(options.path)) {
        await fs.promises.mkdir(options.path, {
            recursive: true,
        });
    }
    await syncPreferences({
        preferences: {
            ...defaultProfilePreferences(options.preferences),
            ...options.preferences,
        },
        path: options.path,
    });
}
function defaultProfilePreferences(extraPrefs) {
    const server = 'dummy.test';
    const defaultPrefs = {
        'app.normandy.api_url': '',
        'app.update.checkInstallTime': false,
        'app.update.disabledForTesting': true,
        'apz.content_response_timeout': 60000,
        'browser.contentblocking.features.standard': '-tp,tpPrivate,cookieBehavior0,-cryptoTP,-fp',
        'browser.dom.window.dump.enabled': true,
        'browser.newtabpage.activity-stream.feeds.system.topstories': false,
        'browser.newtabpage.enabled': false,
        'browser.pagethumbnails.capturing_disabled': true,
        'browser.safebrowsing.blockedURIs.enabled': false,
        'browser.safebrowsing.downloads.enabled': false,
        'browser.safebrowsing.malware.enabled': false,
        'browser.safebrowsing.phishing.enabled': false,
        'browser.search.update': false,
        'browser.sessionstore.resume_from_crash': false,
        'browser.shell.checkDefaultBrowser': false,
        'browser.startup.homepage': 'about:blank',
        'browser.startup.homepage_override.mstone': 'ignore',
        'browser.startup.page': 0,
        'browser.tabs.disableBackgroundZombification': false,
        'browser.tabs.warnOnCloseOtherTabs': false,
        'browser.tabs.warnOnOpen': false,
        'browser.translations.automaticallyPopup': false,
        'browser.uitour.enabled': false,
        'browser.urlbar.suggest.searches': false,
        'browser.usedOnWindows10.introURL': '',
        'browser.warnOnQuit': false,
        'datareporting.healthreport.documentServerURI': `http://${server}/dummy/healthreport/`,
        'datareporting.healthreport.logging.consoleEnabled': false,
        'datareporting.healthreport.service.enabled': false,
        'datareporting.healthreport.service.firstRun': false,
        'datareporting.healthreport.uploadEnabled': false,
        'datareporting.policy.dataSubmissionEnabled': false,
        'datareporting.policy.dataSubmissionPolicyBypassNotification': true,
        'devtools.jsonview.enabled': false,
        'dom.disable_open_during_load': false,
        'dom.file.createInChild': true,
        'dom.ipc.reportProcessHangs': false,
        'dom.max_chrome_script_run_time': 0,
        'dom.max_script_run_time': 0,
        'extensions.autoDisableScopes': 0,
        'extensions.enabledScopes': 5,
        'extensions.getAddons.cache.enabled': false,
        'extensions.installDistroAddons': false,
        'extensions.update.enabled': false,
        'extensions.update.notifyUser': false,
        'extensions.webservice.discoverURL': `http://${server}/dummy/discoveryURL`,
        'focusmanager.testmode': true,
        'general.useragent.updates.enabled': false,
        'geo.provider.testing': true,
        'geo.wifi.scan': false,
        'hangmonitor.timeout': 0,
        'javascript.options.showInConsole': true,
        'media.gmp-manager.updateEnabled': false,
        'media.sanity-test.disabled': true,
        'network.cookie.sameSite.laxByDefault': false,
        'network.http.prompt-temp-redirect': false,
        'network.http.speculative-parallel-limit': 0,
        'network.manage-offline-status': false,
        'network.sntp.pools': server,
        'plugin.state.flash': 0,
        'privacy.trackingprotection.enabled': false,
        'remote.enabled': true,
        'remote.bidi.dismiss_file_pickers.enabled': true,
        'screenshots.browser.component.enabled': false,
        'security.certerrors.mitm.priming.enabled': false,
        'security.fileuri.strict_origin_policy': false,
        'security.notification_enable_delay': 0,
        'services.settings.server': `http://${server}/dummy/blocklist/`,
        'signon.autofillForms': false,
        'signon.rememberSignons': false,
        'startup.homepage_welcome_url': 'about:blank',
        'startup.homepage_welcome_url.additional': '',
        'toolkit.cosmeticAnimations.enabled': false,
        'toolkit.startup.max_resumed_crashes': -1,
    };
    return Object.assign(defaultPrefs, extraPrefs);
}
async function backupFile(input) {
    if (!fs.existsSync(input)) {
        return;
    }
    await fs.promises.copyFile(input, input + '.puppeteer');
}
async function syncPreferences(options) {
    const prefsPath = path$1.join(options.path, 'prefs.js');
    const userPath = path$1.join(options.path, 'user.js');
    const lines = Object.entries(options.preferences).map(([key, value]) => {
        return `user_pref(${JSON.stringify(key)}, ${JSON.stringify(value)});`;
    });
    const result = await Promise.allSettled([
        backupFile(userPath).then(async () => {
            await fs.promises.writeFile(userPath, lines.join('\n'));
        }),
        backupFile(prefsPath),
    ]);
    for (const command of result) {
        if (command.status === 'rejected') {
            throw command.reason;
        }
    }
}
function compareVersions(a, b) {
    return parseInt(a.replace('.', ''), 16) - parseInt(b.replace('.', ''), 16);
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
({
    [Browser.CHROMEDRIVER]: resolveDownloadUrl$2,
    [Browser.CHROMEHEADLESSSHELL]: resolveDownloadUrl$3,
    [Browser.CHROME]: resolveDownloadUrl$4,
    [Browser.CHROMIUM]: resolveDownloadUrl$1,
    [Browser.FIREFOX]: resolveDownloadUrl,
});
({
    [Browser.CHROMEDRIVER]: resolveDownloadPath$2,
    [Browser.CHROMEHEADLESSSHELL]: resolveDownloadPath$3,
    [Browser.CHROME]: resolveDownloadPath$4,
    [Browser.CHROMIUM]: resolveDownloadPath$1,
    [Browser.FIREFOX]: resolveDownloadPath,
});
const executablePathByBrowser = {
    [Browser.CHROMEDRIVER]: relativeExecutablePath$2,
    [Browser.CHROMEHEADLESSSHELL]: relativeExecutablePath$3,
    [Browser.CHROME]: relativeExecutablePath$4,
    [Browser.CHROMIUM]: relativeExecutablePath$1,
    [Browser.FIREFOX]: relativeExecutablePath,
};
const versionComparators = {
    [Browser.CHROMEDRIVER]: compareVersions$2,
    [Browser.CHROMEHEADLESSSHELL]: compareVersions$2,
    [Browser.CHROME]: compareVersions$2,
    [Browser.CHROMIUM]: compareVersions$1,
    [Browser.FIREFOX]: compareVersions,
};
async function resolveBuildIdForBrowserTag(browser, platform, tag) {
    switch (browser) {
        case Browser.FIREFOX:
            switch (tag) {
                case BrowserTag.LATEST:
                    return await resolveBuildId$1(FirefoxChannel.NIGHTLY);
                case BrowserTag.BETA:
                    return await resolveBuildId$1(FirefoxChannel.BETA);
                case BrowserTag.NIGHTLY:
                    return await resolveBuildId$1(FirefoxChannel.NIGHTLY);
                case BrowserTag.DEVEDITION:
                    return await resolveBuildId$1(FirefoxChannel.DEVEDITION);
                case BrowserTag.STABLE:
                    return await resolveBuildId$1(FirefoxChannel.STABLE);
                case BrowserTag.ESR:
                    return await resolveBuildId$1(FirefoxChannel.ESR);
                case BrowserTag.CANARY:
                case BrowserTag.DEV:
                    throw new Error(`${tag.toUpperCase()} is not available for Firefox`);
            }
        case Browser.CHROME: {
            switch (tag) {
                case BrowserTag.LATEST:
                    return await resolveBuildId$3(ChromeReleaseChannel.CANARY);
                case BrowserTag.BETA:
                    return await resolveBuildId$3(ChromeReleaseChannel.BETA);
                case BrowserTag.CANARY:
                    return await resolveBuildId$3(ChromeReleaseChannel.CANARY);
                case BrowserTag.DEV:
                    return await resolveBuildId$3(ChromeReleaseChannel.DEV);
                case BrowserTag.STABLE:
                    return await resolveBuildId$3(ChromeReleaseChannel.STABLE);
                case BrowserTag.NIGHTLY:
                case BrowserTag.DEVEDITION:
                case BrowserTag.ESR:
                    throw new Error(`${tag.toUpperCase()} is not available for Chrome`);
            }
        }
        case Browser.CHROMEDRIVER: {
            switch (tag) {
                case BrowserTag.LATEST:
                case BrowserTag.CANARY:
                    return await resolveBuildId$3(ChromeReleaseChannel.CANARY);
                case BrowserTag.BETA:
                    return await resolveBuildId$3(ChromeReleaseChannel.BETA);
                case BrowserTag.DEV:
                    return await resolveBuildId$3(ChromeReleaseChannel.DEV);
                case BrowserTag.STABLE:
                    return await resolveBuildId$3(ChromeReleaseChannel.STABLE);
                case BrowserTag.NIGHTLY:
                case BrowserTag.DEVEDITION:
                case BrowserTag.ESR:
                    throw new Error(`${tag.toUpperCase()} is not available for ChromeDriver`);
            }
        }
        case Browser.CHROMEHEADLESSSHELL: {
            switch (tag) {
                case BrowserTag.LATEST:
                case BrowserTag.CANARY:
                    return await resolveBuildId$3(ChromeReleaseChannel.CANARY);
                case BrowserTag.BETA:
                    return await resolveBuildId$3(ChromeReleaseChannel.BETA);
                case BrowserTag.DEV:
                    return await resolveBuildId$3(ChromeReleaseChannel.DEV);
                case BrowserTag.STABLE:
                    return await resolveBuildId$3(ChromeReleaseChannel.STABLE);
                case BrowserTag.NIGHTLY:
                case BrowserTag.DEVEDITION:
                case BrowserTag.ESR:
                    throw new Error(`${tag} is not available for chrome-headless-shell`);
            }
        }
        case Browser.CHROMIUM:
            switch (tag) {
                case BrowserTag.LATEST:
                    return await resolveBuildId$2(platform);
                case BrowserTag.NIGHTLY:
                case BrowserTag.CANARY:
                case BrowserTag.DEV:
                case BrowserTag.DEVEDITION:
                case BrowserTag.BETA:
                case BrowserTag.STABLE:
                case BrowserTag.ESR:
                    throw new Error(`${tag} is not supported for Chromium. Use 'latest' instead.`);
            }
    }
}
async function resolveBuildId(browser, platform, tag) {
    const browserTag = tag;
    if (Object.values(BrowserTag).includes(browserTag)) {
        return await resolveBuildIdForBrowserTag(browser, platform, browserTag);
    }
    switch (browser) {
        case Browser.FIREFOX:
            return tag;
        case Browser.CHROME:
            const chromeResult = await resolveBuildId$3(tag);
            if (chromeResult) {
                return chromeResult;
            }
            return tag;
        case Browser.CHROMEDRIVER:
            const chromeDriverResult = await resolveBuildId$3(tag);
            if (chromeDriverResult) {
                return chromeDriverResult;
            }
            return tag;
        case Browser.CHROMEHEADLESSSHELL:
            const chromeHeadlessShellResult = await resolveBuildId$3(tag);
            if (chromeHeadlessShellResult) {
                return chromeHeadlessShellResult;
            }
            return tag;
        case Browser.CHROMIUM:
            return tag;
    }
}
async function createProfile(browser, opts) {
    switch (browser) {
        case Browser.FIREFOX:
            return await createProfile$1(opts);
        case Browser.CHROME:
        case Browser.CHROMIUM:
            throw new Error(`Profile creation is not support for ${browser} yet`);
    }
}
function resolveDefaultUserDataDir(browser, platform, channel) {
    switch (browser) {
        case Browser.CHROMEDRIVER:
        case Browser.CHROMEHEADLESSSHELL:
        case Browser.FIREFOX:
        case Browser.CHROMIUM:
            throw new Error(`Default user dir detection is not supported for ${browser} yet.`);
        case Browser.CHROME:
            return resolveDefaultUserDataDir$1(platform, channel);
    }
}
function resolveSystemExecutablePaths(browser, platform, channel) {
    switch (browser) {
        case Browser.CHROMEDRIVER:
        case Browser.CHROMEHEADLESSSHELL:
        case Browser.FIREFOX:
        case Browser.CHROMIUM:
            throw new Error(`System browser detection is not supported for ${browser} yet.`);
        case Browser.CHROME:
            return resolveSystemExecutablePaths$1(platform, channel);
    }
}
function getVersionComparator(browser) {
    return versionComparators[browser];
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function detectBrowserPlatform() {
    const platform = os.platform();
    const arch = os.arch();
    switch (platform) {
        case 'darwin':
            return arch === 'arm64' ? BrowserPlatform.MAC_ARM : BrowserPlatform.MAC;
        case 'linux':
            return arch === 'arm64'
                ? BrowserPlatform.LINUX_ARM
                : BrowserPlatform.LINUX;
        case 'win32':
            return arch === 'x64' ||
                (arch === 'arm64' && isWindows11(os.release()))
                ? BrowserPlatform.WIN64
                : BrowserPlatform.WIN32;
        default:
            return undefined;
    }
}
function isWindows11(version) {
    const parts = version.split('.');
    if (parts.length > 2) {
        const major = parseInt(parts[0], 10);
        const minor = parseInt(parts[1], 10);
        const patch = parseInt(parts[2], 10);
        return (major > 10 ||
            (major === 10 && minor > 0) ||
            (major === 10 && minor === 0 && patch >= 22000));
    }
    return false;
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const debugCache = debug$2('puppeteer:browsers:cache');
class InstalledBrowser {
    browser;
    buildId;
    platform;
    executablePath;
    #cache;
    constructor(cache, browser, buildId, platform) {
        this.#cache = cache;
        this.browser = browser;
        this.buildId = buildId;
        this.platform = platform;
        this.executablePath = cache.computeExecutablePath({
            browser,
            buildId,
            platform,
        });
    }
    get path() {
        return this.#cache.installationDir(this.browser, this.platform, this.buildId);
    }
    readMetadata() {
        return this.#cache.readMetadata(this.browser);
    }
    writeMetadata(metadata) {
        this.#cache.writeMetadata(this.browser, metadata);
    }
}
let Cache$2 = class Cache {
    #rootDir;
    constructor(rootDir) {
        this.#rootDir = rootDir;
    }
    get rootDir() {
        return this.#rootDir;
    }
    browserRoot(browser) {
        return path$1.join(this.#rootDir, browser);
    }
    metadataFile(browser) {
        return path$1.join(this.browserRoot(browser), '.metadata');
    }
    readMetadata(browser) {
        const metatadaPath = this.metadataFile(browser);
        if (!fs.existsSync(metatadaPath)) {
            return { aliases: {} };
        }
        const data = JSON.parse(fs.readFileSync(metatadaPath, 'utf8'));
        if (typeof data !== 'object') {
            throw new Error('.metadata is not an object');
        }
        return data;
    }
    writeMetadata(browser, metadata) {
        const metatadaPath = this.metadataFile(browser);
        fs.mkdirSync(path$1.dirname(metatadaPath), { recursive: true });
        fs.writeFileSync(metatadaPath, JSON.stringify(metadata, null, 2));
    }
    readExecutablePath(browser, platform, buildId) {
        const metadata = this.readMetadata(browser);
        const key = `${platform}-${buildId}`;
        return metadata.executablePaths?.[key] ?? null;
    }
    writeExecutablePath(browser, platform, buildId, executablePath) {
        const metadata = this.readMetadata(browser);
        if (!metadata.executablePaths) {
            metadata.executablePaths = {};
        }
        const key = `${platform}-${buildId}`;
        metadata.executablePaths[key] = executablePath;
        this.writeMetadata(browser, metadata);
    }
    resolveAlias(browser, alias) {
        const metadata = this.readMetadata(browser);
        if (alias === 'latest') {
            return Object.values(metadata.aliases || {})
                .sort(getVersionComparator(browser))
                .at(-1);
        }
        return metadata.aliases[alias];
    }
    installationDir(browser, platform, buildId) {
        return path$1.join(this.browserRoot(browser), `${platform}-${buildId}`);
    }
    clear() {
        fs.rmSync(this.#rootDir, {
            force: true,
            recursive: true,
            maxRetries: 10,
            retryDelay: 500,
        });
    }
    uninstall(browser, platform, buildId) {
        const metadata = this.readMetadata(browser);
        for (const alias of Object.keys(metadata.aliases)) {
            if (metadata.aliases[alias] === buildId) {
                delete metadata.aliases[alias];
            }
        }
        const key = `${platform}-${buildId}`;
        if (metadata.executablePaths?.[key]) {
            delete metadata.executablePaths[key];
            this.writeMetadata(browser, metadata);
        }
        fs.rmSync(this.installationDir(browser, platform, buildId), {
            force: true,
            recursive: true,
            maxRetries: 10,
            retryDelay: 500,
        });
    }
    getInstalledBrowsers() {
        if (!fs.existsSync(this.#rootDir)) {
            return [];
        }
        const types = fs.readdirSync(this.#rootDir);
        const browsers = types.filter((t) => {
            return Object.values(Browser).includes(t);
        });
        return browsers.flatMap(browser => {
            const files = fs.readdirSync(this.browserRoot(browser));
            return files
                .map(file => {
                const result = parseFolderPath(path$1.join(this.browserRoot(browser), file));
                if (!result) {
                    return null;
                }
                return new InstalledBrowser(this, browser, result.buildId, result.platform);
            })
                .filter((item) => {
                return item !== null;
            });
        });
    }
    computeExecutablePath(options) {
        options.platform ??= detectBrowserPlatform();
        if (!options.platform) {
            throw new Error(`Cannot download a binary for the provided platform: ${os.platform()} (${os.arch()})`);
        }
        try {
            options.buildId =
                this.resolveAlias(options.browser, options.buildId) ?? options.buildId;
        }
        catch {
            debugCache('could not read .metadata file for the browser');
        }
        const installationDir = this.installationDir(options.browser, options.platform, options.buildId);
        const storedExecutablePath = this.readExecutablePath(options.browser, options.platform, options.buildId);
        if (storedExecutablePath) {
            return path$1.join(installationDir, storedExecutablePath);
        }
        return path$1.join(installationDir, executablePathByBrowser[options.browser](options.platform, options.buildId));
    }
};
function parseFolderPath(folderPath) {
    const name = path$1.basename(folderPath);
    const splits = name.split('-');
    if (splits.length !== 2) {
        return;
    }
    const [platform, buildId] = splits;
    if (!buildId || !platform) {
        return;
    }
    return { platform, buildId };
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const debugLaunch = debug$2('puppeteer:browsers:launcher');
function computeExecutablePath(options) {
    if (options.cacheDir === null) {
        options.platform ??= detectBrowserPlatform();
        if (options.platform === undefined) {
            throw new Error(`No platform specified. Couldn't auto-detect browser platform.`);
        }
        return executablePathByBrowser[options.browser](options.platform, options.buildId);
    }
    return new Cache$2(options.cacheDir).computeExecutablePath(options);
}
function computeSystemExecutablePath(options) {
    options.platform ??= detectBrowserPlatform();
    if (!options.platform) {
        throw new Error(`Cannot download a binary for the provided platform: ${os.platform()} (${os.arch()})`);
    }
    const paths = resolveSystemExecutablePaths(options.browser, options.platform, options.channel);
    for (const path of paths) {
        try {
            accessSync(path);
            return path;
        }
        catch { }
    }
    throw new Error(`Could not find Google Chrome executable for channel '${options.channel}' at:${paths.map(path => {
        return `\n - ${path}`;
    })}.`);
}
function launch$1(opts) {
    return new Process(opts);
}
const CDP_WEBSOCKET_ENDPOINT_REGEX = /^DevTools listening on (ws:\/\/.*)$/;
const WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX = /^WebDriver BiDi listening on (ws:\/\/.*)$/;
const processListeners = new Map();
const dispatchers = {
    exit: (...args) => {
        processListeners.get('exit')?.forEach(handler => {
            return handler(...args);
        });
    },
    SIGINT: (...args) => {
        processListeners.get('SIGINT')?.forEach(handler => {
            return handler(...args);
        });
    },
    SIGHUP: (...args) => {
        processListeners.get('SIGHUP')?.forEach(handler => {
            return handler(...args);
        });
    },
    SIGTERM: (...args) => {
        processListeners.get('SIGTERM')?.forEach(handler => {
            return handler(...args);
        });
    },
};
function subscribeToProcessEvent(event, handler) {
    const listeners = processListeners.get(event) || [];
    if (listeners.length === 0) {
        process.on(event, dispatchers[event]);
    }
    listeners.push(handler);
    processListeners.set(event, listeners);
}
function unsubscribeFromProcessEvent(event, handler) {
    const listeners = processListeners.get(event) || [];
    const existingListenerIdx = listeners.indexOf(handler);
    if (existingListenerIdx === -1) {
        return;
    }
    listeners.splice(existingListenerIdx, 1);
    processListeners.set(event, listeners);
    if (listeners.length === 0) {
        process.off(event, dispatchers[event]);
    }
}
class Process {
    #executablePath;
    #args;
    #browserProcess;
    #exited = false;
    #hooksRan = false;
    #onExitHook = async () => { };
    #browserProcessExiting;
    #logs = [];
    #maxLogLinesSize = 1000;
    #lineEmitter = new EventEmitter$1();
    #onAbort = () => {
        this.kill();
    };
    #signal;
    constructor(opts) {
        this.#executablePath = opts.executablePath;
        this.#args = opts.args ?? [];
        this.#signal = opts.signal;
        if (this.#signal?.aborted) {
            throw new Error(this.#signal.reason ? this.#signal.reason : 'Launch aborted');
        }
        this.#signal?.addEventListener('abort', this.#onAbort, { once: true });
        opts.pipe ??= false;
        opts.dumpio ??= false;
        opts.handleSIGINT ??= true;
        opts.handleSIGTERM ??= true;
        opts.handleSIGHUP ??= true;
        opts.detached ??= process.platform !== 'win32';
        const stdio = this.#configureStdio({
            pipe: opts.pipe,
        });
        const env = opts.env || {};
        debugLaunch(`Launching ${this.#executablePath} ${this.#args.join(' ')}`, {
            detached: opts.detached,
            env: Object.keys(env).reduce((res, key) => {
                if (key.toLowerCase().startsWith('puppeteer_')) {
                    res[key] = env[key];
                }
                return res;
            }, {}),
            stdio,
        });
        this.#browserProcess = childProcess.spawn(this.#executablePath, this.#args, {
            detached: opts.detached,
            env,
            stdio,
        });
        this.#recordStream(this.#browserProcess.stderr);
        this.#recordStream(this.#browserProcess.stdout);
        debugLaunch(`Launched ${this.#browserProcess.pid}`);
        if (opts.dumpio) {
            this.#browserProcess.stderr?.pipe(process.stderr);
            this.#browserProcess.stdout?.pipe(process.stdout);
        }
        subscribeToProcessEvent('exit', this.#onDriverProcessExit);
        if (opts.handleSIGINT) {
            subscribeToProcessEvent('SIGINT', this.#onDriverProcessSignal);
        }
        if (opts.handleSIGTERM) {
            subscribeToProcessEvent('SIGTERM', this.#onDriverProcessSignal);
        }
        if (opts.handleSIGHUP) {
            subscribeToProcessEvent('SIGHUP', this.#onDriverProcessSignal);
        }
        if (opts.onExit) {
            this.#onExitHook = opts.onExit;
        }
        this.#browserProcessExiting = new Promise((resolve, reject) => {
            this.#browserProcess.once('exit', async () => {
                debugLaunch(`Browser process ${this.#browserProcess.pid} onExit`);
                this.#clearListeners();
                this.#exited = true;
                try {
                    await this.#runHooks();
                }
                catch (err) {
                    reject(err);
                    return;
                }
                resolve();
            });
        });
    }
    async #runHooks() {
        if (this.#hooksRan) {
            return;
        }
        this.#hooksRan = true;
        await this.#onExitHook();
    }
    get nodeProcess() {
        return this.#browserProcess;
    }
    #configureStdio(opts) {
        if (opts.pipe) {
            return ['pipe', 'pipe', 'pipe', 'pipe', 'pipe'];
        }
        else {
            return ['pipe', 'pipe', 'pipe'];
        }
    }
    #clearListeners() {
        unsubscribeFromProcessEvent('exit', this.#onDriverProcessExit);
        unsubscribeFromProcessEvent('SIGINT', this.#onDriverProcessSignal);
        unsubscribeFromProcessEvent('SIGTERM', this.#onDriverProcessSignal);
        unsubscribeFromProcessEvent('SIGHUP', this.#onDriverProcessSignal);
        this.#signal?.removeEventListener('abort', this.#onAbort);
    }
    #onDriverProcessExit = (_code) => {
        this.kill();
    };
    #onDriverProcessSignal = (signal) => {
        switch (signal) {
            case 'SIGINT':
                this.kill();
                process.exit(130);
            case 'SIGTERM':
            case 'SIGHUP':
                void this.close();
                break;
        }
    };
    async close() {
        await this.#runHooks();
        if (!this.#exited) {
            this.kill();
        }
        return await this.#browserProcessExiting;
    }
    hasClosed() {
        return this.#browserProcessExiting;
    }
    kill() {
        debugLaunch(`Trying to kill ${this.#browserProcess.pid}`);
        if (this.#browserProcess &&
            this.#browserProcess.pid &&
            pidExists(this.#browserProcess.pid)) {
            try {
                debugLaunch(`Browser process ${this.#browserProcess.pid} exists`);
                if (process.platform === 'win32') {
                    try {
                        childProcess.execSync(`taskkill /pid ${this.#browserProcess.pid} /T /F`);
                    }
                    catch (error) {
                        debugLaunch(`Killing ${this.#browserProcess.pid} using taskkill failed`, error);
                        this.#browserProcess.kill();
                    }
                }
                else {
                    const processGroupId = -this.#browserProcess.pid;
                    try {
                        process.kill(processGroupId, 'SIGKILL');
                    }
                    catch (error) {
                        debugLaunch(`Killing ${this.#browserProcess.pid} using process.kill failed`, error);
                        this.#browserProcess.kill('SIGKILL');
                    }
                }
            }
            catch (error) {
                throw new Error(`${PROCESS_ERROR_EXPLANATION}\nError cause: ${isErrorLike(error) ? error.stack : error}`);
            }
        }
        this.#clearListeners();
    }
    #recordStream(stream) {
        const rl = readline.createInterface(stream);
        const cleanup = () => {
            rl.off('line', onLine);
            rl.off('close', onClose);
            try {
                rl.close();
            }
            catch { }
        };
        const onLine = (line) => {
            if (line.trim() === '') {
                return;
            }
            this.#logs.push(line);
            const delta = this.#logs.length - this.#maxLogLinesSize;
            if (delta) {
                this.#logs.splice(0, delta);
            }
            this.#lineEmitter.emit('line', line);
        };
        const onClose = () => {
            cleanup();
        };
        rl.on('line', onLine);
        rl.on('close', onClose);
    }
    getRecentLogs() {
        return [...this.#logs];
    }
    waitForLineOutput(regex, timeout = 0) {
        return new Promise((resolve, reject) => {
            const onClose = (errorOrCode) => {
                cleanup();
                reject(new Error([
                    `Failed to launch the browser process: ${errorOrCode instanceof Error
                        ? ` ${errorOrCode.message}`
                        : ` Code: ${errorOrCode}`}`,
                    '',
                    `stderr:`,
                    this.getRecentLogs().join('\n'),
                    '',
                    'TROUBLESHOOTING: https://pptr.dev/troubleshooting',
                    '',
                ].join('\n')));
            };
            this.#browserProcess.on('exit', onClose);
            this.#browserProcess.on('error', onClose);
            const timeoutId = timeout > 0 ? setTimeout(onTimeout, timeout) : undefined;
            this.#lineEmitter.on('line', onLine);
            const cleanup = () => {
                clearTimeout(timeoutId);
                this.#lineEmitter.off('line', onLine);
                this.#browserProcess.off('exit', onClose);
                this.#browserProcess.off('error', onClose);
            };
            function onTimeout() {
                cleanup();
                reject(new TimeoutError(`Timed out after ${timeout} ms while waiting for the WS endpoint URL to appear in stdout!`));
            }
            for (const line of this.#logs) {
                onLine(line);
            }
            function onLine(line) {
                const match = line.match(regex);
                if (!match) {
                    return;
                }
                cleanup();
                resolve(match[1]);
            }
        });
    }
}
const PROCESS_ERROR_EXPLANATION = `Puppeteer was unable to kill the process which ran the browser binary.
This means that, on future Puppeteer launches, Puppeteer might not be able to launch the browser.
Please check your open processes and ensure that the browser processes that Puppeteer launched have been killed.
If you think this is a bug, please report it on the Puppeteer issue tracker.`;
function pidExists(pid) {
    try {
        return process.kill(pid, 0);
    }
    catch (error) {
        if (isErrnoException(error)) {
            if (error.code && error.code === 'ESRCH') {
                return false;
            }
        }
        throw error;
    }
}
function isErrorLike(obj) {
    return (typeof obj === 'object' && obj !== null && 'name' in obj && 'message' in obj);
}
function isErrnoException(obj) {
    return (isErrorLike(obj) &&
        ('errno' in obj || 'code' in obj || 'path' in obj || 'syscall' in obj));
}
class TimeoutError extends Error {
    constructor(message) {
        super(message);
        this.name = this.constructor.name;
        Error.captureStackTrace(this, this.constructor);
    }
}

var nodeProgress = {exports: {}};

/*!
 * node-progress
 * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

var hasRequiredNodeProgress;

function requireNodeProgress () {
	if (hasRequiredNodeProgress) return nodeProgress.exports;
	hasRequiredNodeProgress = 1;
	(function (module, exports$1) {
		module.exports = ProgressBar;
		function ProgressBar(fmt, options) {
		  this.stream = options.stream || process.stderr;
		  if (typeof(options) == 'number') {
		    var total = options;
		    options = {};
		    options.total = total;
		  } else {
		    options = options || {};
		    if ('string' != typeof fmt) throw new Error('format required');
		    if ('number' != typeof options.total) throw new Error('total required');
		  }
		  this.fmt = fmt;
		  this.curr = options.curr || 0;
		  this.total = options.total;
		  this.width = options.width || this.total;
		  this.clear = options.clear;
		  this.chars = {
		    complete   : options.complete || '=',
		    incomplete : options.incomplete || '-',
		    head       : options.head || (options.complete || '=')
		  };
		  this.renderThrottle = options.renderThrottle !== 0 ? (options.renderThrottle || 16) : 0;
		  this.lastRender = -Infinity;
		  this.callback = options.callback || function () {};
		  this.tokens = {};
		  this.lastDraw = '';
		}
		ProgressBar.prototype.tick = function(len, tokens){
		  if (len !== 0)
		    len = len || 1;
		  if ('object' == typeof len) tokens = len, len = 1;
		  if (tokens) this.tokens = tokens;
		  if (0 == this.curr) this.start = new Date;
		  this.curr += len;
		  this.render();
		  if (this.curr >= this.total) {
		    this.render(undefined, true);
		    this.complete = true;
		    this.terminate();
		    this.callback(this);
		    return;
		  }
		};
		ProgressBar.prototype.render = function (tokens, force) {
		  force = force !== undefined ? force : false;
		  if (tokens) this.tokens = tokens;
		  if (!this.stream.isTTY) return;
		  var now = Date.now();
		  var delta = now - this.lastRender;
		  if (!force && (delta < this.renderThrottle)) {
		    return;
		  } else {
		    this.lastRender = now;
		  }
		  var ratio = this.curr / this.total;
		  ratio = Math.min(Math.max(ratio, 0), 1);
		  var percent = Math.floor(ratio * 100);
		  var incomplete, complete, completeLength;
		  var elapsed = new Date - this.start;
		  var eta = (percent == 100) ? 0 : elapsed * (this.total / this.curr - 1);
		  var rate = this.curr / (elapsed / 1000);
		  var str = this.fmt
		    .replace(':current', this.curr)
		    .replace(':total', this.total)
		    .replace(':elapsed', isNaN(elapsed) ? '0.0' : (elapsed / 1000).toFixed(1))
		    .replace(':eta', (isNaN(eta) || !isFinite(eta)) ? '0.0' : (eta / 1000)
		      .toFixed(1))
		    .replace(':percent', percent.toFixed(0) + '%')
		    .replace(':rate', Math.round(rate));
		  var availableSpace = Math.max(0, this.stream.columns - str.replace(':bar', '').length);
		  if(availableSpace && process.platform === 'win32'){
		    availableSpace = availableSpace - 1;
		  }
		  var width = Math.min(this.width, availableSpace);
		  completeLength = Math.round(width * ratio);
		  complete = Array(Math.max(0, completeLength + 1)).join(this.chars.complete);
		  incomplete = Array(Math.max(0, width - completeLength + 1)).join(this.chars.incomplete);
		  if(completeLength > 0)
		    complete = complete.slice(0, -1) + this.chars.head;
		  str = str.replace(':bar', complete + incomplete);
		  if (this.tokens) for (var key in this.tokens) str = str.replace(':' + key, this.tokens[key]);
		  if (this.lastDraw !== str) {
		    this.stream.cursorTo(0);
		    this.stream.write(str);
		    this.stream.clearLine(1);
		    this.lastDraw = str;
		  }
		};
		ProgressBar.prototype.update = function (ratio, tokens) {
		  var goal = Math.floor(ratio * this.total);
		  var delta = goal - this.curr;
		  this.tick(delta, tokens);
		};
		ProgressBar.prototype.interrupt = function (message) {
		  this.stream.clearLine();
		  this.stream.cursorTo(0);
		  this.stream.write(message);
		  this.stream.write('\n');
		  this.stream.write(this.lastDraw);
		};
		ProgressBar.prototype.terminate = function () {
		  if (this.clear) {
		    if (this.stream.clearLine) {
		      this.stream.clearLine();
		      this.stream.cursorTo(0);
		    }
		  } else {
		    this.stream.write('\n');
		  }
		}; 
	} (nodeProgress));
	return nodeProgress.exports;
}

var progress;
var hasRequiredProgress;

function requireProgress () {
	if (hasRequiredProgress) return progress;
	hasRequiredProgress = 1;
	progress = requireNodeProgress();
	return progress;
}

requireProgress();

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
debug$2('puppeteer:browsers:fileUtil');

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
debug$2('puppeteer:browsers:install');
async function uninstall(options) {
    options.platform ??= detectBrowserPlatform();
    if (!options.platform) {
        throw new Error(`Cannot detect the browser platform for: ${os.platform()} (${os.arch()})`);
    }
    new Cache$2(options.cacheDir).uninstall(options.browser, options.platform, options.buildId);
}
async function getInstalledBrowsers(options) {
    return new Cache$2(options.cacheDir).getInstalledBrowsers();
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */

var main = /*#__PURE__*/Object.freeze({
	__proto__: null,
	get Browser () { return Browser; },
	get BrowserPlatform () { return BrowserPlatform; },
	get BrowserTag () { return BrowserTag; },
	CDP_WEBSOCKET_ENDPOINT_REGEX: CDP_WEBSOCKET_ENDPOINT_REGEX,
	Cache: Cache$2,
	get ChromeReleaseChannel () { return ChromeReleaseChannel; },
	InstalledBrowser: InstalledBrowser,
	Process: Process,
	TimeoutError: TimeoutError,
	WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX: WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX,
	computeExecutablePath: computeExecutablePath,
	computeSystemExecutablePath: computeSystemExecutablePath,
	createProfile: createProfile,
	detectBrowserPlatform: detectBrowserPlatform,
	getInstalledBrowsers: getInstalledBrowsers,
	getVersionComparator: getVersionComparator,
	launch: launch$1,
	resolveBuildId: resolveBuildId,
	resolveDefaultUserDataDir: resolveDefaultUserDataDir,
	uninstall: uninstall
});

var bufferUtil = {exports: {}};

var constants;
var hasRequiredConstants;

function requireConstants () {
	if (hasRequiredConstants) return constants;
	hasRequiredConstants = 1;
	const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];
	const hasBlob = typeof Blob !== 'undefined';
	if (hasBlob) BINARY_TYPES.push('blob');
	constants = {
	  BINARY_TYPES,
	  CLOSE_TIMEOUT: 30000,
	  EMPTY_BUFFER: Buffer.alloc(0),
	  GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
	  hasBlob,
	  kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
	  kListener: Symbol('kListener'),
	  kStatusCode: Symbol('status-code'),
	  kWebSocket: Symbol('websocket'),
	  NOOP: () => {}
	};
	return constants;
}

var hasRequiredBufferUtil;

function requireBufferUtil () {
	if (hasRequiredBufferUtil) return bufferUtil.exports;
	hasRequiredBufferUtil = 1;
	const { EMPTY_BUFFER } = requireConstants();
	const FastBuffer = Buffer[Symbol.species];
	function concat(list, totalLength) {
	  if (list.length === 0) return EMPTY_BUFFER;
	  if (list.length === 1) return list[0];
	  const target = Buffer.allocUnsafe(totalLength);
	  let offset = 0;
	  for (let i = 0; i < list.length; i++) {
	    const buf = list[i];
	    target.set(buf, offset);
	    offset += buf.length;
	  }
	  if (offset < totalLength) {
	    return new FastBuffer(target.buffer, target.byteOffset, offset);
	  }
	  return target;
	}
	function _mask(source, mask, output, offset, length) {
	  for (let i = 0; i < length; i++) {
	    output[offset + i] = source[i] ^ mask[i & 3];
	  }
	}
	function _unmask(buffer, mask) {
	  for (let i = 0; i < buffer.length; i++) {
	    buffer[i] ^= mask[i & 3];
	  }
	}
	function toArrayBuffer(buf) {
	  if (buf.length === buf.buffer.byteLength) {
	    return buf.buffer;
	  }
	  return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
	}
	function toBuffer(data) {
	  toBuffer.readOnly = true;
	  if (Buffer.isBuffer(data)) return data;
	  let buf;
	  if (data instanceof ArrayBuffer) {
	    buf = new FastBuffer(data);
	  } else if (ArrayBuffer.isView(data)) {
	    buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
	  } else {
	    buf = Buffer.from(data);
	    toBuffer.readOnly = false;
	  }
	  return buf;
	}
	bufferUtil.exports = {
	  concat,
	  mask: _mask,
	  toArrayBuffer,
	  toBuffer,
	  unmask: _unmask
	};
	if (!process.env.WS_NO_BUFFER_UTIL) {
	  try {
	    const bufferUtil$1 = require('bufferutil');
	    bufferUtil.exports.mask = function (source, mask, output, offset, length) {
	      if (length < 48) _mask(source, mask, output, offset, length);
	      else bufferUtil$1.mask(source, mask, output, offset, length);
	    };
	    bufferUtil.exports.unmask = function (buffer, mask) {
	      if (buffer.length < 32) _unmask(buffer, mask);
	      else bufferUtil$1.unmask(buffer, mask);
	    };
	  } catch (e) {
	  }
	}
	return bufferUtil.exports;
}

var limiter;
var hasRequiredLimiter;

function requireLimiter () {
	if (hasRequiredLimiter) return limiter;
	hasRequiredLimiter = 1;
	const kDone = Symbol('kDone');
	const kRun = Symbol('kRun');
	class Limiter {
	  constructor(concurrency) {
	    this[kDone] = () => {
	      this.pending--;
	      this[kRun]();
	    };
	    this.concurrency = concurrency || Infinity;
	    this.jobs = [];
	    this.pending = 0;
	  }
	  add(job) {
	    this.jobs.push(job);
	    this[kRun]();
	  }
	  [kRun]() {
	    if (this.pending === this.concurrency) return;
	    if (this.jobs.length) {
	      const job = this.jobs.shift();
	      this.pending++;
	      job(this[kDone]);
	    }
	  }
	}
	limiter = Limiter;
	return limiter;
}

var permessageDeflate;
var hasRequiredPermessageDeflate;

function requirePermessageDeflate () {
	if (hasRequiredPermessageDeflate) return permessageDeflate;
	hasRequiredPermessageDeflate = 1;
	const zlib = require$$0$a;
	const bufferUtil = requireBufferUtil();
	const Limiter = requireLimiter();
	const { kStatusCode } = requireConstants();
	const FastBuffer = Buffer[Symbol.species];
	const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
	const kPerMessageDeflate = Symbol('permessage-deflate');
	const kTotalLength = Symbol('total-length');
	const kCallback = Symbol('callback');
	const kBuffers = Symbol('buffers');
	const kError = Symbol('error');
	let zlibLimiter;
	class PerMessageDeflate {
	  constructor(options, isServer, maxPayload) {
	    this._maxPayload = maxPayload | 0;
	    this._options = options || {};
	    this._threshold =
	      this._options.threshold !== undefined ? this._options.threshold : 1024;
	    this._isServer = !!isServer;
	    this._deflate = null;
	    this._inflate = null;
	    this.params = null;
	    if (!zlibLimiter) {
	      const concurrency =
	        this._options.concurrencyLimit !== undefined
	          ? this._options.concurrencyLimit
	          : 10;
	      zlibLimiter = new Limiter(concurrency);
	    }
	  }
	  static get extensionName() {
	    return 'permessage-deflate';
	  }
	  offer() {
	    const params = {};
	    if (this._options.serverNoContextTakeover) {
	      params.server_no_context_takeover = true;
	    }
	    if (this._options.clientNoContextTakeover) {
	      params.client_no_context_takeover = true;
	    }
	    if (this._options.serverMaxWindowBits) {
	      params.server_max_window_bits = this._options.serverMaxWindowBits;
	    }
	    if (this._options.clientMaxWindowBits) {
	      params.client_max_window_bits = this._options.clientMaxWindowBits;
	    } else if (this._options.clientMaxWindowBits == null) {
	      params.client_max_window_bits = true;
	    }
	    return params;
	  }
	  accept(configurations) {
	    configurations = this.normalizeParams(configurations);
	    this.params = this._isServer
	      ? this.acceptAsServer(configurations)
	      : this.acceptAsClient(configurations);
	    return this.params;
	  }
	  cleanup() {
	    if (this._inflate) {
	      this._inflate.close();
	      this._inflate = null;
	    }
	    if (this._deflate) {
	      const callback = this._deflate[kCallback];
	      this._deflate.close();
	      this._deflate = null;
	      if (callback) {
	        callback(
	          new Error(
	            'The deflate stream was closed while data was being processed'
	          )
	        );
	      }
	    }
	  }
	  acceptAsServer(offers) {
	    const opts = this._options;
	    const accepted = offers.find((params) => {
	      if (
	        (opts.serverNoContextTakeover === false &&
	          params.server_no_context_takeover) ||
	        (params.server_max_window_bits &&
	          (opts.serverMaxWindowBits === false ||
	            (typeof opts.serverMaxWindowBits === 'number' &&
	              opts.serverMaxWindowBits > params.server_max_window_bits))) ||
	        (typeof opts.clientMaxWindowBits === 'number' &&
	          !params.client_max_window_bits)
	      ) {
	        return false;
	      }
	      return true;
	    });
	    if (!accepted) {
	      throw new Error('None of the extension offers can be accepted');
	    }
	    if (opts.serverNoContextTakeover) {
	      accepted.server_no_context_takeover = true;
	    }
	    if (opts.clientNoContextTakeover) {
	      accepted.client_no_context_takeover = true;
	    }
	    if (typeof opts.serverMaxWindowBits === 'number') {
	      accepted.server_max_window_bits = opts.serverMaxWindowBits;
	    }
	    if (typeof opts.clientMaxWindowBits === 'number') {
	      accepted.client_max_window_bits = opts.clientMaxWindowBits;
	    } else if (
	      accepted.client_max_window_bits === true ||
	      opts.clientMaxWindowBits === false
	    ) {
	      delete accepted.client_max_window_bits;
	    }
	    return accepted;
	  }
	  acceptAsClient(response) {
	    const params = response[0];
	    if (
	      this._options.clientNoContextTakeover === false &&
	      params.client_no_context_takeover
	    ) {
	      throw new Error('Unexpected parameter "client_no_context_takeover"');
	    }
	    if (!params.client_max_window_bits) {
	      if (typeof this._options.clientMaxWindowBits === 'number') {
	        params.client_max_window_bits = this._options.clientMaxWindowBits;
	      }
	    } else if (
	      this._options.clientMaxWindowBits === false ||
	      (typeof this._options.clientMaxWindowBits === 'number' &&
	        params.client_max_window_bits > this._options.clientMaxWindowBits)
	    ) {
	      throw new Error(
	        'Unexpected or invalid parameter "client_max_window_bits"'
	      );
	    }
	    return params;
	  }
	  normalizeParams(configurations) {
	    configurations.forEach((params) => {
	      Object.keys(params).forEach((key) => {
	        let value = params[key];
	        if (value.length > 1) {
	          throw new Error(`Parameter "${key}" must have only a single value`);
	        }
	        value = value[0];
	        if (key === 'client_max_window_bits') {
	          if (value !== true) {
	            const num = +value;
	            if (!Number.isInteger(num) || num < 8 || num > 15) {
	              throw new TypeError(
	                `Invalid value for parameter "${key}": ${value}`
	              );
	            }
	            value = num;
	          } else if (!this._isServer) {
	            throw new TypeError(
	              `Invalid value for parameter "${key}": ${value}`
	            );
	          }
	        } else if (key === 'server_max_window_bits') {
	          const num = +value;
	          if (!Number.isInteger(num) || num < 8 || num > 15) {
	            throw new TypeError(
	              `Invalid value for parameter "${key}": ${value}`
	            );
	          }
	          value = num;
	        } else if (
	          key === 'client_no_context_takeover' ||
	          key === 'server_no_context_takeover'
	        ) {
	          if (value !== true) {
	            throw new TypeError(
	              `Invalid value for parameter "${key}": ${value}`
	            );
	          }
	        } else {
	          throw new Error(`Unknown parameter "${key}"`);
	        }
	        params[key] = value;
	      });
	    });
	    return configurations;
	  }
	  decompress(data, fin, callback) {
	    zlibLimiter.add((done) => {
	      this._decompress(data, fin, (err, result) => {
	        done();
	        callback(err, result);
	      });
	    });
	  }
	  compress(data, fin, callback) {
	    zlibLimiter.add((done) => {
	      this._compress(data, fin, (err, result) => {
	        done();
	        callback(err, result);
	      });
	    });
	  }
	  _decompress(data, fin, callback) {
	    const endpoint = this._isServer ? 'client' : 'server';
	    if (!this._inflate) {
	      const key = `${endpoint}_max_window_bits`;
	      const windowBits =
	        typeof this.params[key] !== 'number'
	          ? zlib.Z_DEFAULT_WINDOWBITS
	          : this.params[key];
	      this._inflate = zlib.createInflateRaw({
	        ...this._options.zlibInflateOptions,
	        windowBits
	      });
	      this._inflate[kPerMessageDeflate] = this;
	      this._inflate[kTotalLength] = 0;
	      this._inflate[kBuffers] = [];
	      this._inflate.on('error', inflateOnError);
	      this._inflate.on('data', inflateOnData);
	    }
	    this._inflate[kCallback] = callback;
	    this._inflate.write(data);
	    if (fin) this._inflate.write(TRAILER);
	    this._inflate.flush(() => {
	      const err = this._inflate[kError];
	      if (err) {
	        this._inflate.close();
	        this._inflate = null;
	        callback(err);
	        return;
	      }
	      const data = bufferUtil.concat(
	        this._inflate[kBuffers],
	        this._inflate[kTotalLength]
	      );
	      if (this._inflate._readableState.endEmitted) {
	        this._inflate.close();
	        this._inflate = null;
	      } else {
	        this._inflate[kTotalLength] = 0;
	        this._inflate[kBuffers] = [];
	        if (fin && this.params[`${endpoint}_no_context_takeover`]) {
	          this._inflate.reset();
	        }
	      }
	      callback(null, data);
	    });
	  }
	  _compress(data, fin, callback) {
	    const endpoint = this._isServer ? 'server' : 'client';
	    if (!this._deflate) {
	      const key = `${endpoint}_max_window_bits`;
	      const windowBits =
	        typeof this.params[key] !== 'number'
	          ? zlib.Z_DEFAULT_WINDOWBITS
	          : this.params[key];
	      this._deflate = zlib.createDeflateRaw({
	        ...this._options.zlibDeflateOptions,
	        windowBits
	      });
	      this._deflate[kTotalLength] = 0;
	      this._deflate[kBuffers] = [];
	      this._deflate.on('data', deflateOnData);
	    }
	    this._deflate[kCallback] = callback;
	    this._deflate.write(data);
	    this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
	      if (!this._deflate) {
	        return;
	      }
	      let data = bufferUtil.concat(
	        this._deflate[kBuffers],
	        this._deflate[kTotalLength]
	      );
	      if (fin) {
	        data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
	      }
	      this._deflate[kCallback] = null;
	      this._deflate[kTotalLength] = 0;
	      this._deflate[kBuffers] = [];
	      if (fin && this.params[`${endpoint}_no_context_takeover`]) {
	        this._deflate.reset();
	      }
	      callback(null, data);
	    });
	  }
	}
	permessageDeflate = PerMessageDeflate;
	function deflateOnData(chunk) {
	  this[kBuffers].push(chunk);
	  this[kTotalLength] += chunk.length;
	}
	function inflateOnData(chunk) {
	  this[kTotalLength] += chunk.length;
	  if (
	    this[kPerMessageDeflate]._maxPayload < 1 ||
	    this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
	  ) {
	    this[kBuffers].push(chunk);
	    return;
	  }
	  this[kError] = new RangeError('Max payload size exceeded');
	  this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
	  this[kError][kStatusCode] = 1009;
	  this.removeListener('data', inflateOnData);
	  this.reset();
	}
	function inflateOnError(err) {
	  this[kPerMessageDeflate]._inflate = null;
	  if (this[kError]) {
	    this[kCallback](this[kError]);
	    return;
	  }
	  err[kStatusCode] = 1007;
	  this[kCallback](err);
	}
	return permessageDeflate;
}

var validation = {exports: {}};

var hasRequiredValidation;

function requireValidation () {
	if (hasRequiredValidation) return validation.exports;
	hasRequiredValidation = 1;
	const { isUtf8 } = require$$0$9;
	const { hasBlob } = requireConstants();
	const tokenChars = [
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	  0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
	  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
	];
	function isValidStatusCode(code) {
	  return (
	    (code >= 1000 &&
	      code <= 1014 &&
	      code !== 1004 &&
	      code !== 1005 &&
	      code !== 1006) ||
	    (code >= 3000 && code <= 4999)
	  );
	}
	function _isValidUTF8(buf) {
	  const len = buf.length;
	  let i = 0;
	  while (i < len) {
	    if ((buf[i] & 0x80) === 0) {
	      i++;
	    } else if ((buf[i] & 0xe0) === 0xc0) {
	      if (
	        i + 1 === len ||
	        (buf[i + 1] & 0xc0) !== 0x80 ||
	        (buf[i] & 0xfe) === 0xc0
	      ) {
	        return false;
	      }
	      i += 2;
	    } else if ((buf[i] & 0xf0) === 0xe0) {
	      if (
	        i + 2 >= len ||
	        (buf[i + 1] & 0xc0) !== 0x80 ||
	        (buf[i + 2] & 0xc0) !== 0x80 ||
	        (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) ||
	        (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0)
	      ) {
	        return false;
	      }
	      i += 3;
	    } else if ((buf[i] & 0xf8) === 0xf0) {
	      if (
	        i + 3 >= len ||
	        (buf[i + 1] & 0xc0) !== 0x80 ||
	        (buf[i + 2] & 0xc0) !== 0x80 ||
	        (buf[i + 3] & 0xc0) !== 0x80 ||
	        (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) ||
	        (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
	        buf[i] > 0xf4
	      ) {
	        return false;
	      }
	      i += 4;
	    } else {
	      return false;
	    }
	  }
	  return true;
	}
	function isBlob(value) {
	  return (
	    hasBlob &&
	    typeof value === 'object' &&
	    typeof value.arrayBuffer === 'function' &&
	    typeof value.type === 'string' &&
	    typeof value.stream === 'function' &&
	    (value[Symbol.toStringTag] === 'Blob' ||
	      value[Symbol.toStringTag] === 'File')
	  );
	}
	validation.exports = {
	  isBlob,
	  isValidStatusCode,
	  isValidUTF8: _isValidUTF8,
	  tokenChars
	};
	if (isUtf8) {
	  validation.exports.isValidUTF8 = function (buf) {
	    return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
	  };
	}  else if (!process.env.WS_NO_UTF_8_VALIDATE) {
	  try {
	    const isValidUTF8 = require('utf-8-validate');
	    validation.exports.isValidUTF8 = function (buf) {
	      return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
	    };
	  } catch (e) {
	  }
	}
	return validation.exports;
}

var receiver;
var hasRequiredReceiver;

function requireReceiver () {
	if (hasRequiredReceiver) return receiver;
	hasRequiredReceiver = 1;
	const { Writable } = require$$1$3;
	const PerMessageDeflate = requirePermessageDeflate();
	const {
	  BINARY_TYPES,
	  EMPTY_BUFFER,
	  kStatusCode,
	  kWebSocket
	} = requireConstants();
	const { concat, toArrayBuffer, unmask } = requireBufferUtil();
	const { isValidStatusCode, isValidUTF8 } = requireValidation();
	const FastBuffer = Buffer[Symbol.species];
	const GET_INFO = 0;
	const GET_PAYLOAD_LENGTH_16 = 1;
	const GET_PAYLOAD_LENGTH_64 = 2;
	const GET_MASK = 3;
	const GET_DATA = 4;
	const INFLATING = 5;
	const DEFER_EVENT = 6;
	class Receiver extends Writable {
	  constructor(options = {}) {
	    super();
	    this._allowSynchronousEvents =
	      options.allowSynchronousEvents !== undefined
	        ? options.allowSynchronousEvents
	        : true;
	    this._binaryType = options.binaryType || BINARY_TYPES[0];
	    this._extensions = options.extensions || {};
	    this._isServer = !!options.isServer;
	    this._maxPayload = options.maxPayload | 0;
	    this._skipUTF8Validation = !!options.skipUTF8Validation;
	    this[kWebSocket] = undefined;
	    this._bufferedBytes = 0;
	    this._buffers = [];
	    this._compressed = false;
	    this._payloadLength = 0;
	    this._mask = undefined;
	    this._fragmented = 0;
	    this._masked = false;
	    this._fin = false;
	    this._opcode = 0;
	    this._totalPayloadLength = 0;
	    this._messageLength = 0;
	    this._fragments = [];
	    this._errored = false;
	    this._loop = false;
	    this._state = GET_INFO;
	  }
	  _write(chunk, encoding, cb) {
	    if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
	    this._bufferedBytes += chunk.length;
	    this._buffers.push(chunk);
	    this.startLoop(cb);
	  }
	  consume(n) {
	    this._bufferedBytes -= n;
	    if (n === this._buffers[0].length) return this._buffers.shift();
	    if (n < this._buffers[0].length) {
	      const buf = this._buffers[0];
	      this._buffers[0] = new FastBuffer(
	        buf.buffer,
	        buf.byteOffset + n,
	        buf.length - n
	      );
	      return new FastBuffer(buf.buffer, buf.byteOffset, n);
	    }
	    const dst = Buffer.allocUnsafe(n);
	    do {
	      const buf = this._buffers[0];
	      const offset = dst.length - n;
	      if (n >= buf.length) {
	        dst.set(this._buffers.shift(), offset);
	      } else {
	        dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
	        this._buffers[0] = new FastBuffer(
	          buf.buffer,
	          buf.byteOffset + n,
	          buf.length - n
	        );
	      }
	      n -= buf.length;
	    } while (n > 0);
	    return dst;
	  }
	  startLoop(cb) {
	    this._loop = true;
	    do {
	      switch (this._state) {
	        case GET_INFO:
	          this.getInfo(cb);
	          break;
	        case GET_PAYLOAD_LENGTH_16:
	          this.getPayloadLength16(cb);
	          break;
	        case GET_PAYLOAD_LENGTH_64:
	          this.getPayloadLength64(cb);
	          break;
	        case GET_MASK:
	          this.getMask();
	          break;
	        case GET_DATA:
	          this.getData(cb);
	          break;
	        case INFLATING:
	        case DEFER_EVENT:
	          this._loop = false;
	          return;
	      }
	    } while (this._loop);
	    if (!this._errored) cb();
	  }
	  getInfo(cb) {
	    if (this._bufferedBytes < 2) {
	      this._loop = false;
	      return;
	    }
	    const buf = this.consume(2);
	    if ((buf[0] & 0x30) !== 0x00) {
	      const error = this.createError(
	        RangeError,
	        'RSV2 and RSV3 must be clear',
	        true,
	        1002,
	        'WS_ERR_UNEXPECTED_RSV_2_3'
	      );
	      cb(error);
	      return;
	    }
	    const compressed = (buf[0] & 0x40) === 0x40;
	    if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
	      const error = this.createError(
	        RangeError,
	        'RSV1 must be clear',
	        true,
	        1002,
	        'WS_ERR_UNEXPECTED_RSV_1'
	      );
	      cb(error);
	      return;
	    }
	    this._fin = (buf[0] & 0x80) === 0x80;
	    this._opcode = buf[0] & 0x0f;
	    this._payloadLength = buf[1] & 0x7f;
	    if (this._opcode === 0x00) {
	      if (compressed) {
	        const error = this.createError(
	          RangeError,
	          'RSV1 must be clear',
	          true,
	          1002,
	          'WS_ERR_UNEXPECTED_RSV_1'
	        );
	        cb(error);
	        return;
	      }
	      if (!this._fragmented) {
	        const error = this.createError(
	          RangeError,
	          'invalid opcode 0',
	          true,
	          1002,
	          'WS_ERR_INVALID_OPCODE'
	        );
	        cb(error);
	        return;
	      }
	      this._opcode = this._fragmented;
	    } else if (this._opcode === 0x01 || this._opcode === 0x02) {
	      if (this._fragmented) {
	        const error = this.createError(
	          RangeError,
	          `invalid opcode ${this._opcode}`,
	          true,
	          1002,
	          'WS_ERR_INVALID_OPCODE'
	        );
	        cb(error);
	        return;
	      }
	      this._compressed = compressed;
	    } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
	      if (!this._fin) {
	        const error = this.createError(
	          RangeError,
	          'FIN must be set',
	          true,
	          1002,
	          'WS_ERR_EXPECTED_FIN'
	        );
	        cb(error);
	        return;
	      }
	      if (compressed) {
	        const error = this.createError(
	          RangeError,
	          'RSV1 must be clear',
	          true,
	          1002,
	          'WS_ERR_UNEXPECTED_RSV_1'
	        );
	        cb(error);
	        return;
	      }
	      if (
	        this._payloadLength > 0x7d ||
	        (this._opcode === 0x08 && this._payloadLength === 1)
	      ) {
	        const error = this.createError(
	          RangeError,
	          `invalid payload length ${this._payloadLength}`,
	          true,
	          1002,
	          'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
	        );
	        cb(error);
	        return;
	      }
	    } else {
	      const error = this.createError(
	        RangeError,
	        `invalid opcode ${this._opcode}`,
	        true,
	        1002,
	        'WS_ERR_INVALID_OPCODE'
	      );
	      cb(error);
	      return;
	    }
	    if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
	    this._masked = (buf[1] & 0x80) === 0x80;
	    if (this._isServer) {
	      if (!this._masked) {
	        const error = this.createError(
	          RangeError,
	          'MASK must be set',
	          true,
	          1002,
	          'WS_ERR_EXPECTED_MASK'
	        );
	        cb(error);
	        return;
	      }
	    } else if (this._masked) {
	      const error = this.createError(
	        RangeError,
	        'MASK must be clear',
	        true,
	        1002,
	        'WS_ERR_UNEXPECTED_MASK'
	      );
	      cb(error);
	      return;
	    }
	    if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
	    else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
	    else this.haveLength(cb);
	  }
	  getPayloadLength16(cb) {
	    if (this._bufferedBytes < 2) {
	      this._loop = false;
	      return;
	    }
	    this._payloadLength = this.consume(2).readUInt16BE(0);
	    this.haveLength(cb);
	  }
	  getPayloadLength64(cb) {
	    if (this._bufferedBytes < 8) {
	      this._loop = false;
	      return;
	    }
	    const buf = this.consume(8);
	    const num = buf.readUInt32BE(0);
	    if (num > Math.pow(2, 53 - 32) - 1) {
	      const error = this.createError(
	        RangeError,
	        'Unsupported WebSocket frame: payload length > 2^53 - 1',
	        false,
	        1009,
	        'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
	      );
	      cb(error);
	      return;
	    }
	    this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
	    this.haveLength(cb);
	  }
	  haveLength(cb) {
	    if (this._payloadLength && this._opcode < 0x08) {
	      this._totalPayloadLength += this._payloadLength;
	      if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
	        const error = this.createError(
	          RangeError,
	          'Max payload size exceeded',
	          false,
	          1009,
	          'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
	        );
	        cb(error);
	        return;
	      }
	    }
	    if (this._masked) this._state = GET_MASK;
	    else this._state = GET_DATA;
	  }
	  getMask() {
	    if (this._bufferedBytes < 4) {
	      this._loop = false;
	      return;
	    }
	    this._mask = this.consume(4);
	    this._state = GET_DATA;
	  }
	  getData(cb) {
	    let data = EMPTY_BUFFER;
	    if (this._payloadLength) {
	      if (this._bufferedBytes < this._payloadLength) {
	        this._loop = false;
	        return;
	      }
	      data = this.consume(this._payloadLength);
	      if (
	        this._masked &&
	        (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0
	      ) {
	        unmask(data, this._mask);
	      }
	    }
	    if (this._opcode > 0x07) {
	      this.controlMessage(data, cb);
	      return;
	    }
	    if (this._compressed) {
	      this._state = INFLATING;
	      this.decompress(data, cb);
	      return;
	    }
	    if (data.length) {
	      this._messageLength = this._totalPayloadLength;
	      this._fragments.push(data);
	    }
	    this.dataMessage(cb);
	  }
	  decompress(data, cb) {
	    const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
	    perMessageDeflate.decompress(data, this._fin, (err, buf) => {
	      if (err) return cb(err);
	      if (buf.length) {
	        this._messageLength += buf.length;
	        if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
	          const error = this.createError(
	            RangeError,
	            'Max payload size exceeded',
	            false,
	            1009,
	            'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
	          );
	          cb(error);
	          return;
	        }
	        this._fragments.push(buf);
	      }
	      this.dataMessage(cb);
	      if (this._state === GET_INFO) this.startLoop(cb);
	    });
	  }
	  dataMessage(cb) {
	    if (!this._fin) {
	      this._state = GET_INFO;
	      return;
	    }
	    const messageLength = this._messageLength;
	    const fragments = this._fragments;
	    this._totalPayloadLength = 0;
	    this._messageLength = 0;
	    this._fragmented = 0;
	    this._fragments = [];
	    if (this._opcode === 2) {
	      let data;
	      if (this._binaryType === 'nodebuffer') {
	        data = concat(fragments, messageLength);
	      } else if (this._binaryType === 'arraybuffer') {
	        data = toArrayBuffer(concat(fragments, messageLength));
	      } else if (this._binaryType === 'blob') {
	        data = new Blob(fragments);
	      } else {
	        data = fragments;
	      }
	      if (this._allowSynchronousEvents) {
	        this.emit('message', data, true);
	        this._state = GET_INFO;
	      } else {
	        this._state = DEFER_EVENT;
	        setImmediate(() => {
	          this.emit('message', data, true);
	          this._state = GET_INFO;
	          this.startLoop(cb);
	        });
	      }
	    } else {
	      const buf = concat(fragments, messageLength);
	      if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
	        const error = this.createError(
	          Error,
	          'invalid UTF-8 sequence',
	          true,
	          1007,
	          'WS_ERR_INVALID_UTF8'
	        );
	        cb(error);
	        return;
	      }
	      if (this._state === INFLATING || this._allowSynchronousEvents) {
	        this.emit('message', buf, false);
	        this._state = GET_INFO;
	      } else {
	        this._state = DEFER_EVENT;
	        setImmediate(() => {
	          this.emit('message', buf, false);
	          this._state = GET_INFO;
	          this.startLoop(cb);
	        });
	      }
	    }
	  }
	  controlMessage(data, cb) {
	    if (this._opcode === 0x08) {
	      if (data.length === 0) {
	        this._loop = false;
	        this.emit('conclude', 1005, EMPTY_BUFFER);
	        this.end();
	      } else {
	        const code = data.readUInt16BE(0);
	        if (!isValidStatusCode(code)) {
	          const error = this.createError(
	            RangeError,
	            `invalid status code ${code}`,
	            true,
	            1002,
	            'WS_ERR_INVALID_CLOSE_CODE'
	          );
	          cb(error);
	          return;
	        }
	        const buf = new FastBuffer(
	          data.buffer,
	          data.byteOffset + 2,
	          data.length - 2
	        );
	        if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
	          const error = this.createError(
	            Error,
	            'invalid UTF-8 sequence',
	            true,
	            1007,
	            'WS_ERR_INVALID_UTF8'
	          );
	          cb(error);
	          return;
	        }
	        this._loop = false;
	        this.emit('conclude', code, buf);
	        this.end();
	      }
	      this._state = GET_INFO;
	      return;
	    }
	    if (this._allowSynchronousEvents) {
	      this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
	      this._state = GET_INFO;
	    } else {
	      this._state = DEFER_EVENT;
	      setImmediate(() => {
	        this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
	        this._state = GET_INFO;
	        this.startLoop(cb);
	      });
	    }
	  }
	  createError(ErrorCtor, message, prefix, statusCode, errorCode) {
	    this._loop = false;
	    this._errored = true;
	    const err = new ErrorCtor(
	      prefix ? `Invalid WebSocket frame: ${message}` : message
	    );
	    Error.captureStackTrace(err, this.createError);
	    err.code = errorCode;
	    err[kStatusCode] = statusCode;
	    return err;
	  }
	}
	receiver = Receiver;
	return receiver;
}

var sender;
var hasRequiredSender;

function requireSender () {
	if (hasRequiredSender) return sender;
	hasRequiredSender = 1;
	const { Duplex } = require$$1$3;
	const { randomFillSync } = require$$2$1;
	const PerMessageDeflate = requirePermessageDeflate();
	const { EMPTY_BUFFER, kWebSocket, NOOP } = requireConstants();
	const { isBlob, isValidStatusCode } = requireValidation();
	const { mask: applyMask, toBuffer } = requireBufferUtil();
	const kByteLength = Symbol('kByteLength');
	const maskBuffer = Buffer.alloc(4);
	const RANDOM_POOL_SIZE = 8 * 1024;
	let randomPool;
	let randomPoolPointer = RANDOM_POOL_SIZE;
	const DEFAULT = 0;
	const DEFLATING = 1;
	const GET_BLOB_DATA = 2;
	class Sender {
	  constructor(socket, extensions, generateMask) {
	    this._extensions = extensions || {};
	    if (generateMask) {
	      this._generateMask = generateMask;
	      this._maskBuffer = Buffer.alloc(4);
	    }
	    this._socket = socket;
	    this._firstFragment = true;
	    this._compress = false;
	    this._bufferedBytes = 0;
	    this._queue = [];
	    this._state = DEFAULT;
	    this.onerror = NOOP;
	    this[kWebSocket] = undefined;
	  }
	  static frame(data, options) {
	    let mask;
	    let merge = false;
	    let offset = 2;
	    let skipMasking = false;
	    if (options.mask) {
	      mask = options.maskBuffer || maskBuffer;
	      if (options.generateMask) {
	        options.generateMask(mask);
	      } else {
	        if (randomPoolPointer === RANDOM_POOL_SIZE) {
	          if (randomPool === undefined) {
	            randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
	          }
	          randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
	          randomPoolPointer = 0;
	        }
	        mask[0] = randomPool[randomPoolPointer++];
	        mask[1] = randomPool[randomPoolPointer++];
	        mask[2] = randomPool[randomPoolPointer++];
	        mask[3] = randomPool[randomPoolPointer++];
	      }
	      skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
	      offset = 6;
	    }
	    let dataLength;
	    if (typeof data === 'string') {
	      if (
	        (!options.mask || skipMasking) &&
	        options[kByteLength] !== undefined
	      ) {
	        dataLength = options[kByteLength];
	      } else {
	        data = Buffer.from(data);
	        dataLength = data.length;
	      }
	    } else {
	      dataLength = data.length;
	      merge = options.mask && options.readOnly && !skipMasking;
	    }
	    let payloadLength = dataLength;
	    if (dataLength >= 65536) {
	      offset += 8;
	      payloadLength = 127;
	    } else if (dataLength > 125) {
	      offset += 2;
	      payloadLength = 126;
	    }
	    const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
	    target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
	    if (options.rsv1) target[0] |= 0x40;
	    target[1] = payloadLength;
	    if (payloadLength === 126) {
	      target.writeUInt16BE(dataLength, 2);
	    } else if (payloadLength === 127) {
	      target[2] = target[3] = 0;
	      target.writeUIntBE(dataLength, 4, 6);
	    }
	    if (!options.mask) return [target, data];
	    target[1] |= 0x80;
	    target[offset - 4] = mask[0];
	    target[offset - 3] = mask[1];
	    target[offset - 2] = mask[2];
	    target[offset - 1] = mask[3];
	    if (skipMasking) return [target, data];
	    if (merge) {
	      applyMask(data, mask, target, offset, dataLength);
	      return [target];
	    }
	    applyMask(data, mask, data, 0, dataLength);
	    return [target, data];
	  }
	  close(code, data, mask, cb) {
	    let buf;
	    if (code === undefined) {
	      buf = EMPTY_BUFFER;
	    } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
	      throw new TypeError('First argument must be a valid error code number');
	    } else if (data === undefined || !data.length) {
	      buf = Buffer.allocUnsafe(2);
	      buf.writeUInt16BE(code, 0);
	    } else {
	      const length = Buffer.byteLength(data);
	      if (length > 123) {
	        throw new RangeError('The message must not be greater than 123 bytes');
	      }
	      buf = Buffer.allocUnsafe(2 + length);
	      buf.writeUInt16BE(code, 0);
	      if (typeof data === 'string') {
	        buf.write(data, 2);
	      } else {
	        buf.set(data, 2);
	      }
	    }
	    const options = {
	      [kByteLength]: buf.length,
	      fin: true,
	      generateMask: this._generateMask,
	      mask,
	      maskBuffer: this._maskBuffer,
	      opcode: 0x08,
	      readOnly: false,
	      rsv1: false
	    };
	    if (this._state !== DEFAULT) {
	      this.enqueue([this.dispatch, buf, false, options, cb]);
	    } else {
	      this.sendFrame(Sender.frame(buf, options), cb);
	    }
	  }
	  ping(data, mask, cb) {
	    let byteLength;
	    let readOnly;
	    if (typeof data === 'string') {
	      byteLength = Buffer.byteLength(data);
	      readOnly = false;
	    } else if (isBlob(data)) {
	      byteLength = data.size;
	      readOnly = false;
	    } else {
	      data = toBuffer(data);
	      byteLength = data.length;
	      readOnly = toBuffer.readOnly;
	    }
	    if (byteLength > 125) {
	      throw new RangeError('The data size must not be greater than 125 bytes');
	    }
	    const options = {
	      [kByteLength]: byteLength,
	      fin: true,
	      generateMask: this._generateMask,
	      mask,
	      maskBuffer: this._maskBuffer,
	      opcode: 0x09,
	      readOnly,
	      rsv1: false
	    };
	    if (isBlob(data)) {
	      if (this._state !== DEFAULT) {
	        this.enqueue([this.getBlobData, data, false, options, cb]);
	      } else {
	        this.getBlobData(data, false, options, cb);
	      }
	    } else if (this._state !== DEFAULT) {
	      this.enqueue([this.dispatch, data, false, options, cb]);
	    } else {
	      this.sendFrame(Sender.frame(data, options), cb);
	    }
	  }
	  pong(data, mask, cb) {
	    let byteLength;
	    let readOnly;
	    if (typeof data === 'string') {
	      byteLength = Buffer.byteLength(data);
	      readOnly = false;
	    } else if (isBlob(data)) {
	      byteLength = data.size;
	      readOnly = false;
	    } else {
	      data = toBuffer(data);
	      byteLength = data.length;
	      readOnly = toBuffer.readOnly;
	    }
	    if (byteLength > 125) {
	      throw new RangeError('The data size must not be greater than 125 bytes');
	    }
	    const options = {
	      [kByteLength]: byteLength,
	      fin: true,
	      generateMask: this._generateMask,
	      mask,
	      maskBuffer: this._maskBuffer,
	      opcode: 0x0a,
	      readOnly,
	      rsv1: false
	    };
	    if (isBlob(data)) {
	      if (this._state !== DEFAULT) {
	        this.enqueue([this.getBlobData, data, false, options, cb]);
	      } else {
	        this.getBlobData(data, false, options, cb);
	      }
	    } else if (this._state !== DEFAULT) {
	      this.enqueue([this.dispatch, data, false, options, cb]);
	    } else {
	      this.sendFrame(Sender.frame(data, options), cb);
	    }
	  }
	  send(data, options, cb) {
	    const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
	    let opcode = options.binary ? 2 : 1;
	    let rsv1 = options.compress;
	    let byteLength;
	    let readOnly;
	    if (typeof data === 'string') {
	      byteLength = Buffer.byteLength(data);
	      readOnly = false;
	    } else if (isBlob(data)) {
	      byteLength = data.size;
	      readOnly = false;
	    } else {
	      data = toBuffer(data);
	      byteLength = data.length;
	      readOnly = toBuffer.readOnly;
	    }
	    if (this._firstFragment) {
	      this._firstFragment = false;
	      if (
	        rsv1 &&
	        perMessageDeflate &&
	        perMessageDeflate.params[
	          perMessageDeflate._isServer
	            ? 'server_no_context_takeover'
	            : 'client_no_context_takeover'
	        ]
	      ) {
	        rsv1 = byteLength >= perMessageDeflate._threshold;
	      }
	      this._compress = rsv1;
	    } else {
	      rsv1 = false;
	      opcode = 0;
	    }
	    if (options.fin) this._firstFragment = true;
	    const opts = {
	      [kByteLength]: byteLength,
	      fin: options.fin,
	      generateMask: this._generateMask,
	      mask: options.mask,
	      maskBuffer: this._maskBuffer,
	      opcode,
	      readOnly,
	      rsv1
	    };
	    if (isBlob(data)) {
	      if (this._state !== DEFAULT) {
	        this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
	      } else {
	        this.getBlobData(data, this._compress, opts, cb);
	      }
	    } else if (this._state !== DEFAULT) {
	      this.enqueue([this.dispatch, data, this._compress, opts, cb]);
	    } else {
	      this.dispatch(data, this._compress, opts, cb);
	    }
	  }
	  getBlobData(blob, compress, options, cb) {
	    this._bufferedBytes += options[kByteLength];
	    this._state = GET_BLOB_DATA;
	    blob
	      .arrayBuffer()
	      .then((arrayBuffer) => {
	        if (this._socket.destroyed) {
	          const err = new Error(
	            'The socket was closed while the blob was being read'
	          );
	          process.nextTick(callCallbacks, this, err, cb);
	          return;
	        }
	        this._bufferedBytes -= options[kByteLength];
	        const data = toBuffer(arrayBuffer);
	        if (!compress) {
	          this._state = DEFAULT;
	          this.sendFrame(Sender.frame(data, options), cb);
	          this.dequeue();
	        } else {
	          this.dispatch(data, compress, options, cb);
	        }
	      })
	      .catch((err) => {
	        process.nextTick(onError, this, err, cb);
	      });
	  }
	  dispatch(data, compress, options, cb) {
	    if (!compress) {
	      this.sendFrame(Sender.frame(data, options), cb);
	      return;
	    }
	    const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
	    this._bufferedBytes += options[kByteLength];
	    this._state = DEFLATING;
	    perMessageDeflate.compress(data, options.fin, (_, buf) => {
	      if (this._socket.destroyed) {
	        const err = new Error(
	          'The socket was closed while data was being compressed'
	        );
	        callCallbacks(this, err, cb);
	        return;
	      }
	      this._bufferedBytes -= options[kByteLength];
	      this._state = DEFAULT;
	      options.readOnly = false;
	      this.sendFrame(Sender.frame(buf, options), cb);
	      this.dequeue();
	    });
	  }
	  dequeue() {
	    while (this._state === DEFAULT && this._queue.length) {
	      const params = this._queue.shift();
	      this._bufferedBytes -= params[3][kByteLength];
	      Reflect.apply(params[0], this, params.slice(1));
	    }
	  }
	  enqueue(params) {
	    this._bufferedBytes += params[3][kByteLength];
	    this._queue.push(params);
	  }
	  sendFrame(list, cb) {
	    if (list.length === 2) {
	      this._socket.cork();
	      this._socket.write(list[0]);
	      this._socket.write(list[1], cb);
	      this._socket.uncork();
	    } else {
	      this._socket.write(list[0], cb);
	    }
	  }
	}
	sender = Sender;
	function callCallbacks(sender, err, cb) {
	  if (typeof cb === 'function') cb(err);
	  for (let i = 0; i < sender._queue.length; i++) {
	    const params = sender._queue[i];
	    const callback = params[params.length - 1];
	    if (typeof callback === 'function') callback(err);
	  }
	}
	function onError(sender, err, cb) {
	  callCallbacks(sender, err, cb);
	  sender.onerror(err);
	}
	return sender;
}

var eventTarget;
var hasRequiredEventTarget;

function requireEventTarget () {
	if (hasRequiredEventTarget) return eventTarget;
	hasRequiredEventTarget = 1;
	const { kForOnEventAttribute, kListener } = requireConstants();
	const kCode = Symbol('kCode');
	const kData = Symbol('kData');
	const kError = Symbol('kError');
	const kMessage = Symbol('kMessage');
	const kReason = Symbol('kReason');
	const kTarget = Symbol('kTarget');
	const kType = Symbol('kType');
	const kWasClean = Symbol('kWasClean');
	class Event {
	  constructor(type) {
	    this[kTarget] = null;
	    this[kType] = type;
	  }
	  get target() {
	    return this[kTarget];
	  }
	  get type() {
	    return this[kType];
	  }
	}
	Object.defineProperty(Event.prototype, 'target', { enumerable: true });
	Object.defineProperty(Event.prototype, 'type', { enumerable: true });
	class CloseEvent extends Event {
	  constructor(type, options = {}) {
	    super(type);
	    this[kCode] = options.code === undefined ? 0 : options.code;
	    this[kReason] = options.reason === undefined ? '' : options.reason;
	    this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
	  }
	  get code() {
	    return this[kCode];
	  }
	  get reason() {
	    return this[kReason];
	  }
	  get wasClean() {
	    return this[kWasClean];
	  }
	}
	Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
	Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
	Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
	class ErrorEvent extends Event {
	  constructor(type, options = {}) {
	    super(type);
	    this[kError] = options.error === undefined ? null : options.error;
	    this[kMessage] = options.message === undefined ? '' : options.message;
	  }
	  get error() {
	    return this[kError];
	  }
	  get message() {
	    return this[kMessage];
	  }
	}
	Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
	Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
	class MessageEvent extends Event {
	  constructor(type, options = {}) {
	    super(type);
	    this[kData] = options.data === undefined ? null : options.data;
	  }
	  get data() {
	    return this[kData];
	  }
	}
	Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
	const EventTarget = {
	  addEventListener(type, handler, options = {}) {
	    for (const listener of this.listeners(type)) {
	      if (
	        !options[kForOnEventAttribute] &&
	        listener[kListener] === handler &&
	        !listener[kForOnEventAttribute]
	      ) {
	        return;
	      }
	    }
	    let wrapper;
	    if (type === 'message') {
	      wrapper = function onMessage(data, isBinary) {
	        const event = new MessageEvent('message', {
	          data: isBinary ? data : data.toString()
	        });
	        event[kTarget] = this;
	        callListener(handler, this, event);
	      };
	    } else if (type === 'close') {
	      wrapper = function onClose(code, message) {
	        const event = new CloseEvent('close', {
	          code,
	          reason: message.toString(),
	          wasClean: this._closeFrameReceived && this._closeFrameSent
	        });
	        event[kTarget] = this;
	        callListener(handler, this, event);
	      };
	    } else if (type === 'error') {
	      wrapper = function onError(error) {
	        const event = new ErrorEvent('error', {
	          error,
	          message: error.message
	        });
	        event[kTarget] = this;
	        callListener(handler, this, event);
	      };
	    } else if (type === 'open') {
	      wrapper = function onOpen() {
	        const event = new Event('open');
	        event[kTarget] = this;
	        callListener(handler, this, event);
	      };
	    } else {
	      return;
	    }
	    wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
	    wrapper[kListener] = handler;
	    if (options.once) {
	      this.once(type, wrapper);
	    } else {
	      this.on(type, wrapper);
	    }
	  },
	  removeEventListener(type, handler) {
	    for (const listener of this.listeners(type)) {
	      if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
	        this.removeListener(type, listener);
	        break;
	      }
	    }
	  }
	};
	eventTarget = {
	  CloseEvent,
	  ErrorEvent,
	  Event,
	  EventTarget,
	  MessageEvent
	};
	function callListener(listener, thisArg, event) {
	  if (typeof listener === 'object' && listener.handleEvent) {
	    listener.handleEvent.call(listener, event);
	  } else {
	    listener.call(thisArg, event);
	  }
	}
	return eventTarget;
}

var extension;
var hasRequiredExtension;

function requireExtension () {
	if (hasRequiredExtension) return extension;
	hasRequiredExtension = 1;
	const { tokenChars } = requireValidation();
	function push(dest, name, elem) {
	  if (dest[name] === undefined) dest[name] = [elem];
	  else dest[name].push(elem);
	}
	function parse(header) {
	  const offers = Object.create(null);
	  let params = Object.create(null);
	  let mustUnescape = false;
	  let isEscaping = false;
	  let inQuotes = false;
	  let extensionName;
	  let paramName;
	  let start = -1;
	  let code = -1;
	  let end = -1;
	  let i = 0;
	  for (; i < header.length; i++) {
	    code = header.charCodeAt(i);
	    if (extensionName === undefined) {
	      if (end === -1 && tokenChars[code] === 1) {
	        if (start === -1) start = i;
	      } else if (
	        i !== 0 &&
	        (code === 0x20  || code === 0x09)
	      ) {
	        if (end === -1 && start !== -1) end = i;
	      } else if (code === 0x3b  || code === 0x2c ) {
	        if (start === -1) {
	          throw new SyntaxError(`Unexpected character at index ${i}`);
	        }
	        if (end === -1) end = i;
	        const name = header.slice(start, end);
	        if (code === 0x2c) {
	          push(offers, name, params);
	          params = Object.create(null);
	        } else {
	          extensionName = name;
	        }
	        start = end = -1;
	      } else {
	        throw new SyntaxError(`Unexpected character at index ${i}`);
	      }
	    } else if (paramName === undefined) {
	      if (end === -1 && tokenChars[code] === 1) {
	        if (start === -1) start = i;
	      } else if (code === 0x20 || code === 0x09) {
	        if (end === -1 && start !== -1) end = i;
	      } else if (code === 0x3b || code === 0x2c) {
	        if (start === -1) {
	          throw new SyntaxError(`Unexpected character at index ${i}`);
	        }
	        if (end === -1) end = i;
	        push(params, header.slice(start, end), true);
	        if (code === 0x2c) {
	          push(offers, extensionName, params);
	          params = Object.create(null);
	          extensionName = undefined;
	        }
	        start = end = -1;
	      } else if (code === 0x3d  && start !== -1 && end === -1) {
	        paramName = header.slice(start, i);
	        start = end = -1;
	      } else {
	        throw new SyntaxError(`Unexpected character at index ${i}`);
	      }
	    } else {
	      if (isEscaping) {
	        if (tokenChars[code] !== 1) {
	          throw new SyntaxError(`Unexpected character at index ${i}`);
	        }
	        if (start === -1) start = i;
	        else if (!mustUnescape) mustUnescape = true;
	        isEscaping = false;
	      } else if (inQuotes) {
	        if (tokenChars[code] === 1) {
	          if (start === -1) start = i;
	        } else if (code === 0x22  && start !== -1) {
	          inQuotes = false;
	          end = i;
	        } else if (code === 0x5c ) {
	          isEscaping = true;
	        } else {
	          throw new SyntaxError(`Unexpected character at index ${i}`);
	        }
	      } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
	        inQuotes = true;
	      } else if (end === -1 && tokenChars[code] === 1) {
	        if (start === -1) start = i;
	      } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
	        if (end === -1) end = i;
	      } else if (code === 0x3b || code === 0x2c) {
	        if (start === -1) {
	          throw new SyntaxError(`Unexpected character at index ${i}`);
	        }
	        if (end === -1) end = i;
	        let value = header.slice(start, end);
	        if (mustUnescape) {
	          value = value.replace(/\\/g, '');
	          mustUnescape = false;
	        }
	        push(params, paramName, value);
	        if (code === 0x2c) {
	          push(offers, extensionName, params);
	          params = Object.create(null);
	          extensionName = undefined;
	        }
	        paramName = undefined;
	        start = end = -1;
	      } else {
	        throw new SyntaxError(`Unexpected character at index ${i}`);
	      }
	    }
	  }
	  if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
	    throw new SyntaxError('Unexpected end of input');
	  }
	  if (end === -1) end = i;
	  const token = header.slice(start, end);
	  if (extensionName === undefined) {
	    push(offers, token, params);
	  } else {
	    if (paramName === undefined) {
	      push(params, token, true);
	    } else if (mustUnescape) {
	      push(params, paramName, token.replace(/\\/g, ''));
	    } else {
	      push(params, paramName, token);
	    }
	    push(offers, extensionName, params);
	  }
	  return offers;
	}
	function format(extensions) {
	  return Object.keys(extensions)
	    .map((extension) => {
	      let configurations = extensions[extension];
	      if (!Array.isArray(configurations)) configurations = [configurations];
	      return configurations
	        .map((params) => {
	          return [extension]
	            .concat(
	              Object.keys(params).map((k) => {
	                let values = params[k];
	                if (!Array.isArray(values)) values = [values];
	                return values
	                  .map((v) => (v === true ? k : `${k}=${v}`))
	                  .join('; ');
	              })
	            )
	            .join('; ');
	        })
	        .join(', ');
	    })
	    .join(', ');
	}
	extension = { format, parse };
	return extension;
}

var websocket;
var hasRequiredWebsocket;

function requireWebsocket () {
	if (hasRequiredWebsocket) return websocket;
	hasRequiredWebsocket = 1;
	const EventEmitter = require$$0$8;
	const https = require$$1$1;
	const http = require$$0$6;
	const net = require$$0$7;
	const tls = require$$1$2;
	const { randomBytes, createHash } = require$$2$1;
	const { Duplex, Readable } = require$$1$3;
	const { URL } = require$$5;
	const PerMessageDeflate = requirePermessageDeflate();
	const Receiver = requireReceiver();
	const Sender = requireSender();
	const { isBlob } = requireValidation();
	const {
	  BINARY_TYPES,
	  CLOSE_TIMEOUT,
	  EMPTY_BUFFER,
	  GUID,
	  kForOnEventAttribute,
	  kListener,
	  kStatusCode,
	  kWebSocket,
	  NOOP
	} = requireConstants();
	const {
	  EventTarget: { addEventListener, removeEventListener }
	} = requireEventTarget();
	const { format, parse } = requireExtension();
	const { toBuffer } = requireBufferUtil();
	const kAborted = Symbol('kAborted');
	const protocolVersions = [8, 13];
	const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
	const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
	class WebSocket extends EventEmitter {
	  constructor(address, protocols, options) {
	    super();
	    this._binaryType = BINARY_TYPES[0];
	    this._closeCode = 1006;
	    this._closeFrameReceived = false;
	    this._closeFrameSent = false;
	    this._closeMessage = EMPTY_BUFFER;
	    this._closeTimer = null;
	    this._errorEmitted = false;
	    this._extensions = {};
	    this._paused = false;
	    this._protocol = '';
	    this._readyState = WebSocket.CONNECTING;
	    this._receiver = null;
	    this._sender = null;
	    this._socket = null;
	    if (address !== null) {
	      this._bufferedAmount = 0;
	      this._isServer = false;
	      this._redirects = 0;
	      if (protocols === undefined) {
	        protocols = [];
	      } else if (!Array.isArray(protocols)) {
	        if (typeof protocols === 'object' && protocols !== null) {
	          options = protocols;
	          protocols = [];
	        } else {
	          protocols = [protocols];
	        }
	      }
	      initAsClient(this, address, protocols, options);
	    } else {
	      this._autoPong = options.autoPong;
	      this._closeTimeout = options.closeTimeout;
	      this._isServer = true;
	    }
	  }
	  get binaryType() {
	    return this._binaryType;
	  }
	  set binaryType(type) {
	    if (!BINARY_TYPES.includes(type)) return;
	    this._binaryType = type;
	    if (this._receiver) this._receiver._binaryType = type;
	  }
	  get bufferedAmount() {
	    if (!this._socket) return this._bufferedAmount;
	    return this._socket._writableState.length + this._sender._bufferedBytes;
	  }
	  get extensions() {
	    return Object.keys(this._extensions).join();
	  }
	  get isPaused() {
	    return this._paused;
	  }
	  get onclose() {
	    return null;
	  }
	  get onerror() {
	    return null;
	  }
	  get onopen() {
	    return null;
	  }
	  get onmessage() {
	    return null;
	  }
	  get protocol() {
	    return this._protocol;
	  }
	  get readyState() {
	    return this._readyState;
	  }
	  get url() {
	    return this._url;
	  }
	  setSocket(socket, head, options) {
	    const receiver = new Receiver({
	      allowSynchronousEvents: options.allowSynchronousEvents,
	      binaryType: this.binaryType,
	      extensions: this._extensions,
	      isServer: this._isServer,
	      maxPayload: options.maxPayload,
	      skipUTF8Validation: options.skipUTF8Validation
	    });
	    const sender = new Sender(socket, this._extensions, options.generateMask);
	    this._receiver = receiver;
	    this._sender = sender;
	    this._socket = socket;
	    receiver[kWebSocket] = this;
	    sender[kWebSocket] = this;
	    socket[kWebSocket] = this;
	    receiver.on('conclude', receiverOnConclude);
	    receiver.on('drain', receiverOnDrain);
	    receiver.on('error', receiverOnError);
	    receiver.on('message', receiverOnMessage);
	    receiver.on('ping', receiverOnPing);
	    receiver.on('pong', receiverOnPong);
	    sender.onerror = senderOnError;
	    if (socket.setTimeout) socket.setTimeout(0);
	    if (socket.setNoDelay) socket.setNoDelay();
	    if (head.length > 0) socket.unshift(head);
	    socket.on('close', socketOnClose);
	    socket.on('data', socketOnData);
	    socket.on('end', socketOnEnd);
	    socket.on('error', socketOnError);
	    this._readyState = WebSocket.OPEN;
	    this.emit('open');
	  }
	  emitClose() {
	    if (!this._socket) {
	      this._readyState = WebSocket.CLOSED;
	      this.emit('close', this._closeCode, this._closeMessage);
	      return;
	    }
	    if (this._extensions[PerMessageDeflate.extensionName]) {
	      this._extensions[PerMessageDeflate.extensionName].cleanup();
	    }
	    this._receiver.removeAllListeners();
	    this._readyState = WebSocket.CLOSED;
	    this.emit('close', this._closeCode, this._closeMessage);
	  }
	  close(code, data) {
	    if (this.readyState === WebSocket.CLOSED) return;
	    if (this.readyState === WebSocket.CONNECTING) {
	      const msg = 'WebSocket was closed before the connection was established';
	      abortHandshake(this, this._req, msg);
	      return;
	    }
	    if (this.readyState === WebSocket.CLOSING) {
	      if (
	        this._closeFrameSent &&
	        (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
	      ) {
	        this._socket.end();
	      }
	      return;
	    }
	    this._readyState = WebSocket.CLOSING;
	    this._sender.close(code, data, !this._isServer, (err) => {
	      if (err) return;
	      this._closeFrameSent = true;
	      if (
	        this._closeFrameReceived ||
	        this._receiver._writableState.errorEmitted
	      ) {
	        this._socket.end();
	      }
	    });
	    setCloseTimer(this);
	  }
	  pause() {
	    if (
	      this.readyState === WebSocket.CONNECTING ||
	      this.readyState === WebSocket.CLOSED
	    ) {
	      return;
	    }
	    this._paused = true;
	    this._socket.pause();
	  }
	  ping(data, mask, cb) {
	    if (this.readyState === WebSocket.CONNECTING) {
	      throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
	    }
	    if (typeof data === 'function') {
	      cb = data;
	      data = mask = undefined;
	    } else if (typeof mask === 'function') {
	      cb = mask;
	      mask = undefined;
	    }
	    if (typeof data === 'number') data = data.toString();
	    if (this.readyState !== WebSocket.OPEN) {
	      sendAfterClose(this, data, cb);
	      return;
	    }
	    if (mask === undefined) mask = !this._isServer;
	    this._sender.ping(data || EMPTY_BUFFER, mask, cb);
	  }
	  pong(data, mask, cb) {
	    if (this.readyState === WebSocket.CONNECTING) {
	      throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
	    }
	    if (typeof data === 'function') {
	      cb = data;
	      data = mask = undefined;
	    } else if (typeof mask === 'function') {
	      cb = mask;
	      mask = undefined;
	    }
	    if (typeof data === 'number') data = data.toString();
	    if (this.readyState !== WebSocket.OPEN) {
	      sendAfterClose(this, data, cb);
	      return;
	    }
	    if (mask === undefined) mask = !this._isServer;
	    this._sender.pong(data || EMPTY_BUFFER, mask, cb);
	  }
	  resume() {
	    if (
	      this.readyState === WebSocket.CONNECTING ||
	      this.readyState === WebSocket.CLOSED
	    ) {
	      return;
	    }
	    this._paused = false;
	    if (!this._receiver._writableState.needDrain) this._socket.resume();
	  }
	  send(data, options, cb) {
	    if (this.readyState === WebSocket.CONNECTING) {
	      throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
	    }
	    if (typeof options === 'function') {
	      cb = options;
	      options = {};
	    }
	    if (typeof data === 'number') data = data.toString();
	    if (this.readyState !== WebSocket.OPEN) {
	      sendAfterClose(this, data, cb);
	      return;
	    }
	    const opts = {
	      binary: typeof data !== 'string',
	      mask: !this._isServer,
	      compress: true,
	      fin: true,
	      ...options
	    };
	    if (!this._extensions[PerMessageDeflate.extensionName]) {
	      opts.compress = false;
	    }
	    this._sender.send(data || EMPTY_BUFFER, opts, cb);
	  }
	  terminate() {
	    if (this.readyState === WebSocket.CLOSED) return;
	    if (this.readyState === WebSocket.CONNECTING) {
	      const msg = 'WebSocket was closed before the connection was established';
	      abortHandshake(this, this._req, msg);
	      return;
	    }
	    if (this._socket) {
	      this._readyState = WebSocket.CLOSING;
	      this._socket.destroy();
	    }
	  }
	}
	Object.defineProperty(WebSocket, 'CONNECTING', {
	  enumerable: true,
	  value: readyStates.indexOf('CONNECTING')
	});
	Object.defineProperty(WebSocket.prototype, 'CONNECTING', {
	  enumerable: true,
	  value: readyStates.indexOf('CONNECTING')
	});
	Object.defineProperty(WebSocket, 'OPEN', {
	  enumerable: true,
	  value: readyStates.indexOf('OPEN')
	});
	Object.defineProperty(WebSocket.prototype, 'OPEN', {
	  enumerable: true,
	  value: readyStates.indexOf('OPEN')
	});
	Object.defineProperty(WebSocket, 'CLOSING', {
	  enumerable: true,
	  value: readyStates.indexOf('CLOSING')
	});
	Object.defineProperty(WebSocket.prototype, 'CLOSING', {
	  enumerable: true,
	  value: readyStates.indexOf('CLOSING')
	});
	Object.defineProperty(WebSocket, 'CLOSED', {
	  enumerable: true,
	  value: readyStates.indexOf('CLOSED')
	});
	Object.defineProperty(WebSocket.prototype, 'CLOSED', {
	  enumerable: true,
	  value: readyStates.indexOf('CLOSED')
	});
	[
	  'binaryType',
	  'bufferedAmount',
	  'extensions',
	  'isPaused',
	  'protocol',
	  'readyState',
	  'url'
	].forEach((property) => {
	  Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
	});
	['open', 'error', 'close', 'message'].forEach((method) => {
	  Object.defineProperty(WebSocket.prototype, `on${method}`, {
	    enumerable: true,
	    get() {
	      for (const listener of this.listeners(method)) {
	        if (listener[kForOnEventAttribute]) return listener[kListener];
	      }
	      return null;
	    },
	    set(handler) {
	      for (const listener of this.listeners(method)) {
	        if (listener[kForOnEventAttribute]) {
	          this.removeListener(method, listener);
	          break;
	        }
	      }
	      if (typeof handler !== 'function') return;
	      this.addEventListener(method, handler, {
	        [kForOnEventAttribute]: true
	      });
	    }
	  });
	});
	WebSocket.prototype.addEventListener = addEventListener;
	WebSocket.prototype.removeEventListener = removeEventListener;
	websocket = WebSocket;
	function initAsClient(websocket, address, protocols, options) {
	  const opts = {
	    allowSynchronousEvents: true,
	    autoPong: true,
	    closeTimeout: CLOSE_TIMEOUT,
	    protocolVersion: protocolVersions[1],
	    maxPayload: 100 * 1024 * 1024,
	    skipUTF8Validation: false,
	    perMessageDeflate: true,
	    followRedirects: false,
	    maxRedirects: 10,
	    ...options,
	    socketPath: undefined,
	    hostname: undefined,
	    protocol: undefined,
	    timeout: undefined,
	    method: 'GET',
	    host: undefined,
	    path: undefined,
	    port: undefined
	  };
	  websocket._autoPong = opts.autoPong;
	  websocket._closeTimeout = opts.closeTimeout;
	  if (!protocolVersions.includes(opts.protocolVersion)) {
	    throw new RangeError(
	      `Unsupported protocol version: ${opts.protocolVersion} ` +
	        `(supported versions: ${protocolVersions.join(', ')})`
	    );
	  }
	  let parsedUrl;
	  if (address instanceof URL) {
	    parsedUrl = address;
	  } else {
	    try {
	      parsedUrl = new URL(address);
	    } catch (e) {
	      throw new SyntaxError(`Invalid URL: ${address}`);
	    }
	  }
	  if (parsedUrl.protocol === 'http:') {
	    parsedUrl.protocol = 'ws:';
	  } else if (parsedUrl.protocol === 'https:') {
	    parsedUrl.protocol = 'wss:';
	  }
	  websocket._url = parsedUrl.href;
	  const isSecure = parsedUrl.protocol === 'wss:';
	  const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
	  let invalidUrlMessage;
	  if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {
	    invalidUrlMessage =
	      'The URL\'s protocol must be one of "ws:", "wss:", ' +
	      '"http:", "https:", or "ws+unix:"';
	  } else if (isIpcUrl && !parsedUrl.pathname) {
	    invalidUrlMessage = "The URL's pathname is empty";
	  } else if (parsedUrl.hash) {
	    invalidUrlMessage = 'The URL contains a fragment identifier';
	  }
	  if (invalidUrlMessage) {
	    const err = new SyntaxError(invalidUrlMessage);
	    if (websocket._redirects === 0) {
	      throw err;
	    } else {
	      emitErrorAndClose(websocket, err);
	      return;
	    }
	  }
	  const defaultPort = isSecure ? 443 : 80;
	  const key = randomBytes(16).toString('base64');
	  const request = isSecure ? https.request : http.request;
	  const protocolSet = new Set();
	  let perMessageDeflate;
	  opts.createConnection =
	    opts.createConnection || (isSecure ? tlsConnect : netConnect);
	  opts.defaultPort = opts.defaultPort || defaultPort;
	  opts.port = parsedUrl.port || defaultPort;
	  opts.host = parsedUrl.hostname.startsWith('[')
	    ? parsedUrl.hostname.slice(1, -1)
	    : parsedUrl.hostname;
	  opts.headers = {
	    ...opts.headers,
	    'Sec-WebSocket-Version': opts.protocolVersion,
	    'Sec-WebSocket-Key': key,
	    Connection: 'Upgrade',
	    Upgrade: 'websocket'
	  };
	  opts.path = parsedUrl.pathname + parsedUrl.search;
	  opts.timeout = opts.handshakeTimeout;
	  if (opts.perMessageDeflate) {
	    perMessageDeflate = new PerMessageDeflate(
	      opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
	      false,
	      opts.maxPayload
	    );
	    opts.headers['Sec-WebSocket-Extensions'] = format({
	      [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
	    });
	  }
	  if (protocols.length) {
	    for (const protocol of protocols) {
	      if (
	        typeof protocol !== 'string' ||
	        !subprotocolRegex.test(protocol) ||
	        protocolSet.has(protocol)
	      ) {
	        throw new SyntaxError(
	          'An invalid or duplicated subprotocol was specified'
	        );
	      }
	      protocolSet.add(protocol);
	    }
	    opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
	  }
	  if (opts.origin) {
	    if (opts.protocolVersion < 13) {
	      opts.headers['Sec-WebSocket-Origin'] = opts.origin;
	    } else {
	      opts.headers.Origin = opts.origin;
	    }
	  }
	  if (parsedUrl.username || parsedUrl.password) {
	    opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
	  }
	  if (isIpcUrl) {
	    const parts = opts.path.split(':');
	    opts.socketPath = parts[0];
	    opts.path = parts[1];
	  }
	  let req;
	  if (opts.followRedirects) {
	    if (websocket._redirects === 0) {
	      websocket._originalIpc = isIpcUrl;
	      websocket._originalSecure = isSecure;
	      websocket._originalHostOrSocketPath = isIpcUrl
	        ? opts.socketPath
	        : parsedUrl.host;
	      const headers = options && options.headers;
	      options = { ...options, headers: {} };
	      if (headers) {
	        for (const [key, value] of Object.entries(headers)) {
	          options.headers[key.toLowerCase()] = value;
	        }
	      }
	    } else if (websocket.listenerCount('redirect') === 0) {
	      const isSameHost = isIpcUrl
	        ? websocket._originalIpc
	          ? opts.socketPath === websocket._originalHostOrSocketPath
	          : false
	        : websocket._originalIpc
	          ? false
	          : parsedUrl.host === websocket._originalHostOrSocketPath;
	      if (!isSameHost || (websocket._originalSecure && !isSecure)) {
	        delete opts.headers.authorization;
	        delete opts.headers.cookie;
	        if (!isSameHost) delete opts.headers.host;
	        opts.auth = undefined;
	      }
	    }
	    if (opts.auth && !options.headers.authorization) {
	      options.headers.authorization =
	        'Basic ' + Buffer.from(opts.auth).toString('base64');
	    }
	    req = websocket._req = request(opts);
	    if (websocket._redirects) {
	      websocket.emit('redirect', websocket.url, req);
	    }
	  } else {
	    req = websocket._req = request(opts);
	  }
	  if (opts.timeout) {
	    req.on('timeout', () => {
	      abortHandshake(websocket, req, 'Opening handshake has timed out');
	    });
	  }
	  req.on('error', (err) => {
	    if (req === null || req[kAborted]) return;
	    req = websocket._req = null;
	    emitErrorAndClose(websocket, err);
	  });
	  req.on('response', (res) => {
	    const location = res.headers.location;
	    const statusCode = res.statusCode;
	    if (
	      location &&
	      opts.followRedirects &&
	      statusCode >= 300 &&
	      statusCode < 400
	    ) {
	      if (++websocket._redirects > opts.maxRedirects) {
	        abortHandshake(websocket, req, 'Maximum redirects exceeded');
	        return;
	      }
	      req.abort();
	      let addr;
	      try {
	        addr = new URL(location, address);
	      } catch (e) {
	        const err = new SyntaxError(`Invalid URL: ${location}`);
	        emitErrorAndClose(websocket, err);
	        return;
	      }
	      initAsClient(websocket, addr, protocols, options);
	    } else if (!websocket.emit('unexpected-response', req, res)) {
	      abortHandshake(
	        websocket,
	        req,
	        `Unexpected server response: ${res.statusCode}`
	      );
	    }
	  });
	  req.on('upgrade', (res, socket, head) => {
	    websocket.emit('upgrade', res);
	    if (websocket.readyState !== WebSocket.CONNECTING) return;
	    req = websocket._req = null;
	    const upgrade = res.headers.upgrade;
	    if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
	      abortHandshake(websocket, socket, 'Invalid Upgrade header');
	      return;
	    }
	    const digest = createHash('sha1')
	      .update(key + GUID)
	      .digest('base64');
	    if (res.headers['sec-websocket-accept'] !== digest) {
	      abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
	      return;
	    }
	    const serverProt = res.headers['sec-websocket-protocol'];
	    let protError;
	    if (serverProt !== undefined) {
	      if (!protocolSet.size) {
	        protError = 'Server sent a subprotocol but none was requested';
	      } else if (!protocolSet.has(serverProt)) {
	        protError = 'Server sent an invalid subprotocol';
	      }
	    } else if (protocolSet.size) {
	      protError = 'Server sent no subprotocol';
	    }
	    if (protError) {
	      abortHandshake(websocket, socket, protError);
	      return;
	    }
	    if (serverProt) websocket._protocol = serverProt;
	    const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
	    if (secWebSocketExtensions !== undefined) {
	      if (!perMessageDeflate) {
	        const message =
	          'Server sent a Sec-WebSocket-Extensions header but no extension ' +
	          'was requested';
	        abortHandshake(websocket, socket, message);
	        return;
	      }
	      let extensions;
	      try {
	        extensions = parse(secWebSocketExtensions);
	      } catch (err) {
	        const message = 'Invalid Sec-WebSocket-Extensions header';
	        abortHandshake(websocket, socket, message);
	        return;
	      }
	      const extensionNames = Object.keys(extensions);
	      if (
	        extensionNames.length !== 1 ||
	        extensionNames[0] !== PerMessageDeflate.extensionName
	      ) {
	        const message = 'Server indicated an extension that was not requested';
	        abortHandshake(websocket, socket, message);
	        return;
	      }
	      try {
	        perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
	      } catch (err) {
	        const message = 'Invalid Sec-WebSocket-Extensions header';
	        abortHandshake(websocket, socket, message);
	        return;
	      }
	      websocket._extensions[PerMessageDeflate.extensionName] =
	        perMessageDeflate;
	    }
	    websocket.setSocket(socket, head, {
	      allowSynchronousEvents: opts.allowSynchronousEvents,
	      generateMask: opts.generateMask,
	      maxPayload: opts.maxPayload,
	      skipUTF8Validation: opts.skipUTF8Validation
	    });
	  });
	  if (opts.finishRequest) {
	    opts.finishRequest(req, websocket);
	  } else {
	    req.end();
	  }
	}
	function emitErrorAndClose(websocket, err) {
	  websocket._readyState = WebSocket.CLOSING;
	  websocket._errorEmitted = true;
	  websocket.emit('error', err);
	  websocket.emitClose();
	}
	function netConnect(options) {
	  options.path = options.socketPath;
	  return net.connect(options);
	}
	function tlsConnect(options) {
	  options.path = undefined;
	  if (!options.servername && options.servername !== '') {
	    options.servername = net.isIP(options.host) ? '' : options.host;
	  }
	  return tls.connect(options);
	}
	function abortHandshake(websocket, stream, message) {
	  websocket._readyState = WebSocket.CLOSING;
	  const err = new Error(message);
	  Error.captureStackTrace(err, abortHandshake);
	  if (stream.setHeader) {
	    stream[kAborted] = true;
	    stream.abort();
	    if (stream.socket && !stream.socket.destroyed) {
	      stream.socket.destroy();
	    }
	    process.nextTick(emitErrorAndClose, websocket, err);
	  } else {
	    stream.destroy(err);
	    stream.once('error', websocket.emit.bind(websocket, 'error'));
	    stream.once('close', websocket.emitClose.bind(websocket));
	  }
	}
	function sendAfterClose(websocket, data, cb) {
	  if (data) {
	    const length = isBlob(data) ? data.size : toBuffer(data).length;
	    if (websocket._socket) websocket._sender._bufferedBytes += length;
	    else websocket._bufferedAmount += length;
	  }
	  if (cb) {
	    const err = new Error(
	      `WebSocket is not open: readyState ${websocket.readyState} ` +
	        `(${readyStates[websocket.readyState]})`
	    );
	    process.nextTick(cb, err);
	  }
	}
	function receiverOnConclude(code, reason) {
	  const websocket = this[kWebSocket];
	  websocket._closeFrameReceived = true;
	  websocket._closeMessage = reason;
	  websocket._closeCode = code;
	  if (websocket._socket[kWebSocket] === undefined) return;
	  websocket._socket.removeListener('data', socketOnData);
	  process.nextTick(resume, websocket._socket);
	  if (code === 1005) websocket.close();
	  else websocket.close(code, reason);
	}
	function receiverOnDrain() {
	  const websocket = this[kWebSocket];
	  if (!websocket.isPaused) websocket._socket.resume();
	}
	function receiverOnError(err) {
	  const websocket = this[kWebSocket];
	  if (websocket._socket[kWebSocket] !== undefined) {
	    websocket._socket.removeListener('data', socketOnData);
	    process.nextTick(resume, websocket._socket);
	    websocket.close(err[kStatusCode]);
	  }
	  if (!websocket._errorEmitted) {
	    websocket._errorEmitted = true;
	    websocket.emit('error', err);
	  }
	}
	function receiverOnFinish() {
	  this[kWebSocket].emitClose();
	}
	function receiverOnMessage(data, isBinary) {
	  this[kWebSocket].emit('message', data, isBinary);
	}
	function receiverOnPing(data) {
	  const websocket = this[kWebSocket];
	  if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
	  websocket.emit('ping', data);
	}
	function receiverOnPong(data) {
	  this[kWebSocket].emit('pong', data);
	}
	function resume(stream) {
	  stream.resume();
	}
	function senderOnError(err) {
	  const websocket = this[kWebSocket];
	  if (websocket.readyState === WebSocket.CLOSED) return;
	  if (websocket.readyState === WebSocket.OPEN) {
	    websocket._readyState = WebSocket.CLOSING;
	    setCloseTimer(websocket);
	  }
	  this._socket.end();
	  if (!websocket._errorEmitted) {
	    websocket._errorEmitted = true;
	    websocket.emit('error', err);
	  }
	}
	function setCloseTimer(websocket) {
	  websocket._closeTimer = setTimeout(
	    websocket._socket.destroy.bind(websocket._socket),
	    websocket._closeTimeout
	  );
	}
	function socketOnClose() {
	  const websocket = this[kWebSocket];
	  this.removeListener('close', socketOnClose);
	  this.removeListener('data', socketOnData);
	  this.removeListener('end', socketOnEnd);
	  websocket._readyState = WebSocket.CLOSING;
	  if (
	    !this._readableState.endEmitted &&
	    !websocket._closeFrameReceived &&
	    !websocket._receiver._writableState.errorEmitted &&
	    this._readableState.length !== 0
	  ) {
	    const chunk = this.read(this._readableState.length);
	    websocket._receiver.write(chunk);
	  }
	  websocket._receiver.end();
	  this[kWebSocket] = undefined;
	  clearTimeout(websocket._closeTimer);
	  if (
	    websocket._receiver._writableState.finished ||
	    websocket._receiver._writableState.errorEmitted
	  ) {
	    websocket.emitClose();
	  } else {
	    websocket._receiver.on('error', receiverOnFinish);
	    websocket._receiver.on('finish', receiverOnFinish);
	  }
	}
	function socketOnData(chunk) {
	  if (!this[kWebSocket]._receiver.write(chunk)) {
	    this.pause();
	  }
	}
	function socketOnEnd() {
	  const websocket = this[kWebSocket];
	  websocket._readyState = WebSocket.CLOSING;
	  websocket._receiver.end();
	  this.end();
	}
	function socketOnError() {
	  const websocket = this[kWebSocket];
	  this.removeListener('error', socketOnError);
	  this.on('error', NOOP);
	  if (websocket) {
	    websocket._readyState = WebSocket.CLOSING;
	    this.destroy();
	  }
	}
	return websocket;
}

var stream;
var hasRequiredStream;

function requireStream () {
	if (hasRequiredStream) return stream;
	hasRequiredStream = 1;
	requireWebsocket();
	const { Duplex } = require$$1$3;
	function emitClose(stream) {
	  stream.emit('close');
	}
	function duplexOnEnd() {
	  if (!this.destroyed && this._writableState.finished) {
	    this.destroy();
	  }
	}
	function duplexOnError(err) {
	  this.removeListener('error', duplexOnError);
	  this.destroy();
	  if (this.listenerCount('error') === 0) {
	    this.emit('error', err);
	  }
	}
	function createWebSocketStream(ws, options) {
	  let terminateOnDestroy = true;
	  const duplex = new Duplex({
	    ...options,
	    autoDestroy: false,
	    emitClose: false,
	    objectMode: false,
	    writableObjectMode: false
	  });
	  ws.on('message', function message(msg, isBinary) {
	    const data =
	      !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
	    if (!duplex.push(data)) ws.pause();
	  });
	  ws.once('error', function error(err) {
	    if (duplex.destroyed) return;
	    terminateOnDestroy = false;
	    duplex.destroy(err);
	  });
	  ws.once('close', function close() {
	    if (duplex.destroyed) return;
	    duplex.push(null);
	  });
	  duplex._destroy = function (err, callback) {
	    if (ws.readyState === ws.CLOSED) {
	      callback(err);
	      process.nextTick(emitClose, duplex);
	      return;
	    }
	    let called = false;
	    ws.once('error', function error(err) {
	      called = true;
	      callback(err);
	    });
	    ws.once('close', function close() {
	      if (!called) callback(err);
	      process.nextTick(emitClose, duplex);
	    });
	    if (terminateOnDestroy) ws.terminate();
	  };
	  duplex._final = function (callback) {
	    if (ws.readyState === ws.CONNECTING) {
	      ws.once('open', function open() {
	        duplex._final(callback);
	      });
	      return;
	    }
	    if (ws._socket === null) return;
	    if (ws._socket._writableState.finished) {
	      callback();
	      if (duplex._readableState.endEmitted) duplex.destroy();
	    } else {
	      ws._socket.once('finish', function finish() {
	        callback();
	      });
	      ws.close();
	    }
	  };
	  duplex._read = function () {
	    if (ws.isPaused) ws.resume();
	  };
	  duplex._write = function (chunk, encoding, callback) {
	    if (ws.readyState === ws.CONNECTING) {
	      ws.once('open', function open() {
	        duplex._write(chunk, encoding, callback);
	      });
	      return;
	    }
	    ws.send(chunk, callback);
	  };
	  duplex.on('end', duplexOnEnd);
	  duplex.on('error', duplexOnError);
	  return duplex;
	}
	stream = createWebSocketStream;
	return stream;
}

requireStream();

requireReceiver();

requireSender();

var websocketExports = requireWebsocket();
var WebSocket$1 = /*@__PURE__*/getDefaultExportFromCjs(websocketExports);

var subprotocol;
var hasRequiredSubprotocol;

function requireSubprotocol () {
	if (hasRequiredSubprotocol) return subprotocol;
	hasRequiredSubprotocol = 1;
	const { tokenChars } = requireValidation();
	function parse(header) {
	  const protocols = new Set();
	  let start = -1;
	  let end = -1;
	  let i = 0;
	  for (i; i < header.length; i++) {
	    const code = header.charCodeAt(i);
	    if (end === -1 && tokenChars[code] === 1) {
	      if (start === -1) start = i;
	    } else if (
	      i !== 0 &&
	      (code === 0x20  || code === 0x09)
	    ) {
	      if (end === -1 && start !== -1) end = i;
	    } else if (code === 0x2c ) {
	      if (start === -1) {
	        throw new SyntaxError(`Unexpected character at index ${i}`);
	      }
	      if (end === -1) end = i;
	      const protocol = header.slice(start, end);
	      if (protocols.has(protocol)) {
	        throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
	      }
	      protocols.add(protocol);
	      start = end = -1;
	    } else {
	      throw new SyntaxError(`Unexpected character at index ${i}`);
	    }
	  }
	  if (start === -1 || end !== -1) {
	    throw new SyntaxError('Unexpected end of input');
	  }
	  const protocol = header.slice(start, i);
	  if (protocols.has(protocol)) {
	    throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
	  }
	  protocols.add(protocol);
	  return protocols;
	}
	subprotocol = { parse };
	return subprotocol;
}

var websocketServer;
var hasRequiredWebsocketServer;

function requireWebsocketServer () {
	if (hasRequiredWebsocketServer) return websocketServer;
	hasRequiredWebsocketServer = 1;
	const EventEmitter = require$$0$8;
	const http = require$$0$6;
	const { Duplex } = require$$1$3;
	const { createHash } = require$$2$1;
	const extension = requireExtension();
	const PerMessageDeflate = requirePermessageDeflate();
	const subprotocol = requireSubprotocol();
	const WebSocket = requireWebsocket();
	const { CLOSE_TIMEOUT, GUID, kWebSocket } = requireConstants();
	const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
	const RUNNING = 0;
	const CLOSING = 1;
	const CLOSED = 2;
	class WebSocketServer extends EventEmitter {
	  constructor(options, callback) {
	    super();
	    options = {
	      allowSynchronousEvents: true,
	      autoPong: true,
	      maxPayload: 100 * 1024 * 1024,
	      skipUTF8Validation: false,
	      perMessageDeflate: false,
	      handleProtocols: null,
	      clientTracking: true,
	      closeTimeout: CLOSE_TIMEOUT,
	      verifyClient: null,
	      noServer: false,
	      backlog: null,
	      server: null,
	      host: null,
	      path: null,
	      port: null,
	      WebSocket,
	      ...options
	    };
	    if (
	      (options.port == null && !options.server && !options.noServer) ||
	      (options.port != null && (options.server || options.noServer)) ||
	      (options.server && options.noServer)
	    ) {
	      throw new TypeError(
	        'One and only one of the "port", "server", or "noServer" options ' +
	          'must be specified'
	      );
	    }
	    if (options.port != null) {
	      this._server = http.createServer((req, res) => {
	        const body = http.STATUS_CODES[426];
	        res.writeHead(426, {
	          'Content-Length': body.length,
	          'Content-Type': 'text/plain'
	        });
	        res.end(body);
	      });
	      this._server.listen(
	        options.port,
	        options.host,
	        options.backlog,
	        callback
	      );
	    } else if (options.server) {
	      this._server = options.server;
	    }
	    if (this._server) {
	      const emitConnection = this.emit.bind(this, 'connection');
	      this._removeListeners = addListeners(this._server, {
	        listening: this.emit.bind(this, 'listening'),
	        error: this.emit.bind(this, 'error'),
	        upgrade: (req, socket, head) => {
	          this.handleUpgrade(req, socket, head, emitConnection);
	        }
	      });
	    }
	    if (options.perMessageDeflate === true) options.perMessageDeflate = {};
	    if (options.clientTracking) {
	      this.clients = new Set();
	      this._shouldEmitClose = false;
	    }
	    this.options = options;
	    this._state = RUNNING;
	  }
	  address() {
	    if (this.options.noServer) {
	      throw new Error('The server is operating in "noServer" mode');
	    }
	    if (!this._server) return null;
	    return this._server.address();
	  }
	  close(cb) {
	    if (this._state === CLOSED) {
	      if (cb) {
	        this.once('close', () => {
	          cb(new Error('The server is not running'));
	        });
	      }
	      process.nextTick(emitClose, this);
	      return;
	    }
	    if (cb) this.once('close', cb);
	    if (this._state === CLOSING) return;
	    this._state = CLOSING;
	    if (this.options.noServer || this.options.server) {
	      if (this._server) {
	        this._removeListeners();
	        this._removeListeners = this._server = null;
	      }
	      if (this.clients) {
	        if (!this.clients.size) {
	          process.nextTick(emitClose, this);
	        } else {
	          this._shouldEmitClose = true;
	        }
	      } else {
	        process.nextTick(emitClose, this);
	      }
	    } else {
	      const server = this._server;
	      this._removeListeners();
	      this._removeListeners = this._server = null;
	      server.close(() => {
	        emitClose(this);
	      });
	    }
	  }
	  shouldHandle(req) {
	    if (this.options.path) {
	      const index = req.url.indexOf('?');
	      const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
	      if (pathname !== this.options.path) return false;
	    }
	    return true;
	  }
	  handleUpgrade(req, socket, head, cb) {
	    socket.on('error', socketOnError);
	    const key = req.headers['sec-websocket-key'];
	    const upgrade = req.headers.upgrade;
	    const version = +req.headers['sec-websocket-version'];
	    if (req.method !== 'GET') {
	      const message = 'Invalid HTTP method';
	      abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
	      return;
	    }
	    if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
	      const message = 'Invalid Upgrade header';
	      abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
	      return;
	    }
	    if (key === undefined || !keyRegex.test(key)) {
	      const message = 'Missing or invalid Sec-WebSocket-Key header';
	      abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
	      return;
	    }
	    if (version !== 13 && version !== 8) {
	      const message = 'Missing or invalid Sec-WebSocket-Version header';
	      abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
	        'Sec-WebSocket-Version': '13, 8'
	      });
	      return;
	    }
	    if (!this.shouldHandle(req)) {
	      abortHandshake(socket, 400);
	      return;
	    }
	    const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
	    let protocols = new Set();
	    if (secWebSocketProtocol !== undefined) {
	      try {
	        protocols = subprotocol.parse(secWebSocketProtocol);
	      } catch (err) {
	        const message = 'Invalid Sec-WebSocket-Protocol header';
	        abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
	        return;
	      }
	    }
	    const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
	    const extensions = {};
	    if (
	      this.options.perMessageDeflate &&
	      secWebSocketExtensions !== undefined
	    ) {
	      const perMessageDeflate = new PerMessageDeflate(
	        this.options.perMessageDeflate,
	        true,
	        this.options.maxPayload
	      );
	      try {
	        const offers = extension.parse(secWebSocketExtensions);
	        if (offers[PerMessageDeflate.extensionName]) {
	          perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
	          extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
	        }
	      } catch (err) {
	        const message =
	          'Invalid or unacceptable Sec-WebSocket-Extensions header';
	        abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
	        return;
	      }
	    }
	    if (this.options.verifyClient) {
	      const info = {
	        origin:
	          req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
	        secure: !!(req.socket.authorized || req.socket.encrypted),
	        req
	      };
	      if (this.options.verifyClient.length === 2) {
	        this.options.verifyClient(info, (verified, code, message, headers) => {
	          if (!verified) {
	            return abortHandshake(socket, code || 401, message, headers);
	          }
	          this.completeUpgrade(
	            extensions,
	            key,
	            protocols,
	            req,
	            socket,
	            head,
	            cb
	          );
	        });
	        return;
	      }
	      if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
	    }
	    this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
	  }
	  completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
	    if (!socket.readable || !socket.writable) return socket.destroy();
	    if (socket[kWebSocket]) {
	      throw new Error(
	        'server.handleUpgrade() was called more than once with the same ' +
	          'socket, possibly due to a misconfiguration'
	      );
	    }
	    if (this._state > RUNNING) return abortHandshake(socket, 503);
	    const digest = createHash('sha1')
	      .update(key + GUID)
	      .digest('base64');
	    const headers = [
	      'HTTP/1.1 101 Switching Protocols',
	      'Upgrade: websocket',
	      'Connection: Upgrade',
	      `Sec-WebSocket-Accept: ${digest}`
	    ];
	    const ws = new this.options.WebSocket(null, undefined, this.options);
	    if (protocols.size) {
	      const protocol = this.options.handleProtocols
	        ? this.options.handleProtocols(protocols, req)
	        : protocols.values().next().value;
	      if (protocol) {
	        headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
	        ws._protocol = protocol;
	      }
	    }
	    if (extensions[PerMessageDeflate.extensionName]) {
	      const params = extensions[PerMessageDeflate.extensionName].params;
	      const value = extension.format({
	        [PerMessageDeflate.extensionName]: [params]
	      });
	      headers.push(`Sec-WebSocket-Extensions: ${value}`);
	      ws._extensions = extensions;
	    }
	    this.emit('headers', headers, req);
	    socket.write(headers.concat('\r\n').join('\r\n'));
	    socket.removeListener('error', socketOnError);
	    ws.setSocket(socket, head, {
	      allowSynchronousEvents: this.options.allowSynchronousEvents,
	      maxPayload: this.options.maxPayload,
	      skipUTF8Validation: this.options.skipUTF8Validation
	    });
	    if (this.clients) {
	      this.clients.add(ws);
	      ws.on('close', () => {
	        this.clients.delete(ws);
	        if (this._shouldEmitClose && !this.clients.size) {
	          process.nextTick(emitClose, this);
	        }
	      });
	    }
	    cb(ws, req);
	  }
	}
	websocketServer = WebSocketServer;
	function addListeners(server, map) {
	  for (const event of Object.keys(map)) server.on(event, map[event]);
	  return function removeListeners() {
	    for (const event of Object.keys(map)) {
	      server.removeListener(event, map[event]);
	    }
	  };
	}
	function emitClose(server) {
	  server._state = CLOSED;
	  server.emit('close');
	}
	function socketOnError() {
	  this.destroy();
	}
	function abortHandshake(socket, code, message, headers) {
	  message = message || http.STATUS_CODES[code];
	  headers = {
	    Connection: 'close',
	    'Content-Type': 'text/html',
	    'Content-Length': Buffer.byteLength(message),
	    ...headers
	  };
	  socket.once('finish', socket.destroy);
	  socket.end(
	    `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
	      Object.keys(headers)
	        .map((h) => `${h}: ${headers[h]}`)
	        .join('\r\n') +
	      '\r\n\r\n' +
	      message
	  );
	}
	function abortHandshakeOrEmitwsClientError(
	  server,
	  req,
	  socket,
	  code,
	  message,
	  headers
	) {
	  if (server.listenerCount('wsClientError')) {
	    const err = new Error(message);
	    Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
	    server.emit('wsClientError', err, socket, req);
	  } else {
	    abortHandshake(socket, code, message, headers);
	  }
	}
	return websocketServer;
}

requireWebsocketServer();

/**
 * @license
 * Copyright 2018 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class NodeWebSocketTransport {
    static create(url, headers) {
        return new Promise((resolve, reject) => {
            const ws = new WebSocket$1(url, [], {
                followRedirects: true,
                perMessageDeflate: false,
                allowSynchronousEvents: false,
                maxPayload: 256 * 1024 * 1024,
                headers: {
                    'User-Agent': `Puppeteer ${packageVersion}`,
                    ...headers,
                },
            });
            ws.addEventListener('open', () => {
                return resolve(new NodeWebSocketTransport(ws));
            });
            ws.addEventListener('error', reject);
        });
    }
    #ws;
    onmessage;
    onclose;
    constructor(ws) {
        this.#ws = ws;
        this.#ws.addEventListener('message', event => {
            if (this.onmessage) {
                this.onmessage.call(null, event.data);
            }
        });
        this.#ws.addEventListener('close', () => {
            if (this.onclose) {
                this.onclose.call(null);
            }
        });
        this.#ws.addEventListener('error', () => { });
    }
    send(message) {
        this.#ws.send(message);
    }
    close() {
        this.#ws.close();
    }
}

var NodeWebSocketTransport$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	NodeWebSocketTransport: NodeWebSocketTransport
});

class PipeTransport {
    #pipeWrite;
    #subscriptions = new DisposableStack();
    #isClosed = false;
    #pendingMessage = [];
    onclose;
    onmessage;
    constructor(pipeWrite, pipeRead) {
        this.#pipeWrite = pipeWrite;
        const pipeReadEmitter = this.#subscriptions.use(
        new EventEmitter(pipeRead));
        pipeReadEmitter.on('data', buffer => {
            return this.#dispatch(buffer);
        });
        pipeReadEmitter.on('close', () => {
            if (this.onclose) {
                this.onclose.call(null);
            }
        });
        pipeReadEmitter.on('error', debugError);
        const pipeWriteEmitter = this.#subscriptions.use(
        new EventEmitter(pipeWrite));
        pipeWriteEmitter.on('error', debugError);
    }
    send(message) {
        assert(!this.#isClosed, '`PipeTransport` is closed.');
        this.#pipeWrite.write(message);
        this.#pipeWrite.write('\0');
    }
    #dispatch(buffer) {
        assert(!this.#isClosed, '`PipeTransport` is closed.');
        this.#pendingMessage.push(buffer);
        if (buffer.indexOf('\0') === -1) {
            return;
        }
        const concatBuffer = Buffer.concat(this.#pendingMessage);
        let start = 0;
        let end = concatBuffer.indexOf('\0');
        while (end !== -1) {
            const message = concatBuffer.toString(undefined, start, end);
            setImmediate(() => {
                if (this.onmessage) {
                    this.onmessage.call(null, message);
                }
            });
            start = end + 1;
            end = concatBuffer.indexOf('\0', start);
        }
        if (start >= concatBuffer.length) {
            this.#pendingMessage = [];
        }
        else {
            this.#pendingMessage = [concatBuffer.subarray(start)];
        }
    }
    close() {
        this.#isClosed = true;
        this.#subscriptions.dispose();
    }
}

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class BrowserLauncher {
    #browser;
    puppeteer;
    constructor(puppeteer, browser) {
        this.puppeteer = puppeteer;
        this.#browser = browser;
    }
    get browser() {
        return this.#browser;
    }
    async launch(options = {}) {
        const { dumpio = false, enableExtensions = false, env = process.env, handleSIGINT = true, handleSIGTERM = true, handleSIGHUP = true, acceptInsecureCerts = false, networkEnabled = true, defaultViewport = DEFAULT_VIEWPORT, downloadBehavior, slowMo = 0, timeout = 30000, waitForInitialPage = true, protocolTimeout, handleDevToolsAsPage, idGenerator = createIncrementalIdGenerator(), } = options;
        let { protocol } = options;
        if (this.#browser === 'firefox' && protocol === undefined) {
            protocol = 'webDriverBiDi';
        }
        if (this.#browser === 'firefox' && protocol === 'cdp') {
            throw new Error('Connecting to Firefox using CDP is no longer supported');
        }
        const launchArgs = await this.computeLaunchArguments({
            ...options,
            protocol,
        });
        if (!existsSync(launchArgs.executablePath)) {
            throw new Error(`Browser was not found at the configured executablePath (${launchArgs.executablePath})`);
        }
        const usePipe = launchArgs.args.includes('--remote-debugging-pipe');
        const onProcessExit = async () => {
            await this.cleanUserDataDir(launchArgs.userDataDir, {
                isTemp: launchArgs.isTempUserDataDir,
            });
        };
        if (this.#browser === 'firefox' &&
            protocol === 'webDriverBiDi' &&
            usePipe) {
            throw new Error('Pipe connections are not supported with Firefox and WebDriver BiDi');
        }
        const browserProcess = launch$1({
            executablePath: launchArgs.executablePath,
            args: launchArgs.args,
            handleSIGHUP,
            handleSIGTERM,
            handleSIGINT,
            dumpio,
            env,
            pipe: usePipe,
            onExit: onProcessExit,
            signal: options.signal,
        });
        let browser;
        let cdpConnection;
        let closing = false;
        const browserCloseCallback = async () => {
            if (closing) {
                return;
            }
            closing = true;
            await this.closeBrowser(browserProcess, cdpConnection);
        };
        try {
            if (this.#browser === 'firefox') {
                browser = await this.createBiDiBrowser(browserProcess, browserCloseCallback, {
                    timeout,
                    protocolTimeout,
                    slowMo,
                    defaultViewport,
                    acceptInsecureCerts,
                    networkEnabled,
                    idGenerator,
                });
            }
            else {
                if (usePipe) {
                    cdpConnection = await this.createCdpPipeConnection(browserProcess, {
                        timeout,
                        protocolTimeout,
                        slowMo,
                        idGenerator,
                    });
                }
                else {
                    cdpConnection = await this.createCdpSocketConnection(browserProcess, {
                        timeout,
                        protocolTimeout,
                        slowMo,
                        idGenerator,
                    });
                }
                if (protocol === 'webDriverBiDi') {
                    browser = await this.createBiDiOverCdpBrowser(browserProcess, cdpConnection, browserCloseCallback, {
                        defaultViewport,
                        acceptInsecureCerts,
                        networkEnabled,
                    });
                }
                else {
                    browser = await CdpBrowser._create(cdpConnection, [], acceptInsecureCerts, defaultViewport, downloadBehavior, browserProcess.nodeProcess, browserCloseCallback, options.targetFilter, undefined, undefined, networkEnabled, handleDevToolsAsPage);
                }
            }
        }
        catch (error) {
            void browserCloseCallback();
            const logs = browserProcess.getRecentLogs().join('\n');
            if (logs.includes('Failed to create a ProcessSingleton for your profile directory') ||
                (process.platform === 'win32' &&
                    existsSync(join$1(launchArgs.userDataDir, 'lockfile')))) {
                throw new Error(`The browser is already running for ${launchArgs.userDataDir}. Use a different \`userDataDir\` or stop the running browser first.`);
            }
            if (logs.includes('Missing X server') && options.headless === false) {
                throw new Error(`Missing X server to start the headful browser. Either set headless to true or use xvfb-run to run your Puppeteer script.`);
            }
            if (error instanceof TimeoutError) {
                throw new TimeoutError$1(error.message);
            }
            throw error;
        }
        if (Array.isArray(enableExtensions)) {
            if (this.#browser === 'chrome' && !usePipe) {
                throw new Error('To use `enableExtensions` with a list of paths in Chrome, you must be connected with `--remote-debugging-pipe` (`pipe: true`).');
            }
            await Promise.all([
                enableExtensions.map(path => {
                    return browser.installExtension(path);
                }),
            ]);
        }
        if (waitForInitialPage) {
            await this.waitForPageTarget(browser, timeout);
        }
        return browser;
    }
    async closeBrowser(browserProcess, cdpConnection) {
        if (cdpConnection) {
            try {
                await cdpConnection.closeBrowser();
                await browserProcess.hasClosed();
            }
            catch (error) {
                debugError(error);
                await browserProcess.close();
            }
        }
        else {
            await firstValueFrom(race(from(browserProcess.hasClosed()), timer(5000).pipe(map(() => {
                return from(browserProcess.close());
            }))));
        }
    }
    async waitForPageTarget(browser, timeout) {
        try {
            await browser.waitForTarget(t => {
                return t.type() === 'page';
            }, { timeout });
        }
        catch (error) {
            await browser.close();
            throw error;
        }
    }
    async createCdpSocketConnection(browserProcess, opts) {
        const browserWSEndpoint = await browserProcess.waitForLineOutput(CDP_WEBSOCKET_ENDPOINT_REGEX, opts.timeout);
        const transport = await NodeWebSocketTransport.create(browserWSEndpoint);
        return new Connection(browserWSEndpoint, transport, opts.slowMo, opts.protocolTimeout,
         false, opts.idGenerator);
    }
    async createCdpPipeConnection(browserProcess, opts) {
        const { 3: pipeWrite, 4: pipeRead } = browserProcess.nodeProcess.stdio;
        const transport = new PipeTransport(pipeWrite, pipeRead);
        return new Connection('', transport, opts.slowMo, opts.protocolTimeout,
         false, opts.idGenerator);
    }
    async createBiDiOverCdpBrowser(browserProcess, cdpConnection, closeCallback, opts) {
        const bidiOnly = process.env['PUPPETEER_WEBDRIVER_BIDI_ONLY'] === 'true';
        const BiDi = await import( '../../../node_modules/puppeteer-core/lib/esm/puppeteer/bidi/bidi.js');
        const bidiConnection = await BiDi.connectBidiOverCdp(cdpConnection);
        return await BiDi.BidiBrowser.create({
            connection: bidiConnection,
            cdpConnection: bidiOnly ? undefined : cdpConnection,
            closeCallback,
            process: browserProcess.nodeProcess,
            defaultViewport: opts.defaultViewport,
            acceptInsecureCerts: opts.acceptInsecureCerts,
            networkEnabled: opts.networkEnabled,
        });
    }
    async createBiDiBrowser(browserProcess, closeCallback, opts) {
        const browserWSEndpoint = (await browserProcess.waitForLineOutput(WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX, opts.timeout)) + '/session';
        const transport = await NodeWebSocketTransport.create(browserWSEndpoint);
        const BiDi = await import( '../../../node_modules/puppeteer-core/lib/esm/puppeteer/bidi/bidi.js');
        const bidiConnection = new BiDi.BidiConnection(browserWSEndpoint, transport, opts.idGenerator, opts.slowMo, opts.protocolTimeout);
        return await BiDi.BidiBrowser.create({
            connection: bidiConnection,
            closeCallback,
            process: browserProcess.nodeProcess,
            defaultViewport: opts.defaultViewport,
            acceptInsecureCerts: opts.acceptInsecureCerts,
            networkEnabled: opts.networkEnabled ?? true,
        });
    }
    getProfilePath() {
        return join$1(this.puppeteer.configuration.temporaryDirectory ?? tmpdir(), `puppeteer_dev_${this.browser}_profile-`);
    }
    resolveExecutablePath(headless, validatePath = true) {
        let executablePath = this.puppeteer.configuration.executablePath;
        if (executablePath) {
            if (validatePath && !existsSync(executablePath)) {
                throw new Error(`Tried to find the browser at the configured path (${executablePath}), but no executable was found.`);
            }
            return executablePath;
        }
        function puppeteerBrowserToInstalledBrowser(browser, headless) {
            switch (browser) {
                case 'chrome':
                    if (headless === 'shell') {
                        return Browser.CHROMEHEADLESSSHELL;
                    }
                    return Browser.CHROME;
                case 'firefox':
                    return Browser.FIREFOX;
            }
            return Browser.CHROME;
        }
        const browserType = puppeteerBrowserToInstalledBrowser(this.browser, headless);
        executablePath = computeExecutablePath({
            cacheDir: this.puppeteer.defaultDownloadPath,
            browser: browserType,
            buildId: this.puppeteer.browserVersion,
        });
        if (validatePath && !existsSync(executablePath)) {
            const configVersion = this.puppeteer.configuration?.[this.browser]?.version;
            if (configVersion) {
                throw new Error(`Tried to find the browser at the configured path (${executablePath}) for version ${configVersion}, but no executable was found.`);
            }
            switch (this.browser) {
                case 'chrome':
                    throw new Error(`Could not find Chrome (ver. ${this.puppeteer.browserVersion}). This can occur if either\n` +
                        ` 1. you did not perform an installation before running the script (e.g. \`npx puppeteer browsers install ${browserType}\`) or\n` +
                        ` 2. your cache path is incorrectly configured (which is: ${this.puppeteer.configuration.cacheDirectory}).\n` +
                        'For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.');
                case 'firefox':
                    throw new Error(`Could not find Firefox (rev. ${this.puppeteer.browserVersion}). This can occur if either\n` +
                        ' 1. you did not perform an installation for Firefox before running the script (e.g. `npx puppeteer browsers install firefox`) or\n' +
                        ` 2. your cache path is incorrectly configured (which is: ${this.puppeteer.configuration.cacheDirectory}).\n` +
                        'For (2), check out our guide on configuring puppeteer at https://pptr.dev/guides/configuration.');
            }
        }
        return executablePath;
    }
}

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
function convertPuppeteerChannelToBrowsersChannel(channel) {
    switch (channel) {
        case 'chrome':
            return ChromeReleaseChannel.STABLE;
        case 'chrome-dev':
            return ChromeReleaseChannel.DEV;
        case 'chrome-beta':
            return ChromeReleaseChannel.BETA;
        case 'chrome-canary':
            return ChromeReleaseChannel.CANARY;
    }
}

var LaunchOptions = /*#__PURE__*/Object.freeze({
	__proto__: null,
	convertPuppeteerChannelToBrowsersChannel: convertPuppeteerChannelToBrowsersChannel
});

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
const rmOptions = {
    force: true,
    recursive: true,
    maxRetries: 5,
};
async function rm(path) {
    await fs.promises.rm(path, rmOptions);
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class ChromeLauncher extends BrowserLauncher {
    constructor(puppeteer) {
        super(puppeteer, 'chrome');
    }
    launch(options = {}) {
        if (this.puppeteer.configuration.logLevel === 'warn' &&
            process.platform === 'darwin' &&
            process.arch === 'x64') {
            const cpus = os.cpus();
            if (cpus[0]?.model.includes('Apple')) {
                console.warn([
                    '\x1B[1m\x1B[43m\x1B[30m',
                    'Degraded performance warning:\x1B[0m\x1B[33m',
                    'Launching Chrome on Mac Silicon (arm64) from an x64 Node installation results in',
                    'Rosetta translating the Chrome binary, even if Chrome is already arm64. This would',
                    'result in huge performance issues. To resolve this, you must run Puppeteer with',
                    'a version of Node built for arm64.',
                ].join('\n  '));
            }
        }
        return super.launch(options);
    }
    async computeLaunchArguments(options = {}) {
        const { ignoreDefaultArgs = false, args = [], pipe = false, debuggingPort, channel, executablePath, } = options;
        const chromeArguments = [];
        if (!ignoreDefaultArgs) {
            chromeArguments.push(...this.defaultArgs(options));
        }
        else if (Array.isArray(ignoreDefaultArgs)) {
            chromeArguments.push(...this.defaultArgs(options).filter(arg => {
                return !ignoreDefaultArgs.includes(arg);
            }));
        }
        else {
            chromeArguments.push(...args);
        }
        if (!chromeArguments.some(argument => {
            return argument.startsWith('--remote-debugging-');
        })) {
            if (pipe) {
                assert(!debuggingPort, 'Browser should be launched with either pipe or debugging port - not both.');
                chromeArguments.push('--remote-debugging-pipe');
            }
            else {
                chromeArguments.push(`--remote-debugging-port=${debuggingPort || 0}`);
            }
        }
        let isTempUserDataDir = false;
        let userDataDirIndex = chromeArguments.findIndex(arg => {
            return arg.startsWith('--user-data-dir');
        });
        if (userDataDirIndex < 0) {
            isTempUserDataDir = true;
            chromeArguments.push(`--user-data-dir=${await mkdtemp(this.getProfilePath())}`);
            userDataDirIndex = chromeArguments.length - 1;
        }
        const userDataDir = chromeArguments[userDataDirIndex].split('=', 2)[1];
        assert(typeof userDataDir === 'string', '`--user-data-dir` is malformed');
        let chromeExecutable = executablePath;
        if (!chromeExecutable) {
            assert(channel || !this.puppeteer._isPuppeteerCore, `An \`executablePath\` or \`channel\` must be specified for \`puppeteer-core\``);
            chromeExecutable = channel
                ? this.executablePath(channel)
                : this.resolveExecutablePath(options.headless ?? true);
        }
        return {
            executablePath: chromeExecutable,
            args: chromeArguments,
            isTempUserDataDir,
            userDataDir,
        };
    }
    async cleanUserDataDir(path, opts) {
        if (opts.isTemp) {
            try {
                await rm(path);
            }
            catch (error) {
                debugError(error);
                throw error;
            }
        }
    }
    defaultArgs(options = {}) {
        const userDisabledFeatures = getFeatures('--disable-features', options.args);
        if (options.args && userDisabledFeatures.length > 0) {
            removeMatchingFlags(options.args, '--disable-features');
        }
        const turnOnExperimentalFeaturesForTesting = process.env['PUPPETEER_TEST_EXPERIMENTAL_CHROME_FEATURES'] === 'true';
        const disabledFeatures = [
            'Translate',
            'AcceptCHFrame',
            'MediaRouter',
            'OptimizationHints',
            'RenderDocument',
            'PartitionAllocSchedulerLoopQuarantineTaskControlledPurge',
            ...(turnOnExperimentalFeaturesForTesting
                ? []
                : [
                    'ProcessPerSiteUpToMainFrameThreshold',
                    'IsolateSandboxedIframes',
                ]),
            ...userDisabledFeatures,
        ].filter(feature => {
            return feature !== '';
        });
        const userEnabledFeatures = getFeatures('--enable-features', options.args);
        if (options.args && userEnabledFeatures.length > 0) {
            removeMatchingFlags(options.args, '--enable-features');
        }
        const enabledFeatures = [
            'PdfOopif',
            ...userEnabledFeatures,
        ].filter(feature => {
            return feature !== '';
        });
        const chromeArguments = [
            '--allow-pre-commit-input',
            '--disable-background-networking',
            '--disable-background-timer-throttling',
            '--disable-backgrounding-occluded-windows',
            '--disable-breakpad',
            '--disable-client-side-phishing-detection',
            '--disable-component-extensions-with-background-pages',
            '--disable-crash-reporter',
            '--disable-default-apps',
            '--disable-dev-shm-usage',
            '--disable-hang-monitor',
            '--disable-infobars',
            '--disable-ipc-flooding-protection',
            '--disable-popup-blocking',
            '--disable-prompt-on-repost',
            '--disable-renderer-backgrounding',
            '--disable-search-engine-choice-screen',
            '--disable-sync',
            '--enable-automation',
            '--export-tagged-pdf',
            '--force-color-profile=srgb',
            '--generate-pdf-document-outline',
            '--metrics-recording-only',
            '--no-first-run',
            '--password-store=basic',
            '--use-mock-keychain',
            `--disable-features=${disabledFeatures.join(',')}`,
            `--enable-features=${enabledFeatures.join(',')}`,
        ].filter(arg => {
            return arg !== '';
        });
        const { devtools = false, headless = !devtools, args = [], userDataDir, enableExtensions = false, } = options;
        if (userDataDir) {
            chromeArguments.push(`--user-data-dir=${path$1.posix.isAbsolute(userDataDir) || path$1.win32.isAbsolute(userDataDir) ? userDataDir : path$1.resolve(userDataDir)}`);
        }
        if (devtools) {
            chromeArguments.push('--auto-open-devtools-for-tabs');
        }
        if (headless) {
            chromeArguments.push(headless === 'shell' ? '--headless' : '--headless=new', '--hide-scrollbars', '--mute-audio');
        }
        chromeArguments.push(enableExtensions
            ? '--enable-unsafe-extension-debugging'
            : '--disable-extensions');
        if (args.every(arg => {
            return arg.startsWith('-');
        })) {
            chromeArguments.push('about:blank');
        }
        chromeArguments.push(...args);
        return chromeArguments;
    }
    executablePath(channel, validatePath = true) {
        if (channel) {
            return computeSystemExecutablePath({
                browser: Browser.CHROME,
                channel: convertPuppeteerChannelToBrowsersChannel(channel),
            });
        }
        else {
            return this.resolveExecutablePath(undefined, validatePath);
        }
    }
}
function getFeatures(flag, options = []) {
    return options
        .filter(s => {
        return s.startsWith(flag.endsWith('=') ? flag : `${flag}=`);
    })
        .map(s => {
        return s.split(new RegExp(`${flag}=\\s*`))[1]?.trim();
    })
        .filter(s => {
        return s;
    });
}
function removeMatchingFlags(array, flag) {
    const regex = new RegExp(`^${flag}=.*`);
    let i = 0;
    while (i < array.length) {
        if (regex.test(array[i])) {
            array.splice(i, 1);
        }
        else {
            i++;
        }
    }
    return array;
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class FirefoxLauncher extends BrowserLauncher {
    constructor(puppeteer) {
        super(puppeteer, 'firefox');
    }
    static getPreferences(extraPrefsFirefox) {
        return {
            ...extraPrefsFirefox,
            'fission.webContentIsolationStrategy': 0,
        };
    }
    async computeLaunchArguments(options = {}) {
        const { ignoreDefaultArgs = false, args = [], executablePath, pipe = false, extraPrefsFirefox = {}, debuggingPort = null, } = options;
        const firefoxArguments = [];
        if (!ignoreDefaultArgs) {
            firefoxArguments.push(...this.defaultArgs(options));
        }
        else if (Array.isArray(ignoreDefaultArgs)) {
            firefoxArguments.push(...this.defaultArgs(options).filter(arg => {
                return !ignoreDefaultArgs.includes(arg);
            }));
        }
        else {
            firefoxArguments.push(...args);
        }
        if (!firefoxArguments.some(argument => {
            return argument.startsWith('--remote-debugging-');
        })) {
            if (pipe) {
                assert(debuggingPort === null, 'Browser should be launched with either pipe or debugging port - not both.');
            }
            firefoxArguments.push(`--remote-debugging-port=${debuggingPort || 0}`);
        }
        let userDataDir;
        let isTempUserDataDir = true;
        const profileArgIndex = firefoxArguments.findIndex(arg => {
            return ['-profile', '--profile'].includes(arg);
        });
        if (profileArgIndex !== -1) {
            userDataDir = firefoxArguments[profileArgIndex + 1];
            if (!userDataDir) {
                throw new Error(`Missing value for profile command line argument`);
            }
            isTempUserDataDir = false;
        }
        else {
            userDataDir = await mkdtemp(this.getProfilePath());
            firefoxArguments.push('--profile');
            firefoxArguments.push(userDataDir);
        }
        await createProfile(Browser.FIREFOX, {
            path: userDataDir,
            preferences: FirefoxLauncher.getPreferences(extraPrefsFirefox),
        });
        let firefoxExecutable;
        if (this.puppeteer._isPuppeteerCore || executablePath) {
            assert(executablePath, `An \`executablePath\` must be specified for \`puppeteer-core\``);
            firefoxExecutable = executablePath;
        }
        else {
            firefoxExecutable = this.executablePath(undefined);
        }
        return {
            isTempUserDataDir,
            userDataDir,
            args: firefoxArguments,
            executablePath: firefoxExecutable,
        };
    }
    async cleanUserDataDir(userDataDir, opts) {
        if (opts.isTemp) {
            try {
                await rm(userDataDir);
            }
            catch (error) {
                debugError(error);
                throw error;
            }
        }
        else {
            try {
                const backupSuffix = '.puppeteer';
                const backupFiles = ['prefs.js', 'user.js'];
                const results = await Promise.allSettled(backupFiles.map(async (file) => {
                    const prefsBackupPath = path$1.join(userDataDir, file + backupSuffix);
                    if (fs.existsSync(prefsBackupPath)) {
                        const prefsPath = path$1.join(userDataDir, file);
                        await unlink(prefsPath);
                        await rename(prefsBackupPath, prefsPath);
                    }
                }));
                for (const result of results) {
                    if (result.status === 'rejected') {
                        throw result.reason;
                    }
                }
            }
            catch (error) {
                debugError(error);
            }
        }
    }
    executablePath(_, validatePath = true) {
        return this.resolveExecutablePath(undefined,
         validatePath);
    }
    defaultArgs(options = {}) {
        const { devtools = false, headless = !devtools, args = [], userDataDir = null, } = options;
        const firefoxArguments = [];
        switch (os.platform()) {
            case 'darwin':
                firefoxArguments.push('--foreground');
                break;
            case 'win32':
                firefoxArguments.push('--wait-for-browser');
                break;
        }
        if (userDataDir) {
            firefoxArguments.push('--profile');
            firefoxArguments.push(userDataDir);
        }
        if (headless) {
            firefoxArguments.push('--headless');
        }
        if (devtools) {
            firefoxArguments.push('--devtools');
        }
        if (args.every(arg => {
            return arg.startsWith('-');
        })) {
            firefoxArguments.push('about:blank');
        }
        firefoxArguments.push(...args);
        return firefoxArguments;
    }
}

/**
 * @license
 * Copyright 2020 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
class PuppeteerNode extends Puppeteer {
    #launcher;
    #lastLaunchedBrowser;
    defaultBrowserRevision;
    configuration = {};
    constructor(settings) {
        const { configuration, ...commonSettings } = settings;
        super(commonSettings);
        if (configuration) {
            this.configuration = configuration;
        }
        switch (this.configuration.defaultBrowser) {
            case 'firefox':
                this.defaultBrowserRevision = PUPPETEER_REVISIONS.firefox;
                break;
            default:
                this.configuration.defaultBrowser = 'chrome';
                this.defaultBrowserRevision = PUPPETEER_REVISIONS.chrome;
                break;
        }
        this.connect = this.connect.bind(this);
        this.launch = this.launch.bind(this);
        this.executablePath = this.executablePath.bind(this);
        this.defaultArgs = this.defaultArgs.bind(this);
        this.trimCache = this.trimCache.bind(this);
    }
    connect(options) {
        return super.connect(options);
    }
    launch(options = {}) {
        const { browser = this.defaultBrowser } = options;
        this.#lastLaunchedBrowser = browser;
        switch (browser) {
            case 'chrome':
                this.defaultBrowserRevision = PUPPETEER_REVISIONS.chrome;
                break;
            case 'firefox':
                this.defaultBrowserRevision = PUPPETEER_REVISIONS.firefox;
                break;
            default:
                throw new Error(`Unknown product: ${browser}`);
        }
        this.#launcher = this.#getLauncher(browser);
        return this.#launcher.launch(options);
    }
    #getLauncher(browser) {
        if (this.#launcher && this.#launcher.browser === browser) {
            return this.#launcher;
        }
        switch (browser) {
            case 'chrome':
                return new ChromeLauncher(this);
            case 'firefox':
                return new FirefoxLauncher(this);
            default:
                throw new Error(`Unknown product: ${browser}`);
        }
    }
    executablePath(optsOrChannel) {
        if (optsOrChannel === undefined) {
            return this.#getLauncher(this.lastLaunchedBrowser).executablePath(undefined,
             false);
        }
        if (typeof optsOrChannel === 'string') {
            return this.#getLauncher('chrome').executablePath(optsOrChannel,
             false);
        }
        return this.#getLauncher(optsOrChannel.browser ?? this.lastLaunchedBrowser).resolveExecutablePath(optsOrChannel.headless,  false);
    }
    get browserVersion() {
        return (this.configuration?.[this.lastLaunchedBrowser]?.version ??
            this.defaultBrowserRevision);
    }
    get defaultDownloadPath() {
        return this.configuration.cacheDirectory;
    }
    get lastLaunchedBrowser() {
        return this.#lastLaunchedBrowser ?? this.defaultBrowser;
    }
    get defaultBrowser() {
        return this.configuration.defaultBrowser ?? 'chrome';
    }
    get product() {
        return this.lastLaunchedBrowser;
    }
    defaultArgs(options = {}) {
        return this.#getLauncher(options.browser ?? this.lastLaunchedBrowser).defaultArgs(options);
    }
    async trimCache() {
        const platform = detectBrowserPlatform();
        if (!platform) {
            throw new Error('The current platform is not supported.');
        }
        const cacheDir = this.configuration.cacheDirectory;
        const installedBrowsers = await getInstalledBrowsers({
            cacheDir,
        });
        const puppeteerBrowsers = [
            {
                product: 'chrome',
                browser: Browser.CHROME,
                currentBuildId: '',
            },
            {
                product: 'firefox',
                browser: Browser.FIREFOX,
                currentBuildId: '',
            },
        ];
        await Promise.all(puppeteerBrowsers.map(async (item) => {
            const tag = this.configuration?.[item.product]?.version ??
                PUPPETEER_REVISIONS[item.product];
            item.currentBuildId = await resolveBuildId(item.browser, platform, tag);
        }));
        const currentBrowserBuilds = new Set(puppeteerBrowsers.map(browser => {
            return `${browser.browser}_${browser.currentBuildId}`;
        }));
        const currentBrowsers = new Set(puppeteerBrowsers.map(browser => {
            return browser.browser;
        }));
        for (const installedBrowser of installedBrowsers) {
            if (!currentBrowsers.has(installedBrowser.browser)) {
                continue;
            }
            if (currentBrowserBuilds.has(`${installedBrowser.browser}_${installedBrowser.buildId}`)) {
                continue;
            }
            await uninstall({
                browser: installedBrowser.browser,
                platform,
                cacheDir,
                buildId: installedBrowser.buildId,
            });
        }
    }
}

/**
 * @license
 * Copyright 2023 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
var __runInitializers = (undefined && undefined.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
var __esDecorate = (undefined && undefined.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __setFunctionName = (undefined && undefined.__setFunctionName) || function (f, name, prefix) {
    if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
    return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
const CRF_VALUE = 30;
const DEFAULT_FPS = 30;
const debugFfmpeg = debug$2('puppeteer:ffmpeg');
let ScreenRecorder = (() => {
    let _classSuper = PassThrough;
    let _instanceExtraInitializers = [];
    let _private_writeFrame_decorators;
    let _private_writeFrame_descriptor;
    let _stop_decorators;
    return class ScreenRecorder extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            __esDecorate(this, _private_writeFrame_descriptor = { value: __setFunctionName(async function (buffer) {
                    const error = await new Promise(resolve => {
                        this.#process.stdin.write(buffer, resolve);
                    });
                    if (error) {
                        console.log(`ffmpeg failed to write: ${error.message}.`);
                    }
                }, "#writeFrame") }, _private_writeFrame_decorators, { kind: "method", name: "#writeFrame", static: false, private: true, access: { has: obj => #writeFrame in obj, get: obj => obj.#writeFrame }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate(this, null, _stop_decorators, { kind: "method", name: "stop", static: false, private: false, access: { has: obj => "stop" in obj, get: obj => obj.stop }, metadata: _metadata }, null, _instanceExtraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #page = __runInitializers(this, _instanceExtraInitializers);
        #process;
        #controller = new AbortController();
        #lastFrame;
        #fps;
        constructor(page, width, height, { ffmpegPath, speed, scale, crop, format, fps, loop, delay, quality, colors, path, overwrite, } = {}) {
            super({ allowHalfOpen: false });
            ffmpegPath ??= 'ffmpeg';
            format ??= 'webm';
            fps ??= DEFAULT_FPS;
            loop ||= -1;
            delay ??= -1;
            quality ??= CRF_VALUE;
            colors ??= 256;
            overwrite ??= true;
            this.#fps = fps;
            const { error } = spawnSync(ffmpegPath);
            if (error) {
                throw error;
            }
            const filters = [
                `crop='min(${width},iw):min(${height},ih):0:0'`,
                `pad=${width}:${height}:0:0`,
            ];
            if (speed) {
                filters.push(`setpts=${1 / speed}*PTS`);
            }
            if (crop) {
                filters.push(`crop=${crop.width}:${crop.height}:${crop.x}:${crop.y}`);
            }
            if (scale) {
                filters.push(`scale=iw*${scale}:-1:flags=lanczos`);
            }
            const formatArgs = this.#getFormatArgs(format, fps, loop, delay, quality, colors);
            const vf = formatArgs.indexOf('-vf');
            if (vf !== -1) {
                filters.push(formatArgs.splice(vf, 2).at(-1) ?? '');
            }
            if (path) {
                fs.mkdirSync(dirname$1(path), { recursive: overwrite });
            }
            this.#process = spawn$1(ffmpegPath,
            [
                ['-loglevel', 'error'],
                ['-avioflags', 'direct'],
                [
                    '-fpsprobesize',
                    '0',
                    '-probesize',
                    '32',
                    '-analyzeduration',
                    '0',
                    '-fflags',
                    'nobuffer',
                ],
                ['-f', 'image2pipe', '-vcodec', 'png', '-i', 'pipe:0'],
                ['-an'],
                ['-threads', '1'],
                ['-framerate', `${fps}`],
                ['-b:v', '0'],
                formatArgs,
                ['-vf', filters.join()],
                [overwrite ? '-y' : '-n'],
                'pipe:1',
            ].flat(), { stdio: ['pipe', 'pipe', 'pipe'] });
            this.#process.stdout.pipe(this);
            this.#process.stderr.on('data', (data) => {
                debugFfmpeg(data.toString('utf8'));
            });
            this.#page = page;
            const { client } = this.#page.mainFrame();
            client.once(CDPSessionEvent.Disconnected, () => {
                void this.stop().catch(debugError);
            });
            this.#lastFrame = lastValueFrom(fromEmitterEvent(client, 'Page.screencastFrame').pipe(tap(event => {
                void client.send('Page.screencastFrameAck', {
                    sessionId: event.sessionId,
                });
            }), filter(event => {
                return event.metadata.timestamp !== undefined;
            }), map(event => {
                return {
                    buffer: Buffer.from(event.data, 'base64'),
                    timestamp: event.metadata.timestamp,
                };
            }), bufferCount(2, 1), concatMap(([{ timestamp: previousTimestamp, buffer }, { timestamp }]) => {
                return from(Array(Math.round(fps * Math.max(timestamp - previousTimestamp, 0))).fill(buffer));
            }), map(buffer => {
                void this.#writeFrame(buffer);
                return [buffer, performance.now()];
            }), takeUntil(fromEvent(this.#controller.signal, 'abort'))), { defaultValue: [Buffer.from([]), performance.now()] });
        }
        #getFormatArgs(format, fps, loop, delay, quality, colors) {
            const libvpx = [
                ['-vcodec', 'vp9'],
                ['-crf', `${quality}`],
                [
                    '-deadline',
                    'realtime',
                    '-cpu-used',
                    `${Math.min(os.cpus().length / 2, 8)}`,
                ],
            ];
            switch (format) {
                case 'webm':
                    return [
                        ...libvpx,
                        ['-f', 'webm'],
                    ].flat();
                case 'gif':
                    fps = DEFAULT_FPS === fps ? 20 : 'source_fps';
                    if (loop === Infinity) {
                        loop = 0;
                    }
                    if (delay !== -1) {
                        delay /= 10;
                    }
                    return [
                        [
                            '-vf',
                            `fps=${fps},split[s0][s1];[s0]palettegen=stats_mode=diff:max_colors=${colors}[p];[s1][p]paletteuse=dither=bayer`,
                        ],
                        ['-loop', `${loop}`],
                        ['-final_delay', `${delay}`],
                        ['-f', 'gif'],
                    ].flat();
                case 'mp4':
                    return [
                        ...libvpx,
                        ['-movflags', 'hybrid_fragmented'],
                        ['-f', 'mp4'],
                    ].flat();
            }
        }
        get #writeFrame() { return _private_writeFrame_descriptor.value; }
        async stop() {
            if (this.#controller.signal.aborted) {
                return;
            }
            await this.#page._stopScreencast().catch(debugError);
            this.#controller.abort();
            const [buffer, timestamp] = await this.#lastFrame;
            await Promise.all(Array(Math.max(1, Math.round((this.#fps * (performance.now() - timestamp)) / 1000)))
                .fill(buffer)
                .map(this.#writeFrame.bind(this)));
            this.#process.stdin.end();
            await new Promise(resolve => {
                this.#process.once('close', resolve);
            });
        }
        async [(_private_writeFrame_decorators = [guarded()], _stop_decorators = [guarded()], asyncDisposeSymbol)]() {
            await this.stop();
        }
    };
})();

/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */
environment.value = {
    fs,
    path: path$1,
    ScreenRecorder: ScreenRecorder,
};
const puppeteer = new PuppeteerNode({
    isPuppeteerCore: true,
});
const {
connect,
defaultArgs,
executablePath,
launch, } = puppeteer;

// Copyright 2019 The Chromium Authors

var App = /*#__PURE__*/Object.freeze({
	__proto__: null
});

// Copyright 2025 The Chromium Authors
class DevToolsContext {
    #instances = new Map();
    get(ctor) {
        const instance = this.#instances.get(ctor);
        if (!instance) {
            throw new Error(`No instance for ${ctor.name}. Ensure the bootstrapper creates it.`);
        }
        return instance;
    }
    has(ctor) {
        return this.#instances.has(ctor);
    }
    set(ctor, instance) {
        this.#instances.set(ctor, instance);
    }
    delete(ctor) {
        this.#instances.delete(ctor);
    }
}
let gInstance = null;
function globalInstance() {
    if (!gInstance) {
        gInstance = new DevToolsContext();
    }
    return gInstance;
}

// Copyright 2026 The Chromium Authors
var ExperimentName;
(function (ExperimentName) {
    ExperimentName["ALL"] = "*";
    ExperimentName["CAPTURE_NODE_CREATION_STACKS"] = "capture-node-creation-stacks";
    ExperimentName["LIVE_HEAP_PROFILE"] = "live-heap-profile";
    ExperimentName["PROTOCOL_MONITOR"] = "protocol-monitor";
    ExperimentName["SAMPLING_HEAP_PROFILER_TIMELINE"] = "sampling-heap-profiler-timeline";
    ExperimentName["SHOW_OPTION_TO_EXPOSE_INTERNALS_IN_HEAP_SNAPSHOT"] = "show-option-to-expose-internals-in-heap-snapshot";
    ExperimentName["TIMELINE_INVALIDATION_TRACKING"] = "timeline-invalidation-tracking";
    ExperimentName["TIMELINE_SHOW_ALL_EVENTS"] = "timeline-show-all-events";
    ExperimentName["TIMELINE_V8_RUNTIME_CALL_STATS"] = "timeline-v8-runtime-call-stats";
    ExperimentName["APCA"] = "apca";
    ExperimentName["FONT_EDITOR"] = "font-editor";
    ExperimentName["FULL_ACCESSIBILITY_TREE"] = "full-accessibility-tree";
    ExperimentName["CONTRAST_ISSUES"] = "contrast-issues";
    ExperimentName["EXPERIMENTAL_COOKIE_FEATURES"] = "experimental-cookie-features";
    ExperimentName["INSTRUMENTATION_BREAKPOINTS"] = "instrumentation-breakpoints";
    ExperimentName["AUTHORED_DEPLOYED_GROUPING"] = "authored-deployed-grouping";
    ExperimentName["JUST_MY_CODE"] = "just-my-code";
    ExperimentName["USE_SOURCE_MAP_SCOPES"] = "use-source-map-scopes";
    ExperimentName["TIMELINE_SHOW_POST_MESSAGE_EVENTS"] = "timeline-show-postmessage-events";
    ExperimentName["TIMELINE_DEBUG_MODE"] = "timeline-debug-mode";
    ExperimentName["DURABLE_MESSAGES"] = "durable-messages";
    ExperimentName["JPEG_XL"] = "jpeg-xl";
})(ExperimentName || (ExperimentName = {}));

function getChromeVersion() { return ''; }const hostConfig = {};
const Runtime = {
  isDescriptorEnabled: () => true,
  queryParam: () => null,
};
const experiments = {
  isEnabled: () => false,
};

// Copyright 2019 The Chromium Authors
const registeredAppProvider = [];
function registerAppProvider(registration) {
    registeredAppProvider.push(registration);
}
function getRegisteredAppProviders() {
    return registeredAppProvider
        .filter(provider => Runtime.isDescriptorEnabled({ condition: provider.condition }))
        .sort((firstProvider, secondProvider) => {
        const order1 = firstProvider.order || 0;
        const order2 = secondProvider.order || 0;
        return order1 - order2;
    });
}

var AppProvider = /*#__PURE__*/Object.freeze({
	__proto__: null,
	getRegisteredAppProviders: getRegisteredAppProviders,
	registerAppProvider: registerAppProvider
});

// Copyright 2020 The Chromium Authors
const BASE64_CHARS$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const BASE64_CODES$1 = new Uint8Array(123);
for (let index = 0; index < BASE64_CHARS$1.length; ++index) {
    BASE64_CODES$1[BASE64_CHARS$1.charCodeAt(index)] = index;
}
function decode$1(input) {
    let bytesLength = ((input.length * 3) / 4) >>> 0;
    if (input.charCodeAt(input.length - 2) === 0x3d ) {
        bytesLength -= 2;
    }
    else if (input.charCodeAt(input.length - 1) === 0x3d ) {
        bytesLength -= 1;
    }
    const bytes = new Uint8Array(bytesLength);
    for (let index = 0, offset = 0; index < input.length; index += 4) {
        const a = BASE64_CODES$1[input.charCodeAt(index + 0)];
        const b = BASE64_CODES$1[input.charCodeAt(index + 1)];
        const c = BASE64_CODES$1[input.charCodeAt(index + 2)];
        const d = BASE64_CODES$1[input.charCodeAt(index + 3)];
        bytes[offset++] = (a << 2) | (b >> 4);
        bytes[offset++] = ((b & 0x0f) << 4) | (c >> 2);
        bytes[offset++] = ((c & 0x03) << 6) | (d & 0x3f);
    }
    return bytes;
}
function encode(input) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onerror = () => reject(new Error('failed to convert to base64: internal error'));
        reader.onload = () => {
            if (reader.result === '') {
                reject(new Error('failed to convert to base64: input too large to encode as base64 string'));
                return;
            }
            const blobAsUrl = reader.result;
            const index = blobAsUrl.indexOf(',');
            const base64 = blobAsUrl.slice(index + 1);
            resolve(base64);
        };
        reader.readAsDataURL(new Blob([input]));
    });
}

var Base64 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	BASE64_CHARS: BASE64_CHARS$1,
	BASE64_CODES: BASE64_CODES$1,
	decode: decode$1,
	encode: encode
});

// Copyright 2016 The Chromium Authors
class CharacterIdMap {
    #elementToCharacter = new Map();
    #characterToElement = new Map();
    #charCode = 33;
    toChar(object) {
        let character = this.#elementToCharacter.get(object);
        if (!character) {
            if (this.#charCode >= 0xFFFF) {
                throw new Error('CharacterIdMap ran out of capacity!');
            }
            character = String.fromCharCode(this.#charCode++);
            this.#elementToCharacter.set(object, character);
            this.#characterToElement.set(character, object);
        }
        return character;
    }
    fromChar(character) {
        const object = this.#characterToElement.get(character);
        if (object === undefined) {
            return null;
        }
        return object;
    }
}

var CharacterIdMap$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	CharacterIdMap: CharacterIdMap
});

// Copyright 2020 The Chromium Authors
const removeElement = (array, element, firstOnly) => {
    let index = array.indexOf(element);
    if (index === -1) {
        return false;
    }
    for (let i = index + 1, n = array.length; i < n; ++i) {
        if (array[i] !== element) {
            array[index++] = array[i];
        }
    }
    array.length = index;
    return true;
};
function swap(array, i1, i2) {
    const temp = array[i1];
    array[i1] = array[i2];
    array[i2] = temp;
}
function mergeOrIntersect(array1, array2, comparator, mergeNotIntersect) {
    const result = [];
    let i = 0;
    let j = 0;
    while (i < array1.length && j < array2.length) {
        const compareValue = comparator(array1[i], array2[j]);
        {
            result.push(compareValue <= 0 ? array1[i] : array2[j]);
        }
        if (compareValue <= 0) {
            i++;
        }
        if (compareValue >= 0) {
            j++;
        }
    }
    {
        while (i < array1.length) {
            result.push(array1[i++]);
        }
        while (j < array2.length) {
            result.push(array2[j++]);
        }
    }
    return result;
}
const mergeOrdered = (array1, array2, comparator) => {
    return mergeOrIntersect(array1, array2, comparator);
};
const DEFAULT_COMPARATOR = (a, b) => {
    return a < b ? -1 : (a > b ? 1 : 0);
};
function lowerBound(array, needle, comparator, left, right) {
    let l = 0;
    let r = right !== undefined ? right : array.length;
    while (l < r) {
        const m = (l + r) >> 1;
        if (comparator(needle, array[m]) > 0) {
            l = m + 1;
        }
        else {
            r = m;
        }
    }
    return r;
}
function upperBound(array, needle, comparator, left, right) {
    let l = 0;
    let r = array.length;
    while (l < r) {
        const m = (l + r) >> 1;
        if (comparator(needle, array[m]) >= 0) {
            l = m + 1;
        }
        else {
            r = m;
        }
    }
    return r;
}
function nearestIndex(arr, predicate, searchStart) {
    const searchFromEnd = searchStart === "END" ;
    if (arr.length === 0) {
        return null;
    }
    let left = 0;
    let right = arr.length - 1;
    let pivot = 0;
    let matchesPredicate = false;
    let moveToTheRight = false;
    let middle = 0;
    do {
        middle = left + (right - left) / 2;
        pivot = searchFromEnd ? Math.ceil(middle) : Math.floor(middle);
        matchesPredicate = predicate(arr[pivot]);
        moveToTheRight = matchesPredicate === searchFromEnd;
        if (moveToTheRight) {
            left = Math.min(right, pivot + (left === pivot ? 1 : 0));
        }
        else {
            right = Math.max(left, pivot + (right === pivot ? -1 : 0));
        }
    } while (right !== left);
    if (!predicate(arr[left])) {
        return null;
    }
    return left;
}
function nearestIndexFromBeginning(arr, predicate) {
    return nearestIndex(arr, predicate, "BEGINNING" );
}
function nearestIndexFromEnd(arr, predicate) {
    return nearestIndex(arr, predicate, "END" );
}
function arrayDoesNotContainNullOrUndefined(arr) {
    return !arr.includes(null) && !arr.includes(undefined);
}

// Copyright 2020 The Chromium Authors
const isValid = (date) => {
    return !isNaN(date.getTime());
};

// Copyright 2021 The Chromium Authors
const EmptyUrlString = '';

// Copyright 2025 The Chromium Authors
class NodeWorkerScope {
    postMessage(message) {
        WorkerThreads.parentPort?.postMessage(message);
    }
    set onmessage(listener) {
        WorkerThreads.parentPort?.on('message', data => {
            listener({ data });
        });
    }
}
class NodeWorker {
    #workerPromise;
    #disposed = false;
    #rejectWorkerPromise;
    constructor(url) {
        this.#workerPromise = new Promise((resolve, reject) => {
            this.#rejectWorkerPromise = reject;
            const worker = new WorkerThreads.Worker(new URL(url));
            worker.once('message', (message) => {
                if (message === 'workerReady') {
                    resolve(worker);
                }
            });
            worker.on('error', reject);
        });
    }
    postMessage(message) {
        void this.#workerPromise.then(worker => {
            if (!this.#disposed) {
                worker.postMessage(message);
            }
        });
    }
    dispose() {
        this.#disposed = true;
        void this.#workerPromise.then(worker => worker.terminate());
    }
    terminate(immediately) {
        if (immediately) {
            this.#rejectWorkerPromise?.(new Error('Worker terminated'));
        }
        this.dispose();
    }
    set onmessage(listener) {
        void this.#workerPromise.then(worker => {
            worker.on('message', data => {
                if (!this.#disposed) {
                    listener({ data });
                }
            });
        });
    }
    set onerror(listener) {
        void this.#workerPromise.then(worker => {
            worker.on('error', (error) => {
                if (!this.#disposed) {
                    listener({ type: 'error', ...error });
                }
            });
        });
    }
}
const HOST_RUNTIME$2 = {
    createWorker(url) {
        return new NodeWorker(url);
    },
    workerScope: new NodeWorkerScope(),
};

var HostRuntime$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	HOST_RUNTIME: HOST_RUNTIME$2
});

// Copyright 2025 The Chromium Authors

var node = /*#__PURE__*/Object.freeze({
	__proto__: null,
	HostRuntime: HostRuntime$1
});

// Copyright 2025 The Chromium Authors
class WebWorkerScope {
    postMessage(message) {
        self.postMessage(message);
    }
    set onmessage(listener) {
        self.onmessage = listener;
    }
}
class WebWorker {
    #workerPromise;
    #disposed;
    #rejectWorkerPromise;
    constructor(workerLocation) {
        this.#workerPromise = new Promise((fulfill, reject) => {
            this.#rejectWorkerPromise = reject;
            const worker = new Worker(new URL(workerLocation), { type: 'module' });
            worker.onerror = event => {
                console.error(`Failed to load worker for ${workerLocation}:`, event);
            };
            worker.onmessage = (event) => {
                console.assert(event.data === 'workerReady');
                worker.onmessage = null;
                fulfill(worker);
            };
        });
    }
    postMessage(message, transfer) {
        void this.#workerPromise.then(worker => {
            if (!this.#disposed) {
                worker.postMessage(message, transfer ?? []);
            }
        });
    }
    dispose() {
        this.#disposed = true;
        void this.#workerPromise.then(worker => worker.terminate());
    }
    terminate(immediately = false) {
        if (immediately) {
            this.#rejectWorkerPromise?.(new Error('Worker terminated'));
        }
        this.dispose();
    }
    set onmessage(listener) {
        void this.#workerPromise.then(worker => {
            worker.onmessage = listener;
        });
    }
    set onerror(listener) {
        void this.#workerPromise.then(worker => {
            worker.onerror = listener;
        });
    }
}
const HOST_RUNTIME$1 = {
    createWorker(url) {
        return new WebWorker(url);
    },
    workerScope: new WebWorkerScope(),
};

var HostRuntime = /*#__PURE__*/Object.freeze({
	__proto__: null,
	HOST_RUNTIME: HOST_RUNTIME$1
});

// Copyright 2025 The Chromium Authors

var browser = /*#__PURE__*/Object.freeze({
	__proto__: null,
	HostRuntime: HostRuntime
});

// Copyright 2025 The Chromium Authors
const IS_NODE = typeof process !== 'undefined' && process.versions?.node !== null;
const IS_BROWSER =
typeof window !== 'undefined' || (typeof self !== 'undefined' && typeof self.postMessage === 'function');
const HOST_RUNTIME = await (async () => {
    if (IS_NODE) {
        return (await Promise.resolve().then(function () { return node; })).HostRuntime.HOST_RUNTIME;
    }
    if (IS_BROWSER) {
        return (await Promise.resolve().then(function () { return browser; })).HostRuntime.HOST_RUNTIME;
    }
    throw new Error('Unknown runtime!');
})();

// Copyright 2020 The Chromium Authors
class Multimap {
    map = new Map();
    set(key, value) {
        let set = this.map.get(key);
        if (!set) {
            set = new Set();
            this.map.set(key, set);
        }
        set.add(value);
    }
    get(key) {
        return this.map.get(key) || new Set();
    }
    has(key) {
        return this.map.has(key);
    }
    hasValue(key, value) {
        const set = this.map.get(key);
        if (!set) {
            return false;
        }
        return set.has(value);
    }
    get size() {
        return this.map.size;
    }
    delete(key, value) {
        const values = this.get(key);
        if (!values) {
            return false;
        }
        const result = values.delete(value);
        if (!values.size) {
            this.map.delete(key);
        }
        return result;
    }
    deleteAll(key) {
        this.map.delete(key);
    }
    keysArray() {
        return [...this.map.keys()];
    }
    keys() {
        return this.map.keys();
    }
    valuesArray() {
        const result = [];
        for (const set of this.map.values()) {
            result.push(...set.values());
        }
        return result;
    }
    clear() {
        this.map.clear();
    }
}
function getWithDefault(map, key, defaultValueFactory) {
    let value = map.get(key);
    if (value === undefined || value === null) {
        value = defaultValueFactory(key);
        map.set(key, value);
    }
    return value;
}

// Copyright 2023 The Chromium Authors
const ADDITIONAL_TEXT_MIME_TYPES = new Set([
    'application/ecmascript',
    'application/javascript',
    'application/json',
    'application/json+protobuf',
    'application/mpegurl',
    'application/vnd.apple.mpegurl',
    'application/vnd.dart',
    'application/xml',
    'application/x-aspx',
    'application/x-javascript',
    'application/x-jsp',
    'application/x-httpd-php',
    'application/x-mpegurl',
    'audio/mpegurl',
    'audio/x-mpegurl',
]);
function isTextType(mimeType) {
    return mimeType.startsWith('text/') || mimeType.startsWith('multipart/') || mimeType.includes('json') ||
        mimeType.endsWith('+xml') || ADDITIONAL_TEXT_MIME_TYPES.has(mimeType);
}
function parseContentType(contentType) {
    if (contentType === '*/*') {
        return { mimeType: null, charset: null };
    }
    const { mimeType, params } = parseMimeType(contentType);
    const charset = params.get('charset')?.toLowerCase().trim() ?? null;
    return { mimeType, charset };
}
function parseMimeType(contentType) {
    contentType = contentType.trim();
    let mimeTypeEnd = findFirstIndexOf(contentType, ' \t;(');
    if (mimeTypeEnd < 0) {
        mimeTypeEnd = contentType.length;
    }
    const slashPos = contentType.indexOf('/');
    if (slashPos < 0 || slashPos > mimeTypeEnd) {
        return { mimeType: null, params: new Map() };
    }
    const mimeType = contentType.substring(0, mimeTypeEnd).toLowerCase();
    const params = new Map();
    let offset = contentType.indexOf(';', mimeTypeEnd);
    while (offset >= 0 && offset < contentType.length) {
        ++offset;
        offset = findFirstIndexNotOf(contentType, ' \t', offset);
        if (offset < 0) {
            continue;
        }
        const paramNameStart = offset;
        offset = findFirstIndexOf(contentType, ';=', offset);
        if (offset < 0 || contentType[offset] === ';') {
            continue;
        }
        const paramName = contentType.substring(paramNameStart, offset).toLowerCase();
        ++offset;
        offset = findFirstIndexNotOf(contentType, ' \t', offset);
        let paramValue = '';
        if (offset < 0 || contentType[offset] === ';') {
            continue;
        }
        else if (contentType[offset] !== '"') {
            const valueStart = offset;
            offset = contentType.indexOf(';', offset);
            const valueEnd = offset >= 0 ? offset : contentType.length;
            paramValue = contentType.substring(valueStart, valueEnd).trimEnd();
        }
        else {
            ++offset;
            while (offset < contentType.length && contentType[offset] !== '"') {
                if (contentType[offset] === '\\' && offset + 1 < contentType.length) {
                    ++offset;
                }
                paramValue += contentType[offset];
                ++offset;
            }
            offset = contentType.indexOf(';', offset);
        }
        if (!params.has(paramName)) {
            params.set(paramName, paramValue);
        }
    }
    return { mimeType, params };
}
function findFirstIndexOf(searchString, characters, pos = 0) {
    for (let i = pos; i < searchString.length; i++) {
        if (characters.includes(searchString[i])) {
            return i;
        }
    }
    return -1;
}
function findFirstIndexNotOf(searchString, characters, pos = 0) {
    for (let i = pos; i < searchString.length; i++) {
        if (!characters.includes(searchString[i])) {
            return i;
        }
    }
    return -1;
}

// Copyright 2020 The Chromium Authors
const clamp$1 = (num, min, max) => {
    let clampedNumber = num;
    if (num < min) {
        clampedNumber = min;
    }
    else if (num > max) {
        clampedNumber = max;
    }
    return clampedNumber;
};
const floor = (value, precision = 0) => {
    if (precision > 0 && precision < 1) {
        precision = 1 / precision;
        return Math.floor(value / precision) * precision;
    }
    const mult = Math.pow(10, precision);
    return Math.floor(value * mult) / mult;
};

// Copyright 2020 The Chromium Authors
const escapeCharacters = (inputString, charsToEscape) => {
    let foundChar = false;
    for (let i = 0; i < charsToEscape.length; ++i) {
        if (inputString.indexOf(charsToEscape.charAt(i)) !== -1) {
            foundChar = true;
            break;
        }
    }
    if (!foundChar) {
        return String(inputString);
    }
    let result = '';
    for (let i = 0; i < inputString.length; ++i) {
        if (charsToEscape.indexOf(inputString.charAt(i)) !== -1) {
            result += '\\';
        }
        result += inputString.charAt(i);
    }
    return result;
};
const sprintf = (fmt, ...args) => {
    let argIndex = 0;
    const RE = /%(?:(\d+)\$)?(?:\.(\d*))?([%dfs])/g;
    return fmt.replaceAll(RE, (_, index, precision, specifier) => {
        if (specifier === '%') {
            return '%';
        }
        if (index !== undefined) {
            argIndex = parseInt(index, 10) - 1;
            if (argIndex < 0) {
                throw new RangeError(`Invalid parameter index ${argIndex + 1}`);
            }
        }
        if (argIndex >= args.length) {
            throw new RangeError(`Expected at least ${argIndex + 1} format parameters, but only ${args.length} where given.`);
        }
        if (specifier === 's') {
            const argValue = String(args[argIndex++]);
            if (precision !== undefined) {
                return argValue.substring(0, Number(precision));
            }
            return argValue;
        }
        let argValue = Number(args[argIndex++]);
        if (isNaN(argValue)) {
            argValue = 0;
        }
        if (specifier === 'd') {
            return String(Math.floor(argValue)).padStart(Number(precision), '0');
        }
        if (precision !== undefined) {
            return argValue.toFixed(Number(precision));
        }
        return String(argValue);
    });
};
const findIndexesOfSubString = (inputString, searchString) => {
    const matches = [];
    let i = inputString.indexOf(searchString);
    while (i !== -1) {
        matches.push(i);
        i = inputString.indexOf(searchString, i + searchString.length);
    }
    return matches;
};
const findLineEndingIndexes = (inputString) => {
    const endings = findIndexesOfSubString(inputString, '\n');
    endings.push(inputString.length);
    return endings;
};
const trimURL = (url, baseURLDomain) => {
    let result = url.replace(/^(https|http|file):\/\//i, '');
    if (baseURLDomain) {
        if (result.toLowerCase().startsWith(baseURLDomain.toLowerCase())) {
            result = result.substr(baseURLDomain.length);
        }
    }
    return result;
};
const removeURLFragment = (inputStr) => {
    const url = new URL(inputStr);
    url.hash = '';
    return url.toString();
};
const SPECIAL_REGEX_CHARACTERS = '^[]{}()\\.^$*+?|-,';
const regexSpecialCharacters = function () {
    return SPECIAL_REGEX_CHARACTERS;
};
const createSearchRegex = function (query, caseSensitive, isRegex, matchWholeWord = false) {
    const regexFlags = caseSensitive ? 'g' : 'gi';
    let regexObject;
    if (isRegex) {
        try {
            regexObject = new RegExp(query, regexFlags);
        }
        catch {
        }
    }
    if (!regexObject) {
        regexObject = createPlainTextSearchRegex(query, regexFlags);
    }
    if (matchWholeWord && regexObject) {
        regexObject = new RegExp(`\\b${regexObject.source}\\b`, regexFlags);
    }
    return regexObject;
};
const hashCode = function (string) {
    if (!string) {
        return 0;
    }
    const p = ((1 << 30) * 4 - 5);
    const z = 0x5033d967;
    const z2 = 0x59d2f15d;
    let s = 0;
    let zi = 1;
    for (let i = 0; i < string.length; i++) {
        const xi = string.charCodeAt(i) * z2;
        s = (s + zi * xi) % p;
        zi = (zi * z) % p;
    }
    s = (s + zi * (p - 1)) % p;
    return Math.abs(s | 0);
};
const compare = (a, b) => {
    if (a > b) {
        return 1;
    }
    if (a < b) {
        return -1;
    }
    return 0;
};
const trimEndWithMaxLength = (str, maxLength) => {
    if (str.length <= maxLength) {
        return str;
    }
    const ellipsis = '…';
    const ellipsisLength = 1;
    const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
    const iterator = segmenter.segment(str)[Symbol.iterator]();
    let lastSegmentIndex = 0;
    for (let i = 0; i <= maxLength - ellipsisLength; i++) {
        const result = iterator.next();
        if (result.done) {
            return str;
        }
        lastSegmentIndex = result.value.index;
    }
    for (let i = 0; i < ellipsisLength; i++) {
        if (iterator.next().done) {
            return str;
        }
    }
    return str.slice(0, lastSegmentIndex) + ellipsis;
};
const escapeForRegExp = (str) => {
    return escapeCharacters(str, SPECIAL_REGEX_CHARACTERS);
};
const createPlainTextSearchRegex = function (query, flags) {
    let regex = '';
    for (let i = 0; i < query.length; ++i) {
        const c = query.charAt(i);
        if (regexSpecialCharacters().indexOf(c) !== -1) {
            regex += '\\';
        }
        regex += c;
    }
    return new RegExp(regex, flags);
};
const WORD = /[A-Z]{2,}(?=[A-Z0-9][a-z0-9]+|\b|_)|[A-Za-z][0-9]+[a-z]?|[A-Z]?[a-z]+|[0-9][A-Za-z]+|[A-Z]|[0-9]+|[.]/g;
const toKebabCase = function (input) {
    return (input.match?.(WORD)?.map(w => w.toLowerCase()).join('-').replaceAll('-.-', '.') || input);
};
function toKebabCaseKeys(settingValue) {
    return Object.fromEntries(Object.entries(settingValue).map(([key, value]) => [toKebabCase(key), value]));
}
const stringifyWithPrecision = function stringifyWithPrecision(s, precision = 2) {
    if (precision === 0) {
        return s.toFixed(0);
    }
    const string = s.toFixed(precision).replace(/\.?0*$/, '');
    return string === '-0' ? '0' : string;
};
const concatBase64 = function (lhs, rhs) {
    if (lhs.length === 0 || !lhs.endsWith('=')) {
        return lhs + rhs;
    }
    const lhsLeaveAsIs = lhs.substring(0, lhs.length - 4);
    const lhsToDecode = lhs.substring(lhs.length - 4);
    return lhsLeaveAsIs + globalThis.btoa(globalThis.atob(lhsToDecode) + globalThis.atob(rhs));
};

// Copyright 2023 The Chromium Authors
function milliSecondsToSeconds(x) {
    return (x / 1000);
}
function microSecondsToMilliSeconds(x) {
    return (x / 1000);
}

// Copyright 2020 The Chromium Authors
function assertNotNullOrUndefined(val, message) {
    if (val === null || val === undefined) {
        throw new Error(`Expected given value to not be null/undefined but it was: ${val}${''}`);
    }
}
function assertNever(_type, message) {
    throw new Error(message);
}

// Copyright 2021 The Chromium Authors
const LocalizedEmptyString = '';

var UIString = /*#__PURE__*/Object.freeze({
	__proto__: null,
	LocalizedEmptyString: LocalizedEmptyString
});

// Copyright 2022 The Chromium Authors
const D50_X = 0.9642;
const D50_Y = 1.0;
const D50_Z = 0.8251;
class Vector3 {
    values = [0, 0, 0];
    constructor(values) {
        if (values) {
            this.values = values;
        }
    }
}
class Matrix3x3 {
    values = [
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
    ];
    constructor(values) {
        if (values) {
            this.values = values;
        }
    }
    multiply(other) {
        const dst = new Vector3();
        for (let row = 0; row < 3; ++row) {
            dst.values[row] = this.values[row][0] * other.values[0] + this.values[row][1] * other.values[1] +
                this.values[row][2] * other.values[2];
        }
        return dst;
    }
}
class TransferFunction {
    g;
    a;
    b;
    c;
    d;
    e;
    f;
    constructor(g, a, b = 0, c = 0, d = 0, e = 0, f = 0) {
        this.g = g;
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        this.e = e;
        this.f = f;
    }
    eval(val) {
        const sign = val < 0 ? -1 : 1.0;
        const abs = val * sign;
        if (abs < this.d) {
            return sign * (this.c * abs + this.f);
        }
        return sign * (Math.pow(this.a * abs + this.b, this.g) + this.e);
    }
}
const NAMED_TRANSFER_FN = {
    sRGB: new TransferFunction(2.4, (1 / 1.055), (0.055 / 1.055), (1 / 12.92), 0.04045, 0.0, 0.0),
    sRGB_INVERSE: new TransferFunction(0.416667, 1.13728, -0, 12.92, 0.0031308, -0.0549698, -0),
    proPhotoRGB: new TransferFunction(1.8, 1),
    proPhotoRGB_INVERSE: new TransferFunction(0.555556, 1, -0, 0, 0, 0, 0),
    k2Dot2: new TransferFunction(2.2, 1.0),
    k2Dot2_INVERSE: new TransferFunction(0.454545, 1),
    rec2020: new TransferFunction(2.22222, 0.909672, 0.0903276, 0.222222, 0.0812429, 0, 0),
    rec2020_INVERSE: new TransferFunction(0.45, 1.23439, -0, 4.5, 0.018054, -0.0993195, -0),
};
const NAMED_GAMUTS = {
    sRGB: new Matrix3x3([
        [0.436065674, 0.385147095, 0.143066406],
        [0.222488403, 0.716873169, 0.060607910],
        [0.013916016, 0.097076416, 0.714096069],
    ]),
    sRGB_INVERSE: new Matrix3x3([
        [3.134112151374599, -1.6173924597114966, -0.4906334036481285],
        [-0.9787872938826594, 1.9162795854799963, 0.0334547139520088],
        [0.07198304248352326, -0.2289858493321844, 1.4053851325241447],
    ]),
    displayP3: new Matrix3x3([
        [0.515102, 0.291965, 0.157153],
        [0.241182, 0.692236, 0.0665819],
        [-104941e-8, 0.0418818, 0.784378],
    ]),
    displayP3_INVERSE: new Matrix3x3([
        [2.404045155982687, -0.9898986932663839, -0.3976317191366333],
        [-0.8422283799266768, 1.7988505115115485, 0.016048170293157416],
        [0.04818705979712955, -0.09737385156228891, 1.2735066448052303],
    ]),
    adobeRGB: new Matrix3x3([
        [0.60974, 0.20528, 0.14919],
        [0.31111, 0.62567, 0.06322],
        [0.01947, 0.06087, 0.74457],
    ]),
    adobeRGB_INVERSE: new Matrix3x3([
        [1.9625385510109137, -0.6106892546501431, -0.3413827467482388],
        [-0.9787580455521, 1.9161624707082339, 0.03341676594241408],
        [0.028696263137883395, -0.1406807819331586, 1.349252109991369],
    ]),
    rec2020: new Matrix3x3([
        [0.673459, 0.165661, 0.125100],
        [0.279033, 0.675338, 0.0456288],
        [-193139e-8, 0.0299794, 0.797162],
    ]),
    rec2020_INVERSE: new Matrix3x3([
        [1.647275201661012, -0.3936024771460771, -0.23598028884792507],
        [-0.6826176165196962, 1.647617775014935, 0.01281626807852422],
        [0.029662725298529837, -0.06291668721366285, 1.2533964313435522],
    ])};
function degToRad(deg) {
    return deg * (Math.PI / 180);
}
function radToDeg(rad) {
    return rad * (180 / Math.PI);
}
function applyTransferFns(fn, r, g, b) {
    return [fn.eval(r), fn.eval(g), fn.eval(b)];
}
const OKLAB_TO_LMS_MATRIX = new Matrix3x3([
    [0.99999999845051981432, 0.39633779217376785678, 0.21580375806075880339],
    [1.0000000088817607767, -0.10556134232365635, -0.06385417477170591],
    [1.0000000546724109177, -0.08948418209496575, -1.2914855378640917],
]);
const LMS_TO_OKLAB_MATRIX = new Matrix3x3([
    [0.2104542553, 0.7936177849999999, -0.0040720468],
    [1.9779984951000003, -2.4285922049999997, 0.4505937099000001],
    [0.025904037099999982, 0.7827717662, -0.8086757660000001],
]);
const XYZ_TO_LMS_MATRIX = new Matrix3x3([
    [0.8190224432164319, 0.3619062562801221, -0.12887378261216414],
    [0.0329836671980271, 0.9292868468965546, 0.03614466816999844],
    [0.048177199566046255, 0.26423952494422764, 0.6335478258136937],
]);
const LMS_TO_XYZ_MATRIX = new Matrix3x3([
    [1.226879873374156, -0.5578149965554814, 0.2813910501772159],
    [-0.040575762624313734, 1.1122868293970596, -0.07171106666151703],
    [-0.07637294974672144, -0.4214933239627915, 1.586924024427242],
]);
const PRO_PHOTO_TO_XYZD50_MATRIX = new Matrix3x3([
    [0.7976700747153241, 0.13519395152800417, 0.03135596341127167],
    [0.28803902352472205, 0.7118744007923554, 0.00008661179538844252],
    [2.739876695467402e-7, -14405226518969991e-22, 0.825211112593861],
]);
const XYZD50_TO_PRO_PHOTO_MATRIX = new Matrix3x3([
    [1.3459533710138858, -0.25561367037652133, -0.051116041522131374],
    [-0.544600415668951, 1.5081687311475767, 0.020535163968720935],
    [-13975622054109725e-22, 0.000002717590904589903, 1.2118111696814942],
]);
const XYZD65_TO_XYZD50_MATRIX = new Matrix3x3([
    [1.0478573189120088, 0.022907374491829943, -0.050162247377152525],
    [0.029570500050499514, 0.9904755577034089, -0.017061518194840468],
    [-0.00924047197558879, 0.015052921526981566, 0.7519708530777581],
]);
const XYZD50_TO_XYZD65_MATRIX = new Matrix3x3([
    [0.9555366447632887, -0.02306009252137888, 0.06321844147263304],
    [-0.028315378228764922, 1.009951351591575, 0.021026001591792402],
    [0.012308773293784308, -0.02050053471777469, 1.3301947294775631],
]);
class ColorConverter {
    static labToXyzd50(l, a, b) {
        let y = (l + 16.0) / 116.0;
        let x = y + a / 500.0;
        let z = y - b / 200.0;
        function labInverseTransferFunction(t) {
            const delta = (24.0 / 116.0);
            if (t <= delta) {
                return (108.0 / 841.0) * (t - (16.0 / 116.0));
            }
            return t * t * t;
        }
        x = labInverseTransferFunction(x) * D50_X;
        y = labInverseTransferFunction(y) * D50_Y;
        z = labInverseTransferFunction(z) * D50_Z;
        return [x, y, z];
    }
    static xyzd50ToLab(x, y, z) {
        function labTransferFunction(t) {
            const deltaLimit = (24.0 / 116.0) * (24.0 / 116.0) * (24.0 / 116.0);
            if (t <= deltaLimit) {
                return (841.0 / 108.0) * t + (16.0 / 116.0);
            }
            return Math.pow(t, 1.0 / 3.0);
        }
        x = labTransferFunction(x / D50_X);
        y = labTransferFunction(y / D50_Y);
        z = labTransferFunction(z / D50_Z);
        const l = 116.0 * y - 16.0;
        const a = 500.0 * (x - y);
        const b = 200.0 * (y - z);
        return [l, a, b];
    }
    static oklabToXyzd65(l, a, b) {
        const labInput = new Vector3([l, a, b]);
        const lmsIntermediate = OKLAB_TO_LMS_MATRIX.multiply(labInput);
        lmsIntermediate.values[0] = lmsIntermediate.values[0] * lmsIntermediate.values[0] * lmsIntermediate.values[0];
        lmsIntermediate.values[1] = lmsIntermediate.values[1] * lmsIntermediate.values[1] * lmsIntermediate.values[1];
        lmsIntermediate.values[2] = lmsIntermediate.values[2] * lmsIntermediate.values[2] * lmsIntermediate.values[2];
        const xyzOutput = LMS_TO_XYZ_MATRIX.multiply(lmsIntermediate);
        return xyzOutput.values;
    }
    static xyzd65ToOklab(x, y, z) {
        const xyzInput = new Vector3([x, y, z]);
        const lmsIntermediate = XYZ_TO_LMS_MATRIX.multiply(xyzInput);
        lmsIntermediate.values[0] = Math.pow(lmsIntermediate.values[0], 1.0 / 3.0);
        lmsIntermediate.values[1] = Math.pow(lmsIntermediate.values[1], 1.0 / 3.0);
        lmsIntermediate.values[2] = Math.pow(lmsIntermediate.values[2], 1.0 / 3.0);
        const labOutput = LMS_TO_OKLAB_MATRIX.multiply(lmsIntermediate);
        return [labOutput.values[0], labOutput.values[1], labOutput.values[2]];
    }
    static lchToLab(l, c, h) {
        if (h === undefined) {
            return [l, 0, 0];
        }
        return [l, c * Math.cos(degToRad(h)), c * Math.sin(degToRad(h))];
    }
    static labToLch(l, a, b) {
        return [l, Math.sqrt(a * a + b * b), radToDeg(Math.atan2(b, a))];
    }
    static displayP3ToXyzd50(r, g, b) {
        const [mappedR, mappedG, mappedB] = applyTransferFns(NAMED_TRANSFER_FN.sRGB, r, g, b);
        const rgbInput = new Vector3([mappedR, mappedG, mappedB]);
        const xyzOutput = NAMED_GAMUTS.displayP3.multiply(rgbInput);
        return xyzOutput.values;
    }
    static xyzd50ToDisplayP3(x, y, z) {
        const xyzInput = new Vector3([x, y, z]);
        const rgbOutput = NAMED_GAMUTS.displayP3_INVERSE.multiply(xyzInput);
        return applyTransferFns(NAMED_TRANSFER_FN.sRGB_INVERSE, rgbOutput.values[0], rgbOutput.values[1], rgbOutput.values[2]);
    }
    static proPhotoToXyzd50(r, g, b) {
        const [mappedR, mappedG, mappedB] = applyTransferFns(NAMED_TRANSFER_FN.proPhotoRGB, r, g, b);
        const rgbInput = new Vector3([mappedR, mappedG, mappedB]);
        const xyzOutput = PRO_PHOTO_TO_XYZD50_MATRIX.multiply(rgbInput);
        return xyzOutput.values;
    }
    static xyzd50ToProPhoto(x, y, z) {
        const xyzInput = new Vector3([x, y, z]);
        const rgbOutput = XYZD50_TO_PRO_PHOTO_MATRIX.multiply(xyzInput);
        return applyTransferFns(NAMED_TRANSFER_FN.proPhotoRGB_INVERSE, rgbOutput.values[0], rgbOutput.values[1], rgbOutput.values[2]);
    }
    static adobeRGBToXyzd50(r, g, b) {
        const [mappedR, mappedG, mappedB] = applyTransferFns(NAMED_TRANSFER_FN.k2Dot2, r, g, b);
        const rgbInput = new Vector3([mappedR, mappedG, mappedB]);
        const xyzOutput = NAMED_GAMUTS.adobeRGB.multiply(rgbInput);
        return xyzOutput.values;
    }
    static xyzd50ToAdobeRGB(x, y, z) {
        const xyzInput = new Vector3([x, y, z]);
        const rgbOutput = NAMED_GAMUTS.adobeRGB_INVERSE.multiply(xyzInput);
        return applyTransferFns(NAMED_TRANSFER_FN.k2Dot2_INVERSE, rgbOutput.values[0], rgbOutput.values[1], rgbOutput.values[2]);
    }
    static rec2020ToXyzd50(r, g, b) {
        const [mappedR, mappedG, mappedB] = applyTransferFns(NAMED_TRANSFER_FN.rec2020, r, g, b);
        const rgbInput = new Vector3([mappedR, mappedG, mappedB]);
        const xyzOutput = NAMED_GAMUTS.rec2020.multiply(rgbInput);
        return xyzOutput.values;
    }
    static xyzd50ToRec2020(x, y, z) {
        const xyzInput = new Vector3([x, y, z]);
        const rgbOutput = NAMED_GAMUTS.rec2020_INVERSE.multiply(xyzInput);
        return applyTransferFns(NAMED_TRANSFER_FN.rec2020_INVERSE, rgbOutput.values[0], rgbOutput.values[1], rgbOutput.values[2]);
    }
    static xyzd50ToD65(x, y, z) {
        const xyzInput = new Vector3([x, y, z]);
        const xyzOutput = XYZD50_TO_XYZD65_MATRIX.multiply(xyzInput);
        return xyzOutput.values;
    }
    static xyzd65ToD50(x, y, z) {
        const xyzInput = new Vector3([x, y, z]);
        const xyzOutput = XYZD65_TO_XYZD50_MATRIX.multiply(xyzInput);
        return xyzOutput.values;
    }
    static xyzd50TosRGBLinear(x, y, z) {
        const xyzInput = new Vector3([x, y, z]);
        const rgbResult = NAMED_GAMUTS.sRGB_INVERSE.multiply(xyzInput);
        return rgbResult.values;
    }
    static srgbLinearToXyzd50(r, g, b) {
        const rgbInput = new Vector3([r, g, b]);
        const xyzOutput = NAMED_GAMUTS.sRGB.multiply(rgbInput);
        return xyzOutput.values;
    }
    static srgbToXyzd50(r, g, b) {
        const [mappedR, mappedG, mappedB] = applyTransferFns(NAMED_TRANSFER_FN.sRGB, r, g, b);
        const rgbInput = new Vector3([mappedR, mappedG, mappedB]);
        const xyzOutput = NAMED_GAMUTS.sRGB.multiply(rgbInput);
        return xyzOutput.values;
    }
    static xyzd50ToSrgb(x, y, z) {
        const xyzInput = new Vector3([x, y, z]);
        const rgbOutput = NAMED_GAMUTS.sRGB_INVERSE.multiply(xyzInput);
        return applyTransferFns(NAMED_TRANSFER_FN.sRGB_INVERSE, rgbOutput.values[0], rgbOutput.values[1], rgbOutput.values[2]);
    }
    static oklchToXyzd50(lInput, c, h) {
        const [l, a, b] = ColorConverter.lchToLab(lInput, c, h);
        const [x65, y65, z65] = ColorConverter.oklabToXyzd65(l, a, b);
        return ColorConverter.xyzd65ToD50(x65, y65, z65);
    }
    static xyzd50ToOklch(x, y, z) {
        const [x65, y65, z65] = ColorConverter.xyzd50ToD65(x, y, z);
        const [l, a, b] = ColorConverter.xyzd65ToOklab(x65, y65, z65);
        return ColorConverter.labToLch(l, a, b);
    }
}

var ColorConverter$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ColorConverter: ColorConverter
});

// Copyright 2020 The Chromium Authors
function blendColors(fgRGBA, bgRGBA) {
    const alpha = fgRGBA[3];
    return [
        ((1 - alpha) * bgRGBA[0]) + (alpha * fgRGBA[0]),
        ((1 - alpha) * bgRGBA[1]) + (alpha * fgRGBA[1]),
        ((1 - alpha) * bgRGBA[2]) + (alpha * fgRGBA[2]),
        alpha + (bgRGBA[3] * (1 - alpha)),
    ];
}
function rgbToHue([r, g, b]) {
    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    const diff = max - min;
    let h;
    if (min === max) {
        h = 0;
    }
    else if (r === max) {
        h = ((1 / 6 * (g - b) / diff) + 1) % 1;
    }
    else if (g === max) {
        h = (1 / 6 * (b - r) / diff) + 1 / 3;
    }
    else {
        h = (1 / 6 * (r - g) / diff) + 2 / 3;
    }
    return h;
}
function rgbToHsl(rgb) {
    const [h, s, l] = rgbaToHsla([...rgb, undefined]);
    return [h, s, l];
}
function rgbaToHsla([r, g, b, a]) {
    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    const diff = max - min;
    const sum = max + min;
    const h = rgbToHue([r, g, b]);
    const l = 0.5 * sum;
    let s;
    if (l === 0) {
        s = 0;
    }
    else if (l === 1) {
        s = 0;
    }
    else if (l <= 0.5) {
        s = diff / sum;
    }
    else {
        s = diff / (2 - sum);
    }
    return [h, s, l, a];
}
function rgbToHwb(rgb) {
    const [h, w, b] = rgbaToHwba([...rgb, undefined]);
    return [h, w, b];
}
function rgbaToHwba([r, g, b, a]) {
    const h = rgbToHue([r, g, b]);
    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    return [h, min, 1 - max, a];
}
function luminance([rSRGB, gSRGB, bSRGB]) {
    const r = rSRGB <= 0.04045 ? rSRGB / 12.92 : Math.pow(((rSRGB + 0.055) / 1.055), 2.4);
    const g = gSRGB <= 0.04045 ? gSRGB / 12.92 : Math.pow(((gSRGB + 0.055) / 1.055), 2.4);
    const b = bSRGB <= 0.04045 ? bSRGB / 12.92 : Math.pow(((bSRGB + 0.055) / 1.055), 2.4);
    return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
function contrastRatio(fgRGBA, bgRGBA) {
    const blendedFg = blendColors(fgRGBA, bgRGBA);
    const fgLuminance = luminance(blendedFg);
    const bgLuminance = luminance(bgRGBA);
    const contrastRatio = (Math.max(fgLuminance, bgLuminance) + 0.05) / (Math.min(fgLuminance, bgLuminance) + 0.05);
    return contrastRatio;
}
const mainTRC = 2.4;
const normBgExp = 0.56;
const normFgExp = 0.57;
const revBgExp = 0.65;
const revFgExp = 0.62;
const blkThrs = 0.022;
const blkClmp = 1.414;
const scaleBoW = 1.14;
const scaleWoB = 1.14;
const loConOffset = 0.027;
const loClip = 0.1;
const deltaLuminanceMin = 0.0005;
function luminanceAPCA([rSRGB, gSRGB, bSRGB]) {
    const r = Math.pow(rSRGB, mainTRC);
    const g = Math.pow(gSRGB, mainTRC);
    const b = Math.pow(bSRGB, mainTRC);
    return 0.2126729 * r + 0.7151522 * g + 0.0721750 * b;
}
function contrastRatioAPCA(fgRGBA, bgRGBA) {
    const blendedFg = blendColors(fgRGBA, bgRGBA);
    return contrastRatioByLuminanceAPCA(luminanceAPCA(blendedFg), luminanceAPCA(bgRGBA));
}
function clampLuminance(value) {
    return value > blkThrs ? value : (value + Math.pow(blkThrs - value, blkClmp));
}
function contrastRatioByLuminanceAPCA(fgLuminance, bgLuminance) {
    fgLuminance = clampLuminance(fgLuminance);
    bgLuminance = clampLuminance(bgLuminance);
    if (Math.abs(fgLuminance - bgLuminance) < deltaLuminanceMin) {
        return 0;
    }
    let result = 0;
    if (bgLuminance > fgLuminance) {
        result = (Math.pow(bgLuminance, normBgExp) - Math.pow(fgLuminance, normFgExp)) * scaleBoW;
        result = result < loClip ? 0 : result - loConOffset;
    }
    else {
        result = (Math.pow(bgLuminance, revBgExp) - Math.pow(fgLuminance, revFgExp)) * scaleWoB;
        result = result > -loClip ? 0 : result + loConOffset;
    }
    return result * 100;
}
function desiredLuminanceAPCA(luminance, contrast, lighter) {
    luminance = clampLuminance(luminance);
    contrast /= 100;
    function computeLuminance() {
        if (!lighter) {
            return Math.pow(Math.abs(Math.pow(luminance, normBgExp) - (contrast + loConOffset) / scaleBoW), 1 / normFgExp);
        }
        return Math.pow(Math.abs(Math.pow(luminance, revBgExp) - (-contrast - loConOffset) / scaleWoB), 1 / revFgExp);
    }
    let desiredLuminance = computeLuminance();
    if (desiredLuminance < 0 || desiredLuminance > 1) {
        lighter = !lighter;
        desiredLuminance = computeLuminance();
    }
    return desiredLuminance;
}
const contrastAPCALookupTable = [
    [12, -1, -1, -1, -1, 100, 90, 80, -1, -1],
    [14, -1, -1, -1, 100, 90, 80, 60, 60, -1],
    [16, -1, -1, 100, 90, 80, 60, 55, 50, 50],
    [18, -1, -1, 90, 80, 60, 55, 50, 40, 40],
    [24, -1, 100, 80, 60, 55, 50, 40, 38, 35],
    [30, -1, 90, 70, 55, 50, 40, 38, 35, 40],
    [36, -1, 80, 60, 50, 40, 38, 35, 30, 25],
    [48, 100, 70, 55, 40, 38, 35, 30, 25, 20],
    [60, 90, 60, 50, 38, 35, 30, 25, 20, 20],
    [72, 80, 55, 40, 35, 30, 25, 20, 20, 20],
    [96, 70, 50, 35, 30, 25, 20, 20, 20, 20],
    [120, 60, 40, 30, 25, 20, 20, 20, 20, 20],
];
contrastAPCALookupTable.reverse();
function getAPCAThreshold(fontSize, fontWeight) {
    const size = parseFloat(fontSize.replace('px', ''));
    const weight = parseFloat(fontWeight);
    for (const [rowSize, ...rowWeights] of contrastAPCALookupTable) {
        if (size >= rowSize) {
            for (const [idx, keywordWeight] of [900, 800, 700, 600, 500, 400, 300, 200, 100].entries()) {
                if (weight >= keywordWeight) {
                    const threshold = rowWeights[rowWeights.length - 1 - idx];
                    return threshold === -1 ? null : threshold;
                }
            }
        }
    }
    return null;
}
function isLargeFont(fontSize, fontWeight) {
    const boldWeights = ['bold', 'bolder'];
    const fontSizePx = parseFloat(fontSize.replace('px', ''));
    const isBold = isNaN(Number(fontWeight)) ? boldWeights.includes(fontWeight) : Number(fontWeight) >= 600;
    const fontSizePt = fontSizePx * 72 / 96;
    if (isBold) {
        return fontSizePt >= 14;
    }
    return fontSizePt >= 18;
}
const contrastThresholds = {
    largeFont: { aa: 3.0, aaa: 4.5 },
    normalFont: { aa: 4.5, aaa: 7.0 },
};
function getContrastThreshold(fontSize, fontWeight) {
    if (isLargeFont(fontSize, fontWeight)) {
        return contrastThresholds.largeFont;
    }
    return contrastThresholds.normalFont;
}

var ColorUtils = /*#__PURE__*/Object.freeze({
	__proto__: null,
	blendColors: blendColors,
	contrastRatio: contrastRatio,
	contrastRatioAPCA: contrastRatioAPCA,
	contrastRatioByLuminanceAPCA: contrastRatioByLuminanceAPCA,
	desiredLuminanceAPCA: desiredLuminanceAPCA,
	getAPCAThreshold: getAPCAThreshold,
	getContrastThreshold: getContrastThreshold,
	isLargeFont: isLargeFont,
	luminance: luminance,
	luminanceAPCA: luminanceAPCA,
	rgbToHsl: rgbToHsl,
	rgbToHwb: rgbToHwb,
	rgbaToHsla: rgbaToHsla,
	rgbaToHwba: rgbaToHwba
});

// Copyright 2021 The Chromium Authors
/*
 * Copyright (C) 2009 Apple Inc.  All rights reserved.
 * Copyright (C) 2009 Joseph Pecoraro
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
function normalizeHue(hue) {
    return ((hue % 360) + 360) % 360;
}
function parseAngle(angleText) {
    const angle = angleText.replace(/(deg|g?rad|turn)$/, '');
    if (isNaN(angle) || angleText.match(/\s+(deg|g?rad|turn)/)) {
        return null;
    }
    const number = parseFloat(angle);
    if (angleText.includes('turn')) {
        return number * 360;
    }
    if (angleText.includes('grad')) {
        return number * 9 / 10;
    }
    if (angleText.includes('rad')) {
        return number * 180 / Math.PI;
    }
    return number;
}
function getFormat(formatText) {
    switch (formatText) {
        case "hex" :
            return "hex" ;
        case "hexa" :
            return "hexa" ;
        case "rgb" :
            return "rgb" ;
        case "rgba" :
            return "rgba" ;
        case "hsl" :
            return "hsl" ;
        case "hsla" :
            return "hsla" ;
        case "hwb" :
            return "hwb" ;
        case "hwba" :
            return "hwba" ;
        case "lch" :
            return "lch" ;
        case "oklch" :
            return "oklch" ;
        case "lab" :
            return "lab" ;
        case "oklab" :
            return "oklab" ;
    }
    return getColorSpace(formatText);
}
function getColorSpace(colorSpaceText) {
    switch (colorSpaceText) {
        case "srgb" :
            return "srgb" ;
        case "srgb-linear" :
            return "srgb-linear" ;
        case "display-p3" :
            return "display-p3" ;
        case "a98-rgb" :
            return "a98-rgb" ;
        case "prophoto-rgb" :
            return "prophoto-rgb" ;
        case "rec2020" :
            return "rec2020" ;
        case "xyz" :
            return "xyz" ;
        case "xyz-d50" :
            return "xyz-d50" ;
        case "xyz-d65" :
            return "xyz-d65" ;
    }
    return null;
}
function mapPercentToRange(percent, range) {
    const sign = Math.sign(percent);
    const absPercent = Math.abs(percent);
    const [outMin, outMax] = range;
    return sign * (absPercent * (outMax - outMin) / 100 + outMin);
}
function parse$2(text) {
    if (!text.match(/\s/)) {
        const match = text.toLowerCase().match(/^(?:#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|(\w+))$/i);
        if (match) {
            if (match[1]) {
                return Legacy.fromHex(match[1], text);
            }
            if (match[2]) {
                return Nickname.fromName(match[2], text);
            }
            return null;
        }
    }
    const match = text.toLowerCase().match(/^\s*(?:(rgba?)|(hsla?)|(hwba?)|(lch)|(oklch)|(lab)|(oklab)|(color))\((.*)\)\s*$/);
    if (match) {
        const isRgbaMatch = Boolean(match[1]);
        const isHslaMatch = Boolean(match[2]);
        const isHwbaMatch = Boolean(match[3]);
        const isLchMatch = Boolean(match[4]);
        const isOklchMatch = Boolean(match[5]);
        const isLabMatch = Boolean(match[6]);
        const isOklabMatch = Boolean(match[7]);
        const isColorMatch = Boolean(match[8]);
        const valuesText = match[9];
        if (isColorMatch) {
            return ColorFunction.fromSpec(text, valuesText);
        }
        const isOldSyntax = isRgbaMatch || isHslaMatch || isHwbaMatch;
        const allowCommas = isRgbaMatch || isHslaMatch;
        const convertNoneToZero = !isOldSyntax;
        const values = splitColorFunctionParameters(valuesText, { allowCommas, convertNoneToZero });
        if (!values) {
            return null;
        }
        const spec = [values[0], values[1], values[2], values[3]];
        if (isRgbaMatch) {
            return Legacy.fromRGBAFunction(values[0], values[1], values[2], values[3], text);
        }
        if (isHslaMatch) {
            return HSL.fromSpec(spec, text);
        }
        if (isHwbaMatch) {
            return HWB.fromSpec(spec, text);
        }
        if (isLchMatch) {
            return LCH.fromSpec(spec, text);
        }
        if (isOklchMatch) {
            return Oklch.fromSpec(spec, text);
        }
        if (isLabMatch) {
            return Lab.fromSpec(spec, text);
        }
        if (isOklabMatch) {
            return Oklab.fromSpec(spec, text);
        }
    }
    return null;
}
function splitColorFunctionParameters(content, { allowCommas, convertNoneToZero }) {
    const components = content.trim();
    let values = [];
    if (allowCommas) {
        values = components.split(/\s*,\s*/);
    }
    if (!allowCommas || values.length === 1) {
        values = components.split(/\s+/);
        if (values[3] === '/') {
            values.splice(3, 1);
            if (values.length !== 4) {
                return null;
            }
        }
        else if ((values.length > 2 && values[2].indexOf('/') !== -1) || (values.length > 3 && values[3].indexOf('/') !== -1)) {
            const alpha = values.slice(2, 4).join('');
            values = values.slice(0, 2).concat(alpha.split(/\//)).concat(values.slice(4));
        }
        else if (values.length >= 4) {
            return null;
        }
    }
    if (values.length !== 3 && values.length !== 4 || values.indexOf('') > -1) {
        return null;
    }
    if (convertNoneToZero) {
        return values.map(value => value === 'none' ? '0' : value);
    }
    return values;
}
function clamp(value, { min, max }) {
    if (value === null) {
        return value;
    }
    {
        value = Math.max(value, min);
    }
    if (max !== undefined) {
        value = Math.min(value, max);
    }
    return value;
}
function parsePercentage(value, range) {
    if (!value.endsWith('%')) {
        return null;
    }
    const percentage = parseFloat(value.substr(0, value.length - 1));
    return isNaN(percentage) ? null : mapPercentToRange(percentage, range);
}
function parseNumber(value) {
    const number = parseFloat(value);
    return isNaN(number) ? null : number;
}
function parseAlpha(value) {
    if (value === undefined) {
        return null;
    }
    return clamp(parsePercentage(value, [0, 1]) ?? parseNumber(value), { min: 0, max: 1 });
}
function parsePercentOrNumber(value, range = [0, 1]) {
    if (isNaN(value.replace('%', ''))) {
        return null;
    }
    const parsed = parseFloat(value);
    if (value.indexOf('%') !== -1) {
        if (value.indexOf('%') !== value.length - 1) {
            return null;
        }
        return mapPercentToRange(parsed, range);
    }
    return parsed;
}
function parseRgbNumeric(value) {
    const parsed = parsePercentOrNumber(value);
    if (parsed === null) {
        return null;
    }
    if (value.indexOf('%') !== -1) {
        return parsed;
    }
    return parsed / 255;
}
function parseHueNumeric(value) {
    const angle = value.replace(/(deg|g?rad|turn)$/, '');
    if (isNaN(angle) || value.match(/\s+(deg|g?rad|turn)/)) {
        return null;
    }
    const number = parseFloat(angle);
    if (value.indexOf('turn') !== -1) {
        return number % 1;
    }
    if (value.indexOf('grad') !== -1) {
        return (number / 400) % 1;
    }
    if (value.indexOf('rad') !== -1) {
        return (number / (2 * Math.PI)) % 1;
    }
    return (number / 360) % 1;
}
function parseSatLightNumeric(value) {
    if (value.indexOf('%') !== value.length - 1 || isNaN(value.replace('%', ''))) {
        return null;
    }
    const parsed = parseFloat(value);
    return parsed / 100;
}
function parseAlphaNumeric(value) {
    return parsePercentOrNumber(value);
}
function hsva2hsla(hsva) {
    const h = hsva[0];
    let s = hsva[1];
    const v = hsva[2];
    const t = (2 - s) * v;
    if (v === 0 || s === 0) {
        s = 0;
    }
    else {
        s *= v / (t < 1 ? t : 2 - t);
    }
    return [h, s, t / 2, hsva[3]];
}
function hsl2rgb(hsl) {
    const h = hsl[0];
    let s = hsl[1];
    const l = hsl[2];
    function hue2rgb(p, q, h) {
        if (h < 0) {
            h += 1;
        }
        else if (h > 1) {
            h -= 1;
        }
        if ((h * 6) < 1) {
            return p + (q - p) * h * 6;
        }
        if ((h * 2) < 1) {
            return q;
        }
        if ((h * 3) < 2) {
            return p + (q - p) * ((2 / 3) - h) * 6;
        }
        return p;
    }
    if (s < 0) {
        s = 0;
    }
    let q;
    if (l <= 0.5) {
        q = l * (1 + s);
    }
    else {
        q = l + s - (l * s);
    }
    const p = 2 * l - q;
    const tr = h + (1 / 3);
    const tg = h;
    const tb = h - (1 / 3);
    return [hue2rgb(p, q, tr), hue2rgb(p, q, tg), hue2rgb(p, q, tb), hsl[3]];
}
function hwb2rgb(hwb) {
    const h = hwb[0];
    const w = hwb[1];
    const b = hwb[2];
    const whiteRatio = w / (w + b);
    let result = [whiteRatio, whiteRatio, whiteRatio, hwb[3]];
    if (w + b < 1) {
        result = hsl2rgb([h, 1, 0.5, hwb[3]]);
        for (let i = 0; i < 3; ++i) {
            result[i] += w - (w + b) * result[i];
        }
    }
    return result;
}
function hsva2rgba(hsva) {
    return hsl2rgb(hsva2hsla(hsva));
}
function rgb2hsv(rgba) {
    const hsla = rgbToHsl(rgba);
    const h = hsla[0];
    let s = hsla[1];
    const l = hsla[2];
    s *= l < 0.5 ? l : 1 - l;
    return [h, s !== 0 ? 2 * s / (l + s) : 0, (l + s)];
}
function desiredLuminance(luminance, contrast, lighter) {
    function computeLuminance() {
        if (lighter) {
            return (luminance + 0.05) * contrast - 0.05;
        }
        return (luminance + 0.05) / contrast - 0.05;
    }
    let desiredLuminance = computeLuminance();
    if (desiredLuminance < 0 || desiredLuminance > 1) {
        lighter = !lighter;
        desiredLuminance = computeLuminance();
    }
    return desiredLuminance;
}
function approachColorValue(candidateHSVA, index, desiredLuminance, candidateLuminance) {
    const epsilon = 0.0002;
    let x = candidateHSVA[index];
    let multiplier = 1;
    let dLuminance = candidateLuminance(candidateHSVA) - desiredLuminance;
    let previousSign = Math.sign(dLuminance);
    for (let guard = 100; guard; guard--) {
        if (Math.abs(dLuminance) < epsilon) {
            candidateHSVA[index] = x;
            return x;
        }
        const sign = Math.sign(dLuminance);
        if (sign !== previousSign) {
            multiplier /= 2;
            previousSign = sign;
        }
        else if (x < 0 || x > 1) {
            return null;
        }
        x += multiplier * (index === 2 ? -dLuminance : dLuminance);
        candidateHSVA[index] = x;
        dLuminance = candidateLuminance(candidateHSVA) - desiredLuminance;
    }
    return null;
}
function findFgColorForContrast(fgColor, bgColor, requiredContrast) {
    const candidateHSVA = fgColor.as("hsl" ).hsva();
    const bgRGBA = bgColor.rgba();
    const candidateLuminance = (candidateHSVA) => {
        return luminance(blendColors(Legacy.fromHSVA(candidateHSVA).rgba(), bgRGBA));
    };
    const bgLuminance = luminance(bgColor.rgba());
    const fgLuminance = candidateLuminance(candidateHSVA);
    const fgIsLighter = fgLuminance > bgLuminance;
    const desired = desiredLuminance(bgLuminance, requiredContrast, fgIsLighter);
    const saturationComponentIndex = 1;
    const valueComponentIndex = 2;
    if (approachColorValue(candidateHSVA, valueComponentIndex, desired, candidateLuminance)) {
        return Legacy.fromHSVA(candidateHSVA);
    }
    candidateHSVA[valueComponentIndex] = 1;
    if (approachColorValue(candidateHSVA, saturationComponentIndex, desired, candidateLuminance)) {
        return Legacy.fromHSVA(candidateHSVA);
    }
    return null;
}
function findFgColorForContrastAPCA(fgColor, bgColor, requiredContrast) {
    const candidateHSVA = fgColor.as("hsl" ).hsva();
    const candidateLuminance = (candidateHSVA) => {
        return luminanceAPCA(Legacy.fromHSVA(candidateHSVA).rgba());
    };
    const bgLuminance = luminanceAPCA(bgColor.rgba());
    const fgLuminance = candidateLuminance(candidateHSVA);
    const fgIsLighter = fgLuminance >= bgLuminance;
    const desiredLuminance = desiredLuminanceAPCA(bgLuminance, requiredContrast, fgIsLighter);
    const saturationComponentIndex = 1;
    const valueComponentIndex = 2;
    if (approachColorValue(candidateHSVA, valueComponentIndex, desiredLuminance, candidateLuminance)) {
        const candidate = Legacy.fromHSVA(candidateHSVA);
        if (Math.abs(contrastRatioAPCA(bgColor.rgba(), candidate.rgba())) >= requiredContrast) {
            return candidate;
        }
    }
    candidateHSVA[valueComponentIndex] = 1;
    if (approachColorValue(candidateHSVA, saturationComponentIndex, desiredLuminance, candidateLuminance)) {
        const candidate = Legacy.fromHSVA(candidateHSVA);
        if (Math.abs(contrastRatioAPCA(bgColor.rgba(), candidate.rgba())) >= requiredContrast) {
            return candidate;
        }
    }
    return null;
}
const EPSILON = 0.01;
const WIDE_RANGE_EPSILON = 1;
function equals(a, b, accuracy = EPSILON) {
    if (Array.isArray(a) && Array.isArray(b)) {
        if (a.length !== b.length) {
            return false;
        }
        for (const i in a) {
            if (!equals(a[i], b[i])) {
                return false;
            }
        }
        return true;
    }
    if (Array.isArray(a) || Array.isArray(b)) {
        return false;
    }
    if (a === null || b === null) {
        return a === b;
    }
    return Math.abs(a - b) < accuracy;
}
function lessOrEquals(a, b, accuracy = EPSILON) {
    return a - b <= accuracy;
}
class Lab {
    l;
    a;
    b;
    alpha;
    #authoredText;
    #rawParams;
    channels = ["l" , "a" , "b" , "alpha" ];
    static #conversions = {
        ["hex" ]: (self) => new Legacy(self.#getRGBArray( false), "hex" ),
        ["hexa" ]: (self) => new Legacy(self.#getRGBArray( true), "hexa" ),
        ["rgb" ]: (self) => new Legacy(self.#getRGBArray( false), "rgb" ),
        ["rgba" ]: (self) => new Legacy(self.#getRGBArray( true), "rgba" ),
        ["hsl" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hsla" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hwb" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["hwba" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["lch" ]: (self) => new LCH(...ColorConverter.labToLch(self.l, self.a, self.b), self.alpha),
        ["oklch" ]: (self) => new Oklch(...ColorConverter.xyzd50ToOklch(...self.#toXyzd50()), self.alpha),
        ["lab" ]: (self) => self,
        ["oklab" ]: (self) => new Oklab(...ColorConverter.xyzd65ToOklab(...ColorConverter.xyzd50ToD65(...self.#toXyzd50())), self.alpha),
        ["srgb" ]: (self) => new ColorFunction("srgb" , ...ColorConverter.xyzd50ToSrgb(...self.#toXyzd50()), self.alpha),
        ["srgb-linear" ]: (self) => new ColorFunction("srgb-linear" , ...ColorConverter.xyzd50TosRGBLinear(...self.#toXyzd50()), self.alpha),
        ["display-p3" ]: (self) => new ColorFunction("display-p3" , ...ColorConverter.xyzd50ToDisplayP3(...self.#toXyzd50()), self.alpha),
        ["a98-rgb" ]: (self) => new ColorFunction("a98-rgb" , ...ColorConverter.xyzd50ToAdobeRGB(...self.#toXyzd50()), self.alpha),
        ["prophoto-rgb" ]: (self) => new ColorFunction("prophoto-rgb" , ...ColorConverter.xyzd50ToProPhoto(...self.#toXyzd50()), self.alpha),
        ["rec2020" ]: (self) => new ColorFunction("rec2020" , ...ColorConverter.xyzd50ToRec2020(...self.#toXyzd50()), self.alpha),
        ["xyz" ]: (self) => new ColorFunction("xyz" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
        ["xyz-d50" ]: (self) => new ColorFunction("xyz-d50" , ...self.#toXyzd50(), self.alpha),
        ["xyz-d65" ]: (self) => new ColorFunction("xyz-d65" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
    };
    #toXyzd50() {
        return ColorConverter.labToXyzd50(this.l, this.a, this.b);
    }
    #getRGBArray(withAlpha = true) {
        const params = ColorConverter.xyzd50ToSrgb(...this.#toXyzd50());
        if (withAlpha) {
            return [...params, this.alpha ?? undefined];
        }
        return params;
    }
    constructor(l, a, b, alpha, authoredText) {
        this.#rawParams = [l, a, b];
        this.l = clamp(l, { min: 0, max: 100 });
        if (equals(this.l, 0, WIDE_RANGE_EPSILON) || equals(this.l, 100, WIDE_RANGE_EPSILON)) {
            a = b = 0;
        }
        this.a = a;
        this.b = b;
        this.alpha = clamp(alpha, { min: 0, max: 1 });
        this.#authoredText = authoredText;
    }
    is(format) {
        return format === this.format();
    }
    as(format) {
        return Lab.#conversions[format](this);
    }
    asLegacyColor() {
        return this.as("rgba" );
    }
    equal(color) {
        const lab = color.as("lab" );
        return equals(lab.l, this.l, WIDE_RANGE_EPSILON) && equals(lab.a, this.a) && equals(lab.b, this.b) &&
            equals(lab.alpha, this.alpha);
    }
    format() {
        return "lab" ;
    }
    setAlpha(alpha) {
        return new Lab(this.l, this.a, this.b, alpha, undefined);
    }
    asString(format) {
        if (format) {
            return this.as(format).asString();
        }
        return this.#stringify(this.l, this.a, this.b);
    }
    #stringify(l, a, b) {
        const alpha = this.alpha === null || equals(this.alpha, 1) ?
            '' :
            ` / ${stringifyWithPrecision(this.alpha)}`;
        return `lab(${stringifyWithPrecision(l, 0)} ${stringifyWithPrecision(a)} ${stringifyWithPrecision(b)}${alpha})`;
    }
    getAuthoredText() {
        return this.#authoredText ?? null;
    }
    getRawParameters() {
        return [...this.#rawParams];
    }
    getAsRawString(format) {
        if (format) {
            return this.as(format).getAsRawString();
        }
        return this.#stringify(...this.#rawParams);
    }
    isGamutClipped() {
        return false;
    }
    static fromSpec(spec, text) {
        const L = parsePercentage(spec[0], [0, 100]) ?? parseNumber(spec[0]);
        if (L === null) {
            return null;
        }
        const a = parsePercentage(spec[1], [0, 125]) ?? parseNumber(spec[1]);
        if (a === null) {
            return null;
        }
        const b = parsePercentage(spec[2], [0, 125]) ?? parseNumber(spec[2]);
        if (b === null) {
            return null;
        }
        const alpha = parseAlpha(spec[3]);
        return new Lab(L, a, b, alpha, text);
    }
}
class LCH {
    #rawParams;
    l;
    c;
    h;
    alpha;
    #authoredText;
    channels = ["l" , "c" , "h" , "alpha" ];
    static #conversions = {
        ["hex" ]: (self) => new Legacy(self.#getRGBArray( false), "hex" ),
        ["hexa" ]: (self) => new Legacy(self.#getRGBArray( true), "hexa" ),
        ["rgb" ]: (self) => new Legacy(self.#getRGBArray( false), "rgb" ),
        ["rgba" ]: (self) => new Legacy(self.#getRGBArray( true), "rgba" ),
        ["hsl" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hsla" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hwb" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["hwba" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["lch" ]: (self) => self,
        ["oklch" ]: (self) => new Oklch(...ColorConverter.xyzd50ToOklch(...self.#toXyzd50()), self.alpha),
        ["lab" ]: (self) => new Lab(...ColorConverter.lchToLab(self.l, self.c, self.h), self.alpha),
        ["oklab" ]: (self) => new Oklab(...ColorConverter.xyzd65ToOklab(...ColorConverter.xyzd50ToD65(...self.#toXyzd50())), self.alpha),
        ["srgb" ]: (self) => new ColorFunction("srgb" , ...ColorConverter.xyzd50ToSrgb(...self.#toXyzd50()), self.alpha),
        ["srgb-linear" ]: (self) => new ColorFunction("srgb-linear" , ...ColorConverter.xyzd50TosRGBLinear(...self.#toXyzd50()), self.alpha),
        ["display-p3" ]: (self) => new ColorFunction("display-p3" , ...ColorConverter.xyzd50ToDisplayP3(...self.#toXyzd50()), self.alpha),
        ["a98-rgb" ]: (self) => new ColorFunction("a98-rgb" , ...ColorConverter.xyzd50ToAdobeRGB(...self.#toXyzd50()), self.alpha),
        ["prophoto-rgb" ]: (self) => new ColorFunction("prophoto-rgb" , ...ColorConverter.xyzd50ToProPhoto(...self.#toXyzd50()), self.alpha),
        ["rec2020" ]: (self) => new ColorFunction("rec2020" , ...ColorConverter.xyzd50ToRec2020(...self.#toXyzd50()), self.alpha),
        ["xyz" ]: (self) => new ColorFunction("xyz" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
        ["xyz-d50" ]: (self) => new ColorFunction("xyz-d50" , ...self.#toXyzd50(), self.alpha),
        ["xyz-d65" ]: (self) => new ColorFunction("xyz-d65" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
    };
    #toXyzd50() {
        return ColorConverter.labToXyzd50(...ColorConverter.lchToLab(this.l, this.c, this.h));
    }
    #getRGBArray(withAlpha = true) {
        const params = ColorConverter.xyzd50ToSrgb(...this.#toXyzd50());
        if (withAlpha) {
            return [...params, this.alpha ?? undefined];
        }
        return params;
    }
    constructor(l, c, h, alpha, authoredText) {
        this.#rawParams = [l, c, h];
        this.l = clamp(l, { min: 0, max: 100 });
        c = equals(this.l, 0, WIDE_RANGE_EPSILON) || equals(this.l, 100, WIDE_RANGE_EPSILON) ? 0 : c;
        this.c = clamp(c, { min: 0 });
        h = equals(c, 0) ? 0 : h;
        this.h = normalizeHue(h);
        this.alpha = clamp(alpha, { min: 0, max: 1 });
        this.#authoredText = authoredText;
    }
    asLegacyColor() {
        return this.as("rgba" );
    }
    is(format) {
        return format === this.format();
    }
    as(format) {
        return LCH.#conversions[format](this);
    }
    equal(color) {
        const lch = color.as("lch" );
        return equals(lch.l, this.l, WIDE_RANGE_EPSILON) && equals(lch.c, this.c) && equals(lch.h, this.h) &&
            equals(lch.alpha, this.alpha);
    }
    format() {
        return "lch" ;
    }
    setAlpha(alpha) {
        return new LCH(this.l, this.c, this.h, alpha);
    }
    asString(format) {
        if (format) {
            return this.as(format).asString();
        }
        return this.#stringify(this.l, this.c, this.h);
    }
    #stringify(l, c, h) {
        const alpha = this.alpha === null || equals(this.alpha, 1) ?
            '' :
            ` / ${stringifyWithPrecision(this.alpha)}`;
        return `lch(${stringifyWithPrecision(l, 0)} ${stringifyWithPrecision(c)} ${stringifyWithPrecision(h)}${alpha})`;
    }
    getAuthoredText() {
        return this.#authoredText ?? null;
    }
    getRawParameters() {
        return [...this.#rawParams];
    }
    getAsRawString(format) {
        if (format) {
            return this.as(format).getAsRawString();
        }
        return this.#stringify(...this.#rawParams);
    }
    isGamutClipped() {
        return false;
    }
    isHuePowerless() {
        return equals(this.c, 0);
    }
    static fromSpec(spec, text) {
        const L = parsePercentage(spec[0], [0, 100]) ?? parseNumber(spec[0]);
        if (L === null) {
            return null;
        }
        const c = parsePercentage(spec[1], [0, 150]) ?? parseNumber(spec[1]);
        if (c === null) {
            return null;
        }
        const h = parseAngle(spec[2]);
        if (h === null) {
            return null;
        }
        const alpha = parseAlpha(spec[3]);
        return new LCH(L, c, h, alpha, text);
    }
}
class Oklab {
    #rawParams;
    l;
    a;
    b;
    alpha;
    #authoredText;
    channels = ["l" , "a" , "b" , "alpha" ];
    static #conversions = {
        ["hex" ]: (self) => new Legacy(self.#getRGBArray( false), "hex" ),
        ["hexa" ]: (self) => new Legacy(self.#getRGBArray( true), "hexa" ),
        ["rgb" ]: (self) => new Legacy(self.#getRGBArray( false), "rgb" ),
        ["rgba" ]: (self) => new Legacy(self.#getRGBArray( true), "rgba" ),
        ["hsl" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hsla" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hwb" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["hwba" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["lch" ]: (self) => new LCH(...ColorConverter.labToLch(...ColorConverter.xyzd50ToLab(...self.#toXyzd50())), self.alpha),
        ["oklch" ]: (self) => new Oklch(...ColorConverter.xyzd50ToOklch(...self.#toXyzd50()), self.alpha),
        ["lab" ]: (self) => new Lab(...ColorConverter.xyzd50ToLab(...self.#toXyzd50()), self.alpha),
        ["oklab" ]: (self) => self,
        ["srgb" ]: (self) => new ColorFunction("srgb" , ...ColorConverter.xyzd50ToSrgb(...self.#toXyzd50()), self.alpha),
        ["srgb-linear" ]: (self) => new ColorFunction("srgb-linear" , ...ColorConverter.xyzd50TosRGBLinear(...self.#toXyzd50()), self.alpha),
        ["display-p3" ]: (self) => new ColorFunction("display-p3" , ...ColorConverter.xyzd50ToDisplayP3(...self.#toXyzd50()), self.alpha),
        ["a98-rgb" ]: (self) => new ColorFunction("a98-rgb" , ...ColorConverter.xyzd50ToAdobeRGB(...self.#toXyzd50()), self.alpha),
        ["prophoto-rgb" ]: (self) => new ColorFunction("prophoto-rgb" , ...ColorConverter.xyzd50ToProPhoto(...self.#toXyzd50()), self.alpha),
        ["rec2020" ]: (self) => new ColorFunction("rec2020" , ...ColorConverter.xyzd50ToRec2020(...self.#toXyzd50()), self.alpha),
        ["xyz" ]: (self) => new ColorFunction("xyz" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
        ["xyz-d50" ]: (self) => new ColorFunction("xyz-d50" , ...self.#toXyzd50(), self.alpha),
        ["xyz-d65" ]: (self) => new ColorFunction("xyz-d65" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
    };
    #toXyzd50() {
        return ColorConverter.xyzd65ToD50(...ColorConverter.oklabToXyzd65(this.l, this.a, this.b));
    }
    #getRGBArray(withAlpha = true) {
        const params = ColorConverter.xyzd50ToSrgb(...this.#toXyzd50());
        if (withAlpha) {
            return [...params, this.alpha ?? undefined];
        }
        return params;
    }
    constructor(l, a, b, alpha, authoredText) {
        this.#rawParams = [l, a, b];
        this.l = clamp(l, { min: 0, max: 1 });
        if (equals(this.l, 0) || equals(this.l, 1)) {
            a = b = 0;
        }
        this.a = a;
        this.b = b;
        this.alpha = clamp(alpha, { min: 0, max: 1 });
        this.#authoredText = authoredText;
    }
    asLegacyColor() {
        return this.as("rgba" );
    }
    is(format) {
        return format === this.format();
    }
    as(format) {
        return Oklab.#conversions[format](this);
    }
    equal(color) {
        const oklab = color.as("oklab" );
        return equals(oklab.l, this.l) && equals(oklab.a, this.a) && equals(oklab.b, this.b) &&
            equals(oklab.alpha, this.alpha);
    }
    format() {
        return "oklab" ;
    }
    setAlpha(alpha) {
        return new Oklab(this.l, this.a, this.b, alpha);
    }
    asString(format) {
        if (format) {
            return this.as(format).asString();
        }
        return this.#stringify(this.l, this.a, this.b);
    }
    #stringify(l, a, b) {
        const alpha = this.alpha === null || equals(this.alpha, 1) ?
            '' :
            ` / ${stringifyWithPrecision(this.alpha)}`;
        return `oklab(${stringifyWithPrecision(l)} ${stringifyWithPrecision(a)} ${stringifyWithPrecision(b)}${alpha})`;
    }
    getAuthoredText() {
        return this.#authoredText ?? null;
    }
    getRawParameters() {
        return [...this.#rawParams];
    }
    getAsRawString(format) {
        if (format) {
            return this.as(format).getAsRawString();
        }
        return this.#stringify(...this.#rawParams);
    }
    isGamutClipped() {
        return false;
    }
    static fromSpec(spec, text) {
        const L = parsePercentage(spec[0], [0, 1]) ?? parseNumber(spec[0]);
        if (L === null) {
            return null;
        }
        const a = parsePercentage(spec[1], [0, 0.4]) ?? parseNumber(spec[1]);
        if (a === null) {
            return null;
        }
        const b = parsePercentage(spec[2], [0, 0.4]) ?? parseNumber(spec[2]);
        if (b === null) {
            return null;
        }
        const alpha = parseAlpha(spec[3]);
        return new Oklab(L, a, b, alpha, text);
    }
}
class Oklch {
    #rawParams;
    l;
    c;
    h;
    alpha;
    #authoredText;
    channels = ["l" , "c" , "h" , "alpha" ];
    static #conversions = {
        ["hex" ]: (self) => new Legacy(self.#getRGBArray( false), "hex" ),
        ["hexa" ]: (self) => new Legacy(self.#getRGBArray( true), "hexa" ),
        ["rgb" ]: (self) => new Legacy(self.#getRGBArray( false), "rgb" ),
        ["rgba" ]: (self) => new Legacy(self.#getRGBArray( true), "rgba" ),
        ["hsl" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hsla" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hwb" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["hwba" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["lch" ]: (self) => new LCH(...ColorConverter.labToLch(...ColorConverter.xyzd50ToLab(...self.#toXyzd50())), self.alpha),
        ["oklch" ]: (self) => self,
        ["lab" ]: (self) => new Lab(...ColorConverter.xyzd50ToLab(...self.#toXyzd50()), self.alpha),
        ["oklab" ]: (self) => new Oklab(...ColorConverter.xyzd65ToOklab(...ColorConverter.xyzd50ToD65(...self.#toXyzd50())), self.alpha),
        ["srgb" ]: (self) => new ColorFunction("srgb" , ...ColorConverter.xyzd50ToSrgb(...self.#toXyzd50()), self.alpha),
        ["srgb-linear" ]: (self) => new ColorFunction("srgb-linear" , ...ColorConverter.xyzd50TosRGBLinear(...self.#toXyzd50()), self.alpha),
        ["display-p3" ]: (self) => new ColorFunction("display-p3" , ...ColorConverter.xyzd50ToDisplayP3(...self.#toXyzd50()), self.alpha),
        ["a98-rgb" ]: (self) => new ColorFunction("a98-rgb" , ...ColorConverter.xyzd50ToAdobeRGB(...self.#toXyzd50()), self.alpha),
        ["prophoto-rgb" ]: (self) => new ColorFunction("prophoto-rgb" , ...ColorConverter.xyzd50ToProPhoto(...self.#toXyzd50()), self.alpha),
        ["rec2020" ]: (self) => new ColorFunction("rec2020" , ...ColorConverter.xyzd50ToRec2020(...self.#toXyzd50()), self.alpha),
        ["xyz" ]: (self) => new ColorFunction("xyz" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
        ["xyz-d50" ]: (self) => new ColorFunction("xyz-d50" , ...self.#toXyzd50(), self.alpha),
        ["xyz-d65" ]: (self) => new ColorFunction("xyz-d65" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
    };
    #toXyzd50() {
        return ColorConverter.oklchToXyzd50(this.l, this.c, this.h);
    }
    #getRGBArray(withAlpha = true) {
        const params = ColorConverter.xyzd50ToSrgb(...this.#toXyzd50());
        if (withAlpha) {
            return [...params, this.alpha ?? undefined];
        }
        return params;
    }
    constructor(l, c, h, alpha, authoredText) {
        this.#rawParams = [l, c, h];
        this.l = clamp(l, { min: 0, max: 1 });
        c = equals(this.l, 0) || equals(this.l, 1) ? 0 : c;
        this.c = clamp(c, { min: 0 });
        h = equals(c, 0) ? 0 : h;
        this.h = normalizeHue(h);
        this.alpha = clamp(alpha, { min: 0, max: 1 });
        this.#authoredText = authoredText;
    }
    asLegacyColor() {
        return this.as("rgba" );
    }
    is(format) {
        return format === this.format();
    }
    as(format) {
        return Oklch.#conversions[format](this);
    }
    equal(color) {
        const oklch = color.as("oklch" );
        return equals(oklch.l, this.l) && equals(oklch.c, this.c) && equals(oklch.h, this.h) &&
            equals(oklch.alpha, this.alpha);
    }
    format() {
        return "oklch" ;
    }
    setAlpha(alpha) {
        return new Oklch(this.l, this.c, this.h, alpha);
    }
    asString(format) {
        if (format) {
            return this.as(format).asString();
        }
        return this.#stringify(this.l, this.c, this.h);
    }
    #stringify(l, c, h) {
        const alpha = this.alpha === null || equals(this.alpha, 1) ?
            '' :
            ` / ${stringifyWithPrecision(this.alpha)}`;
        return `oklch(${stringifyWithPrecision(l)} ${stringifyWithPrecision(c)} ${stringifyWithPrecision(h)}${alpha})`;
    }
    getAuthoredText() {
        return this.#authoredText ?? null;
    }
    getRawParameters() {
        return [...this.#rawParams];
    }
    getAsRawString(format) {
        if (format) {
            return this.as(format).getAsRawString();
        }
        return this.#stringify(...this.#rawParams);
    }
    isGamutClipped() {
        return false;
    }
    static fromSpec(spec, text) {
        const L = parsePercentage(spec[0], [0, 1]) ?? parseNumber(spec[0]);
        if (L === null) {
            return null;
        }
        const c = parsePercentage(spec[1], [0, 0.4]) ?? parseNumber(spec[1]);
        if (c === null) {
            return null;
        }
        const h = parseAngle(spec[2]);
        if (h === null) {
            return null;
        }
        const alpha = parseAlpha(spec[3]);
        return new Oklch(L, c, h, alpha, text);
    }
}
class ColorFunction {
    #rawParams;
    p0;
    p1;
    p2;
    alpha;
    colorSpace;
    #authoredText;
    get channels() {
        return this.isXYZ() ? ["x" , "y" , "z" , "alpha" ] :
            ["r" , "g" , "b" , "alpha" ];
    }
    static #conversions = {
        ["hex" ]: (self) => new Legacy(self.#getRGBArray( false), "hex" ),
        ["hexa" ]: (self) => new Legacy(self.#getRGBArray( true), "hexa" ),
        ["rgb" ]: (self) => new Legacy(self.#getRGBArray( false), "rgb" ),
        ["rgba" ]: (self) => new Legacy(self.#getRGBArray( true), "rgba" ),
        ["hsl" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hsla" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hwb" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["hwba" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["lch" ]: (self) => new LCH(...ColorConverter.labToLch(...ColorConverter.xyzd50ToLab(...self.#toXyzd50())), self.alpha),
        ["oklch" ]: (self) => new Oklch(...ColorConverter.xyzd50ToOklch(...self.#toXyzd50()), self.alpha),
        ["lab" ]: (self) => new Lab(...ColorConverter.xyzd50ToLab(...self.#toXyzd50()), self.alpha),
        ["oklab" ]: (self) => new Oklab(...ColorConverter.xyzd65ToOklab(...ColorConverter.xyzd50ToD65(...self.#toXyzd50())), self.alpha),
        ["srgb" ]: (self) => new ColorFunction("srgb" , ...ColorConverter.xyzd50ToSrgb(...self.#toXyzd50()), self.alpha),
        ["srgb-linear" ]: (self) => new ColorFunction("srgb-linear" , ...ColorConverter.xyzd50TosRGBLinear(...self.#toXyzd50()), self.alpha),
        ["display-p3" ]: (self) => new ColorFunction("display-p3" , ...ColorConverter.xyzd50ToDisplayP3(...self.#toXyzd50()), self.alpha),
        ["a98-rgb" ]: (self) => new ColorFunction("a98-rgb" , ...ColorConverter.xyzd50ToAdobeRGB(...self.#toXyzd50()), self.alpha),
        ["prophoto-rgb" ]: (self) => new ColorFunction("prophoto-rgb" , ...ColorConverter.xyzd50ToProPhoto(...self.#toXyzd50()), self.alpha),
        ["rec2020" ]: (self) => new ColorFunction("rec2020" , ...ColorConverter.xyzd50ToRec2020(...self.#toXyzd50()), self.alpha),
        ["xyz" ]: (self) => new ColorFunction("xyz" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
        ["xyz-d50" ]: (self) => new ColorFunction("xyz-d50" , ...self.#toXyzd50(), self.alpha),
        ["xyz-d65" ]: (self) => new ColorFunction("xyz-d65" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
    };
    #toXyzd50() {
        const [p0, p1, p2] = this.#rawParams;
        switch (this.colorSpace) {
            case "srgb" :
                return ColorConverter.srgbToXyzd50(p0, p1, p2);
            case "srgb-linear" :
                return ColorConverter.srgbLinearToXyzd50(p0, p1, p2);
            case "display-p3" :
                return ColorConverter.displayP3ToXyzd50(p0, p1, p2);
            case "a98-rgb" :
                return ColorConverter.adobeRGBToXyzd50(p0, p1, p2);
            case "prophoto-rgb" :
                return ColorConverter.proPhotoToXyzd50(p0, p1, p2);
            case "rec2020" :
                return ColorConverter.rec2020ToXyzd50(p0, p1, p2);
            case "xyz-d50" :
                return [p0, p1, p2];
            case "xyz" :
            case "xyz-d65" :
                return ColorConverter.xyzd65ToD50(p0, p1, p2);
        }
        throw new Error('Invalid color space');
    }
    #getRGBArray(withAlpha = true) {
        const [p0, p1, p2] = this.#rawParams;
        const params = this.colorSpace === "srgb"  ? [p0, p1, p2] : [...ColorConverter.xyzd50ToSrgb(...this.#toXyzd50())];
        if (withAlpha) {
            return [...params, this.alpha ?? undefined];
        }
        return params;
    }
    constructor(colorSpace, p0, p1, p2, alpha, authoredText) {
        this.#rawParams = [p0, p1, p2];
        this.colorSpace = colorSpace;
        this.#authoredText = authoredText;
        if (this.colorSpace !== "xyz-d50"  && this.colorSpace !== "xyz-d65"  && this.colorSpace !== "xyz" ) {
            p0 = clamp(p0, { min: 0, max: 1 });
            p1 = clamp(p1, { min: 0, max: 1 });
            p2 = clamp(p2, { min: 0, max: 1 });
        }
        this.p0 = p0;
        this.p1 = p1;
        this.p2 = p2;
        this.alpha = clamp(alpha, { min: 0, max: 1 });
    }
    asLegacyColor() {
        return this.as("rgba" );
    }
    is(format) {
        return format === this.format();
    }
    as(format) {
        if (this.colorSpace === format) {
            return this;
        }
        return ColorFunction.#conversions[format](this);
    }
    equal(color) {
        const space = color.as(this.colorSpace);
        return equals(this.p0, space.p0) && equals(this.p1, space.p1) && equals(this.p2, space.p2) &&
            equals(this.alpha, space.alpha);
    }
    format() {
        return this.colorSpace;
    }
    setAlpha(alpha) {
        return new ColorFunction(this.colorSpace, this.p0, this.p1, this.p2, alpha);
    }
    asString(format) {
        if (format) {
            return this.as(format).asString();
        }
        return this.#stringify(this.p0, this.p1, this.p2);
    }
    #stringify(p0, p1, p2) {
        const alpha = this.alpha === null || equals(this.alpha, 1) ?
            '' :
            ` / ${stringifyWithPrecision(this.alpha)}`;
        return `color(${this.colorSpace} ${stringifyWithPrecision(p0)} ${stringifyWithPrecision(p1)} ${stringifyWithPrecision(p2)}${alpha})`;
    }
    getAuthoredText() {
        return this.#authoredText ?? null;
    }
    getRawParameters() {
        return [...this.#rawParams];
    }
    getAsRawString(format) {
        if (format) {
            return this.as(format).getAsRawString();
        }
        return this.#stringify(...this.#rawParams);
    }
    isGamutClipped() {
        if (this.colorSpace !== "xyz-d50"  && this.colorSpace !== "xyz-d65"  && this.colorSpace !== "xyz" ) {
            return !equals(this.#rawParams, [this.p0, this.p1, this.p2]);
        }
        return false;
    }
    isXYZ() {
        switch (this.colorSpace) {
            case "xyz" :
            case "xyz-d50" :
            case "xyz-d65" :
                return true;
        }
        return false;
    }
    static fromSpec(authoredText, parametersWithAlphaText) {
        const [parametersText, alphaText] = parametersWithAlphaText.split('/', 2);
        const parameters = parametersText.trim().split(/\s+/);
        const [colorSpaceText, ...remainingParams] = parameters;
        const colorSpace = getColorSpace(colorSpaceText);
        if (!colorSpace) {
            return null;
        }
        if (remainingParams.length === 0 && alphaText === undefined) {
            return new ColorFunction(colorSpace, 0, 0, 0, null, authoredText);
        }
        if (remainingParams.length === 0 && alphaText !== undefined && alphaText.trim().split(/\s+/).length > 1) {
            return null;
        }
        if (remainingParams.length > 3) {
            return null;
        }
        const nonesReplacedParams = remainingParams.map(param => param === 'none' ? '0' : param);
        const values = nonesReplacedParams.map(param => parsePercentOrNumber(param, [0, 1]));
        const containsNull = values.includes(null);
        if (containsNull) {
            return null;
        }
        const alphaValue = alphaText ? parsePercentOrNumber(alphaText, [0, 1]) ?? 1 : 1;
        const rgbOrXyza = [
            values[0] ?? 0,
            values[1] ?? 0,
            values[2] ?? 0,
            alphaValue,
        ];
        return new ColorFunction(colorSpace, ...rgbOrXyza, authoredText);
    }
}
class HSL {
    h;
    s;
    l;
    alpha;
    #rawParams;
    #authoredText;
    channels = ["h" , "s" , "l" , "alpha" ];
    static #conversions = {
        ["hex" ]: (self) => new Legacy(self.#getRGBArray( false), "hex" ),
        ["hexa" ]: (self) => new Legacy(self.#getRGBArray( true), "hexa" ),
        ["rgb" ]: (self) => new Legacy(self.#getRGBArray( false), "rgb" ),
        ["rgba" ]: (self) => new Legacy(self.#getRGBArray( true), "rgba" ),
        ["hsl" ]: (self) => self,
        ["hsla" ]: (self) => self,
        ["hwb" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["hwba" ]: (self) => new HWB(...rgbToHwb(self.#getRGBArray( false)), self.alpha),
        ["lch" ]: (self) => new LCH(...ColorConverter.labToLch(...ColorConverter.xyzd50ToLab(...self.#toXyzd50())), self.alpha),
        ["oklch" ]: (self) => new Oklch(...ColorConverter.xyzd50ToOklch(...self.#toXyzd50()), self.alpha),
        ["lab" ]: (self) => new Lab(...ColorConverter.xyzd50ToLab(...self.#toXyzd50()), self.alpha),
        ["oklab" ]: (self) => new Oklab(...ColorConverter.xyzd65ToOklab(...ColorConverter.xyzd50ToD65(...self.#toXyzd50())), self.alpha),
        ["srgb" ]: (self) => new ColorFunction("srgb" , ...ColorConverter.xyzd50ToSrgb(...self.#toXyzd50()), self.alpha),
        ["srgb-linear" ]: (self) => new ColorFunction("srgb-linear" , ...ColorConverter.xyzd50TosRGBLinear(...self.#toXyzd50()), self.alpha),
        ["display-p3" ]: (self) => new ColorFunction("display-p3" , ...ColorConverter.xyzd50ToDisplayP3(...self.#toXyzd50()), self.alpha),
        ["a98-rgb" ]: (self) => new ColorFunction("a98-rgb" , ...ColorConverter.xyzd50ToAdobeRGB(...self.#toXyzd50()), self.alpha),
        ["prophoto-rgb" ]: (self) => new ColorFunction("prophoto-rgb" , ...ColorConverter.xyzd50ToProPhoto(...self.#toXyzd50()), self.alpha),
        ["rec2020" ]: (self) => new ColorFunction("rec2020" , ...ColorConverter.xyzd50ToRec2020(...self.#toXyzd50()), self.alpha),
        ["xyz" ]: (self) => new ColorFunction("xyz" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
        ["xyz-d50" ]: (self) => new ColorFunction("xyz-d50" , ...self.#toXyzd50(), self.alpha),
        ["xyz-d65" ]: (self) => new ColorFunction("xyz-d65" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
    };
    #getRGBArray(withAlpha = true) {
        const rgb = hsl2rgb([this.h, this.s, this.l, 0]);
        if (withAlpha) {
            return [rgb[0], rgb[1], rgb[2], this.alpha ?? undefined];
        }
        return [rgb[0], rgb[1], rgb[2]];
    }
    #toXyzd50() {
        const rgb = this.#getRGBArray(false);
        return ColorConverter.srgbToXyzd50(rgb[0], rgb[1], rgb[2]);
    }
    constructor(h, s, l, alpha, authoredText) {
        this.#rawParams = [h, s, l];
        this.l = clamp(l, { min: 0, max: 1 });
        s = equals(this.l, 0) || equals(this.l, 1) ? 0 : s;
        this.s = clamp(s, { min: 0, max: 1 });
        h = equals(this.s, 0) ? 0 : h;
        this.h = normalizeHue(h * 360) / 360;
        this.alpha = clamp(alpha ?? null, { min: 0, max: 1 });
        this.#authoredText = authoredText;
    }
    equal(color) {
        const hsl = color.as("hsl" );
        return equals(this.h, hsl.h) && equals(this.s, hsl.s) && equals(this.l, hsl.l) && equals(this.alpha, hsl.alpha);
    }
    asString(format) {
        if (format) {
            return this.as(format).asString();
        }
        return this.#stringify(this.h, this.s, this.l);
    }
    #stringify(h, s, l) {
        const start = sprintf('hsl(%sdeg %s% %s%', stringifyWithPrecision(h * 360), stringifyWithPrecision(s * 100), stringifyWithPrecision(l * 100));
        if (this.alpha !== null && this.alpha !== 1) {
            return start +
                sprintf(' / %s%)', stringifyWithPrecision(this.alpha * 100));
        }
        return start + ')';
    }
    setAlpha(alpha) {
        return new HSL(this.h, this.s, this.l, alpha);
    }
    format() {
        return this.alpha === null || this.alpha === 1 ? "hsl"  : "hsla" ;
    }
    is(format) {
        return format === this.format();
    }
    as(format) {
        if (format === this.format()) {
            return this;
        }
        return HSL.#conversions[format](this);
    }
    asLegacyColor() {
        return this.as("rgba" );
    }
    getAuthoredText() {
        return this.#authoredText ?? null;
    }
    getRawParameters() {
        return [...this.#rawParams];
    }
    getAsRawString(format) {
        if (format) {
            return this.as(format).getAsRawString();
        }
        return this.#stringify(...this.#rawParams);
    }
    isGamutClipped() {
        return !lessOrEquals(this.#rawParams[1], 1) || !lessOrEquals(0, this.#rawParams[1]);
    }
    static fromSpec(spec, text) {
        const h = parseHueNumeric(spec[0]);
        if (h === null) {
            return null;
        }
        const s = parseSatLightNumeric(spec[1]);
        if (s === null) {
            return null;
        }
        const l = parseSatLightNumeric(spec[2]);
        if (l === null) {
            return null;
        }
        const alpha = parseAlpha(spec[3]);
        return new HSL(h, s, l, alpha, text);
    }
    hsva() {
        const s = this.s * (this.l < 0.5 ? this.l : 1 - this.l);
        return [this.h, s !== 0 ? 2 * s / (this.l + s) : 0, (this.l + s), this.alpha ?? 1];
    }
    canonicalHSLA() {
        return [Math.round(this.h * 360), Math.round(this.s * 100), Math.round(this.l * 100), this.alpha ?? 1];
    }
}
class HWB {
    h;
    w;
    b;
    alpha;
    #rawParams;
    #authoredText;
    channels = ["h" , "w" , "b" , "alpha" ];
    static #conversions = {
        ["hex" ]: (self) => new Legacy(self.#getRGBArray( false), "hex" ),
        ["hexa" ]: (self) => new Legacy(self.#getRGBArray( true), "hexa" ),
        ["rgb" ]: (self) => new Legacy(self.#getRGBArray( false), "rgb" ),
        ["rgba" ]: (self) => new Legacy(self.#getRGBArray( true), "rgba" ),
        ["hsl" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hsla" ]: (self) => new HSL(...rgbToHsl(self.#getRGBArray( false)), self.alpha),
        ["hwb" ]: (self) => self,
        ["hwba" ]: (self) => self,
        ["lch" ]: (self) => new LCH(...ColorConverter.labToLch(...ColorConverter.xyzd50ToLab(...self.#toXyzd50())), self.alpha),
        ["oklch" ]: (self) => new Oklch(...ColorConverter.xyzd50ToOklch(...self.#toXyzd50()), self.alpha),
        ["lab" ]: (self) => new Lab(...ColorConverter.xyzd50ToLab(...self.#toXyzd50()), self.alpha),
        ["oklab" ]: (self) => new Oklab(...ColorConverter.xyzd65ToOklab(...ColorConverter.xyzd50ToD65(...self.#toXyzd50())), self.alpha),
        ["srgb" ]: (self) => new ColorFunction("srgb" , ...ColorConverter.xyzd50ToSrgb(...self.#toXyzd50()), self.alpha),
        ["srgb-linear" ]: (self) => new ColorFunction("srgb-linear" , ...ColorConverter.xyzd50TosRGBLinear(...self.#toXyzd50()), self.alpha),
        ["display-p3" ]: (self) => new ColorFunction("display-p3" , ...ColorConverter.xyzd50ToDisplayP3(...self.#toXyzd50()), self.alpha),
        ["a98-rgb" ]: (self) => new ColorFunction("a98-rgb" , ...ColorConverter.xyzd50ToAdobeRGB(...self.#toXyzd50()), self.alpha),
        ["prophoto-rgb" ]: (self) => new ColorFunction("prophoto-rgb" , ...ColorConverter.xyzd50ToProPhoto(...self.#toXyzd50()), self.alpha),
        ["rec2020" ]: (self) => new ColorFunction("rec2020" , ...ColorConverter.xyzd50ToRec2020(...self.#toXyzd50()), self.alpha),
        ["xyz" ]: (self) => new ColorFunction("xyz" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
        ["xyz-d50" ]: (self) => new ColorFunction("xyz-d50" , ...self.#toXyzd50(), self.alpha),
        ["xyz-d65" ]: (self) => new ColorFunction("xyz-d65" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
    };
    #getRGBArray(withAlpha = true) {
        const rgb = hwb2rgb([this.h, this.w, this.b, 0]);
        if (withAlpha) {
            return [rgb[0], rgb[1], rgb[2], this.alpha ?? undefined];
        }
        return [rgb[0], rgb[1], rgb[2]];
    }
    #toXyzd50() {
        const rgb = this.#getRGBArray(false);
        return ColorConverter.srgbToXyzd50(rgb[0], rgb[1], rgb[2]);
    }
    constructor(h, w, b, alpha, authoredText) {
        this.#rawParams = [h, w, b];
        this.w = clamp(w, { min: 0, max: 1 });
        this.b = clamp(b, { min: 0, max: 1 });
        h = lessOrEquals(1, this.w + this.b) ? 0 : h;
        this.h = normalizeHue(h * 360) / 360;
        this.alpha = clamp(alpha, { min: 0, max: 1 });
        if (lessOrEquals(1, this.w + this.b)) {
            const ratio = this.w / this.b;
            this.b = 1 / (1 + ratio);
            this.w = 1 - this.b;
        }
        this.#authoredText = authoredText;
    }
    equal(color) {
        const hwb = color.as("hwb" );
        return equals(this.h, hwb.h) && equals(this.w, hwb.w) && equals(this.b, hwb.b) && equals(this.alpha, hwb.alpha);
    }
    asString(format) {
        if (format) {
            return this.as(format).asString();
        }
        return this.#stringify(this.h, this.w, this.b);
    }
    #stringify(h, w, b) {
        const start = sprintf('hwb(%sdeg %s% %s%', stringifyWithPrecision(h * 360), stringifyWithPrecision(w * 100), stringifyWithPrecision(b * 100));
        if (this.alpha !== null && this.alpha !== 1) {
            return start +
                sprintf(' / %s%)', stringifyWithPrecision(this.alpha * 100));
        }
        return start + ')';
    }
    setAlpha(alpha) {
        return new HWB(this.h, this.w, this.b, alpha, this.#authoredText);
    }
    format() {
        return this.alpha !== null && !equals(this.alpha, 1) ? "hwba"  : "hwb" ;
    }
    is(format) {
        return format === this.format();
    }
    as(format) {
        if (format === this.format()) {
            return this;
        }
        return HWB.#conversions[format](this);
    }
    asLegacyColor() {
        return this.as("rgba" );
    }
    getAuthoredText() {
        return this.#authoredText ?? null;
    }
    canonicalHWBA() {
        return [
            Math.round(this.h * 360),
            Math.round(this.w * 100),
            Math.round(this.b * 100),
            this.alpha ?? 1,
        ];
    }
    getRawParameters() {
        return [...this.#rawParams];
    }
    getAsRawString(format) {
        if (format) {
            return this.as(format).getAsRawString();
        }
        return this.#stringify(...this.#rawParams);
    }
    isGamutClipped() {
        return !lessOrEquals(this.#rawParams[1], 1) || !lessOrEquals(0, this.#rawParams[1]) ||
            !lessOrEquals(this.#rawParams[2], 1) || !lessOrEquals(0, this.#rawParams[2]);
    }
    static fromSpec(spec, text) {
        const h = parseHueNumeric(spec[0]);
        if (h === null) {
            return null;
        }
        const w = parseSatLightNumeric(spec[1]);
        if (w === null) {
            return null;
        }
        const b = parseSatLightNumeric(spec[2]);
        if (b === null) {
            return null;
        }
        const alpha = parseAlpha(spec[3]);
        return new HWB(h, w, b, alpha, text);
    }
}
function toRgbValue(value) {
    return Math.round(value * 255);
}
class ShortFormatColorBase {
    color;
    channels = ["r" , "g" , "b" , "alpha" ];
    constructor(color) {
        this.color = color;
    }
    get alpha() {
        return this.color.alpha;
    }
    rgba() {
        return this.color.rgba();
    }
    equal(color) {
        return this.color.equal(color);
    }
    setAlpha(alpha) {
        return this.color.setAlpha(alpha);
    }
    format() {
        return (this.alpha ?? 1) !== 1 ? "hexa"  : "hex" ;
    }
    as(format) {
        return this.color.as(format);
    }
    is(format) {
        return this.color.is(format);
    }
    asLegacyColor() {
        return this.color.asLegacyColor();
    }
    getAuthoredText() {
        return this.color.getAuthoredText();
    }
    getRawParameters() {
        return this.color.getRawParameters();
    }
    isGamutClipped() {
        return this.color.isGamutClipped();
    }
    asString(format) {
        if (format) {
            return this.as(format).asString();
        }
        const [r, g, b] = this.color.rgba();
        return this.stringify(r, g, b);
    }
    getAsRawString(format) {
        if (format) {
            return this.as(format).getAsRawString();
        }
        const [r, g, b] = this.getRawParameters();
        return this.stringify(r, g, b);
    }
}
class ShortHex extends ShortFormatColorBase {
    setAlpha(alpha) {
        return new ShortHex(this.color.setAlpha(alpha));
    }
    asString(format) {
        return format && format !== this.format() ? super.as(format).asString() : super.asString();
    }
    stringify(r, g, b) {
        function toShortHexValue(value) {
            return (Math.round(value * 255) / 17).toString(16);
        }
        if (this.color.hasAlpha()) {
            return sprintf('#%s%s%s%s', toShortHexValue(r), toShortHexValue(g), toShortHexValue(b), toShortHexValue(this.alpha ?? 1))
                .toLowerCase();
        }
        return sprintf('#%s%s%s', toShortHexValue(r), toShortHexValue(g), toShortHexValue(b))
            .toLowerCase();
    }
}
class Nickname extends ShortFormatColorBase {
    nickname;
    constructor(nickname, color) {
        super(color);
        this.nickname = nickname;
    }
    static fromName(name, text) {
        const nickname = name.toLowerCase();
        const rgba = Nicknames.get(nickname);
        if (rgba !== undefined) {
            return new Nickname(nickname, Legacy.fromRGBA(rgba, text));
        }
        return null;
    }
    stringify() {
        return this.nickname;
    }
    getAsRawString(format) {
        return this.color.getAsRawString(format);
    }
}
class Legacy {
    #rawParams;
    #rgba;
    #authoredText;
    #format;
    channels = ["r" , "g" , "b" , "alpha" ];
    static #conversions = {
        ["hex" ]: (self) => new Legacy(self.#rgba, "hex" ),
        ["hexa" ]: (self) => new Legacy(self.#rgba, "hexa" ),
        ["rgb" ]: (self) => new Legacy(self.#rgba, "rgb" ),
        ["rgba" ]: (self) => new Legacy(self.#rgba, "rgba" ),
        ["hsl" ]: (self) => new HSL(...rgbToHsl([self.#rgba[0], self.#rgba[1], self.#rgba[2]]), self.alpha),
        ["hsla" ]: (self) => new HSL(...rgbToHsl([self.#rgba[0], self.#rgba[1], self.#rgba[2]]), self.alpha),
        ["hwb" ]: (self) => new HWB(...rgbToHwb([self.#rgba[0], self.#rgba[1], self.#rgba[2]]), self.alpha),
        ["hwba" ]: (self) => new HWB(...rgbToHwb([self.#rgba[0], self.#rgba[1], self.#rgba[2]]), self.alpha),
        ["lch" ]: (self) => new LCH(...ColorConverter.labToLch(...ColorConverter.xyzd50ToLab(...self.#toXyzd50())), self.alpha),
        ["oklch" ]: (self) => new Oklch(...ColorConverter.xyzd50ToOklch(...self.#toXyzd50()), self.alpha),
        ["lab" ]: (self) => new Lab(...ColorConverter.xyzd50ToLab(...self.#toXyzd50()), self.alpha),
        ["oklab" ]: (self) => new Oklab(...ColorConverter.xyzd65ToOklab(...ColorConverter.xyzd50ToD65(...self.#toXyzd50())), self.alpha),
        ["srgb" ]: (self) => new ColorFunction("srgb" , ...ColorConverter.xyzd50ToSrgb(...self.#toXyzd50()), self.alpha),
        ["srgb-linear" ]: (self) => new ColorFunction("srgb-linear" , ...ColorConverter.xyzd50TosRGBLinear(...self.#toXyzd50()), self.alpha),
        ["display-p3" ]: (self) => new ColorFunction("display-p3" , ...ColorConverter.xyzd50ToDisplayP3(...self.#toXyzd50()), self.alpha),
        ["a98-rgb" ]: (self) => new ColorFunction("a98-rgb" , ...ColorConverter.xyzd50ToAdobeRGB(...self.#toXyzd50()), self.alpha),
        ["prophoto-rgb" ]: (self) => new ColorFunction("prophoto-rgb" , ...ColorConverter.xyzd50ToProPhoto(...self.#toXyzd50()), self.alpha),
        ["rec2020" ]: (self) => new ColorFunction("rec2020" , ...ColorConverter.xyzd50ToRec2020(...self.#toXyzd50()), self.alpha),
        ["xyz" ]: (self) => new ColorFunction("xyz" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
        ["xyz-d50" ]: (self) => new ColorFunction("xyz-d50" , ...self.#toXyzd50(), self.alpha),
        ["xyz-d65" ]: (self) => new ColorFunction("xyz-d65" , ...ColorConverter.xyzd50ToD65(...self.#toXyzd50()), self.alpha),
    };
    #toXyzd50() {
        const [r, g, b] = this.#rgba;
        return ColorConverter.srgbToXyzd50(r, g, b);
    }
    get alpha() {
        switch (this.format()) {
            case "hexa" :
            case "rgba" :
                return this.#rgba[3];
            default:
                return null;
        }
    }
    asLegacyColor() {
        return this;
    }
    nickname() {
        const nickname = RGBAToNickname.get(String(this.canonicalRGBA()));
        return nickname ? new Nickname(nickname, this) : null;
    }
    shortHex() {
        for (let i = 0; i < 4; ++i) {
            const c = Math.round(this.#rgba[i] * 255);
            if (c % 0x11) {
                return null;
            }
        }
        return new ShortHex(this);
    }
    constructor(rgba, format, authoredText) {
        this.#authoredText = authoredText || null;
        this.#format = format;
        this.#rawParams = [rgba[0], rgba[1], rgba[2]];
        this.#rgba = [
            clamp(rgba[0], { min: 0, max: 1 }),
            clamp(rgba[1], { min: 0, max: 1 }),
            clamp(rgba[2], { min: 0, max: 1 }),
            clamp(rgba[3] ?? 1, { min: 0, max: 1 }),
        ];
    }
    static fromHex(hex, text) {
        hex = hex.toLowerCase();
        const hasAlpha = hex.length === 4 || hex.length === 8;
        const format = hasAlpha ? "hexa"  : "hex" ;
        const isShort = hex.length <= 4;
        if (isShort) {
            hex = hex.charAt(0) + hex.charAt(0) + hex.charAt(1) + hex.charAt(1) + hex.charAt(2) + hex.charAt(2) +
                hex.charAt(3) + hex.charAt(3);
        }
        const r = parseInt(hex.substring(0, 2), 16);
        const g = parseInt(hex.substring(2, 4), 16);
        const b = parseInt(hex.substring(4, 6), 16);
        let a = 1;
        if (hex.length === 8) {
            a = parseInt(hex.substring(6, 8), 16) / 255;
        }
        const color = new Legacy([r / 255, g / 255, b / 255, a], format, text);
        return isShort ? new ShortHex(color) : color;
    }
    static fromRGBAFunction(r, g, b, alpha, text) {
        const rgba = [
            parseRgbNumeric(r),
            parseRgbNumeric(g),
            parseRgbNumeric(b),
            alpha ? parseAlphaNumeric(alpha) : 1,
        ];
        if (!arrayDoesNotContainNullOrUndefined(rgba)) {
            return null;
        }
        return new Legacy(rgba, alpha ? "rgba"  : "rgb" , text);
    }
    static fromRGBA(rgba, authoredText) {
        return new Legacy([rgba[0] / 255, rgba[1] / 255, rgba[2] / 255, rgba[3]], "rgba" , authoredText);
    }
    static fromHSVA(hsva) {
        const rgba = hsva2rgba(hsva);
        return new Legacy(rgba, "rgba" );
    }
    is(format) {
        return format === this.format();
    }
    as(format) {
        if (format === this.format()) {
            return this;
        }
        return Legacy.#conversions[format](this);
    }
    format() {
        return this.#format;
    }
    hasAlpha() {
        return this.#rgba[3] !== 1;
    }
    detectHEXFormat() {
        const hasAlpha = this.hasAlpha();
        return hasAlpha ? "hexa"  : "hex" ;
    }
    asString(format) {
        if (format) {
            return this.as(format).asString();
        }
        return this.#stringify(format, this.#rgba[0], this.#rgba[1], this.#rgba[2]);
    }
    #stringify(format, r, g, b) {
        if (!format) {
            format = this.#format;
        }
        function toHexValue(value) {
            const hex = Math.round(value * 255).toString(16);
            return hex.length === 1 ? '0' + hex : hex;
        }
        switch (format) {
            case "rgb" :
            case "rgba" : {
                const start = sprintf('rgb(%d %d %d', toRgbValue(r), toRgbValue(g), toRgbValue(b));
                if (this.hasAlpha()) {
                    return start + sprintf(' / %d%)', Math.round(this.#rgba[3] * 100));
                }
                return start + ')';
            }
            case "hex" :
            case "hexa" : {
                if (this.hasAlpha()) {
                    return sprintf('#%s%s%s%s', toHexValue(r), toHexValue(g), toHexValue(b), toHexValue(this.#rgba[3]))
                        .toLowerCase();
                }
                return sprintf('#%s%s%s', toHexValue(r), toHexValue(g), toHexValue(b)).toLowerCase();
            }
        }
    }
    getAuthoredText() {
        return this.#authoredText ?? null;
    }
    getRawParameters() {
        return [...this.#rawParams];
    }
    getAsRawString(format) {
        if (format) {
            return this.as(format).getAsRawString();
        }
        return this.#stringify(format, ...this.#rawParams);
    }
    isGamutClipped() {
        return !equals(this.#rawParams.map(toRgbValue), [this.#rgba[0], this.#rgba[1], this.#rgba[2]].map(toRgbValue), WIDE_RANGE_EPSILON);
    }
    rgba() {
        return [...this.#rgba];
    }
    canonicalRGBA() {
        const rgba = new Array(4);
        for (let i = 0; i < 3; ++i) {
            rgba[i] = Math.round(this.#rgba[i] * 255);
        }
        rgba[3] = this.#rgba[3];
        return rgba;
    }
    toProtocolRGBA() {
        const rgba = this.canonicalRGBA();
        const result = { r: rgba[0], g: rgba[1], b: rgba[2] };
        if (rgba[3] !== 1) {
            result.a = rgba[3];
        }
        return result;
    }
    invert() {
        const rgba = [0, 0, 0, 0];
        rgba[0] = 1 - this.#rgba[0];
        rgba[1] = 1 - this.#rgba[1];
        rgba[2] = 1 - this.#rgba[2];
        rgba[3] = this.#rgba[3];
        return new Legacy(rgba, "rgba" );
    }
    grayscale() {
        const [r, g, b] = this.#rgba;
        const gray = r * 0.299 + g * 0.587 + b * 0.114;
        return new Legacy([gray, gray, gray, 0.5], "rgba" );
    }
    setAlpha(alpha) {
        const rgba = [...this.#rgba];
        rgba[3] = alpha;
        return new Legacy(rgba, "rgba" );
    }
    blendWith(fgColor) {
        const rgba = blendColors(fgColor.#rgba, this.#rgba);
        return new Legacy(rgba, "rgba" );
    }
    blendWithAlpha(alpha) {
        const rgba = [...this.#rgba];
        rgba[3] *= alpha;
        return new Legacy(rgba, "rgba" );
    }
    setFormat(format) {
        this.#format = format;
    }
    equal(other) {
        const legacy = other.as(this.#format);
        return equals(toRgbValue(this.#rgba[0]), toRgbValue(legacy.#rgba[0]), WIDE_RANGE_EPSILON) &&
            equals(toRgbValue(this.#rgba[1]), toRgbValue(legacy.#rgba[1]), WIDE_RANGE_EPSILON) &&
            equals(toRgbValue(this.#rgba[2]), toRgbValue(legacy.#rgba[2]), WIDE_RANGE_EPSILON) &&
            equals(this.#rgba[3], legacy.#rgba[3]);
    }
}
const Regex = /((?:rgba?|hsla?|hwba?|lab|lch|oklab|oklch|color)\([^)]+\)|#[0-9a-fA-F]{8}|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,4}|\b[a-zA-Z]+\b(?!-))/g;
const ColorMixRegex = /color-mix\(.*,\s*(?<firstColor>.+)\s*,\s*(?<secondColor>.+)\s*\)/g;
const COLOR_TO_RGBA_ENTRIES = [
    ['aliceblue', [240, 248, 255]],
    ['antiquewhite', [250, 235, 215]],
    ['aqua', [0, 255, 255]],
    ['aquamarine', [127, 255, 212]],
    ['azure', [240, 255, 255]],
    ['beige', [245, 245, 220]],
    ['bisque', [255, 228, 196]],
    ['black', [0, 0, 0]],
    ['blanchedalmond', [255, 235, 205]],
    ['blue', [0, 0, 255]],
    ['blueviolet', [138, 43, 226]],
    ['brown', [165, 42, 42]],
    ['burlywood', [222, 184, 135]],
    ['cadetblue', [95, 158, 160]],
    ['chartreuse', [127, 255, 0]],
    ['chocolate', [210, 105, 30]],
    ['coral', [255, 127, 80]],
    ['cornflowerblue', [100, 149, 237]],
    ['cornsilk', [255, 248, 220]],
    ['crimson', [237, 20, 61]],
    ['cyan', [0, 255, 255]],
    ['darkblue', [0, 0, 139]],
    ['darkcyan', [0, 139, 139]],
    ['darkgoldenrod', [184, 134, 11]],
    ['darkgray', [169, 169, 169]],
    ['darkgrey', [169, 169, 169]],
    ['darkgreen', [0, 100, 0]],
    ['darkkhaki', [189, 183, 107]],
    ['darkmagenta', [139, 0, 139]],
    ['darkolivegreen', [85, 107, 47]],
    ['darkorange', [255, 140, 0]],
    ['darkorchid', [153, 50, 204]],
    ['darkred', [139, 0, 0]],
    ['darksalmon', [233, 150, 122]],
    ['darkseagreen', [143, 188, 143]],
    ['darkslateblue', [72, 61, 139]],
    ['darkslategray', [47, 79, 79]],
    ['darkslategrey', [47, 79, 79]],
    ['darkturquoise', [0, 206, 209]],
    ['darkviolet', [148, 0, 211]],
    ['deeppink', [255, 20, 147]],
    ['deepskyblue', [0, 191, 255]],
    ['dimgray', [105, 105, 105]],
    ['dimgrey', [105, 105, 105]],
    ['dodgerblue', [30, 144, 255]],
    ['firebrick', [178, 34, 34]],
    ['floralwhite', [255, 250, 240]],
    ['forestgreen', [34, 139, 34]],
    ['fuchsia', [255, 0, 255]],
    ['gainsboro', [220, 220, 220]],
    ['ghostwhite', [248, 248, 255]],
    ['gold', [255, 215, 0]],
    ['goldenrod', [218, 165, 32]],
    ['gray', [128, 128, 128]],
    ['grey', [128, 128, 128]],
    ['green', [0, 128, 0]],
    ['greenyellow', [173, 255, 47]],
    ['honeydew', [240, 255, 240]],
    ['hotpink', [255, 105, 180]],
    ['indianred', [205, 92, 92]],
    ['indigo', [75, 0, 130]],
    ['ivory', [255, 255, 240]],
    ['khaki', [240, 230, 140]],
    ['lavender', [230, 230, 250]],
    ['lavenderblush', [255, 240, 245]],
    ['lawngreen', [124, 252, 0]],
    ['lemonchiffon', [255, 250, 205]],
    ['lightblue', [173, 216, 230]],
    ['lightcoral', [240, 128, 128]],
    ['lightcyan', [224, 255, 255]],
    ['lightgoldenrodyellow', [250, 250, 210]],
    ['lightgreen', [144, 238, 144]],
    ['lightgray', [211, 211, 211]],
    ['lightgrey', [211, 211, 211]],
    ['lightpink', [255, 182, 193]],
    ['lightsalmon', [255, 160, 122]],
    ['lightseagreen', [32, 178, 170]],
    ['lightskyblue', [135, 206, 250]],
    ['lightslategray', [119, 136, 153]],
    ['lightslategrey', [119, 136, 153]],
    ['lightsteelblue', [176, 196, 222]],
    ['lightyellow', [255, 255, 224]],
    ['lime', [0, 255, 0]],
    ['limegreen', [50, 205, 50]],
    ['linen', [250, 240, 230]],
    ['magenta', [255, 0, 255]],
    ['maroon', [128, 0, 0]],
    ['mediumaquamarine', [102, 205, 170]],
    ['mediumblue', [0, 0, 205]],
    ['mediumorchid', [186, 85, 211]],
    ['mediumpurple', [147, 112, 219]],
    ['mediumseagreen', [60, 179, 113]],
    ['mediumslateblue', [123, 104, 238]],
    ['mediumspringgreen', [0, 250, 154]],
    ['mediumturquoise', [72, 209, 204]],
    ['mediumvioletred', [199, 21, 133]],
    ['midnightblue', [25, 25, 112]],
    ['mintcream', [245, 255, 250]],
    ['mistyrose', [255, 228, 225]],
    ['moccasin', [255, 228, 181]],
    ['navajowhite', [255, 222, 173]],
    ['navy', [0, 0, 128]],
    ['oldlace', [253, 245, 230]],
    ['olive', [128, 128, 0]],
    ['olivedrab', [107, 142, 35]],
    ['orange', [255, 165, 0]],
    ['orangered', [255, 69, 0]],
    ['orchid', [218, 112, 214]],
    ['palegoldenrod', [238, 232, 170]],
    ['palegreen', [152, 251, 152]],
    ['paleturquoise', [175, 238, 238]],
    ['palevioletred', [219, 112, 147]],
    ['papayawhip', [255, 239, 213]],
    ['peachpuff', [255, 218, 185]],
    ['peru', [205, 133, 63]],
    ['pink', [255, 192, 203]],
    ['plum', [221, 160, 221]],
    ['powderblue', [176, 224, 230]],
    ['purple', [128, 0, 128]],
    ['rebeccapurple', [102, 51, 153]],
    ['red', [255, 0, 0]],
    ['rosybrown', [188, 143, 143]],
    ['royalblue', [65, 105, 225]],
    ['saddlebrown', [139, 69, 19]],
    ['salmon', [250, 128, 114]],
    ['sandybrown', [244, 164, 96]],
    ['seagreen', [46, 139, 87]],
    ['seashell', [255, 245, 238]],
    ['sienna', [160, 82, 45]],
    ['silver', [192, 192, 192]],
    ['skyblue', [135, 206, 235]],
    ['slateblue', [106, 90, 205]],
    ['slategray', [112, 128, 144]],
    ['slategrey', [112, 128, 144]],
    ['snow', [255, 250, 250]],
    ['springgreen', [0, 255, 127]],
    ['steelblue', [70, 130, 180]],
    ['tan', [210, 180, 140]],
    ['teal', [0, 128, 128]],
    ['thistle', [216, 191, 216]],
    ['tomato', [255, 99, 71]],
    ['turquoise', [64, 224, 208]],
    ['violet', [238, 130, 238]],
    ['wheat', [245, 222, 179]],
    ['white', [255, 255, 255]],
    ['whitesmoke', [245, 245, 245]],
    ['yellow', [255, 255, 0]],
    ['yellowgreen', [154, 205, 50]],
    ['transparent', [0, 0, 0, 0]],
];
console.assert(COLOR_TO_RGBA_ENTRIES.every(([nickname]) => nickname.toLowerCase() === nickname), 'All color nicknames must be lowercase.');
const Nicknames = new Map(COLOR_TO_RGBA_ENTRIES);
const RGBAToNickname = new Map(
COLOR_TO_RGBA_ENTRIES.map(([nickname, [r, g, b, a = 1]]) => {
    return [String([r, g, b, a]), nickname];
}));
const LAYOUT_LINES_HIGHLIGHT_COLOR = [127, 32, 210];
const PageHighlight = {
    Content: Legacy.fromRGBA([111, 168, 220, .66]),
    ContentLight: Legacy.fromRGBA([111, 168, 220, .5]),
    ContentOutline: Legacy.fromRGBA([9, 83, 148]),
    Padding: Legacy.fromRGBA([147, 196, 125, .55]),
    PaddingLight: Legacy.fromRGBA([147, 196, 125, .4]),
    Border: Legacy.fromRGBA([255, 229, 153, .66]),
    BorderLight: Legacy.fromRGBA([255, 229, 153, .5]),
    Margin: Legacy.fromRGBA([246, 178, 107, .66]),
    MarginLight: Legacy.fromRGBA([246, 178, 107, .5]),
    EventTarget: Legacy.fromRGBA([255, 196, 196, .66]),
    Shape: Legacy.fromRGBA([96, 82, 177, 0.8]),
    ShapeMargin: Legacy.fromRGBA([96, 82, 127, .6]),
    CssGrid: Legacy.fromRGBA([0x4b, 0, 0x82, 1]),
    LayoutLine: Legacy.fromRGBA([...LAYOUT_LINES_HIGHLIGHT_COLOR, 1]),
    GridBorder: Legacy.fromRGBA([...LAYOUT_LINES_HIGHLIGHT_COLOR, 1]),
    GapBackground: Legacy.fromRGBA([...LAYOUT_LINES_HIGHLIGHT_COLOR, .3]),
    GapHatch: Legacy.fromRGBA([...LAYOUT_LINES_HIGHLIGHT_COLOR, .8]),
    GridAreaBorder: Legacy.fromRGBA([26, 115, 232, 1]),
};
const SourceOrderHighlight = {
    ParentOutline: Legacy.fromRGBA([224, 90, 183, 1]),
    ChildOutline: Legacy.fromRGBA([0, 120, 212, 1]),
};
const IsolationModeHighlight = {
    Resizer: Legacy.fromRGBA([222, 225, 230, 1]),
    ResizerHandle: Legacy.fromRGBA([166, 166, 166, 1]),
    Mask: Legacy.fromRGBA([248, 249, 249, 1]),
};
class Generator {
    #hueSpace;
    #satSpace;
    #lightnessSpace;
    #alphaSpace;
    #colors = new Map();
    constructor(hueSpace, satSpace, lightnessSpace, alphaSpace) {
        this.#hueSpace = hueSpace || { min: 0, max: 360 };
        this.#satSpace = satSpace || 67;
        this.#lightnessSpace = lightnessSpace || 80;
        this.#alphaSpace = alphaSpace || 1;
    }
    setColorForID(id, color) {
        this.#colors.set(id, color);
    }
    colorForID(id) {
        let color = this.#colors.get(id);
        if (!color) {
            color = this.generateColorForID(id);
            this.#colors.set(id, color);
        }
        return color;
    }
    generateColorForID(id) {
        const hash = hashCode(id);
        const h = this.indexToValueInSpace(hash, this.#hueSpace);
        const s = this.indexToValueInSpace(hash >> 8, this.#satSpace);
        const l = this.indexToValueInSpace(hash >> 16, this.#lightnessSpace);
        const a = this.indexToValueInSpace(hash >> 24, this.#alphaSpace);
        const start = `hsl(${h}deg ${s}% ${l}%`;
        if (a !== 1) {
            return `${start} / ${Math.floor(a * 100)}%)`;
        }
        return `${start})`;
    }
    indexToValueInSpace(index, space) {
        if (typeof space === 'number') {
            return space;
        }
        const count = space.count || space.max - space.min;
        index %= count;
        return space.min + Math.floor(index / (count - 1) * (space.max - space.min));
    }
}

var Color = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ColorFunction: ColorFunction,
	ColorMixRegex: ColorMixRegex,
	Generator: Generator,
	HSL: HSL,
	HWB: HWB,
	IsolationModeHighlight: IsolationModeHighlight,
	LCH: LCH,
	Lab: Lab,
	Legacy: Legacy,
	Nickname: Nickname,
	Nicknames: Nicknames,
	Oklab: Oklab,
	Oklch: Oklch,
	PageHighlight: PageHighlight,
	Regex: Regex,
	ShortHex: ShortHex,
	SourceOrderHighlight: SourceOrderHighlight,
	approachColorValue: approachColorValue,
	desiredLuminance: desiredLuminance,
	findFgColorForContrast: findFgColorForContrast,
	findFgColorForContrastAPCA: findFgColorForContrastAPCA,
	getFormat: getFormat,
	hsl2rgb: hsl2rgb,
	hsva2rgba: hsva2rgba,
	parse: parse$2,
	parseHueNumeric: parseHueNumeric,
	rgb2hsv: rgb2hsv
});

// Copyright 2021 The Chromium Authors
class ObjectWrapper {
    listeners;
    addEventListener(eventType, listener, thisObject) {
        if (!this.listeners) {
            this.listeners = new Map();
        }
        let listenersForEventType = this.listeners.get(eventType);
        if (!listenersForEventType) {
            listenersForEventType = new Set();
            this.listeners.set(eventType, listenersForEventType);
        }
        listenersForEventType.add({ thisObject, listener });
        return { eventTarget: this, eventType, thisObject, listener };
    }
    once(eventType) {
        return new Promise(resolve => {
            const descriptor = this.addEventListener(eventType, event => {
                this.removeEventListener(eventType, descriptor.listener);
                resolve(event.data);
            });
        });
    }
    removeEventListener(eventType, listener, thisObject) {
        const listeners = this.listeners?.get(eventType);
        if (!listeners) {
            return;
        }
        for (const listenerTuple of listeners) {
            if (listenerTuple.listener === listener && listenerTuple.thisObject === thisObject) {
                listenerTuple.disposed = true;
                listeners.delete(listenerTuple);
            }
        }
        if (!listeners.size) {
            this.listeners?.delete(eventType);
        }
    }
    hasEventListeners(eventType) {
        return Boolean(this.listeners?.has(eventType));
    }
    dispatchEventToListeners(eventType, ...[eventData]) {
        const listeners = this.listeners?.get(eventType);
        if (!listeners) {
            return;
        }
        const event = { data: eventData, source: this };
        for (const listener of [...listeners]) {
            if (!listener.disposed) {
                try {
                    listener.listener.call(listener.thisObject, event);
                }
                catch (err) {
                    console.error(`Event listener for ${String(eventType)} throw an error:`, err);
                }
            }
        }
    }
}
function eventMixin(base) {
    console.assert(base !== HTMLElement);
    return class EventHandling extends base {
        #events = new ObjectWrapper();
        addEventListener(eventType, listener, thisObject) {
            return this.#events.addEventListener(eventType, listener, thisObject);
        }
        once(eventType) {
            return this.#events.once(eventType);
        }
        removeEventListener(eventType, listener, thisObject) {
            this.#events.removeEventListener(eventType, listener, thisObject);
        }
        hasEventListeners(eventType) {
            return this.#events.hasEventListeners(eventType);
        }
        dispatchEventToListeners(eventType, ...eventData) {
            this.#events.dispatchEventToListeners(eventType, ...eventData);
        }
    };
}

var Object$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ObjectWrapper: ObjectWrapper,
	eventMixin: eventMixin
});

// Copyright 2021 The Chromium Authors
let devToolsLocaleInstance = null;
class DevToolsLocale {
    locale;
    lookupClosestDevToolsLocale;
    constructor(data) {
        this.lookupClosestDevToolsLocale = data.lookupClosestDevToolsLocale;
        if (data.settingLanguage === 'browserLanguage') {
            this.locale = data.navigatorLanguage || 'en-US';
        }
        else {
            this.locale = data.settingLanguage;
        }
        this.locale = this.lookupClosestDevToolsLocale(this.locale);
    }
    static instance(opts = { create: false }) {
        if (!devToolsLocaleInstance && !opts.create) {
            throw new Error('No LanguageSelector instance exists yet.');
        }
        if (opts.create) {
            devToolsLocaleInstance = new DevToolsLocale(opts.data);
        }
        return devToolsLocaleInstance;
    }
    static removeInstance() {
        devToolsLocaleInstance = null;
    }
    forceFallbackLocale() {
        this.locale = 'en-US';
    }
    languageIsSupportedByDevTools(localeString) {
        return localeLanguagesMatch(localeString, this.lookupClosestDevToolsLocale(localeString));
    }
}
function localeLanguagesMatch(localeString1, localeString2) {
    const locale1 = new Intl.Locale(localeString1);
    const locale2 = new Intl.Locale(localeString2);
    return locale1.language === locale2.language;
}

var DevToolsLocale$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	DevToolsLocale: DevToolsLocale,
	localeLanguagesMatch: localeLanguagesMatch
});

// Copyright 2024 The Chromium Authors
function defineFormatter(options) {
    let intlNumberFormat;
    return {
        format(value, separator) {
            if (!intlNumberFormat) {
                intlNumberFormat = new Intl.NumberFormat(DevToolsLocale.instance().locale, options);
            }
            return formatAndEnsureSpace$1(intlNumberFormat, value, separator);
        },
        formatToParts(value) {
            if (!intlNumberFormat) {
                intlNumberFormat = new Intl.NumberFormat(DevToolsLocale.instance().locale, options);
            }
            return intlNumberFormat.formatToParts(value);
        },
    };
}
function formatAndEnsureSpace$1(formatter, value, separator = '\xA0') {
    const parts = formatter.formatToParts(value);
    let hasSpace = false;
    for (const part of parts) {
        if (part.type === 'literal') {
            if (part.value === ' ') {
                hasSpace = true;
                part.value = separator;
            }
            else if (part.value === separator) {
                hasSpace = true;
            }
        }
    }
    if (hasSpace) {
        return parts.map(part => part.value).join('');
    }
    const unitIndex = parts.findIndex(part => part.type === 'unit');
    if (unitIndex === -1) {
        return parts.map(part => part.value).join('');
    }
    if (unitIndex === 0) {
        return parts[0].value + separator + parts.slice(1).map(part => part.value).join('');
    }
    return parts.slice(0, unitIndex).map(part => part.value).join('') + separator +
        parts.slice(unitIndex).map(part => part.value).join('');
}

var NumberFormatter = /*#__PURE__*/Object.freeze({
	__proto__: null,
	defineFormatter: defineFormatter
});

// Copyright 2024 The Chromium Authors
const narrowBytes = defineFormatter({
    style: 'unit',
    unit: 'byte',
    unitDisplay: 'narrow',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
});
const narrowKilobytesDecimal = defineFormatter({
    style: 'unit',
    unit: 'kilobyte',
    unitDisplay: 'narrow',
    minimumFractionDigits: 1,
    maximumFractionDigits: 1,
});
const narrowKilobytesInteger = defineFormatter({
    style: 'unit',
    unit: 'kilobyte',
    unitDisplay: 'narrow',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
});
const narrowMegabytesDecimal = defineFormatter({
    style: 'unit',
    unit: 'megabyte',
    unitDisplay: 'narrow',
    minimumFractionDigits: 1,
    maximumFractionDigits: 1,
});
const narrowMegabytesInteger = defineFormatter({
    style: 'unit',
    unit: 'megabyte',
    unitDisplay: 'narrow',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
});
const bytesToString = (bytes) => {
    if (bytes < 1000) {
        return narrowBytes.format(bytes);
    }
    const kilobytes = bytes / 1000;
    if (kilobytes < 100) {
        return narrowKilobytesDecimal.format(kilobytes);
    }
    if (kilobytes < 1000) {
        return narrowKilobytesInteger.format(kilobytes);
    }
    const megabytes = kilobytes / 1000;
    if (megabytes < 100) {
        return narrowMegabytesDecimal.format(megabytes);
    }
    return narrowMegabytesInteger.format(megabytes);
};
const formatBytesToKb = (bytes) => {
    const kilobytes = bytes / 1000;
    if (kilobytes < 100) {
        return narrowKilobytesDecimal.format(kilobytes);
    }
    return narrowKilobytesInteger.format(kilobytes);
};

var ByteUtilities = /*#__PURE__*/Object.freeze({
	__proto__: null,
	bytesToString: bytesToString,
	formatBytesToKb: formatBytesToKb
});

var __assign = function () {
    __assign = Object.assign || function __assign2(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s)
                if (Object.prototype.hasOwnProperty.call(s, p))
                    t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var ErrorKind;
(function (ErrorKind2) {
    ErrorKind2[ErrorKind2["EXPECT_ARGUMENT_CLOSING_BRACE"] = 1] = "EXPECT_ARGUMENT_CLOSING_BRACE";
    ErrorKind2[ErrorKind2["EMPTY_ARGUMENT"] = 2] = "EMPTY_ARGUMENT";
    ErrorKind2[ErrorKind2["MALFORMED_ARGUMENT"] = 3] = "MALFORMED_ARGUMENT";
    ErrorKind2[ErrorKind2["EXPECT_ARGUMENT_TYPE"] = 4] = "EXPECT_ARGUMENT_TYPE";
    ErrorKind2[ErrorKind2["INVALID_ARGUMENT_TYPE"] = 5] = "INVALID_ARGUMENT_TYPE";
    ErrorKind2[ErrorKind2["EXPECT_ARGUMENT_STYLE"] = 6] = "EXPECT_ARGUMENT_STYLE";
    ErrorKind2[ErrorKind2["INVALID_NUMBER_SKELETON"] = 7] = "INVALID_NUMBER_SKELETON";
    ErrorKind2[ErrorKind2["INVALID_DATE_TIME_SKELETON"] = 8] = "INVALID_DATE_TIME_SKELETON";
    ErrorKind2[ErrorKind2["EXPECT_NUMBER_SKELETON"] = 9] = "EXPECT_NUMBER_SKELETON";
    ErrorKind2[ErrorKind2["EXPECT_DATE_TIME_SKELETON"] = 10] = "EXPECT_DATE_TIME_SKELETON";
    ErrorKind2[ErrorKind2["UNCLOSED_QUOTE_IN_ARGUMENT_STYLE"] = 11] = "UNCLOSED_QUOTE_IN_ARGUMENT_STYLE";
    ErrorKind2[ErrorKind2["EXPECT_SELECT_ARGUMENT_OPTIONS"] = 12] = "EXPECT_SELECT_ARGUMENT_OPTIONS";
    ErrorKind2[ErrorKind2["EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE"] = 13] = "EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE";
    ErrorKind2[ErrorKind2["INVALID_PLURAL_ARGUMENT_OFFSET_VALUE"] = 14] = "INVALID_PLURAL_ARGUMENT_OFFSET_VALUE";
    ErrorKind2[ErrorKind2["EXPECT_SELECT_ARGUMENT_SELECTOR"] = 15] = "EXPECT_SELECT_ARGUMENT_SELECTOR";
    ErrorKind2[ErrorKind2["EXPECT_PLURAL_ARGUMENT_SELECTOR"] = 16] = "EXPECT_PLURAL_ARGUMENT_SELECTOR";
    ErrorKind2[ErrorKind2["EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT"] = 17] = "EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT";
    ErrorKind2[ErrorKind2["EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT"] = 18] = "EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT";
    ErrorKind2[ErrorKind2["INVALID_PLURAL_ARGUMENT_SELECTOR"] = 19] = "INVALID_PLURAL_ARGUMENT_SELECTOR";
    ErrorKind2[ErrorKind2["DUPLICATE_PLURAL_ARGUMENT_SELECTOR"] = 20] = "DUPLICATE_PLURAL_ARGUMENT_SELECTOR";
    ErrorKind2[ErrorKind2["DUPLICATE_SELECT_ARGUMENT_SELECTOR"] = 21] = "DUPLICATE_SELECT_ARGUMENT_SELECTOR";
    ErrorKind2[ErrorKind2["MISSING_OTHER_CLAUSE"] = 22] = "MISSING_OTHER_CLAUSE";
    ErrorKind2[ErrorKind2["INVALID_TAG"] = 23] = "INVALID_TAG";
    ErrorKind2[ErrorKind2["INVALID_TAG_NAME"] = 25] = "INVALID_TAG_NAME";
    ErrorKind2[ErrorKind2["UNMATCHED_CLOSING_TAG"] = 26] = "UNMATCHED_CLOSING_TAG";
    ErrorKind2[ErrorKind2["UNCLOSED_TAG"] = 27] = "UNCLOSED_TAG";
})(ErrorKind || (ErrorKind = {}));
var TYPE;
(function (TYPE2) {
    TYPE2[TYPE2["literal"] = 0] = "literal";
    TYPE2[TYPE2["argument"] = 1] = "argument";
    TYPE2[TYPE2["number"] = 2] = "number";
    TYPE2[TYPE2["date"] = 3] = "date";
    TYPE2[TYPE2["time"] = 4] = "time";
    TYPE2[TYPE2["select"] = 5] = "select";
    TYPE2[TYPE2["plural"] = 6] = "plural";
    TYPE2[TYPE2["pound"] = 7] = "pound";
    TYPE2[TYPE2["tag"] = 8] = "tag";
})(TYPE || (TYPE = {}));
var SKELETON_TYPE;
(function (SKELETON_TYPE2) {
    SKELETON_TYPE2[SKELETON_TYPE2["number"] = 0] = "number";
    SKELETON_TYPE2[SKELETON_TYPE2["dateTime"] = 1] = "dateTime";
})(SKELETON_TYPE || (SKELETON_TYPE = {}));
function isLiteralElement(el) {
    return el.type === TYPE.literal;
}
function isArgumentElement(el) {
    return el.type === TYPE.argument;
}
function isNumberElement(el) {
    return el.type === TYPE.number;
}
function isDateElement(el) {
    return el.type === TYPE.date;
}
function isTimeElement(el) {
    return el.type === TYPE.time;
}
function isSelectElement(el) {
    return el.type === TYPE.select;
}
function isPluralElement(el) {
    return el.type === TYPE.plural;
}
function isPoundElement(el) {
    return el.type === TYPE.pound;
}
function isTagElement(el) {
    return el.type === TYPE.tag;
}
function isNumberSkeleton(el) {
    return !!(el && typeof el === "object" && el.type === SKELETON_TYPE.number);
}
function isDateTimeSkeleton(el) {
    return !!(el && typeof el === "object" && el.type === SKELETON_TYPE.dateTime);
}
var SPACE_SEPARATOR_REGEX = /[ \xA0\u1680\u2000-\u200A\u202F\u205F\u3000]/;
var DATE_TIME_REGEX = /(?:[Eec]{1,6}|G{1,5}|[Qq]{1,5}|(?:[yYur]+|U{1,5})|[ML]{1,5}|d{1,2}|D{1,3}|F{1}|[abB]{1,5}|[hkHK]{1,2}|w{1,2}|W{1}|m{1,2}|s{1,2}|[zZOvVxX]{1,4})(?=([^']*'[^']*')*[^']*$)/g;
function parseDateTimeSkeleton(skeleton) {
    var result = {};
    skeleton.replace(DATE_TIME_REGEX, function (match) {
        var len = match.length;
        switch (match[0]) {
            case "G":
                result.era = len === 4 ? "long" : len === 5 ? "narrow" : "short";
                break;
            case "y":
                result.year = len === 2 ? "2-digit" : "numeric";
                break;
            case "Y":
            case "u":
            case "U":
            case "r":
                throw new RangeError("`Y/u/U/r` (year) patterns are not supported, use `y` instead");
            case "q":
            case "Q":
                throw new RangeError("`q/Q` (quarter) patterns are not supported");
            case "M":
            case "L":
                result.month = ["numeric", "2-digit", "short", "long", "narrow"][len - 1];
                break;
            case "w":
            case "W":
                throw new RangeError("`w/W` (week) patterns are not supported");
            case "d":
                result.day = ["numeric", "2-digit"][len - 1];
                break;
            case "D":
            case "F":
            case "g":
                throw new RangeError("`D/F/g` (day) patterns are not supported, use `d` instead");
            case "E":
                result.weekday = len === 4 ? "short" : len === 5 ? "narrow" : "short";
                break;
            case "e":
                if (len < 4) {
                    throw new RangeError("`e..eee` (weekday) patterns are not supported");
                }
                result.weekday = ["short", "long", "narrow", "short"][len - 4];
                break;
            case "c":
                if (len < 4) {
                    throw new RangeError("`c..ccc` (weekday) patterns are not supported");
                }
                result.weekday = ["short", "long", "narrow", "short"][len - 4];
                break;
            case "a":
                result.hour12 = true;
                break;
            case "b":
            case "B":
                throw new RangeError("`b/B` (period) patterns are not supported, use `a` instead");
            case "h":
                result.hourCycle = "h12";
                result.hour = ["numeric", "2-digit"][len - 1];
                break;
            case "H":
                result.hourCycle = "h23";
                result.hour = ["numeric", "2-digit"][len - 1];
                break;
            case "K":
                result.hourCycle = "h11";
                result.hour = ["numeric", "2-digit"][len - 1];
                break;
            case "k":
                result.hourCycle = "h24";
                result.hour = ["numeric", "2-digit"][len - 1];
                break;
            case "j":
            case "J":
            case "C":
                throw new RangeError("`j/J/C` (hour) patterns are not supported, use `h/H/K/k` instead");
            case "m":
                result.minute = ["numeric", "2-digit"][len - 1];
                break;
            case "s":
                result.second = ["numeric", "2-digit"][len - 1];
                break;
            case "S":
            case "A":
                throw new RangeError("`S/A` (second) patterns are not supported, use `s` instead");
            case "z":
                result.timeZoneName = len < 4 ? "short" : "long";
                break;
            case "Z":
            case "O":
            case "v":
            case "V":
            case "X":
            case "x":
                throw new RangeError("`Z/O/v/V/X/x` (timeZone) patterns are not supported, use `z` instead");
        }
        return "";
    });
    return result;
}
var WHITE_SPACE_REGEX = /[\t-\r \x85\u200E\u200F\u2028\u2029]/i;
function parseNumberSkeletonFromString(skeleton) {
    if (skeleton.length === 0) {
        throw new Error("Number skeleton cannot be empty");
    }
    var stringTokens = skeleton.split(WHITE_SPACE_REGEX).filter(function (x) {
        return x.length > 0;
    });
    var tokens = [];
    for (var _i = 0, stringTokens_1 = stringTokens; _i < stringTokens_1.length; _i++) {
        var stringToken = stringTokens_1[_i];
        var stemAndOptions = stringToken.split("/");
        if (stemAndOptions.length === 0) {
            throw new Error("Invalid number skeleton");
        }
        var stem = stemAndOptions[0], options = stemAndOptions.slice(1);
        for (var _a2 = 0, options_1 = options; _a2 < options_1.length; _a2++) {
            var option = options_1[_a2];
            if (option.length === 0) {
                throw new Error("Invalid number skeleton");
            }
        }
        tokens.push({ stem, options });
    }
    return tokens;
}
function icuUnitToEcma(unit) {
    return unit.replace(/^(.*?)-/, "");
}
var FRACTION_PRECISION_REGEX = /^\.(?:(0+)(\*)?|(#+)|(0+)(#+))$/g;
var SIGNIFICANT_PRECISION_REGEX = /^(@+)?(\+|#+)?$/g;
var INTEGER_WIDTH_REGEX = /(\*)(0+)|(#+)(0+)|(0+)/g;
var CONCISE_INTEGER_WIDTH_REGEX = /^(0+)$/;
function parseSignificantPrecision(str) {
    var result = {};
    str.replace(SIGNIFICANT_PRECISION_REGEX, function (_, g1, g2) {
        if (typeof g2 !== "string") {
            result.minimumSignificantDigits = g1.length;
            result.maximumSignificantDigits = g1.length;
        }
        else if (g2 === "+") {
            result.minimumSignificantDigits = g1.length;
        }
        else if (g1[0] === "#") {
            result.maximumSignificantDigits = g1.length;
        }
        else {
            result.minimumSignificantDigits = g1.length;
            result.maximumSignificantDigits = g1.length + (typeof g2 === "string" ? g2.length : 0);
        }
        return "";
    });
    return result;
}
function parseSign(str) {
    switch (str) {
        case "sign-auto":
            return {
                signDisplay: "auto"
            };
        case "sign-accounting":
        case "()":
            return {
                currencySign: "accounting"
            };
        case "sign-always":
        case "+!":
            return {
                signDisplay: "always"
            };
        case "sign-accounting-always":
        case "()!":
            return {
                signDisplay: "always",
                currencySign: "accounting"
            };
        case "sign-except-zero":
        case "+?":
            return {
                signDisplay: "exceptZero"
            };
        case "sign-accounting-except-zero":
        case "()?":
            return {
                signDisplay: "exceptZero",
                currencySign: "accounting"
            };
        case "sign-never":
        case "+_":
            return {
                signDisplay: "never"
            };
    }
}
function parseConciseScientificAndEngineeringStem(stem) {
    var result;
    if (stem[0] === "E" && stem[1] === "E") {
        result = {
            notation: "engineering"
        };
        stem = stem.slice(2);
    }
    else if (stem[0] === "E") {
        result = {
            notation: "scientific"
        };
        stem = stem.slice(1);
    }
    if (result) {
        var signDisplay = stem.slice(0, 2);
        if (signDisplay === "+!") {
            result.signDisplay = "always";
            stem = stem.slice(2);
        }
        else if (signDisplay === "+?") {
            result.signDisplay = "exceptZero";
            stem = stem.slice(2);
        }
        if (!CONCISE_INTEGER_WIDTH_REGEX.test(stem)) {
            throw new Error("Malformed concise eng/scientific notation");
        }
        result.minimumIntegerDigits = stem.length;
    }
    return result;
}
function parseNotationOptions(opt) {
    var result = {};
    var signOpts = parseSign(opt);
    if (signOpts) {
        return signOpts;
    }
    return result;
}
function parseNumberSkeleton(tokens) {
    var result = {};
    for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
        var token = tokens_1[_i];
        switch (token.stem) {
            case "percent":
            case "%":
                result.style = "percent";
                continue;
            case "%x100":
                result.style = "percent";
                result.scale = 100;
                continue;
            case "currency":
                result.style = "currency";
                result.currency = token.options[0];
                continue;
            case "group-off":
            case ",_":
                result.useGrouping = false;
                continue;
            case "precision-integer":
            case ".":
                result.maximumFractionDigits = 0;
                continue;
            case "measure-unit":
            case "unit":
                result.style = "unit";
                result.unit = icuUnitToEcma(token.options[0]);
                continue;
            case "compact-short":
            case "K":
                result.notation = "compact";
                result.compactDisplay = "short";
                continue;
            case "compact-long":
            case "KK":
                result.notation = "compact";
                result.compactDisplay = "long";
                continue;
            case "scientific":
                result = __assign(__assign(__assign({}, result), { notation: "scientific" }), token.options.reduce(function (all, opt) {
                    return __assign(__assign({}, all), parseNotationOptions(opt));
                }, {}));
                continue;
            case "engineering":
                result = __assign(__assign(__assign({}, result), { notation: "engineering" }), token.options.reduce(function (all, opt) {
                    return __assign(__assign({}, all), parseNotationOptions(opt));
                }, {}));
                continue;
            case "notation-simple":
                result.notation = "standard";
                continue;
            case "unit-width-narrow":
                result.currencyDisplay = "narrowSymbol";
                result.unitDisplay = "narrow";
                continue;
            case "unit-width-short":
                result.currencyDisplay = "code";
                result.unitDisplay = "short";
                continue;
            case "unit-width-full-name":
                result.currencyDisplay = "name";
                result.unitDisplay = "long";
                continue;
            case "unit-width-iso-code":
                result.currencyDisplay = "symbol";
                continue;
            case "scale":
                result.scale = parseFloat(token.options[0]);
                continue;
            case "integer-width":
                if (token.options.length > 1) {
                    throw new RangeError("integer-width stems only accept a single optional option");
                }
                token.options[0].replace(INTEGER_WIDTH_REGEX, function (_, g1, g2, g3, g4, g5) {
                    if (g1) {
                        result.minimumIntegerDigits = g2.length;
                    }
                    else if (g3 && g4) {
                        throw new Error("We currently do not support maximum integer digits");
                    }
                    else if (g5) {
                        throw new Error("We currently do not support exact integer digits");
                    }
                    return "";
                });
                continue;
        }
        if (CONCISE_INTEGER_WIDTH_REGEX.test(token.stem)) {
            result.minimumIntegerDigits = token.stem.length;
            continue;
        }
        if (FRACTION_PRECISION_REGEX.test(token.stem)) {
            if (token.options.length > 1) {
                throw new RangeError("Fraction-precision stems only accept a single optional option");
            }
            token.stem.replace(FRACTION_PRECISION_REGEX, function (_, g1, g2, g3, g4, g5) {
                if (g2 === "*") {
                    result.minimumFractionDigits = g1.length;
                }
                else if (g3 && g3[0] === "#") {
                    result.maximumFractionDigits = g3.length;
                }
                else if (g4 && g5) {
                    result.minimumFractionDigits = g4.length;
                    result.maximumFractionDigits = g4.length + g5.length;
                }
                else {
                    result.minimumFractionDigits = g1.length;
                    result.maximumFractionDigits = g1.length;
                }
                return "";
            });
            if (token.options.length) {
                result = __assign(__assign({}, result), parseSignificantPrecision(token.options[0]));
            }
            continue;
        }
        if (SIGNIFICANT_PRECISION_REGEX.test(token.stem)) {
            result = __assign(__assign({}, result), parseSignificantPrecision(token.stem));
            continue;
        }
        var signOpts = parseSign(token.stem);
        if (signOpts) {
            result = __assign(__assign({}, result), signOpts);
        }
        var conciseScientificAndEngineeringOpts = parseConciseScientificAndEngineeringStem(token.stem);
        if (conciseScientificAndEngineeringOpts) {
            result = __assign(__assign({}, result), conciseScientificAndEngineeringOpts);
        }
    }
    return result;
}
var _a$6;
var SPACE_SEPARATOR_START_REGEX = new RegExp("^" + SPACE_SEPARATOR_REGEX.source + "*");
var SPACE_SEPARATOR_END_REGEX = new RegExp(SPACE_SEPARATOR_REGEX.source + "*$");
function createLocation(start, end) {
    return { start, end };
}
var hasNativeStartsWith = !!String.prototype.startsWith;
var hasNativeFromCodePoint = !!String.fromCodePoint;
var hasNativeFromEntries = !!Object.fromEntries;
var hasNativeCodePointAt = !!String.prototype.codePointAt;
var hasTrimStart = !!String.prototype.trimStart;
var hasTrimEnd = !!String.prototype.trimEnd;
var hasNativeIsSafeInteger = !!Number.isSafeInteger;
var isSafeInteger = hasNativeIsSafeInteger ? Number.isSafeInteger : function (n) {
    return typeof n === "number" && isFinite(n) && Math.floor(n) === n && Math.abs(n) <= 9007199254740991;
};
var REGEX_SUPPORTS_U_AND_Y = true;
try {
    re = RE("([^\\p{White_Space}\\p{Pattern_Syntax}]*)", "yu");
    REGEX_SUPPORTS_U_AND_Y = ((_a$6 = re.exec("a")) === null || _a$6 === void 0 ? void 0 : _a$6[0]) === "a";
}
catch (_) {
    REGEX_SUPPORTS_U_AND_Y = false;
}
var re;
var startsWith = hasNativeStartsWith ? function startsWith2(s, search, position) {
    return s.startsWith(search, position);
} : function startsWith3(s, search, position) {
    return s.slice(position, position + search.length) === search;
};
var fromCodePoint = hasNativeFromCodePoint ? String.fromCodePoint : function fromCodePoint2() {
    var codePoints = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        codePoints[_i] = arguments[_i];
    }
    var elements = "";
    var length = codePoints.length;
    var i = 0;
    var code;
    while (length > i) {
        code = codePoints[i++];
        if (code > 1114111)
            throw RangeError(code + " is not a valid code point");
        elements += code < 65536 ? String.fromCharCode(code) : String.fromCharCode(((code -= 65536) >> 10) + 55296, code % 1024 + 56320);
    }
    return elements;
};
var fromEntries = hasNativeFromEntries ? Object.fromEntries : function fromEntries2(entries) {
    var obj = {};
    for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
        var _a2 = entries_1[_i], k = _a2[0], v = _a2[1];
        obj[k] = v;
    }
    return obj;
};
var codePointAt = hasNativeCodePointAt ? function codePointAt2(s, index) {
    return s.codePointAt(index);
} : function codePointAt3(s, index) {
    var size = s.length;
    if (index < 0 || index >= size) {
        return void 0;
    }
    var first = s.charCodeAt(index);
    var second;
    return first < 55296 || first > 56319 || index + 1 === size || (second = s.charCodeAt(index + 1)) < 56320 || second > 57343 ? first : (first - 55296 << 10) + (second - 56320) + 65536;
};
var trimStart = hasTrimStart ? function trimStart2(s) {
    return s.trimStart();
} : function trimStart3(s) {
    return s.replace(SPACE_SEPARATOR_START_REGEX, "");
};
var trimEnd = hasTrimEnd ? function trimEnd2(s) {
    return s.trimEnd();
} : function trimEnd3(s) {
    return s.replace(SPACE_SEPARATOR_END_REGEX, "");
};
function RE(s, flag) {
    return new RegExp(s, flag);
}
var matchIdentifierAtIndex;
if (REGEX_SUPPORTS_U_AND_Y) {
    IDENTIFIER_PREFIX_RE_1 = RE("([^\\p{White_Space}\\p{Pattern_Syntax}]*)", "yu");
    matchIdentifierAtIndex = function matchIdentifierAtIndex2(s, index) {
        var _a2;
        IDENTIFIER_PREFIX_RE_1.lastIndex = index;
        var match = IDENTIFIER_PREFIX_RE_1.exec(s);
        return (_a2 = match[1]) !== null && _a2 !== void 0 ? _a2 : "";
    };
}
else {
    matchIdentifierAtIndex = function matchIdentifierAtIndex2(s, index) {
        var match = [];
        while (true) {
            var c = codePointAt(s, index);
            if (c === void 0 || _isWhiteSpace(c) || _isPatternSyntax(c)) {
                break;
            }
            match.push(c);
            index += c >= 65536 ? 2 : 1;
        }
        return fromCodePoint.apply(void 0, match);
    };
}
var IDENTIFIER_PREFIX_RE_1;
var Parser = function () {
    function Parser2(message, options) {
        if (options === void 0) {
            options = {};
        }
        this.message = message;
        this.position = { offset: 0, line: 1, column: 1 };
        this.ignoreTag = !!options.ignoreTag;
        this.requiresOtherClause = !!options.requiresOtherClause;
        this.shouldParseSkeletons = !!options.shouldParseSkeletons;
    }
    Parser2.prototype.parse = function () {
        if (this.offset() !== 0) {
            throw Error("parser can only be used once");
        }
        return this.parseMessage(0, "", false);
    };
    Parser2.prototype.parseMessage = function (nestingLevel, parentArgType, expectingCloseTag) {
        var elements = [];
        while (!this.isEOF()) {
            var char = this.char();
            if (char === 123) {
                var result = this.parseArgument(nestingLevel, expectingCloseTag);
                if (result.err) {
                    return result;
                }
                elements.push(result.val);
            }
            else if (char === 125 && nestingLevel > 0) {
                break;
            }
            else if (char === 35 && (parentArgType === "plural" || parentArgType === "selectordinal")) {
                var position = this.clonePosition();
                this.bump();
                elements.push({
                    type: TYPE.pound,
                    location: createLocation(position, this.clonePosition())
                });
            }
            else if (char === 60 && !this.ignoreTag && this.peek() === 47) {
                if (expectingCloseTag) {
                    break;
                }
                else {
                    return this.error(ErrorKind.UNMATCHED_CLOSING_TAG, createLocation(this.clonePosition(), this.clonePosition()));
                }
            }
            else if (char === 60 && !this.ignoreTag && _isAlpha(this.peek() || 0)) {
                var result = this.parseTag(nestingLevel, parentArgType);
                if (result.err) {
                    return result;
                }
                elements.push(result.val);
            }
            else {
                var result = this.parseLiteral(nestingLevel, parentArgType);
                if (result.err) {
                    return result;
                }
                elements.push(result.val);
            }
        }
        return { val: elements, err: null };
    };
    Parser2.prototype.parseTag = function (nestingLevel, parentArgType) {
        var startPosition = this.clonePosition();
        this.bump();
        var tagName = this.parseTagName();
        this.bumpSpace();
        if (this.bumpIf("/>")) {
            return {
                val: {
                    type: TYPE.literal,
                    value: "<" + tagName + "/>",
                    location: createLocation(startPosition, this.clonePosition())
                },
                err: null
            };
        }
        else if (this.bumpIf(">")) {
            var childrenResult = this.parseMessage(nestingLevel + 1, parentArgType, true);
            if (childrenResult.err) {
                return childrenResult;
            }
            var children = childrenResult.val;
            var endTagStartPosition = this.clonePosition();
            if (this.bumpIf("</")) {
                if (this.isEOF() || !_isAlpha(this.char())) {
                    return this.error(ErrorKind.INVALID_TAG, createLocation(endTagStartPosition, this.clonePosition()));
                }
                var closingTagNameStartPosition = this.clonePosition();
                var closingTagName = this.parseTagName();
                if (tagName !== closingTagName) {
                    return this.error(ErrorKind.UNMATCHED_CLOSING_TAG, createLocation(closingTagNameStartPosition, this.clonePosition()));
                }
                this.bumpSpace();
                if (!this.bumpIf(">")) {
                    return this.error(ErrorKind.INVALID_TAG, createLocation(endTagStartPosition, this.clonePosition()));
                }
                return {
                    val: {
                        type: TYPE.tag,
                        value: tagName,
                        children,
                        location: createLocation(startPosition, this.clonePosition())
                    },
                    err: null
                };
            }
            else {
                return this.error(ErrorKind.UNCLOSED_TAG, createLocation(startPosition, this.clonePosition()));
            }
        }
        else {
            return this.error(ErrorKind.INVALID_TAG, createLocation(startPosition, this.clonePosition()));
        }
    };
    Parser2.prototype.parseTagName = function () {
        var startOffset = this.offset();
        this.bump();
        while (!this.isEOF() && _isPotentialElementNameChar(this.char())) {
            this.bump();
        }
        return this.message.slice(startOffset, this.offset());
    };
    Parser2.prototype.parseLiteral = function (nestingLevel, parentArgType) {
        var start = this.clonePosition();
        var value = "";
        while (true) {
            var parseQuoteResult = this.tryParseQuote(parentArgType);
            if (parseQuoteResult) {
                value += parseQuoteResult;
                continue;
            }
            var parseUnquotedResult = this.tryParseUnquoted(nestingLevel, parentArgType);
            if (parseUnquotedResult) {
                value += parseUnquotedResult;
                continue;
            }
            var parseLeftAngleResult = this.tryParseLeftAngleBracket();
            if (parseLeftAngleResult) {
                value += parseLeftAngleResult;
                continue;
            }
            break;
        }
        var location = createLocation(start, this.clonePosition());
        return {
            val: { type: TYPE.literal, value, location },
            err: null
        };
    };
    Parser2.prototype.tryParseLeftAngleBracket = function () {
        if (!this.isEOF() && this.char() === 60 && (this.ignoreTag || !_isAlphaOrSlash(this.peek() || 0))) {
            this.bump();
            return "<";
        }
        return null;
    };
    Parser2.prototype.tryParseQuote = function (parentArgType) {
        if (this.isEOF() || this.char() !== 39) {
            return null;
        }
        switch (this.peek()) {
            case 39:
                this.bump();
                this.bump();
                return "'";
            case 123:
            case 60:
            case 62:
            case 125:
                break;
            case 35:
                if (parentArgType === "plural" || parentArgType === "selectordinal") {
                    break;
                }
                return null;
            default:
                return null;
        }
        this.bump();
        var codePoints = [this.char()];
        this.bump();
        while (!this.isEOF()) {
            var ch = this.char();
            if (ch === 39) {
                if (this.peek() === 39) {
                    codePoints.push(39);
                    this.bump();
                }
                else {
                    this.bump();
                    break;
                }
            }
            else {
                codePoints.push(ch);
            }
            this.bump();
        }
        return fromCodePoint.apply(void 0, codePoints);
    };
    Parser2.prototype.tryParseUnquoted = function (nestingLevel, parentArgType) {
        if (this.isEOF()) {
            return null;
        }
        var ch = this.char();
        if (ch === 60 || ch === 123 || ch === 35 && (parentArgType === "plural" || parentArgType === "selectordinal") || ch === 125 && nestingLevel > 0) {
            return null;
        }
        else {
            this.bump();
            return fromCodePoint(ch);
        }
    };
    Parser2.prototype.parseArgument = function (nestingLevel, expectingCloseTag) {
        var openingBracePosition = this.clonePosition();
        this.bump();
        this.bumpSpace();
        if (this.isEOF()) {
            return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
        }
        if (this.char() === 125) {
            this.bump();
            return this.error(ErrorKind.EMPTY_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));
        }
        var value = this.parseIdentifierIfPossible().value;
        if (!value) {
            return this.error(ErrorKind.MALFORMED_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));
        }
        this.bumpSpace();
        if (this.isEOF()) {
            return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
        }
        switch (this.char()) {
            case 125: {
                this.bump();
                return {
                    val: {
                        type: TYPE.argument,
                        value,
                        location: createLocation(openingBracePosition, this.clonePosition())
                    },
                    err: null
                };
            }
            case 44: {
                this.bump();
                this.bumpSpace();
                if (this.isEOF()) {
                    return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
                }
                return this.parseArgumentOptions(nestingLevel, expectingCloseTag, value, openingBracePosition);
            }
            default:
                return this.error(ErrorKind.MALFORMED_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));
        }
    };
    Parser2.prototype.parseIdentifierIfPossible = function () {
        var startingPosition = this.clonePosition();
        var startOffset = this.offset();
        var value = matchIdentifierAtIndex(this.message, startOffset);
        var endOffset = startOffset + value.length;
        this.bumpTo(endOffset);
        var endPosition = this.clonePosition();
        var location = createLocation(startingPosition, endPosition);
        return { value, location };
    };
    Parser2.prototype.parseArgumentOptions = function (nestingLevel, expectingCloseTag, value, openingBracePosition) {
        var _a2;
        var typeStartPosition = this.clonePosition();
        var argType = this.parseIdentifierIfPossible().value;
        var typeEndPosition = this.clonePosition();
        switch (argType) {
            case "":
                return this.error(ErrorKind.EXPECT_ARGUMENT_TYPE, createLocation(typeStartPosition, typeEndPosition));
            case "number":
            case "date":
            case "time": {
                this.bumpSpace();
                var styleAndLocation = null;
                if (this.bumpIf(",")) {
                    this.bumpSpace();
                    var styleStartPosition = this.clonePosition();
                    var result = this.parseSimpleArgStyleIfPossible();
                    if (result.err) {
                        return result;
                    }
                    var style = trimEnd(result.val);
                    if (style.length === 0) {
                        return this.error(ErrorKind.EXPECT_ARGUMENT_STYLE, createLocation(this.clonePosition(), this.clonePosition()));
                    }
                    var styleLocation = createLocation(styleStartPosition, this.clonePosition());
                    styleAndLocation = { style, styleLocation };
                }
                var argCloseResult = this.tryParseArgumentClose(openingBracePosition);
                if (argCloseResult.err) {
                    return argCloseResult;
                }
                var location_1 = createLocation(openingBracePosition, this.clonePosition());
                if (styleAndLocation && startsWith(styleAndLocation === null || styleAndLocation === void 0 ? void 0 : styleAndLocation.style, "::", 0)) {
                    var skeleton = trimStart(styleAndLocation.style.slice(2));
                    if (argType === "number") {
                        var result = this.parseNumberSkeletonFromString(skeleton, styleAndLocation.styleLocation);
                        if (result.err) {
                            return result;
                        }
                        return {
                            val: { type: TYPE.number, value, location: location_1, style: result.val },
                            err: null
                        };
                    }
                    else {
                        if (skeleton.length === 0) {
                            return this.error(ErrorKind.EXPECT_DATE_TIME_SKELETON, location_1);
                        }
                        var style = {
                            type: SKELETON_TYPE.dateTime,
                            pattern: skeleton,
                            location: styleAndLocation.styleLocation,
                            parsedOptions: this.shouldParseSkeletons ? parseDateTimeSkeleton(skeleton) : {}
                        };
                        var type = argType === "date" ? TYPE.date : TYPE.time;
                        return {
                            val: { type, value, location: location_1, style },
                            err: null
                        };
                    }
                }
                return {
                    val: {
                        type: argType === "number" ? TYPE.number : argType === "date" ? TYPE.date : TYPE.time,
                        value,
                        location: location_1,
                        style: (_a2 = styleAndLocation === null || styleAndLocation === void 0 ? void 0 : styleAndLocation.style) !== null && _a2 !== void 0 ? _a2 : null
                    },
                    err: null
                };
            }
            case "plural":
            case "selectordinal":
            case "select": {
                var typeEndPosition_1 = this.clonePosition();
                this.bumpSpace();
                if (!this.bumpIf(",")) {
                    return this.error(ErrorKind.EXPECT_SELECT_ARGUMENT_OPTIONS, createLocation(typeEndPosition_1, __assign({}, typeEndPosition_1)));
                }
                this.bumpSpace();
                var identifierAndLocation = this.parseIdentifierIfPossible();
                var pluralOffset = 0;
                if (argType !== "select" && identifierAndLocation.value === "offset") {
                    if (!this.bumpIf(":")) {
                        return this.error(ErrorKind.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE, createLocation(this.clonePosition(), this.clonePosition()));
                    }
                    this.bumpSpace();
                    var result = this.tryParseDecimalInteger(ErrorKind.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE, ErrorKind.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE);
                    if (result.err) {
                        return result;
                    }
                    this.bumpSpace();
                    identifierAndLocation = this.parseIdentifierIfPossible();
                    pluralOffset = result.val;
                }
                var optionsResult = this.tryParsePluralOrSelectOptions(nestingLevel, argType, expectingCloseTag, identifierAndLocation);
                if (optionsResult.err) {
                    return optionsResult;
                }
                var argCloseResult = this.tryParseArgumentClose(openingBracePosition);
                if (argCloseResult.err) {
                    return argCloseResult;
                }
                var location_2 = createLocation(openingBracePosition, this.clonePosition());
                if (argType === "select") {
                    return {
                        val: {
                            type: TYPE.select,
                            value,
                            options: fromEntries(optionsResult.val),
                            location: location_2
                        },
                        err: null
                    };
                }
                else {
                    return {
                        val: {
                            type: TYPE.plural,
                            value,
                            options: fromEntries(optionsResult.val),
                            offset: pluralOffset,
                            pluralType: argType === "plural" ? "cardinal" : "ordinal",
                            location: location_2
                        },
                        err: null
                    };
                }
            }
            default:
                return this.error(ErrorKind.INVALID_ARGUMENT_TYPE, createLocation(typeStartPosition, typeEndPosition));
        }
    };
    Parser2.prototype.tryParseArgumentClose = function (openingBracePosition) {
        if (this.isEOF() || this.char() !== 125) {
            return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
        }
        this.bump();
        return { val: true, err: null };
    };
    Parser2.prototype.parseSimpleArgStyleIfPossible = function () {
        var nestedBraces = 0;
        var startPosition = this.clonePosition();
        while (!this.isEOF()) {
            var ch = this.char();
            switch (ch) {
                case 39: {
                    this.bump();
                    var apostrophePosition = this.clonePosition();
                    if (!this.bumpUntil("'")) {
                        return this.error(ErrorKind.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE, createLocation(apostrophePosition, this.clonePosition()));
                    }
                    this.bump();
                    break;
                }
                case 123: {
                    nestedBraces += 1;
                    this.bump();
                    break;
                }
                case 125: {
                    if (nestedBraces > 0) {
                        nestedBraces -= 1;
                    }
                    else {
                        return {
                            val: this.message.slice(startPosition.offset, this.offset()),
                            err: null
                        };
                    }
                    break;
                }
                default:
                    this.bump();
                    break;
            }
        }
        return {
            val: this.message.slice(startPosition.offset, this.offset()),
            err: null
        };
    };
    Parser2.prototype.parseNumberSkeletonFromString = function (skeleton, location) {
        var tokens = [];
        try {
            tokens = parseNumberSkeletonFromString(skeleton);
        }
        catch (e) {
            return this.error(ErrorKind.INVALID_NUMBER_SKELETON, location);
        }
        return {
            val: {
                type: SKELETON_TYPE.number,
                tokens,
                location,
                parsedOptions: this.shouldParseSkeletons ? parseNumberSkeleton(tokens) : {}
            },
            err: null
        };
    };
    Parser2.prototype.tryParsePluralOrSelectOptions = function (nestingLevel, parentArgType, expectCloseTag, parsedFirstIdentifier) {
        var _a2;
        var hasOtherClause = false;
        var options = [];
        var parsedSelectors = new Set();
        var selector = parsedFirstIdentifier.value, selectorLocation = parsedFirstIdentifier.location;
        while (true) {
            if (selector.length === 0) {
                var startPosition = this.clonePosition();
                if (parentArgType !== "select" && this.bumpIf("=")) {
                    var result = this.tryParseDecimalInteger(ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR, ErrorKind.INVALID_PLURAL_ARGUMENT_SELECTOR);
                    if (result.err) {
                        return result;
                    }
                    selectorLocation = createLocation(startPosition, this.clonePosition());
                    selector = this.message.slice(startPosition.offset, this.offset());
                }
                else {
                    break;
                }
            }
            if (parsedSelectors.has(selector)) {
                return this.error(parentArgType === "select" ? ErrorKind.DUPLICATE_SELECT_ARGUMENT_SELECTOR : ErrorKind.DUPLICATE_PLURAL_ARGUMENT_SELECTOR, selectorLocation);
            }
            if (selector === "other") {
                hasOtherClause = true;
            }
            this.bumpSpace();
            var openingBracePosition = this.clonePosition();
            if (!this.bumpIf("{")) {
                return this.error(parentArgType === "select" ? ErrorKind.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT : ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT, createLocation(this.clonePosition(), this.clonePosition()));
            }
            var fragmentResult = this.parseMessage(nestingLevel + 1, parentArgType, expectCloseTag);
            if (fragmentResult.err) {
                return fragmentResult;
            }
            var argCloseResult = this.tryParseArgumentClose(openingBracePosition);
            if (argCloseResult.err) {
                return argCloseResult;
            }
            options.push([
                selector,
                {
                    value: fragmentResult.val,
                    location: createLocation(openingBracePosition, this.clonePosition())
                }
            ]);
            parsedSelectors.add(selector);
            this.bumpSpace();
            _a2 = this.parseIdentifierIfPossible(), selector = _a2.value, selectorLocation = _a2.location;
        }
        if (options.length === 0) {
            return this.error(parentArgType === "select" ? ErrorKind.EXPECT_SELECT_ARGUMENT_SELECTOR : ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR, createLocation(this.clonePosition(), this.clonePosition()));
        }
        if (this.requiresOtherClause && !hasOtherClause) {
            return this.error(ErrorKind.MISSING_OTHER_CLAUSE, createLocation(this.clonePosition(), this.clonePosition()));
        }
        return { val: options, err: null };
    };
    Parser2.prototype.tryParseDecimalInteger = function (expectNumberError, invalidNumberError) {
        var sign = 1;
        var startingPosition = this.clonePosition();
        if (this.bumpIf("+")) ;
        else if (this.bumpIf("-")) {
            sign = -1;
        }
        var hasDigits = false;
        var decimal = 0;
        while (!this.isEOF()) {
            var ch = this.char();
            if (ch >= 48 && ch <= 57) {
                hasDigits = true;
                decimal = decimal * 10 + (ch - 48);
                this.bump();
            }
            else {
                break;
            }
        }
        var location = createLocation(startingPosition, this.clonePosition());
        if (!hasDigits) {
            return this.error(expectNumberError, location);
        }
        decimal *= sign;
        if (!isSafeInteger(decimal)) {
            return this.error(invalidNumberError, location);
        }
        return { val: decimal, err: null };
    };
    Parser2.prototype.offset = function () {
        return this.position.offset;
    };
    Parser2.prototype.isEOF = function () {
        return this.offset() === this.message.length;
    };
    Parser2.prototype.clonePosition = function () {
        return {
            offset: this.position.offset,
            line: this.position.line,
            column: this.position.column
        };
    };
    Parser2.prototype.char = function () {
        var offset = this.position.offset;
        if (offset >= this.message.length) {
            throw Error("out of bound");
        }
        var code = codePointAt(this.message, offset);
        if (code === void 0) {
            throw Error("Offset " + offset + " is at invalid UTF-16 code unit boundary");
        }
        return code;
    };
    Parser2.prototype.error = function (kind, location) {
        return {
            val: null,
            err: {
                kind,
                message: this.message,
                location
            }
        };
    };
    Parser2.prototype.bump = function () {
        if (this.isEOF()) {
            return;
        }
        var code = this.char();
        if (code === 10) {
            this.position.line += 1;
            this.position.column = 1;
            this.position.offset += 1;
        }
        else {
            this.position.column += 1;
            this.position.offset += code < 65536 ? 1 : 2;
        }
    };
    Parser2.prototype.bumpIf = function (prefix) {
        if (startsWith(this.message, prefix, this.offset())) {
            for (var i = 0; i < prefix.length; i++) {
                this.bump();
            }
            return true;
        }
        return false;
    };
    Parser2.prototype.bumpUntil = function (pattern) {
        var currentOffset = this.offset();
        var index = this.message.indexOf(pattern, currentOffset);
        if (index >= 0) {
            this.bumpTo(index);
            return true;
        }
        else {
            this.bumpTo(this.message.length);
            return false;
        }
    };
    Parser2.prototype.bumpTo = function (targetOffset) {
        if (this.offset() > targetOffset) {
            throw Error("targetOffset " + targetOffset + " must be greater than or equal to the current offset " + this.offset());
        }
        targetOffset = Math.min(targetOffset, this.message.length);
        while (true) {
            var offset = this.offset();
            if (offset === targetOffset) {
                break;
            }
            if (offset > targetOffset) {
                throw Error("targetOffset " + targetOffset + " is at invalid UTF-16 code unit boundary");
            }
            this.bump();
            if (this.isEOF()) {
                break;
            }
        }
    };
    Parser2.prototype.bumpSpace = function () {
        while (!this.isEOF() && _isWhiteSpace(this.char())) {
            this.bump();
        }
    };
    Parser2.prototype.peek = function () {
        if (this.isEOF()) {
            return null;
        }
        var code = this.char();
        var offset = this.offset();
        var nextCode = this.message.charCodeAt(offset + (code >= 65536 ? 2 : 1));
        return nextCode !== null && nextCode !== void 0 ? nextCode : null;
    };
    return Parser2;
}();
function _isAlpha(codepoint) {
    return codepoint >= 97 && codepoint <= 122 || codepoint >= 65 && codepoint <= 90;
}
function _isAlphaOrSlash(codepoint) {
    return _isAlpha(codepoint) || codepoint === 47;
}
function _isPotentialElementNameChar(c) {
    return c === 45 || c === 46 || c >= 48 && c <= 57 || c === 95 || c >= 97 && c <= 122 || c >= 65 && c <= 90 || c == 183 || c >= 192 && c <= 214 || c >= 216 && c <= 246 || c >= 248 && c <= 893 || c >= 895 && c <= 8191 || c >= 8204 && c <= 8205 || c >= 8255 && c <= 8256 || c >= 8304 && c <= 8591 || c >= 11264 && c <= 12271 || c >= 12289 && c <= 55295 || c >= 63744 && c <= 64975 || c >= 65008 && c <= 65533 || c >= 65536 && c <= 983039;
}
function _isWhiteSpace(c) {
    return c >= 9 && c <= 13 || c === 32 || c === 133 || c >= 8206 && c <= 8207 || c === 8232 || c === 8233;
}
function _isPatternSyntax(c) {
    return c >= 33 && c <= 35 || c === 36 || c >= 37 && c <= 39 || c === 40 || c === 41 || c === 42 || c === 43 || c === 44 || c === 45 || c >= 46 && c <= 47 || c >= 58 && c <= 59 || c >= 60 && c <= 62 || c >= 63 && c <= 64 || c === 91 || c === 92 || c === 93 || c === 94 || c === 96 || c === 123 || c === 124 || c === 125 || c === 126 || c === 161 || c >= 162 && c <= 165 || c === 166 || c === 167 || c === 169 || c === 171 || c === 172 || c === 174 || c === 176 || c === 177 || c === 182 || c === 187 || c === 191 || c === 215 || c === 247 || c >= 8208 && c <= 8213 || c >= 8214 && c <= 8215 || c === 8216 || c === 8217 || c === 8218 || c >= 8219 && c <= 8220 || c === 8221 || c === 8222 || c === 8223 || c >= 8224 && c <= 8231 || c >= 8240 && c <= 8248 || c === 8249 || c === 8250 || c >= 8251 && c <= 8254 || c >= 8257 && c <= 8259 || c === 8260 || c === 8261 || c === 8262 || c >= 8263 && c <= 8273 || c === 8274 || c === 8275 || c >= 8277 && c <= 8286 || c >= 8592 && c <= 8596 || c >= 8597 && c <= 8601 || c >= 8602 && c <= 8603 || c >= 8604 && c <= 8607 || c === 8608 || c >= 8609 && c <= 8610 || c === 8611 || c >= 8612 && c <= 8613 || c === 8614 || c >= 8615 && c <= 8621 || c === 8622 || c >= 8623 && c <= 8653 || c >= 8654 && c <= 8655 || c >= 8656 && c <= 8657 || c === 8658 || c === 8659 || c === 8660 || c >= 8661 && c <= 8691 || c >= 8692 && c <= 8959 || c >= 8960 && c <= 8967 || c === 8968 || c === 8969 || c === 8970 || c === 8971 || c >= 8972 && c <= 8991 || c >= 8992 && c <= 8993 || c >= 8994 && c <= 9e3 || c === 9001 || c === 9002 || c >= 9003 && c <= 9083 || c === 9084 || c >= 9085 && c <= 9114 || c >= 9115 && c <= 9139 || c >= 9140 && c <= 9179 || c >= 9180 && c <= 9185 || c >= 9186 && c <= 9254 || c >= 9255 && c <= 9279 || c >= 9280 && c <= 9290 || c >= 9291 && c <= 9311 || c >= 9472 && c <= 9654 || c === 9655 || c >= 9656 && c <= 9664 || c === 9665 || c >= 9666 && c <= 9719 || c >= 9720 && c <= 9727 || c >= 9728 && c <= 9838 || c === 9839 || c >= 9840 && c <= 10087 || c === 10088 || c === 10089 || c === 10090 || c === 10091 || c === 10092 || c === 10093 || c === 10094 || c === 10095 || c === 10096 || c === 10097 || c === 10098 || c === 10099 || c === 10100 || c === 10101 || c >= 10132 && c <= 10175 || c >= 10176 && c <= 10180 || c === 10181 || c === 10182 || c >= 10183 && c <= 10213 || c === 10214 || c === 10215 || c === 10216 || c === 10217 || c === 10218 || c === 10219 || c === 10220 || c === 10221 || c === 10222 || c === 10223 || c >= 10224 && c <= 10239 || c >= 10240 && c <= 10495 || c >= 10496 && c <= 10626 || c === 10627 || c === 10628 || c === 10629 || c === 10630 || c === 10631 || c === 10632 || c === 10633 || c === 10634 || c === 10635 || c === 10636 || c === 10637 || c === 10638 || c === 10639 || c === 10640 || c === 10641 || c === 10642 || c === 10643 || c === 10644 || c === 10645 || c === 10646 || c === 10647 || c === 10648 || c >= 10649 && c <= 10711 || c === 10712 || c === 10713 || c === 10714 || c === 10715 || c >= 10716 && c <= 10747 || c === 10748 || c === 10749 || c >= 10750 && c <= 11007 || c >= 11008 && c <= 11055 || c >= 11056 && c <= 11076 || c >= 11077 && c <= 11078 || c >= 11079 && c <= 11084 || c >= 11085 && c <= 11123 || c >= 11124 && c <= 11125 || c >= 11126 && c <= 11157 || c === 11158 || c >= 11159 && c <= 11263 || c >= 11776 && c <= 11777 || c === 11778 || c === 11779 || c === 11780 || c === 11781 || c >= 11782 && c <= 11784 || c === 11785 || c === 11786 || c === 11787 || c === 11788 || c === 11789 || c >= 11790 && c <= 11798 || c === 11799 || c >= 11800 && c <= 11801 || c === 11802 || c === 11803 || c === 11804 || c === 11805 || c >= 11806 && c <= 11807 || c === 11808 || c === 11809 || c === 11810 || c === 11811 || c === 11812 || c === 11813 || c === 11814 || c === 11815 || c === 11816 || c === 11817 || c >= 11818 && c <= 11822 || c === 11823 || c >= 11824 && c <= 11833 || c >= 11834 && c <= 11835 || c >= 11836 && c <= 11839 || c === 11840 || c === 11841 || c === 11842 || c >= 11843 && c <= 11855 || c >= 11856 && c <= 11857 || c === 11858 || c >= 11859 && c <= 11903 || c >= 12289 && c <= 12291 || c === 12296 || c === 12297 || c === 12298 || c === 12299 || c === 12300 || c === 12301 || c === 12302 || c === 12303 || c === 12304 || c === 12305 || c >= 12306 && c <= 12307 || c === 12308 || c === 12309 || c === 12310 || c === 12311 || c === 12312 || c === 12313 || c === 12314 || c === 12315 || c === 12316 || c === 12317 || c >= 12318 && c <= 12319 || c === 12320 || c === 12336 || c === 64830 || c === 64831 || c >= 65093 && c <= 65094;
}
function pruneLocation(els) {
    els.forEach(function (el) {
        delete el.location;
        if (isSelectElement(el) || isPluralElement(el)) {
            for (var k in el.options) {
                delete el.options[k].location;
                pruneLocation(el.options[k].value);
            }
        }
        else if (isNumberElement(el) && isNumberSkeleton(el.style)) {
            delete el.style.location;
        }
        else if ((isDateElement(el) || isTimeElement(el)) && isDateTimeSkeleton(el.style)) {
            delete el.style.location;
        }
        else if (isTagElement(el)) {
            pruneLocation(el.children);
        }
    });
}
function parse$1(message, opts) {
    if (opts === void 0) {
        opts = {};
    }
    opts = __assign({ shouldParseSkeletons: true, requiresOtherClause: true }, opts);
    var result = new Parser(message, opts).parse();
    if (result.err) {
        var error = SyntaxError(ErrorKind[result.err.kind]);
        error.location = result.err.location;
        error.originalMessage = result.err.message;
        throw error;
    }
    if (!(opts === null || opts === void 0 ? void 0 : opts.captureLocation)) {
        pruneLocation(result.val);
    }
    return result.val;
}
function memoize(fn, options) {
    var cache = options && options.cache ? options.cache : cacheDefault;
    var serializer = options && options.serializer ? options.serializer : serializerDefault;
    var strategy = options && options.strategy ? options.strategy : strategyDefault;
    return strategy(fn, {
        cache,
        serializer
    });
}
function isPrimitive(value) {
    return value == null || typeof value === "number" || typeof value === "boolean";
}
function monadic(fn, cache, serializer, arg) {
    var cacheKey = isPrimitive(arg) ? arg : serializer(arg);
    var computedValue = cache.get(cacheKey);
    if (typeof computedValue === "undefined") {
        computedValue = fn.call(this, arg);
        cache.set(cacheKey, computedValue);
    }
    return computedValue;
}
function variadic(fn, cache, serializer) {
    var args = Array.prototype.slice.call(arguments, 3);
    var cacheKey = serializer(args);
    var computedValue = cache.get(cacheKey);
    if (typeof computedValue === "undefined") {
        computedValue = fn.apply(this, args);
        cache.set(cacheKey, computedValue);
    }
    return computedValue;
}
function assemble(fn, context, strategy, cache, serialize) {
    return strategy.bind(context, fn, cache, serialize);
}
function strategyDefault(fn, options) {
    var strategy = fn.length === 1 ? monadic : variadic;
    return assemble(fn, this, strategy, options.cache.create(), options.serializer);
}
function strategyVariadic(fn, options) {
    return assemble(fn, this, variadic, options.cache.create(), options.serializer);
}
var serializerDefault = function () {
    return JSON.stringify(arguments);
};
function ObjectWithoutPrototypeCache() {
    this.cache = Object.create(null);
}
ObjectWithoutPrototypeCache.prototype.has = function (key) {
    return key in this.cache;
};
ObjectWithoutPrototypeCache.prototype.get = function (key) {
    return this.cache[key];
};
ObjectWithoutPrototypeCache.prototype.set = function (key, value) {
    this.cache[key] = value;
};
var cacheDefault = {
    create: function create() {
        return new ObjectWithoutPrototypeCache();
    }
};
var strategies = {
    variadic: strategyVariadic};
var ErrorCode;
(function (ErrorCode2) {
    ErrorCode2["MISSING_VALUE"] = "MISSING_VALUE";
    ErrorCode2["INVALID_VALUE"] = "INVALID_VALUE";
    ErrorCode2["MISSING_INTL_API"] = "MISSING_INTL_API";
})(ErrorCode || (ErrorCode = {}));
var FormatError = class extends Error {
    constructor(msg, code, originalMessage) {
        super(msg);
        this.code = code;
        this.originalMessage = originalMessage;
    }
    toString() {
        return `[formatjs Error: ${this.code}] ${this.message}`;
    }
};
var InvalidValueError = class extends FormatError {
    constructor(variableId, value, options, originalMessage) {
        super(`Invalid values for "${variableId}": "${value}". Options are "${Object.keys(options).join('", "')}"`, ErrorCode.INVALID_VALUE, originalMessage);
    }
};
var InvalidValueTypeError = class extends FormatError {
    constructor(value, type, originalMessage) {
        super(`Value for "${value}" must be of type ${type}`, ErrorCode.INVALID_VALUE, originalMessage);
    }
};
var MissingValueError = class extends FormatError {
    constructor(variableId, originalMessage) {
        super(`The intl string context variable "${variableId}" was not provided to the string "${originalMessage}"`, ErrorCode.MISSING_VALUE, originalMessage);
    }
};
var PART_TYPE;
(function (PART_TYPE2) {
    PART_TYPE2[PART_TYPE2["literal"] = 0] = "literal";
    PART_TYPE2[PART_TYPE2["object"] = 1] = "object";
})(PART_TYPE || (PART_TYPE = {}));
function mergeLiteral(parts) {
    if (parts.length < 2) {
        return parts;
    }
    return parts.reduce((all, part) => {
        const lastPart = all[all.length - 1];
        if (!lastPart || lastPart.type !== PART_TYPE.literal || part.type !== PART_TYPE.literal) {
            all.push(part);
        }
        else {
            lastPart.value += part.value;
        }
        return all;
    }, []);
}
function isFormatXMLElementFn(el) {
    return typeof el === "function";
}
function formatToParts(els, locales, formatters, formats, values, currentPluralValue, originalMessage) {
    if (els.length === 1 && isLiteralElement(els[0])) {
        return [
            {
                type: PART_TYPE.literal,
                value: els[0].value
            }
        ];
    }
    const result = [];
    for (const el of els) {
        if (isLiteralElement(el)) {
            result.push({
                type: PART_TYPE.literal,
                value: el.value
            });
            continue;
        }
        if (isPoundElement(el)) {
            if (typeof currentPluralValue === "number") {
                result.push({
                    type: PART_TYPE.literal,
                    value: formatters.getNumberFormat(locales).format(currentPluralValue)
                });
            }
            continue;
        }
        const { value: varName } = el;
        if (!(values && varName in values)) {
            throw new MissingValueError(varName, originalMessage);
        }
        let value = values[varName];
        if (isArgumentElement(el)) {
            if (!value || typeof value === "string" || typeof value === "number") {
                value = typeof value === "string" || typeof value === "number" ? String(value) : "";
            }
            result.push({
                type: typeof value === "string" ? PART_TYPE.literal : PART_TYPE.object,
                value
            });
            continue;
        }
        if (isDateElement(el)) {
            const style = typeof el.style === "string" ? formats.date[el.style] : isDateTimeSkeleton(el.style) ? el.style.parsedOptions : void 0;
            result.push({
                type: PART_TYPE.literal,
                value: formatters.getDateTimeFormat(locales, style).format(value)
            });
            continue;
        }
        if (isTimeElement(el)) {
            const style = typeof el.style === "string" ? formats.time[el.style] : isDateTimeSkeleton(el.style) ? el.style.parsedOptions : void 0;
            result.push({
                type: PART_TYPE.literal,
                value: formatters.getDateTimeFormat(locales, style).format(value)
            });
            continue;
        }
        if (isNumberElement(el)) {
            const style = typeof el.style === "string" ? formats.number[el.style] : isNumberSkeleton(el.style) ? el.style.parsedOptions : void 0;
            if (style && style.scale) {
                value = value * (style.scale || 1);
            }
            result.push({
                type: PART_TYPE.literal,
                value: formatters.getNumberFormat(locales, style).format(value)
            });
            continue;
        }
        if (isTagElement(el)) {
            const { children, value: value2 } = el;
            const formatFn = values[value2];
            if (!isFormatXMLElementFn(formatFn)) {
                throw new InvalidValueTypeError(value2, "function", originalMessage);
            }
            const parts = formatToParts(children, locales, formatters, formats, values, currentPluralValue);
            let chunks = formatFn(parts.map((p) => p.value));
            if (!Array.isArray(chunks)) {
                chunks = [chunks];
            }
            result.push(...chunks.map((c) => {
                return {
                    type: typeof c === "string" ? PART_TYPE.literal : PART_TYPE.object,
                    value: c
                };
            }));
        }
        if (isSelectElement(el)) {
            const opt = el.options[value] || el.options.other;
            if (!opt) {
                throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);
            }
            result.push(...formatToParts(opt.value, locales, formatters, formats, values));
            continue;
        }
        if (isPluralElement(el)) {
            let opt = el.options[`=${value}`];
            if (!opt) {
                if (!Intl.PluralRules) {
                    throw new FormatError(`Intl.PluralRules is not available in this environment.
Try polyfilling it using "@formatjs/intl-pluralrules"
`, ErrorCode.MISSING_INTL_API, originalMessage);
                }
                const rule = formatters.getPluralRules(locales, { type: el.pluralType }).select(value - (el.offset || 0));
                opt = el.options[rule] || el.options.other;
            }
            if (!opt) {
                throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);
            }
            result.push(...formatToParts(opt.value, locales, formatters, formats, values, value - (el.offset || 0)));
            continue;
        }
    }
    return mergeLiteral(result);
}
function mergeConfig(c1, c2) {
    if (!c2) {
        return c1;
    }
    return {
        ...c1 || {},
        ...c2 || {},
        ...Object.keys(c1).reduce((all, k) => {
            all[k] = {
                ...c1[k],
                ...c2[k] || {}
            };
            return all;
        }, {})
    };
}
function mergeConfigs(defaultConfig, configs) {
    if (!configs) {
        return defaultConfig;
    }
    return Object.keys(defaultConfig).reduce((all, k) => {
        all[k] = mergeConfig(defaultConfig[k], configs[k]);
        return all;
    }, { ...defaultConfig });
}
function createFastMemoizeCache(store) {
    return {
        create() {
            return {
                has(key) {
                    return key in store;
                },
                get(key) {
                    return store[key];
                },
                set(key, value) {
                    store[key] = value;
                }
            };
        }
    };
}
function createDefaultFormatters(cache = {
    number: {},
    dateTime: {},
    pluralRules: {}
}) {
    return {
        getNumberFormat: memoize((...args) => new Intl.NumberFormat(...args), {
            cache: createFastMemoizeCache(cache.number),
            strategy: strategies.variadic
        }),
        getDateTimeFormat: memoize((...args) => new Intl.DateTimeFormat(...args), {
            cache: createFastMemoizeCache(cache.dateTime),
            strategy: strategies.variadic
        }),
        getPluralRules: memoize((...args) => new Intl.PluralRules(...args), {
            cache: createFastMemoizeCache(cache.pluralRules),
            strategy: strategies.variadic
        })
    };
}
var IntlMessageFormat = class {
    constructor(message, locales = IntlMessageFormat.defaultLocale, overrideFormats, opts) {
        this.formatterCache = {
            number: {},
            dateTime: {},
            pluralRules: {}
        };
        this.format = (values) => {
            const parts = this.formatToParts(values);
            if (parts.length === 1) {
                return parts[0].value;
            }
            const result = parts.reduce((all, part) => {
                if (!all.length || part.type !== PART_TYPE.literal || typeof all[all.length - 1] !== "string") {
                    all.push(part.value);
                }
                else {
                    all[all.length - 1] += part.value;
                }
                return all;
            }, []);
            if (result.length <= 1) {
                return result[0] || "";
            }
            return result;
        };
        this.formatToParts = (values) => formatToParts(this.ast, this.locales, this.formatters, this.formats, values, void 0, this.message);
        this.resolvedOptions = () => ({
            locale: Intl.NumberFormat.supportedLocalesOf(this.locales)[0]
        });
        this.getAst = () => this.ast;
        if (typeof message === "string") {
            this.message = message;
            if (!IntlMessageFormat.__parse) {
                throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");
            }
            this.ast = IntlMessageFormat.__parse(message, {
                ignoreTag: opts?.ignoreTag
            });
        }
        else {
            this.ast = message;
        }
        if (!Array.isArray(this.ast)) {
            throw new TypeError("A message must be provided as a String or AST.");
        }
        this.formats = mergeConfigs(IntlMessageFormat.formats, overrideFormats);
        this.locales = locales;
        this.formatters = opts && opts.formatters || createDefaultFormatters(this.formatterCache);
    }
    static get defaultLocale() {
        if (!IntlMessageFormat.memoizedDefaultLocale) {
            IntlMessageFormat.memoizedDefaultLocale = new Intl.NumberFormat().resolvedOptions().locale;
        }
        return IntlMessageFormat.memoizedDefaultLocale;
    }
};
IntlMessageFormat.memoizedDefaultLocale = null;
IntlMessageFormat.__parse = parse$1;
IntlMessageFormat.formats = {
    number: {
        integer: {
            maximumFractionDigits: 0
        },
        currency: {
            style: "currency"
        },
        percent: {
            style: "percent"
        }
    },
    date: {
        short: {
            month: "numeric",
            day: "numeric",
            year: "2-digit"
        },
        medium: {
            month: "short",
            day: "numeric",
            year: "numeric"
        },
        long: {
            month: "long",
            day: "numeric",
            year: "numeric"
        },
        full: {
            weekday: "long",
            month: "long",
            day: "numeric",
            year: "numeric"
        }
    },
    time: {
        short: {
            hour: "numeric",
            minute: "numeric"
        },
        medium: {
            hour: "numeric",
            minute: "numeric",
            second: "numeric"
        },
        long: {
            hour: "numeric",
            minute: "numeric",
            second: "numeric",
            timeZoneName: "short"
        },
        full: {
            hour: "numeric",
            minute: "numeric",
            second: "numeric",
            timeZoneName: "short"
        }
    }
};
var lib_esnext_default = IntlMessageFormat;
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

// Copyright 2018 The Lighthouse Authors. All Rights Reserved.
const EMPTY_VALUES_OBJECT = {};
class RegisteredFileStrings {
    filename;
    stringStructure;
    localizedMessages;
    localizedStringSet;
    constructor(filename, stringStructure, localizedMessages) {
        this.filename = filename;
        this.stringStructure = stringStructure;
        this.localizedMessages = localizedMessages;
    }
    getLocalizedStringSetFor(locale) {
        if (this.localizedStringSet) {
            return this.localizedStringSet;
        }
        const localeData = this.localizedMessages.get(locale);
        if (!localeData) {
            throw new Error(`No locale data registered for '${locale}'`);
        }
        this.localizedStringSet = new LocalizedStringSet(this.filename, this.stringStructure, locale, localeData);
        return this.localizedStringSet;
    }
}
class LocalizedStringSet {
    filename;
    stringStructure;
    localizedMessages;
    cachedSimpleStrings = new Map();
    cachedMessageFormatters = new Map();
    localeForFormatter;
    constructor(filename, stringStructure, locale, localizedMessages) {
        this.filename = filename;
        this.stringStructure = stringStructure;
        this.localizedMessages = localizedMessages;
        this.localeForFormatter = (locale === 'en-XA' || locale === 'en-XL') ? 'de-DE' : locale;
    }
    getLocalizedString(message, values = EMPTY_VALUES_OBJECT) {
        if (values === EMPTY_VALUES_OBJECT || Object.keys(values).length === 0) {
            return this.getSimpleLocalizedString(message);
        }
        return this.getFormattedLocalizedString(message, values);
    }
    getMessageFormatterFor(message) {
        const keyname = Object.keys(this.stringStructure).find(key => this.stringStructure[key] === message);
        if (!keyname) {
            throw new Error(`Unable to locate '${message}' in UIStrings object`);
        }
        const i18nId = `${this.filename} | ${keyname}`;
        const localeMessage = this.localizedMessages[i18nId];
        const messageToTranslate = localeMessage ? localeMessage.message : message;
        return new lib_esnext_default(messageToTranslate, this.localeForFormatter, undefined, { ignoreTag: true });
    }
    getSimpleLocalizedString(message) {
        const cachedSimpleString = this.cachedSimpleStrings.get(message);
        if (cachedSimpleString) {
            return cachedSimpleString;
        }
        const formatter = this.getMessageFormatterFor(message);
        try {
            const translatedString = formatter.format();
            this.cachedSimpleStrings.set(message, translatedString);
            return translatedString;
        }
        catch {
            const formatter = new lib_esnext_default(message, this.localeForFormatter, undefined, { ignoreTag: true });
            const translatedString = formatter.format();
            this.cachedSimpleStrings.set(message, translatedString);
            return translatedString;
        }
    }
    getFormattedLocalizedString(message, values) {
        let formatter = this.cachedMessageFormatters.get(message);
        if (!formatter) {
            formatter = this.getMessageFormatterFor(message);
            this.cachedMessageFormatters.set(message, formatter);
        }
        try {
            return formatter.format(values);
        }
        catch {
            const formatter = new lib_esnext_default(message, this.localeForFormatter, undefined, { ignoreTag: true });
            return formatter.format(values);
        }
    }
}

// Copyright 2018 The Lighthouse Authors. All Rights Reserved.
class I18n {
    supportedLocales;
    localeData = new Map();
    defaultLocale;
    constructor(supportedLocales, defaultLocale) {
        this.defaultLocale = defaultLocale;
        this.supportedLocales = new Set(supportedLocales);
    }
    registerLocaleData(locale, messages) {
        this.localeData.set(locale, messages);
    }
    hasLocaleDataForTest(locale) {
        return this.localeData.has(locale);
    }
    resetLocaleDataForTest() {
        this.localeData.clear();
    }
    registerFileStrings(filename, stringStructure) {
        return new RegisteredFileStrings(filename, stringStructure, this.localeData);
    }
    lookupClosestSupportedLocale(locale) {
        const canonicalLocale = Intl.getCanonicalLocales(locale)[0];
        const localeParts = canonicalLocale.split('-');
        while (localeParts.length) {
            const candidate = localeParts.join('-');
            if (this.supportedLocales.has(candidate)) {
                return candidate;
            }
            localeParts.pop();
        }
        return this.defaultLocale;
    }
}

const LOCALES = [
  'en-US',
];
const DEFAULT_LOCALE = 'en-US';
const LOCAL_FETCH_PATTERN = './locales/@LOCALE@.json';

// Copyright 2020 The Chromium Authors
const i18nInstance = new I18n(LOCALES, DEFAULT_LOCALE);
function lookupClosestSupportedDevToolsLocale(locale) {
    return i18nInstance.lookupClosestSupportedLocale(locale);
}
function getAllSupportedDevToolsLocales() {
    return [...i18nInstance.supportedLocales];
}
function getLocaleFetchUrl(locale, location) {
    undefined(location);
    const path = LOCAL_FETCH_PATTERN.replace('@LOCALE@', locale);
    return new URL(path, import.meta.url).toString();
}
async function fetchAndRegisterLocaleData(locale, location = self.location.toString()) {
    const localeDataTextPromise = fetch(getLocaleFetchUrl(locale, location)).then(result => result.json());
    const timeoutPromise = new Promise((_, reject) => window.setTimeout(() => reject(new Error('timed out fetching locale')), 5000));
    const localeData = await Promise.race([timeoutPromise, localeDataTextPromise]);
    i18nInstance.registerLocaleData(locale, localeData);
}
function hasLocaleDataForTest(locale) {
    return i18nInstance.hasLocaleDataForTest(locale);
}
function resetLocaleDataForTest() {
    i18nInstance.resetLocaleDataForTest();
}
function registerLocaleDataForTest(locale, messages) {
    i18nInstance.registerLocaleData(locale, messages);
}
function getLazilyComputedLocalizedString(registeredStrings, id, values = {}) {
    return () => getLocalizedString(registeredStrings, id, values);
}
function getLocalizedString(registeredStrings, id, values = {}) {
    return registeredStrings.getLocalizedStringSetFor(DevToolsLocale.instance().locale).getLocalizedString(id, values);
}
function registerUIStrings(path, stringStructure) {
    return i18nInstance.registerFileStrings(path, stringStructure);
}
function serializeUIString(string, values = {}) {
    const serializedMessage = { string, values };
    return JSON.stringify(serializedMessage);
}
function deserializeUIString(serializedMessage) {
    if (!serializedMessage) {
        return { string: '', values: {} };
    }
    return JSON.parse(serializedMessage);
}
function lockedString(str) {
    return str;
}
function lockedLazyString(str) {
    return () => str;
}
function getLocalizedLanguageRegion(localeString, devtoolsLocale) {
    const locale = new Intl.Locale(localeString);
    const { language, baseName } = locale;
    const devtoolsLoc = new Intl.Locale(devtoolsLocale.locale);
    const targetLanguage = language === devtoolsLoc.language ? 'en' : baseName;
    const languageInCurrentLocale = new Intl.DisplayNames([devtoolsLocale.locale], { type: 'language' }).of(language);
    const languageInTargetLocale = new Intl.DisplayNames([targetLanguage], { type: 'language' }).of(language);
    let wrappedRegionInCurrentLocale = '';
    let wrappedRegionInTargetLocale = '';
    if (locale.region) {
        const regionInCurrentLocale = new Intl.DisplayNames([devtoolsLocale.locale], { type: 'region', style: 'short' }).of(locale.region);
        const regionInTargetLocale = new Intl.DisplayNames([targetLanguage], { type: 'region', style: 'short' }).of(locale.region);
        wrappedRegionInCurrentLocale = ` (${regionInCurrentLocale})`;
        wrappedRegionInTargetLocale = ` (${regionInTargetLocale})`;
    }
    return `${languageInCurrentLocale}${wrappedRegionInCurrentLocale} - ${languageInTargetLocale}${wrappedRegionInTargetLocale}`;
}

var i18nImpl = /*#__PURE__*/Object.freeze({
	__proto__: null,
	deserializeUIString: deserializeUIString,
	fetchAndRegisterLocaleData: fetchAndRegisterLocaleData,
	getAllSupportedDevToolsLocales: getAllSupportedDevToolsLocales,
	getLazilyComputedLocalizedString: getLazilyComputedLocalizedString,
	getLocalizedLanguageRegion: getLocalizedLanguageRegion,
	getLocalizedString: getLocalizedString,
	hasLocaleDataForTest: hasLocaleDataForTest,
	lockedLazyString: lockedLazyString,
	lockedString: lockedString,
	lookupClosestSupportedDevToolsLocale: lookupClosestSupportedDevToolsLocale,
	registerLocaleDataForTest: registerLocaleDataForTest,
	registerUIStrings: registerUIStrings,
	resetLocaleDataForTest: resetLocaleDataForTest,
	serializeUIString: serializeUIString
});

// Copyright 2021 The Chromium Authors
const narrowMillisecondsInteger = defineFormatter({
    style: 'unit',
    unit: 'millisecond',
    unitDisplay: 'narrow',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
});
const longMilliseconds = defineFormatter({
    style: 'unit',
    unit: 'millisecond',
    unitDisplay: 'long',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
});
const narrowMicrosecondsInteger = defineFormatter({
    style: 'unit',
    unit: 'microsecond',
    unitDisplay: 'narrow',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
});
const narrowMillisecondsDecimal = defineFormatter({
    style: 'unit',
    unit: 'millisecond',
    unitDisplay: 'narrow',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
});
const narrowSecondsDecimal = defineFormatter({
    style: 'unit',
    unit: 'second',
    unitDisplay: 'narrow',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
});
const shortMinutesDecimal = defineFormatter({
    style: 'unit',
    unit: 'minute',
    unitDisplay: 'short',
    minimumFractionDigits: 0,
    maximumFractionDigits: 1,
});
const shortHoursDecimal = defineFormatter({
    style: 'unit',
    unit: 'hour',
    unitDisplay: 'short',
    minimumFractionDigits: 0,
    maximumFractionDigits: 1,
});
const longDaysDecimal = defineFormatter({
    style: 'unit',
    unit: 'day',
    unitDisplay: 'long',
    minimumFractionDigits: 0,
    maximumFractionDigits: 1,
});
function formatMicroSecondsTime(time) {
    return millisToString(microSecondsToMilliSeconds(time), true);
}
function formatMicroSecondsAsSeconds(time) {
    const milliseconds = microSecondsToMilliSeconds(time);
    const seconds = milliSecondsToSeconds(milliseconds);
    return narrowSecondsDecimal.format(seconds);
}
function formatMicroSecondsAsMillisFixed(time) {
    const milliseconds = microSecondsToMilliSeconds(time);
    return narrowMillisecondsInteger.format(milliseconds);
}
function formatMicroSecondsAsMillisFixedExpanded(time) {
    const milliseconds = microSecondsToMilliSeconds(time);
    return longMilliseconds.format(milliseconds);
}
function millisToString(ms, higherResolution) {
    if (!isFinite(ms)) {
        return '-';
    }
    if (higherResolution && ms < 0.1) {
        return narrowMicrosecondsInteger.format(ms * 1000);
    }
    if (higherResolution && ms < 1000) {
        return narrowMillisecondsDecimal.format(ms);
    }
    if (ms < 1000) {
        return narrowMillisecondsInteger.format(ms);
    }
    const seconds = ms / 1000;
    if (seconds < 60) {
        return narrowSecondsDecimal.format(seconds);
    }
    const minutes = seconds / 60;
    if (minutes < 60) {
        return shortMinutesDecimal.format(minutes);
    }
    const hours = minutes / 60;
    if (hours < 24) {
        return shortHoursDecimal.format(hours);
    }
    const days = hours / 24;
    return longDaysDecimal.format(days);
}
const preciseMillisToStringFormattersCache = new Map();
function preciseMillisToString(ms, precision = 0, separator) {
    let formatter = preciseMillisToStringFormattersCache.get(precision);
    if (!formatter) {
        formatter = defineFormatter({
            style: 'unit',
            unit: 'millisecond',
            unitDisplay: 'narrow',
            minimumFractionDigits: precision,
            maximumFractionDigits: precision,
        });
        preciseMillisToStringFormattersCache.set(precision, formatter);
    }
    return formatter.format(ms, separator);
}
const preciseSecondsToStringFormattersCache = new Map();
function preciseSecondsToString(ms, precision = 0) {
    let formatter = preciseSecondsToStringFormattersCache.get(precision);
    if (!formatter) {
        formatter = defineFormatter({
            style: 'unit',
            unit: 'second',
            unitDisplay: 'narrow',
            minimumFractionDigits: precision,
            maximumFractionDigits: precision,
        });
        preciseSecondsToStringFormattersCache.set(precision, formatter);
    }
    return formatter.format(ms);
}
function secondsToString(seconds, higherResolution) {
    if (!isFinite(seconds)) {
        return '-';
    }
    return millisToString(seconds * 1000, higherResolution);
}

var timeUtilities = /*#__PURE__*/Object.freeze({
	__proto__: null,
	formatMicroSecondsAsMillisFixed: formatMicroSecondsAsMillisFixed,
	formatMicroSecondsAsMillisFixedExpanded: formatMicroSecondsAsMillisFixedExpanded,
	formatMicroSecondsAsSeconds: formatMicroSecondsAsSeconds,
	formatMicroSecondsTime: formatMicroSecondsTime,
	millisToString: millisToString,
	preciseMillisToString: preciseMillisToString,
	preciseSecondsToString: preciseSecondsToString,
	secondsToString: secondsToString
});

// Copyright 2020 The Chromium Authors

var i18n = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ByteUtilities: ByteUtilities,
	DevToolsLocale: DevToolsLocale$1,
	NumberFormatter: NumberFormatter,
	TimeUtilities: timeUtilities,
	i18n: i18nImpl
});

// Copyright 2014 The Chromium Authors
const UIStrings$1b = {
    elementsPanel: 'Elements panel',
    stylesSidebar: 'styles sidebar',
    changesDrawer: 'Changes drawer',
    issuesView: 'Issues view',
    networkPanel: 'Network panel',
    requestConditionsDrawer: 'Request conditions drawer',
    applicationPanel: 'Application panel',
    sourcesPanel: 'Sources panel',
    timelinePanel: 'Performance panel',
    memoryInspectorPanel: 'Memory inspector panel',
    developerResourcesPanel: 'Developer Resources panel',
    animationsPanel: 'Animations panel',
};
const str_$1a = registerUIStrings('core/common/Revealer.ts', UIStrings$1b);
const i18nLazyString$h = getLazilyComputedLocalizedString.bind(undefined, str_$1a);
let revealerRegistry;
class RevealerRegistry {
    registeredRevealers = [];
    static instance() {
        if (revealerRegistry === undefined) {
            revealerRegistry = new RevealerRegistry();
        }
        return revealerRegistry;
    }
    static removeInstance() {
        revealerRegistry = undefined;
    }
    register(registration) {
        this.registeredRevealers.push(registration);
    }
    async reveal(revealable, omitFocus) {
        const revealers = await Promise.all(this.getApplicableRegisteredRevealers(revealable).map(registration => registration.loadRevealer()));
        if (revealers.length < 1) {
            throw new Error(`No revealers found for ${revealable}`);
        }
        if (revealers.length > 1) {
            throw new Error(`Conflicting reveals found for ${revealable}`);
        }
        return await revealers[0].reveal(revealable, omitFocus);
    }
    getApplicableRegisteredRevealers(revealable) {
        return this.registeredRevealers.filter(registration => {
            for (const contextType of registration.contextTypes()) {
                if (revealable instanceof contextType) {
                    return true;
                }
            }
            return false;
        });
    }
}
function revealDestination(revealable) {
    const revealers = RevealerRegistry.instance().getApplicableRegisteredRevealers(revealable);
    for (const { destination } of revealers) {
        if (destination) {
            return destination();
        }
    }
    return null;
}
function registerRevealer(registration) {
    RevealerRegistry.instance().register(registration);
}
async function reveal(revealable, omitFocus = false) {
    await RevealerRegistry.instance().reveal(revealable, omitFocus);
}
const RevealerDestination = {
    DEVELOPER_RESOURCES_PANEL: i18nLazyString$h(UIStrings$1b.developerResourcesPanel),
    ELEMENTS_PANEL: i18nLazyString$h(UIStrings$1b.elementsPanel),
    STYLES_SIDEBAR: i18nLazyString$h(UIStrings$1b.stylesSidebar),
    CHANGES_DRAWER: i18nLazyString$h(UIStrings$1b.changesDrawer),
    ISSUES_VIEW: i18nLazyString$h(UIStrings$1b.issuesView),
    NETWORK_PANEL: i18nLazyString$h(UIStrings$1b.networkPanel),
    REQUEST_CONDITIONS_DRAWER: i18nLazyString$h(UIStrings$1b.requestConditionsDrawer),
    TIMELINE_PANEL: i18nLazyString$h(UIStrings$1b.timelinePanel),
    APPLICATION_PANEL: i18nLazyString$h(UIStrings$1b.applicationPanel),
    SOURCES_PANEL: i18nLazyString$h(UIStrings$1b.sourcesPanel),
    MEMORY_INSPECTOR_PANEL: i18nLazyString$h(UIStrings$1b.memoryInspectorPanel),
    ANIMATIONS_PANEL: i18nLazyString$h(UIStrings$1b.animationsPanel),
};

var Revealer = /*#__PURE__*/Object.freeze({
	__proto__: null,
	RevealerDestination: RevealerDestination,
	RevealerRegistry: RevealerRegistry,
	registerRevealer: registerRevealer,
	reveal: reveal,
	revealDestination: revealDestination
});

// Copyright 2014 The Chromium Authors
let consoleInstance;
class Console extends ObjectWrapper {
    #messages = [];
    static instance(opts) {
        if (!consoleInstance || opts?.forceNew) {
            consoleInstance = new Console();
        }
        return consoleInstance;
    }
    static removeInstance() {
        consoleInstance = undefined;
    }
    addMessage(text, level = "info" , show = false, source) {
        const message = new Message$1(text, level, Date.now(), show, source);
        this.#messages.push(message);
        this.dispatchEventToListeners("messageAdded" , message);
    }
    log(text) {
        this.addMessage(text, "info" );
    }
    warn(text, source) {
        this.addMessage(text, "warning" , undefined, source);
    }
    error(text, show = true) {
        this.addMessage(text, "error" , show);
    }
    messages() {
        return this.#messages;
    }
    show() {
        void this.showPromise();
    }
    showPromise() {
        return reveal(this);
    }
}
var FrontendMessageSource;
(function (FrontendMessageSource) {
    FrontendMessageSource["CSS"] = "css";
    FrontendMessageSource["ConsoleAPI"] = "console-api";
    FrontendMessageSource["ISSUE_PANEL"] = "issue-panel";
    FrontendMessageSource["SELF_XSS"] = "self-xss";
})(FrontendMessageSource || (FrontendMessageSource = {}));
let Message$1 = class Message {
    text;
    level;
    timestamp;
    show;
    source;
    constructor(text, level, timestamp, show, source) {
        this.text = text;
        this.level = level;
        this.timestamp = (typeof timestamp === 'number') ? timestamp : Date.now();
        this.show = show;
        if (source) {
            this.source = source;
        }
    }
};

var Console$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Console: Console,
	get FrontendMessageSource () { return FrontendMessageSource; },
	Message: Message$1
});

// Copyright 2020 The Chromium Authors
const debounce = function (func, delay) {
    let timer;
    const debounced = (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => func(...args), testDebounceOverride ? 0 : delay);
    };
    return debounced;
};
let testDebounceOverride = false;
function enableTestOverride() {
    testDebounceOverride = true;
}
function disableTestOverride() {
    testDebounceOverride = false;
}

var Debouncer = /*#__PURE__*/Object.freeze({
	__proto__: null,
	debounce: debounce,
	disableTestOverride: disableTestOverride,
	enableTestOverride: enableTestOverride
});

// Copyright 2021 The Chromium Authors
function removeEventListeners(eventList) {
    for (const eventInfo of eventList) {
        eventInfo.eventTarget.removeEventListener(eventInfo.eventType, eventInfo.listener, eventInfo.thisObject);
    }
    eventList.splice(0);
}
function fireEvent(name, detail = {}, target = window) {
    const evt = new CustomEvent(name, { bubbles: true, cancelable: true, detail });
    target.dispatchEvent(evt);
}

var EventTarget$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	fireEvent: fireEvent,
	removeEventListeners: removeEventListeners
});

// Copyright 2025 The Chromium Authors
function isGzip(ab) {
    const buf = new Uint8Array(ab);
    if (!buf || buf.length < 3) {
        return false;
    }
    return buf[0] === 0x1F && buf[1] === 0x8B && buf[2] === 0x08;
}
async function arrayBufferToString(ab) {
    if (isGzip(ab)) {
        return await decompress(ab);
    }
    const str = new TextDecoder('utf-8').decode(ab);
    return str;
}
async function fileToString(file) {
    let stream = file.stream();
    if (file.type.endsWith('gzip')) {
        stream = decompressStream(stream);
    }
    const arrayBuffer = await new Response(stream).arrayBuffer();
    const str = new TextDecoder('utf-8').decode(arrayBuffer);
    return str;
}
async function decompress(gzippedBuffer, charset = 'utf-8') {
    const buffer = await gzipCodec(gzippedBuffer, new DecompressionStream('gzip'));
    const str = new TextDecoder(charset).decode(buffer);
    return str;
}
async function decompressDeflate(buffer, charset = 'utf-8') {
    let decompressedBuffer;
    try {
        decompressedBuffer = await gzipCodec(buffer, new DecompressionStream('deflate'));
    }
    catch {
        decompressedBuffer = await gzipCodec(buffer, new DecompressionStream('deflate-raw'));
    }
    return new TextDecoder(charset).decode(decompressedBuffer);
}
async function compress(str) {
    const encoded = new TextEncoder().encode(str);
    const buffer = await gzipCodec(encoded, new CompressionStream('gzip'));
    return buffer;
}
async function gzipCodec(buffer, codecStream) {
    const readable = new ReadableStream({
        start(controller) {
            controller.enqueue(buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer);
            controller.close();
        }
    });
    const codecReadable = readable.pipeThrough(codecStream);
    return await new Response(codecReadable).arrayBuffer();
}
function decompressStream(stream) {
    const ds = new DecompressionStream('gzip');
    return stream.pipeThrough(ds);
}
function compressStream(stream) {
    const cs = new CompressionStream('gzip');
    return stream.pipeThrough(cs);
}
function createMonitoredStream(stream, onProgress) {
    let bytesRead = 0;
    const progressTransformer = new TransformStream({
        transform(chunk, controller) {
            bytesRead += chunk.byteLength;
            onProgress(bytesRead);
            controller.enqueue(chunk);
        }
    });
    return stream.pipeThrough(progressTransformer);
}

var Gzip = /*#__PURE__*/Object.freeze({
	__proto__: null,
	arrayBufferToString: arrayBufferToString,
	compress: compress,
	compressStream: compressStream,
	createMonitoredStream: createMonitoredStream,
	decompress: decompress,
	decompressDeflate: decompressDeflate,
	decompressStream: decompressStream,
	fileToString: fileToString,
	isGzip: isGzip
});

// Copyright 2019 The Chromium Authors

var JavaScriptMetaData = /*#__PURE__*/Object.freeze({
	__proto__: null
});

// Copyright 2020 The Chromium Authors
const UNINITIALIZED = Symbol('uninitialized');
const ERROR_STATE = Symbol('error');
function lazy(producer) {
    let value = UNINITIALIZED;
    let error = new Error('Initial');
    return () => {
        if (value === ERROR_STATE) {
            throw error;
        }
        else if (value !== UNINITIALIZED) {
            return value;
        }
        try {
            value = producer();
            return value;
        }
        catch (err) {
            error = err instanceof Error ? err : new Error(err);
            value = ERROR_STATE;
            throw error;
        }
    };
}

var Lazy = /*#__PURE__*/Object.freeze({
	__proto__: null,
	lazy: lazy
});

// Copyright 2024 The Chromium Authors
class MapWithDefault extends Map {
    getOrInsert(key, defaultValue) {
        if (!this.has(key)) {
            this.set(key, defaultValue);
        }
        return this.get(key);
    }
    getOrInsertComputed(key, callbackFunction) {
        if (!this.has(key)) {
            this.set(key, callbackFunction(key));
        }
        return this.get(key);
    }
}

var MapWithDefault$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	MapWithDefault: MapWithDefault
});

// Copyright 2022 The Chromium Authors
class Mutex {
    #locked = false;
    #acquirers = [];
    acquire() {
        const state = { resolved: false };
        if (this.#locked) {
            return new Promise(resolve => {
                this.#acquirers.push(() => resolve(this.#release.bind(this, state)));
            });
        }
        this.#locked = true;
        return Promise.resolve(this.#release.bind(this, state));
    }
    #release(state) {
        if (state.resolved) {
            throw new Error('Cannot release more than once.');
        }
        state.resolved = true;
        const resolve = this.#acquirers.shift();
        if (!resolve) {
            this.#locked = false;
            return;
        }
        resolve();
    }
    async run(action) {
        const release = await this.acquire();
        try {
            const result = await action();
            return result;
        }
        finally {
            release();
        }
    }
}

var Mutex$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Mutex: Mutex
});

// Copyright 2012 The Chromium Authors
function normalizePath(path) {
    if (path.indexOf('..') === -1 && path.indexOf('.') === -1) {
        return path;
    }
    const segments = (path[0] === '/' ? path.substring(1) : path).split('/');
    const normalizedSegments = [];
    for (const segment of segments) {
        if (segment === '.') {
            continue;
        }
        else if (segment === '..') {
            normalizedSegments.pop();
        }
        else {
            normalizedSegments.push(segment);
        }
    }
    let normalizedPath = normalizedSegments.join('/');
    if (path[0] === '/' && normalizedPath) {
        normalizedPath = '/' + normalizedPath;
    }
    if (normalizedPath[normalizedPath.length - 1] !== '/' &&
        ((path[path.length - 1] === '/') || (segments[segments.length - 1] === '.') ||
            (segments[segments.length - 1] === '..'))) {
        normalizedPath = normalizedPath + '/';
    }
    return normalizedPath;
}
function schemeIs(url, scheme) {
    try {
        return (new URL(url)).protocol === scheme;
    }
    catch {
        return false;
    }
}
class ParsedURL {
    isValid = false;
    url;
    scheme = '';
    user = '';
    host = '';
    port = '';
    path = '';
    queryParams = '';
    fragment = '';
    folderPathComponents = '';
    lastPathComponent = '';
    blobInnerScheme;
    #displayName;
    #dataURLDisplayName;
    constructor(url) {
        this.url = url;
        const isBlobUrl = this.url.startsWith('blob:');
        const urlToMatch = isBlobUrl ? url.substring(5) : url;
        const match = urlToMatch.match(ParsedURL.urlRegex());
        if (match) {
            this.isValid = true;
            if (isBlobUrl) {
                this.blobInnerScheme = match[2].toLowerCase();
                this.scheme = 'blob';
            }
            else {
                this.scheme = match[2].toLowerCase();
            }
            this.user = match[3] ?? '';
            this.host = match[4] ?? '';
            this.port = match[5] ?? '';
            this.path = match[6] ?? '/';
            this.queryParams = match[7] ?? '';
            this.fragment = match[8] ?? '';
        }
        else {
            if (this.url.startsWith('data:')) {
                this.scheme = 'data';
                return;
            }
            if (this.url.startsWith('blob:')) {
                this.scheme = 'blob';
                return;
            }
            if (this.url === 'about:blank') {
                this.scheme = 'about';
                return;
            }
            this.path = this.url;
        }
        const lastSlashExceptTrailingIndex = this.path.lastIndexOf('/', this.path.length - 2);
        if (lastSlashExceptTrailingIndex !== -1) {
            this.lastPathComponent = this.path.substring(lastSlashExceptTrailingIndex + 1);
        }
        else {
            this.lastPathComponent = this.path;
        }
        const lastSlashIndex = this.path.lastIndexOf('/');
        if (lastSlashIndex !== -1) {
            this.folderPathComponents = this.path.substring(0, lastSlashIndex);
        }
    }
    static fromString(string) {
        const parsedURL = new ParsedURL(string.toString());
        if (parsedURL.isValid) {
            return parsedURL;
        }
        return null;
    }
    static preEncodeSpecialCharactersInPath(path) {
        for (const specialChar of ['%', ';', '#', '?', ' ']) {
            (path) = path.replaceAll(specialChar, encodeURIComponent(specialChar));
        }
        return path;
    }
    static rawPathToEncodedPathString(path) {
        const partiallyEncoded = ParsedURL.preEncodeSpecialCharactersInPath(path);
        if (path.startsWith('/')) {
            return new URL(partiallyEncoded, 'file:///').pathname;
        }
        return new URL('/' + partiallyEncoded, 'file:///').pathname.substr(1);
    }
    static encodedFromParentPathAndName(parentPath, name) {
        return ParsedURL.concatenate(parentPath, '/', ParsedURL.preEncodeSpecialCharactersInPath(name));
    }
    static urlFromParentUrlAndName(parentUrl, name) {
        return ParsedURL.concatenate(parentUrl, '/', ParsedURL.preEncodeSpecialCharactersInPath(name));
    }
    static encodedPathToRawPathString(encPath) {
        return decodeURIComponent(encPath);
    }
    static rawPathToUrlString(fileSystemPath) {
        let preEncodedPath = ParsedURL.preEncodeSpecialCharactersInPath(fileSystemPath.replace(/\\/g, '/'));
        preEncodedPath = preEncodedPath.replace(/\\/g, '/');
        if (!preEncodedPath.startsWith('file://')) {
            if (preEncodedPath.startsWith('/')) {
                preEncodedPath = 'file://' + preEncodedPath;
            }
            else {
                preEncodedPath = 'file:///' + preEncodedPath;
            }
        }
        return new URL(preEncodedPath).toString();
    }
    static relativePathToUrlString(relativePath, baseURL) {
        const preEncodedPath = ParsedURL.preEncodeSpecialCharactersInPath(relativePath.replace(/\\/g, '/'));
        return new URL(preEncodedPath, baseURL).toString();
    }
    static urlToRawPathString(fileURL, isWindows) {
        console.assert(fileURL.startsWith('file://'), 'This must be a file URL.');
        const decodedFileURL = decodeURIComponent(fileURL);
        if (isWindows) {
            return decodedFileURL.substr('file:///'.length).replace(/\//g, '\\');
        }
        return decodedFileURL.substr('file://'.length);
    }
    static sliceUrlToEncodedPathString(url, start) {
        return url.substring(start);
    }
    static substr(devToolsPath, from, length) {
        return devToolsPath.substr(from, length);
    }
    static substring(devToolsPath, start, end) {
        return devToolsPath.substring(start, end);
    }
    static prepend(prefix, devToolsPath) {
        return prefix + devToolsPath;
    }
    static concatenate(devToolsPath, ...appendage) {
        return devToolsPath.concat(...appendage);
    }
    static trim(devToolsPath) {
        return devToolsPath.trim();
    }
    static slice(devToolsPath, start, end) {
        return devToolsPath.slice(start, end);
    }
    static join(devToolsPaths, separator) {
        return devToolsPaths.join(separator);
    }
    static split(devToolsPath, separator, limit) {
        return devToolsPath.split(separator, limit);
    }
    static toLowerCase(devToolsPath) {
        return devToolsPath.toLowerCase();
    }
    static isValidUrlString(str) {
        return new ParsedURL(str).isValid;
    }
    static urlWithoutHash(url) {
        const hashIndex = url.indexOf('#');
        if (hashIndex !== -1) {
            return url.substr(0, hashIndex);
        }
        return url;
    }
    static urlRegex() {
        if (ParsedURL.urlRegexInstance) {
            return ParsedURL.urlRegexInstance;
        }
        const schemeRegex = /([A-Za-z][A-Za-z0-9+.-]*):\/\//;
        const userRegex = /(?:([A-Za-z0-9\-._~%!$&'()*+,;=:]*)@)?/;
        const hostRegex = /((?:\[::\d?\])|(?:[^\s\/:]*))/;
        const portRegex = /(?::([\d]+))?/;
        const pathRegex = /(\/[^#?]*)?/;
        const queryRegex = /(?:\?([^#]*))?/;
        const fragmentRegex = /(?:#(.*))?/;
        ParsedURL.urlRegexInstance = new RegExp('^(' + schemeRegex.source + userRegex.source + hostRegex.source + portRegex.source + ')' + pathRegex.source +
            queryRegex.source + fragmentRegex.source + '$');
        return ParsedURL.urlRegexInstance;
    }
    static extractPath(url) {
        const parsedURL = this.fromString(url);
        return (parsedURL ? parsedURL.path : '');
    }
    static extractOrigin(url) {
        const parsedURL = this.fromString(url);
        return parsedURL ? parsedURL.securityOrigin() : EmptyUrlString;
    }
    static extractExtension(url) {
        url = ParsedURL.urlWithoutHash(url);
        const indexOfQuestionMark = url.indexOf('?');
        if (indexOfQuestionMark !== -1) {
            url = url.substr(0, indexOfQuestionMark);
        }
        const lastIndexOfSlash = url.lastIndexOf('/');
        if (lastIndexOfSlash !== -1) {
            url = url.substr(lastIndexOfSlash + 1);
        }
        const lastIndexOfDot = url.lastIndexOf('.');
        if (lastIndexOfDot !== -1) {
            url = url.substr(lastIndexOfDot + 1);
            const lastIndexOfPercent = url.indexOf('%');
            if (lastIndexOfPercent !== -1) {
                return url.substr(0, lastIndexOfPercent);
            }
            return url;
        }
        return '';
    }
    static extractName(url) {
        if (url.endsWith('/')) {
            url = url.slice(0, -1);
        }
        let index = url.lastIndexOf('/');
        const pathAndQuery = index !== -1 ? url.substr(index + 1) : url;
        index = pathAndQuery.indexOf('?');
        return index < 0 ? pathAndQuery : pathAndQuery.substr(0, index);
    }
    static completeURL(baseURL, href) {
        if (href.startsWith('data:') || href.startsWith('blob:') || href.startsWith('javascript:') ||
            href.startsWith('mailto:')) {
            return href;
        }
        const trimmedHref = href.trim();
        const parsedHref = this.fromString(trimmedHref);
        if (parsedHref?.scheme) {
            const securityOrigin = parsedHref.securityOrigin();
            const pathText = normalizePath(parsedHref.path);
            const queryText = parsedHref.queryParams && `?${parsedHref.queryParams}`;
            const fragmentText = parsedHref.fragment && `#${parsedHref.fragment}`;
            return securityOrigin + pathText + queryText + fragmentText;
        }
        const parsedURL = this.fromString(baseURL);
        if (!parsedURL) {
            return null;
        }
        if (parsedURL.isDataURL()) {
            return href;
        }
        if (href.length > 1 && href.charAt(0) === '/' && href.charAt(1) === '/') {
            return parsedURL.scheme + ':' + href;
        }
        const securityOrigin = parsedURL.securityOrigin();
        const pathText = parsedURL.path;
        const queryText = parsedURL.queryParams ? '?' + parsedURL.queryParams : '';
        if (!href.length) {
            return securityOrigin + pathText + queryText;
        }
        if (href.charAt(0) === '#') {
            return securityOrigin + pathText + queryText + href;
        }
        if (href.charAt(0) === '?') {
            return securityOrigin + pathText + href;
        }
        const hrefMatches = href.match(/^[^#?]*/);
        if (!hrefMatches || !href.length) {
            throw new Error('Invalid href');
        }
        let hrefPath = hrefMatches[0];
        const hrefSuffix = href.substring(hrefPath.length);
        if (hrefPath.charAt(0) !== '/') {
            hrefPath = parsedURL.folderPathComponents + '/' + hrefPath;
        }
        return securityOrigin + normalizePath(hrefPath) + hrefSuffix;
    }
    static splitLineAndColumn(string) {
        const beforePathMatch = string.match(ParsedURL.urlRegex());
        let beforePath = '';
        let pathAndAfter = string;
        if (beforePathMatch) {
            beforePath = beforePathMatch[1];
            pathAndAfter = string.substring(beforePathMatch[1].length);
        }
        const lineColumnRegEx = /(?::(\d+))?(?::(\d+))?$/;
        const lineColumnMatch = lineColumnRegEx.exec(pathAndAfter);
        let lineNumber;
        let columnNumber;
        console.assert(Boolean(lineColumnMatch));
        if (!lineColumnMatch) {
            return { url: string, lineNumber: 0, columnNumber: 0 };
        }
        if (typeof (lineColumnMatch[1]) === 'string') {
            lineNumber = parseInt(lineColumnMatch[1], 10);
            lineNumber = isNaN(lineNumber) ? undefined : lineNumber - 1;
        }
        if (typeof (lineColumnMatch[2]) === 'string') {
            columnNumber = parseInt(lineColumnMatch[2], 10);
            columnNumber = isNaN(columnNumber) ? undefined : columnNumber - 1;
        }
        let url = beforePath + pathAndAfter.substring(0, pathAndAfter.length - lineColumnMatch[0].length);
        if (lineColumnMatch[1] === undefined && lineColumnMatch[2] === undefined) {
            const wasmCodeOffsetRegex = /wasm-function\[\d+\]:0x([a-z0-9]+)$/g;
            const wasmCodeOffsetMatch = wasmCodeOffsetRegex.exec(pathAndAfter);
            if (wasmCodeOffsetMatch && typeof (wasmCodeOffsetMatch[1]) === 'string') {
                url = ParsedURL.removeWasmFunctionInfoFromURL(url);
                columnNumber = parseInt(wasmCodeOffsetMatch[1], 16);
                columnNumber = isNaN(columnNumber) ? undefined : columnNumber;
            }
        }
        return { url, lineNumber, columnNumber };
    }
    static removeWasmFunctionInfoFromURL(url) {
        const wasmFunctionRegEx = /:wasm-function\[\d+\]/;
        const wasmFunctionIndex = url.search(wasmFunctionRegEx);
        if (wasmFunctionIndex === -1) {
            return url;
        }
        return ParsedURL.substring(url, 0, wasmFunctionIndex);
    }
    static beginsWithWindowsDriveLetter(url) {
        return /^[A-Za-z]:/.test(url);
    }
    static beginsWithScheme(url) {
        return /^[A-Za-z][A-Za-z0-9+.-]*:/.test(url);
    }
    static isRelativeURL(url) {
        return !this.beginsWithScheme(url) || this.beginsWithWindowsDriveLetter(url);
    }
    get displayName() {
        if (this.#displayName) {
            return this.#displayName;
        }
        if (this.isDataURL()) {
            return this.dataURLDisplayName();
        }
        if (this.isBlobURL()) {
            return this.url;
        }
        if (this.isAboutBlank()) {
            return this.url;
        }
        this.#displayName = this.lastPathComponent;
        if (!this.#displayName) {
            this.#displayName = (this.host || '') + '/';
        }
        if (this.#displayName === '/') {
            this.#displayName = this.url;
        }
        return this.#displayName;
    }
    dataURLDisplayName() {
        if (this.#dataURLDisplayName) {
            return this.#dataURLDisplayName;
        }
        if (!this.isDataURL()) {
            return '';
        }
        this.#dataURLDisplayName = trimEndWithMaxLength(this.url, 20);
        return this.#dataURLDisplayName;
    }
    isAboutBlank() {
        return this.url === 'about:blank';
    }
    isDataURL() {
        return this.scheme === 'data';
    }
    extractDataUrlMimeType() {
        const regexp = /^data:((?<type>\w+)\/(?<subtype>\w+))?(;base64)?,/;
        const match = this.url.match(regexp);
        return {
            type: match?.groups?.type,
            subtype: match?.groups?.subtype,
        };
    }
    isBlobURL() {
        return this.url.startsWith('blob:');
    }
    lastPathComponentWithFragment() {
        return this.lastPathComponent + (this.fragment ? '#' + this.fragment : '');
    }
    domain() {
        if (this.isDataURL()) {
            return 'data:';
        }
        return this.host + (this.port ? ':' + this.port : '');
    }
    securityOrigin() {
        if (this.isDataURL()) {
            return 'data:';
        }
        const scheme = this.isBlobURL() ? this.blobInnerScheme : this.scheme;
        return scheme + '://' + this.domain();
    }
    urlWithoutScheme() {
        if (this.scheme && this.url.startsWith(this.scheme + '://')) {
            return this.url.substring(this.scheme.length + 3);
        }
        return this.url;
    }
    static urlRegexInstance = null;
}

var ParsedURL$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ParsedURL: ParsedURL,
	normalizePath: normalizePath,
	schemeIs: schemeIs
});

// Copyright 2012 The Chromium Authors
class Progress {
    totalWork = 0;
    worked = 0;
    title;
    canceled = false;
    done = false;
}
class CompositeProgress {
    parent;
    #children;
    #childrenDone;
    constructor(parent) {
        this.parent = parent;
        this.#children = [];
        this.#childrenDone = 0;
        this.parent.totalWork = 1;
        this.parent.worked = 0;
    }
    childDone() {
        if (++this.#childrenDone !== this.#children.length) {
            return;
        }
        this.parent.done = true;
    }
    createSubProgress(weight) {
        const child = new SubProgress(this, weight);
        this.#children.push(child);
        return child;
    }
    update() {
        let totalWeights = 0;
        let done = 0;
        for (let i = 0; i < this.#children.length; ++i) {
            const child = this.#children[i];
            if (child.totalWork) {
                done += child.weight * child.worked / child.totalWork;
            }
            totalWeights += child.weight;
        }
        this.parent.worked = done / totalWeights;
    }
}
class SubProgress {
    #composite;
    #weight;
    #worked;
    #totalWork;
    constructor(composite, weight) {
        this.#composite = composite;
        this.#weight = weight || 1;
        this.#worked = 0;
        this.#totalWork = 0;
    }
    get canceled() {
        return this.#composite.parent.canceled;
    }
    set title(title) {
        this.#composite.parent.title = title;
    }
    set done(done) {
        if (!done) {
            return;
        }
        this.worked = this.#totalWork;
        this.#composite.childDone();
    }
    set totalWork(totalWork) {
        this.#totalWork = totalWork;
        this.#composite.update();
    }
    set worked(worked) {
        this.#worked = worked;
        this.#composite.update();
    }
    get weight() {
        return this.#weight;
    }
    get worked() {
        return this.#worked;
    }
    get totalWork() {
        return this.#totalWork;
    }
}
class ProgressProxy {
    #delegate;
    #doneCallback;
    #updateCallback;
    constructor(delegate, doneCallback, updateCallback) {
        this.#delegate = delegate;
        this.#doneCallback = doneCallback;
        this.#updateCallback = updateCallback;
    }
    get canceled() {
        return this.#delegate ? this.#delegate.canceled : false;
    }
    set title(title) {
        if (this.#delegate) {
            this.#delegate.title = title;
        }
        if (this.#updateCallback) {
            this.#updateCallback();
        }
    }
    get title() {
        return this.#delegate?.title ?? '';
    }
    set done(done) {
        if (this.#delegate) {
            this.#delegate.done = done;
        }
        if (done && this.#doneCallback) {
            this.#doneCallback();
        }
    }
    get done() {
        return this.#delegate ? this.#delegate.done : false;
    }
    set totalWork(totalWork) {
        if (this.#delegate) {
            this.#delegate.totalWork = totalWork;
        }
        if (this.#updateCallback) {
            this.#updateCallback();
        }
    }
    get totalWork() {
        return this.#delegate ? this.#delegate.totalWork : 0;
    }
    set worked(worked) {
        if (this.#delegate) {
            this.#delegate.worked = worked;
        }
        if (this.#updateCallback) {
            this.#updateCallback?.();
        }
    }
    get worked() {
        return this.#delegate ? this.#delegate.worked : 0;
    }
}

var Progress$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	CompositeProgress: CompositeProgress,
	Progress: Progress,
	ProgressProxy: ProgressProxy,
	SubProgress: SubProgress
});

// Copyright 2021 The Chromium Authors
class ResolverBase {
    #unresolvedIds = new Map();
    async waitFor(id) {
        const obj = this.getForId(id);
        if (!obj) {
            return await this.getOrCreatePromise(id);
        }
        return obj;
    }
    tryGet(id, callback) {
        const obj = this.getForId(id);
        if (!obj) {
            const swallowTheError = () => { };
            void this.getOrCreatePromise(id).catch(swallowTheError).then(obj => {
                if (obj) {
                    callback(obj);
                }
            });
            return null;
        }
        return obj;
    }
    clear() {
        this.stopListening();
        for (const [id, { reject }] of this.#unresolvedIds.entries()) {
            reject(new Error(`Object with ${id} never resolved.`));
        }
        this.#unresolvedIds.clear();
    }
    getOrCreatePromise(id) {
        const promiseInfo = this.#unresolvedIds.get(id);
        if (promiseInfo) {
            return promiseInfo.promise;
        }
        const { resolve, reject, promise } = Promise.withResolvers();
        this.#unresolvedIds.set(id, { promise, resolve, reject });
        this.startListening();
        return promise;
    }
    onResolve(id, t) {
        const promiseInfo = this.#unresolvedIds.get(id);
        this.#unresolvedIds.delete(id);
        if (this.#unresolvedIds.size === 0) {
            this.stopListening();
        }
        promiseInfo?.resolve(t);
    }
}

var ResolverBase$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ResolverBase: ResolverBase
});

// Copyright 2021 The Chromium Authors
/*
 * Copyright (C) 2012 Google Inc.  All rights reserved.
 * Copyright (C) 2007, 2008 Apple Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
const UIStrings$1a = {
    fetchAndXHR: '`Fetch` and `XHR`',
    javascript: 'JavaScript',
    js: 'JS',
    css: 'CSS',
    img: 'Img',
    media: 'Media',
    font: 'Font',
    doc: 'Doc',
    socketShort: 'Socket',
    webassembly: 'WebAssembly',
    wasm: 'Wasm',
    manifest: 'Manifest',
    other: 'Other',
    document: 'Document',
    stylesheet: 'Stylesheet',
    image: 'Image',
    script: 'Script',
    texttrack: 'TextTrack',
    fetch: 'Fetch',
    eventsource: 'EventSource',
    websocket: 'WebSocket',
    webtransport: 'WebTransport',
    directsocket: 'DirectSocket',
    signedexchange: 'SignedExchange',
    ping: 'Ping',
    cspviolationreport: 'CSPViolationReport',
    preflight: 'Preflight',
    fedcm: 'FedCM',
};
const str_$19 = registerUIStrings('core/common/ResourceType.ts', UIStrings$1a);
const i18nLazyString$g = getLazilyComputedLocalizedString.bind(undefined, str_$19);
class ResourceType {
    #name;
    #title;
    #category;
    #isTextType;
    constructor(name, title, category, isTextType) {
        this.#name = name;
        this.#title = title;
        this.#category = category;
        this.#isTextType = isTextType;
    }
    static fromMimeType(mimeType) {
        if (!mimeType) {
            return resourceTypes.Other;
        }
        if (mimeType.startsWith('text/html')) {
            return resourceTypes.Document;
        }
        if (mimeType.startsWith('text/css')) {
            return resourceTypes.Stylesheet;
        }
        if (mimeType.startsWith('image/')) {
            return resourceTypes.Image;
        }
        if (mimeType.startsWith('text/')) {
            return resourceTypes.Script;
        }
        if (mimeType.includes('font')) {
            return resourceTypes.Font;
        }
        if (mimeType.includes('script')) {
            return resourceTypes.Script;
        }
        if (mimeType.includes('octet')) {
            return resourceTypes.Other;
        }
        if (mimeType.includes('application')) {
            return resourceTypes.Script;
        }
        return resourceTypes.Other;
    }
    static fromMimeTypeOverride(mimeType) {
        if (mimeType === 'application/manifest+json') {
            return resourceTypes.Manifest;
        }
        if (mimeType === 'application/wasm') {
            return resourceTypes.Wasm;
        }
        return null;
    }
    static fromURL(url) {
        return resourceTypeByExtension.get(ParsedURL.extractExtension(url)) || null;
    }
    static fromName(name) {
        for (const resourceType of Object.values(resourceTypes)) {
            if (resourceType.name() === name) {
                return resourceType;
            }
        }
        return null;
    }
    static mimeFromURL(url) {
        if (url.startsWith('snippet://') || url.startsWith('debugger://')) {
            return 'text/javascript';
        }
        const name = ParsedURL.extractName(url);
        if (mimeTypeByName.has(name)) {
            return mimeTypeByName.get(name);
        }
        let ext = ParsedURL.extractExtension(url).toLowerCase();
        if (ext === 'html' && name.endsWith('.component.html')) {
            ext = 'component.html';
        }
        return mimeTypeByExtension.get(ext);
    }
    static mimeFromExtension(ext) {
        return mimeTypeByExtension.get(ext);
    }
    static simplifyContentType(contentType) {
        const regex = new RegExp('^application(.*json$|\/json\+.*)');
        return regex.test(contentType) ? 'application/json' : contentType;
    }
    static isJavaScriptMimeType(mimeType) {
        return mimeType === 'application/javascript' || mimeType === 'text/javascript';
    }
    static mediaTypeForMetrics(mimeType, isFromSourceMap, isMinified, isSnippet, isDebugger) {
        if (mimeType !== 'text/javascript') {
            return mimeType;
        }
        if (isFromSourceMap) {
            return 'text/javascript+sourcemapped';
        }
        if (isMinified) {
            return 'text/javascript+minified';
        }
        if (isSnippet) {
            return 'text/javascript+snippet';
        }
        if (isDebugger) {
            return 'text/javascript+eval';
        }
        return 'text/javascript+plain';
    }
    name() {
        return this.#name;
    }
    title() {
        return this.#title();
    }
    category() {
        return this.#category;
    }
    isTextType() {
        return this.#isTextType;
    }
    isScript() {
        return this.#name === 'script' || this.#name === 'sm-script';
    }
    hasScripts() {
        return this.isScript() || this.isDocument();
    }
    isStyleSheet() {
        return this.#name === 'stylesheet' || this.#name === 'sm-stylesheet';
    }
    hasStyleSheets() {
        return this.isStyleSheet() || this.isDocument();
    }
    isDocument() {
        return this.#name === 'document';
    }
    isDocumentOrScriptOrStyleSheet() {
        return this.isDocument() || this.isScript() || this.isStyleSheet();
    }
    isFont() {
        return this.#name === 'font';
    }
    isImage() {
        return this.#name === 'image';
    }
    isFromSourceMap() {
        return this.#name.startsWith('sm-');
    }
    toString() {
        return this.#name;
    }
    canonicalMimeType() {
        if (this.isDocument()) {
            return 'text/html';
        }
        if (this.isScript()) {
            return 'text/javascript';
        }
        if (this.isStyleSheet()) {
            return 'text/css';
        }
        return '';
    }
}
class ResourceCategory {
    name;
    title;
    shortTitle;
    constructor(name, title, shortTitle) {
        this.name = name;
        this.title = title;
        this.shortTitle = shortTitle;
    }
}
const resourceCategories = {
    XHR: new ResourceCategory('Fetch and XHR', i18nLazyString$g(UIStrings$1a.fetchAndXHR), lockedLazyString('Fetch/XHR')),
    Document: new ResourceCategory(UIStrings$1a.document, i18nLazyString$g(UIStrings$1a.document), i18nLazyString$g(UIStrings$1a.doc)),
    Stylesheet: new ResourceCategory(UIStrings$1a.css, i18nLazyString$g(UIStrings$1a.css), i18nLazyString$g(UIStrings$1a.css)),
    Script: new ResourceCategory(UIStrings$1a.javascript, i18nLazyString$g(UIStrings$1a.javascript), i18nLazyString$g(UIStrings$1a.js)),
    Font: new ResourceCategory(UIStrings$1a.font, i18nLazyString$g(UIStrings$1a.font), i18nLazyString$g(UIStrings$1a.font)),
    Image: new ResourceCategory(UIStrings$1a.image, i18nLazyString$g(UIStrings$1a.image), i18nLazyString$g(UIStrings$1a.img)),
    Media: new ResourceCategory(UIStrings$1a.media, i18nLazyString$g(UIStrings$1a.media), i18nLazyString$g(UIStrings$1a.media)),
    Manifest: new ResourceCategory(UIStrings$1a.manifest, i18nLazyString$g(UIStrings$1a.manifest), i18nLazyString$g(UIStrings$1a.manifest)),
    Socket: new ResourceCategory('Socket', lockedLazyString('WebSocket | WebTransport | DirectSocket'), i18nLazyString$g(UIStrings$1a.socketShort)),
    Wasm: new ResourceCategory(UIStrings$1a.webassembly, i18nLazyString$g(UIStrings$1a.webassembly), i18nLazyString$g(UIStrings$1a.wasm)),
    Other: new ResourceCategory(UIStrings$1a.other, i18nLazyString$g(UIStrings$1a.other), i18nLazyString$g(UIStrings$1a.other)),
};
const resourceTypes = {
    Document: new ResourceType('document', i18nLazyString$g(UIStrings$1a.document), resourceCategories.Document, true),
    Stylesheet: new ResourceType('stylesheet', i18nLazyString$g(UIStrings$1a.stylesheet), resourceCategories.Stylesheet, true),
    Image: new ResourceType('image', i18nLazyString$g(UIStrings$1a.image), resourceCategories.Image, false),
    Media: new ResourceType('media', i18nLazyString$g(UIStrings$1a.media), resourceCategories.Media, false),
    Font: new ResourceType('font', i18nLazyString$g(UIStrings$1a.font), resourceCategories.Font, false),
    Script: new ResourceType('script', i18nLazyString$g(UIStrings$1a.script), resourceCategories.Script, true),
    TextTrack: new ResourceType('texttrack', i18nLazyString$g(UIStrings$1a.texttrack), resourceCategories.Other, true),
    XHR: new ResourceType('xhr', lockedLazyString('XHR'), resourceCategories.XHR, true),
    Fetch: new ResourceType('fetch', i18nLazyString$g(UIStrings$1a.fetch), resourceCategories.XHR, true),
    Prefetch: new ResourceType('prefetch', lockedLazyString('Prefetch'), resourceCategories.Document, true),
    EventSource: new ResourceType('eventsource', i18nLazyString$g(UIStrings$1a.eventsource), resourceCategories.XHR, true),
    WebSocket: new ResourceType('websocket', i18nLazyString$g(UIStrings$1a.websocket), resourceCategories.Socket, false),
    WebTransport: new ResourceType('webtransport', i18nLazyString$g(UIStrings$1a.webtransport), resourceCategories.Socket, false),
    DirectSocket: new ResourceType('directsocket', i18nLazyString$g(UIStrings$1a.directsocket), resourceCategories.Socket, false),
    Wasm: new ResourceType('wasm', i18nLazyString$g(UIStrings$1a.wasm), resourceCategories.Wasm, false),
    Manifest: new ResourceType('manifest', i18nLazyString$g(UIStrings$1a.manifest), resourceCategories.Manifest, true),
    SignedExchange: new ResourceType('signed-exchange', i18nLazyString$g(UIStrings$1a.signedexchange), resourceCategories.Other, false),
    Ping: new ResourceType('ping', i18nLazyString$g(UIStrings$1a.ping), resourceCategories.Other, false),
    CSPViolationReport: new ResourceType('csp-violation-report', i18nLazyString$g(UIStrings$1a.cspviolationreport), resourceCategories.Other, false),
    Other: new ResourceType('other', i18nLazyString$g(UIStrings$1a.other), resourceCategories.Other, false),
    Preflight: new ResourceType('preflight', i18nLazyString$g(UIStrings$1a.preflight), resourceCategories.Other, true),
    SourceMapScript: new ResourceType('sm-script', i18nLazyString$g(UIStrings$1a.script), resourceCategories.Script, true),
    SourceMapStyleSheet: new ResourceType('sm-stylesheet', i18nLazyString$g(UIStrings$1a.stylesheet), resourceCategories.Stylesheet, true),
    FedCM: new ResourceType('fedcm', i18nLazyString$g(UIStrings$1a.fedcm), resourceCategories.Other, false),
};
const mimeTypeByName = new Map([
    ['Cakefile', 'text/x-coffeescript'],
]);
const resourceTypeByExtension = new Map([
    ['js', resourceTypes.Script],
    ['mjs', resourceTypes.Script],
    ['css', resourceTypes.Stylesheet],
    ['xsl', resourceTypes.Stylesheet],
    ['avif', resourceTypes.Image],
    ['bmp', resourceTypes.Image],
    ['gif', resourceTypes.Image],
    ['ico', resourceTypes.Image],
    ['jpeg', resourceTypes.Image],
    ['jpg', resourceTypes.Image],
    ['jxl', resourceTypes.Image],
    ['png', resourceTypes.Image],
    ['svg', resourceTypes.Image],
    ['tif', resourceTypes.Image],
    ['tiff', resourceTypes.Image],
    ['vue', resourceTypes.Document],
    ['webmanifest', resourceTypes.Manifest],
    ['webp', resourceTypes.Media],
    ['otf', resourceTypes.Font],
    ['ttc', resourceTypes.Font],
    ['ttf', resourceTypes.Font],
    ['woff', resourceTypes.Font],
    ['woff2', resourceTypes.Font],
    ['wasm', resourceTypes.Wasm],
]);
const mimeTypeByExtension = new Map([
    ['js', 'text/javascript'],
    ['mjs', 'text/javascript'],
    ['css', 'text/css'],
    ['html', 'text/html'],
    ['htm', 'text/html'],
    ['xml', 'application/xml'],
    ['xsl', 'application/xml'],
    ['wasm', 'application/wasm'],
    ['webmanifest', 'application/manifest+json'],
    ['asp', 'application/x-aspx'],
    ['aspx', 'application/x-aspx'],
    ['jsp', 'application/x-jsp'],
    ['c', 'text/x-c++src'],
    ['cc', 'text/x-c++src'],
    ['cpp', 'text/x-c++src'],
    ['h', 'text/x-c++src'],
    ['m', 'text/x-c++src'],
    ['mm', 'text/x-c++src'],
    ['coffee', 'text/x-coffeescript'],
    ['dart', 'application/vnd.dart'],
    ['ts', 'text/typescript'],
    ['tsx', 'text/typescript-jsx'],
    ['json', 'application/json'],
    ['gyp', 'application/json'],
    ['gypi', 'application/json'],
    ['map', 'application/json'],
    ['cs', 'text/x-csharp'],
    ['go', 'text/x-go'],
    ['java', 'text/x-java'],
    ['kt', 'text/x-kotlin'],
    ['scala', 'text/x-scala'],
    ['less', 'text/x-less'],
    ['php', 'application/x-httpd-php'],
    ['phtml', 'application/x-httpd-php'],
    ['py', 'text/x-python'],
    ['sh', 'text/x-sh'],
    ['gss', 'text/x-gss'],
    ['sass', 'text/x-sass'],
    ['scss', 'text/x-scss'],
    ['vtt', 'text/vtt'],
    ['ls', 'text/x-livescript'],
    ['md', 'text/markdown'],
    ['cljs', 'text/x-clojure'],
    ['cljc', 'text/x-clojure'],
    ['cljx', 'text/x-clojure'],
    ['styl', 'text/x-styl'],
    ['jsx', 'text/jsx'],
    ['avif', 'image/avif'],
    ['bmp', 'image/bmp'],
    ['gif', 'image/gif'],
    ['ico', 'image/ico'],
    ['jpeg', 'image/jpeg'],
    ['jpg', 'image/jpeg'],
    ['jxl', 'image/jxl'],
    ['png', 'image/png'],
    ['svg', 'image/svg+xml'],
    ['tif', 'image/tif'],
    ['tiff', 'image/tiff'],
    ['webp', 'image/webp'],
    ['otf', 'font/otf'],
    ['ttc', 'font/collection'],
    ['ttf', 'font/ttf'],
    ['woff', 'font/woff'],
    ['woff2', 'font/woff2'],
    ['component.html', 'text/x.angular'],
    ['svelte', 'text/x.svelte'],
    ['vue', 'text/x.vue'],
]);

var ResourceType$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ResourceCategory: ResourceCategory,
	ResourceType: ResourceType,
	mimeTypeByExtension: mimeTypeByExtension,
	resourceCategories: resourceCategories,
	resourceTypeByExtension: resourceTypeByExtension,
	resourceTypes: resourceTypes
});

// Copyright 2025 The Chromium Authors
class ReturnToPanelFlavor {
    viewId;
    constructor(viewId) {
        this.viewId = viewId;
    }
}

var ReturnToPanel = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ReturnToPanelFlavor: ReturnToPanelFlavor
});

// Copyright 2019 The Chromium Authors
const registeredLateInitializationRunnables = new Map();
function registerLateInitializationRunnable(setting) {
    const { id, loadRunnable } = setting;
    if (registeredLateInitializationRunnables.has(id)) {
        throw new Error(`Duplicate late Initializable runnable id '${id}'`);
    }
    registeredLateInitializationRunnables.set(id, loadRunnable);
}
function maybeRemoveLateInitializationRunnable(runnableId) {
    return registeredLateInitializationRunnables.delete(runnableId);
}
function lateInitializationRunnables() {
    return [...registeredLateInitializationRunnables.values()];
}
const registeredEarlyInitializationRunnables = [];
function registerEarlyInitializationRunnable(runnable) {
    registeredEarlyInitializationRunnables.push(runnable);
}
function earlyInitializationRunnables() {
    return registeredEarlyInitializationRunnables;
}

var Runnable = /*#__PURE__*/Object.freeze({
	__proto__: null,
	earlyInitializationRunnables: earlyInitializationRunnables,
	lateInitializationRunnables: lateInitializationRunnables,
	maybeRemoveLateInitializationRunnable: maybeRemoveLateInitializationRunnable,
	registerEarlyInitializationRunnable: registerEarlyInitializationRunnable,
	registerLateInitializationRunnable: registerLateInitializationRunnable
});

// Copyright 2016 The Chromium Authors
class Segment {
    begin;
    end;
    data;
    constructor(begin, end, data) {
        if (begin > end) {
            throw new Error('Invalid segment');
        }
        this.begin = begin;
        this.end = end;
        this.data = data;
    }
    intersects(that) {
        return this.begin < that.end && that.begin < this.end;
    }
}
class SegmentedRange {
    #segments = [];
    #mergeCallback;
    constructor(mergeCallback) {
        this.#mergeCallback = mergeCallback;
    }
    append(newSegment) {
        let startIndex = lowerBound(this.#segments, newSegment, (a, b) => a.begin - b.begin);
        let endIndex = startIndex;
        let merged = null;
        if (startIndex > 0) {
            const precedingSegment = this.#segments[startIndex - 1];
            merged = this.tryMerge(precedingSegment, newSegment);
            if (merged) {
                --startIndex;
                newSegment = merged;
            }
            else if (this.#segments[startIndex - 1].end >= newSegment.begin) {
                if (newSegment.end < precedingSegment.end) {
                    this.#segments.splice(startIndex, 0, new Segment(newSegment.end, precedingSegment.end, precedingSegment.data));
                }
                precedingSegment.end = newSegment.begin;
            }
        }
        while (endIndex < this.#segments.length && this.#segments[endIndex].end <= newSegment.end) {
            ++endIndex;
        }
        if (endIndex < this.#segments.length) {
            merged = this.tryMerge(newSegment, this.#segments[endIndex]);
            if (merged) {
                endIndex++;
                newSegment = merged;
            }
            else if (newSegment.intersects(this.#segments[endIndex])) {
                this.#segments[endIndex].begin = newSegment.end;
            }
        }
        this.#segments.splice(startIndex, endIndex - startIndex, newSegment);
    }
    segments() {
        return this.#segments;
    }
    tryMerge(first, second) {
        const merged = this.#mergeCallback && this.#mergeCallback(first, second);
        if (!merged) {
            return null;
        }
        merged.begin = first.begin;
        merged.end = Math.max(first.end, second.end);
        return merged;
    }
}

var SegmentedRange$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Segment: Segment,
	SegmentedRange: SegmentedRange
});

// Copyright 2020 The Chromium Authors
const UIStrings$19 = {
    elements: 'Elements',
    ai: 'AI',
    appearance: 'Appearance',
    sources: 'Sources',
    network: 'Network',
    performance: 'Performance',
    console: 'Console',
    persistence: 'Persistence',
    debugger: 'Debugger',
    global: 'Global',
    rendering: 'Rendering',
    grid: 'Grid',
    mobile: 'Mobile',
    memory: 'Memory',
    extension: 'Extension',
    adorner: 'Adorner',
    account: 'Account',
    privacy: 'Privacy',
};
const str_$18 = registerUIStrings('core/common/SettingRegistration.ts', UIStrings$19);
const i18nString$R = getLocalizedString.bind(undefined, str_$18);
let registeredSettings = [];
const settingNameSet = new Set();
function registerSettingExtension(registration) {
    const settingName = registration.settingName;
    if (settingNameSet.has(settingName)) {
        throw new Error(`Duplicate setting name '${settingName}'`);
    }
    settingNameSet.add(settingName);
    registeredSettings.push(registration);
}
function getRegisteredSettings() {
    return registeredSettings.filter(setting => Runtime.isDescriptorEnabled(setting));
}
function registerSettingsForTest(settings, forceReset = false) {
    if (registeredSettings.length === 0 || forceReset) {
        registeredSettings = settings;
        settingNameSet.clear();
        for (const setting of settings) {
            const settingName = setting.settingName;
            if (settingNameSet.has(settingName)) {
                throw new Error(`Duplicate setting name '${settingName}'`);
            }
            settingNameSet.add(settingName);
        }
    }
}
function resetSettings() {
    registeredSettings = [];
    settingNameSet.clear();
}
function maybeRemoveSettingExtension(settingName) {
    const settingIndex = registeredSettings.findIndex(setting => setting.settingName === settingName);
    if (settingIndex < 0 || !settingNameSet.delete(settingName)) {
        return false;
    }
    registeredSettings.splice(settingIndex, 1);
    return true;
}
function getLocalizedSettingsCategory(category) {
    switch (category) {
        case "ELEMENTS" :
            return i18nString$R(UIStrings$19.elements);
        case "AI" :
            return i18nString$R(UIStrings$19.ai);
        case "APPEARANCE" :
            return i18nString$R(UIStrings$19.appearance);
        case "SOURCES" :
            return i18nString$R(UIStrings$19.sources);
        case "NETWORK" :
            return i18nString$R(UIStrings$19.network);
        case "PERFORMANCE" :
            return i18nString$R(UIStrings$19.performance);
        case "CONSOLE" :
            return i18nString$R(UIStrings$19.console);
        case "PERSISTENCE" :
            return i18nString$R(UIStrings$19.persistence);
        case "DEBUGGER" :
            return i18nString$R(UIStrings$19.debugger);
        case "GLOBAL" :
            return i18nString$R(UIStrings$19.global);
        case "RENDERING" :
            return i18nString$R(UIStrings$19.rendering);
        case "GRID" :
            return i18nString$R(UIStrings$19.grid);
        case "MOBILE" :
            return i18nString$R(UIStrings$19.mobile);
        case "EMULATION" :
            return i18nString$R(UIStrings$19.console);
        case "MEMORY" :
            return i18nString$R(UIStrings$19.memory);
        case "EXTENSIONS" :
            return i18nString$R(UIStrings$19.extension);
        case "ADORNER" :
            return i18nString$R(UIStrings$19.adorner);
        case "" :
            return lockedString('');
        case "ACCOUNT" :
            return i18nString$R(UIStrings$19.account);
        case "PRIVACY" :
            return i18nString$R(UIStrings$19.privacy);
    }
}

var SettingRegistration = /*#__PURE__*/Object.freeze({
	__proto__: null,
	getLocalizedSettingsCategory: getLocalizedSettingsCategory,
	getRegisteredSettings: getRegisteredSettings,
	maybeRemoveSettingExtension: maybeRemoveSettingExtension,
	registerSettingExtension: registerSettingExtension,
	registerSettingsForTest: registerSettingsForTest,
	resetSettings: resetSettings
});

// Copyright 2009 The Chromium Authors
let settingsInstance;
class Settings {
    syncedStorage;
    globalStorage;
    localStorage;
    #settingRegistrations;
    #sessionStorage = new SettingsStorage({});
    settingNameSet = new Set();
    orderValuesBySettingCategory = new Map();
    #eventSupport = new ObjectWrapper();
    #registry = new Map();
    moduleSettings = new Map();
    #logSettingAccess;
    constructor({ syncedStorage, globalStorage, localStorage, settingRegistrations, logSettingAccess, runSettingsMigration }) {
        this.syncedStorage = syncedStorage;
        this.globalStorage = globalStorage;
        this.localStorage = localStorage;
        this.#settingRegistrations = settingRegistrations;
        this.#logSettingAccess = logSettingAccess;
        for (const registration of this.#settingRegistrations) {
            const { settingName, defaultValue, storageType } = registration;
            const isRegex = registration.settingType === "regex" ;
            const evaluatedDefaultValue = typeof defaultValue === 'function' ? defaultValue(hostConfig) : defaultValue;
            const setting = isRegex && typeof evaluatedDefaultValue === 'string' ?
                this.createRegExpSetting(settingName, evaluatedDefaultValue, undefined, storageType) :
                this.createSetting(settingName, evaluatedDefaultValue, storageType);
            setting.setTitleFunction(registration.title);
            if (registration.userActionCondition) {
                setting.setRequiresUserAction(Boolean(Runtime.queryParam(registration.userActionCondition)));
            }
            setting.setRegistration(registration);
            this.registerModuleSetting(setting);
        }
        if (runSettingsMigration) {
            new VersionController(this).updateVersion();
        }
    }
    getRegisteredSettings() {
        return this.#settingRegistrations;
    }
    static hasInstance() {
        return typeof settingsInstance !== 'undefined';
    }
    static instance(opts = { forceNew: null, syncedStorage: null, globalStorage: null, localStorage: null, settingRegistrations: null }) {
        const { forceNew, syncedStorage, globalStorage, localStorage, settingRegistrations, logSettingAccess, runSettingsMigration } = opts;
        if (!settingsInstance || forceNew) {
            if (!syncedStorage || !globalStorage || !localStorage || !settingRegistrations) {
                throw new Error(`Unable to create settings: global and local storage must be provided: ${new Error().stack}`);
            }
            settingsInstance = new Settings({ syncedStorage, globalStorage, localStorage, settingRegistrations, logSettingAccess, runSettingsMigration });
        }
        return settingsInstance;
    }
    static removeInstance() {
        settingsInstance = undefined;
    }
    registerModuleSetting(setting) {
        const settingName = setting.name;
        const category = setting.category();
        const order = setting.order();
        if (this.settingNameSet.has(settingName)) {
            throw new Error(`Duplicate Setting name '${settingName}'`);
        }
        if (category && order) {
            const orderValues = this.orderValuesBySettingCategory.get(category) || new Set();
            if (orderValues.has(order)) {
                throw new Error(`Duplicate order value '${order}' for settings category '${category}'`);
            }
            orderValues.add(order);
            this.orderValuesBySettingCategory.set(category, orderValues);
        }
        this.settingNameSet.add(settingName);
        this.moduleSettings.set(setting.name, setting);
    }
    static normalizeSettingName(name) {
        if ([
            VersionController.GLOBAL_VERSION_SETTING_NAME,
            VersionController.SYNCED_VERSION_SETTING_NAME,
            VersionController.LOCAL_VERSION_SETTING_NAME,
            'currentDockState',
            'isUnderTest',
        ].includes(name)) {
            return name;
        }
        return toKebabCase(name);
    }
    moduleSetting(settingName) {
        const setting = this.moduleSettings.get(settingName);
        if (!setting) {
            throw new Error('No setting registered: ' + settingName);
        }
        return setting;
    }
    settingForTest(settingName) {
        const setting = this.#registry.get(settingName);
        if (!setting) {
            throw new Error('No setting registered: ' + settingName);
        }
        return setting;
    }
    createSetting(key, defaultValue, storageType) {
        const storage = this.storageFromType(storageType);
        let setting = this.#registry.get(key);
        if (!setting) {
            setting = new Setting(key, defaultValue, this.#eventSupport, storage, this.#logSettingAccess);
            this.#registry.set(key, setting);
        }
        return setting;
    }
    createLocalSetting(key, defaultValue) {
        return this.createSetting(key, defaultValue, "Local" );
    }
    createRegExpSetting(key, defaultValue, regexFlags, storageType) {
        if (!this.#registry.get(key)) {
            this.#registry.set(key, new RegExpSetting(key, defaultValue, this.#eventSupport, this.storageFromType(storageType), regexFlags, this.#logSettingAccess));
        }
        return this.#registry.get(key);
    }
    clearAll() {
        this.globalStorage.removeAll();
        this.syncedStorage.removeAll();
        this.localStorage.removeAll();
        new VersionController(this).resetToCurrent();
    }
    storageFromType(storageType) {
        switch (storageType) {
            case "Local" :
                return this.localStorage;
            case "Session" :
                return this.#sessionStorage;
            case "Global" :
                return this.globalStorage;
            case "Synced" :
                return this.syncedStorage;
        }
        return this.globalStorage;
    }
    getRegistry() {
        return this.#registry;
    }
}
class InMemoryStorage {
    #store = new Map();
    register(_setting) {
    }
    set(key, value) {
        this.#store.set(key, value);
    }
    get(key) {
        return this.#store.get(key);
    }
    remove(key) {
        this.#store.delete(key);
    }
    clear() {
        this.#store.clear();
    }
}
class SettingsStorage {
    object;
    backingStore;
    storagePrefix;
    constructor(object, backingStore = new InMemoryStorage(), storagePrefix = '') {
        this.object = object;
        this.backingStore = backingStore;
        this.storagePrefix = storagePrefix;
    }
    register(name) {
        name = this.storagePrefix + name;
        this.backingStore.register(name);
    }
    set(name, value) {
        name = this.storagePrefix + name;
        this.object[name] = value;
        this.backingStore.set(name, value);
    }
    has(name) {
        name = this.storagePrefix + name;
        return name in this.object;
    }
    get(name) {
        name = this.storagePrefix + name;
        return this.object[name];
    }
    async forceGet(originalName) {
        const name = this.storagePrefix + originalName;
        const value = await this.backingStore.get(name);
        if (value && value !== this.object[name]) {
            this.set(originalName, value);
        }
        else if (!value) {
            this.remove(originalName);
        }
        return value;
    }
    remove(name) {
        name = this.storagePrefix + name;
        delete this.object[name];
        this.backingStore.remove(name);
    }
    removeAll() {
        this.object = {};
        this.backingStore.clear();
    }
    keys() {
        return Object.keys(this.object);
    }
    dumpSizes() {
        Console.instance().log('Ten largest settings: ');
        const sizes = { __proto__: null };
        for (const key in this.object) {
            sizes[key] = this.object[key].length;
        }
        const keys = Object.keys(sizes);
        function comparator(key1, key2) {
            return sizes[key2] - sizes[key1];
        }
        keys.sort(comparator);
        for (let i = 0; i < 10 && i < keys.length; ++i) {
            Console.instance().log('Setting: \'' + keys[i] + '\', size: ' + sizes[keys[i]]);
        }
    }
}
class Deprecation {
    disabled;
    warning;
    experiment;
    constructor({ deprecationNotice }) {
        if (!deprecationNotice) {
            throw new Error('Cannot create deprecation info for a non-deprecated setting');
        }
        this.disabled = deprecationNotice.disabled;
        this.warning = deprecationNotice.warning();
        this.experiment = deprecationNotice.experiment ?
            experiments.allConfigurableExperiments().find(e => e.name === deprecationNotice.experiment) :
            undefined;
    }
}
class Setting {
    name;
    defaultValue;
    eventSupport;
    storage;
    #titleFunction;
    #title;
    #registration = null;
    #requiresUserAction;
    #value;
    #serializer = JSON;
    #hadUserAction;
    #disabled;
    #deprecation = null;
    #loggedInitialAccess = false;
    #logSettingAccess;
    constructor(name, defaultValue, eventSupport, storage, logSettingAccess) {
        this.name = name;
        this.defaultValue = defaultValue;
        this.eventSupport = eventSupport;
        this.storage = storage;
        storage.register(this.name);
        this.#logSettingAccess = logSettingAccess;
    }
    setSerializer(serializer) {
        this.#serializer = serializer;
    }
    addChangeListener(listener, thisObject) {
        return this.eventSupport.addEventListener(this.name, listener, thisObject);
    }
    removeChangeListener(listener, thisObject) {
        this.eventSupport.removeEventListener(this.name, listener, thisObject);
    }
    title() {
        if (this.#title) {
            return this.#title;
        }
        if (this.#titleFunction) {
            return this.#titleFunction();
        }
        return '';
    }
    setTitleFunction(titleFunction) {
        if (titleFunction) {
            this.#titleFunction = titleFunction;
        }
    }
    setTitle(title) {
        this.#title = title;
    }
    setRequiresUserAction(requiresUserAction) {
        this.#requiresUserAction = requiresUserAction;
    }
    disabled() {
        if (this.#registration?.disabledCondition) {
            const { disabled } = this.#registration.disabledCondition(hostConfig);
            if (disabled) {
                return true;
            }
        }
        return this.#disabled || false;
    }
    disabledReasons() {
        if (this.#registration?.disabledCondition) {
            const result = this.#registration.disabledCondition(hostConfig);
            if (result.disabled) {
                return result.reasons;
            }
        }
        return [];
    }
    setDisabled(disabled) {
        this.#disabled = disabled;
        this.eventSupport.dispatchEventToListeners(this.name);
    }
    #maybeLogAccess(value) {
        try {
            const valueToLog = typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ?
                value :
                this.#serializer?.stringify(value);
            if (valueToLog !== undefined && this.#logSettingAccess) {
                void this.#logSettingAccess(this.name, valueToLog);
            }
        }
        catch {
        }
    }
    #maybeLogInitialAccess(value) {
        if (!this.#loggedInitialAccess) {
            this.#maybeLogAccess(value);
            this.#loggedInitialAccess = true;
        }
    }
    get() {
        if (this.#requiresUserAction && !this.#hadUserAction) {
            this.#maybeLogInitialAccess(this.defaultValue);
            return this.defaultValue;
        }
        if (typeof this.#value !== 'undefined') {
            this.#maybeLogInitialAccess(this.#value);
            return this.#value;
        }
        this.#value = this.defaultValue;
        if (this.storage.has(this.name)) {
            try {
                this.#value = this.#serializer.parse(this.storage.get(this.name));
            }
            catch {
                this.storage.remove(this.name);
            }
        }
        this.#maybeLogInitialAccess(this.#value);
        return this.#value;
    }
    getIfNotDisabled() {
        if (this.disabled()) {
            return;
        }
        return this.get();
    }
    async forceGet() {
        const name = this.name;
        const oldValue = this.storage.get(name);
        const value = await this.storage.forceGet(name);
        this.#value = this.defaultValue;
        if (value) {
            try {
                this.#value = this.#serializer.parse(value);
            }
            catch {
                this.storage.remove(this.name);
            }
        }
        if (oldValue !== value) {
            this.eventSupport.dispatchEventToListeners(this.name, this.#value);
        }
        this.#maybeLogInitialAccess(this.#value);
        return this.#value;
    }
    set(value) {
        this.#maybeLogAccess(value);
        this.#hadUserAction = true;
        this.#value = value;
        try {
            const settingString = this.#serializer.stringify(value);
            try {
                this.storage.set(this.name, settingString);
            }
            catch (e) {
                this.printSettingsSavingError(e.message, settingString);
            }
        }
        catch (e) {
            Console.instance().error('Cannot stringify setting with name: ' + this.name + ', error: ' + e.message);
        }
        this.eventSupport.dispatchEventToListeners(this.name, value);
    }
    setRegistration(registration) {
        this.#registration = registration;
        const { deprecationNotice } = registration;
        if (deprecationNotice?.disabled) {
            const experiment = deprecationNotice.experiment ?
                experiments.allConfigurableExperiments().find(e => e.name === deprecationNotice.experiment) :
                undefined;
            if ((!experiment || experiment.isEnabled())) {
                this.set(this.defaultValue);
                this.setDisabled(true);
            }
        }
    }
    type() {
        if (this.#registration) {
            return this.#registration.settingType;
        }
        return null;
    }
    options() {
        if (this.#registration && this.#registration.options) {
            return this.#registration.options.map(opt => {
                const { value, title, text, raw } = opt;
                return {
                    value,
                    title: title(),
                    text: typeof text === 'function' ? text() : text,
                    raw,
                };
            });
        }
        return [];
    }
    reloadRequired() {
        if (this.#registration) {
            return this.#registration.reloadRequired || null;
        }
        return null;
    }
    category() {
        if (this.#registration) {
            return this.#registration.category || null;
        }
        return null;
    }
    tags() {
        if (this.#registration && this.#registration.tags) {
            return this.#registration.tags.map(tag => tag()).join('\0');
        }
        return null;
    }
    order() {
        if (this.#registration) {
            return this.#registration.order || null;
        }
        return null;
    }
    learnMore() {
        return this.#registration?.learnMore ?? null;
    }
    get deprecation() {
        if (!this.#registration || !this.#registration.deprecationNotice) {
            return null;
        }
        if (!this.#deprecation) {
            this.#deprecation = new Deprecation(this.#registration);
        }
        return this.#deprecation;
    }
    printSettingsSavingError(message, value) {
        const errorMessage = 'Error saving setting with name: ' + this.name + ', value length: ' + value.length + '. Error: ' + message;
        console.error(errorMessage);
        Console.instance().error(errorMessage);
        this.storage.dumpSizes();
    }
}
class RegExpSetting extends Setting {
    #regexFlags;
    #regex;
    constructor(name, defaultValue, eventSupport, storage, regexFlags, logSettingAccess) {
        super(name, defaultValue ? [{ pattern: defaultValue }] : [], eventSupport, storage, logSettingAccess);
        this.#regexFlags = regexFlags;
    }
    get() {
        const result = [];
        const items = this.getAsArray();
        for (let i = 0; i < items.length; ++i) {
            const item = items[i];
            if (item.pattern && !item.disabled) {
                result.push(item.pattern);
            }
        }
        return result.join('|');
    }
    getAsArray() {
        return super.get();
    }
    set(value) {
        this.setAsArray([{ pattern: value, disabled: false }]);
    }
    setAsArray(value) {
        this.#regex = undefined;
        super.set(value);
    }
    asRegExp() {
        if (typeof this.#regex !== 'undefined') {
            return this.#regex;
        }
        this.#regex = null;
        try {
            const pattern = this.get();
            if (pattern) {
                this.#regex = new RegExp(pattern, this.#regexFlags || '');
            }
        }
        catch {
        }
        return this.#regex;
    }
}
class VersionController {
    static GLOBAL_VERSION_SETTING_NAME = 'inspectorVersion';
    static SYNCED_VERSION_SETTING_NAME = 'syncedInspectorVersion';
    static LOCAL_VERSION_SETTING_NAME = 'localInspectorVersion';
    static CURRENT_VERSION = 41;
    #settings;
    #globalVersionSetting;
    #syncedVersionSetting;
    #localVersionSetting;
    constructor(settings) {
        this.#settings = settings;
        this.#globalVersionSetting = this.#settings.createSetting(VersionController.GLOBAL_VERSION_SETTING_NAME, VersionController.CURRENT_VERSION, "Global" );
        this.#syncedVersionSetting = this.#settings.createSetting(VersionController.SYNCED_VERSION_SETTING_NAME, VersionController.CURRENT_VERSION, "Synced" );
        this.#localVersionSetting = this.#settings.createSetting(VersionController.LOCAL_VERSION_SETTING_NAME, VersionController.CURRENT_VERSION, "Local" );
    }
    resetToCurrent() {
        this.#globalVersionSetting.set(VersionController.CURRENT_VERSION);
        this.#syncedVersionSetting.set(VersionController.CURRENT_VERSION);
        this.#localVersionSetting.set(VersionController.CURRENT_VERSION);
    }
    #removeSetting(setting) {
        const name = setting.name;
        this.#settings.getRegistry().delete(name);
        this.#settings.moduleSettings.delete(name);
        setting.storage.remove(name);
    }
    updateVersion() {
        const currentVersion = VersionController.CURRENT_VERSION;
        const minimumVersion = Math.min(this.#globalVersionSetting.get(), this.#syncedVersionSetting.get(), this.#localVersionSetting.get());
        const methodsToRun = this.methodsToRunToUpdateVersion(minimumVersion, currentVersion);
        console.assert(
        this[`updateVersionFrom${currentVersion}To${currentVersion + 1}`] === undefined, 'Unexpected migration method found. Increment CURRENT_VERSION or remove the method.');
        for (const method of methodsToRun) {
            this[method].call(this);
        }
        this.resetToCurrent();
    }
    methodsToRunToUpdateVersion(oldVersion, currentVersion) {
        const result = [];
        for (let i = oldVersion; i < currentVersion; ++i) {
            result.push('updateVersionFrom' + i + 'To' + (i + 1));
        }
        return result;
    }
    updateVersionFrom0To1() {
        this.clearBreakpointsWhenTooMany(this.#settings.createLocalSetting('breakpoints', []), 500000);
    }
    updateVersionFrom1To2() {
        this.#settings.createSetting('previouslyViewedFiles', []).set([]);
    }
    updateVersionFrom2To3() {
        this.#settings.createSetting('fileSystemMapping', {}).set({});
        this.#removeSetting(this.#settings.createSetting('fileMappingEntries', []));
    }
    updateVersionFrom3To4() {
        const advancedMode = this.#settings.createSetting('showHeaSnapshotObjectsHiddenProperties', false);
        this.#settings.moduleSetting('showAdvancedHeapSnapshotProperties').set(advancedMode.get());
        this.#removeSetting(advancedMode);
    }
    updateVersionFrom4To5() {
        const settingNames = {
            FileSystemViewSidebarWidth: 'fileSystemViewSplitViewState',
            elementsSidebarWidth: 'elementsPanelSplitViewState',
            StylesPaneSplitRatio: 'stylesPaneSplitViewState',
            heapSnapshotRetainersViewSize: 'heapSnapshotSplitViewState',
            'InspectorView.splitView': 'InspectorView.splitViewState',
            'InspectorView.screencastSplitView': 'InspectorView.screencastSplitViewState',
            'Inspector.drawerSplitView': 'Inspector.drawerSplitViewState',
            layerDetailsSplitView: 'layerDetailsSplitViewState',
            networkSidebarWidth: 'networkPanelSplitViewState',
            sourcesSidebarWidth: 'sourcesPanelSplitViewState',
            scriptsPanelNavigatorSidebarWidth: 'sourcesPanelNavigatorSplitViewState',
            sourcesPanelSplitSidebarRatio: 'sourcesPanelDebuggerSidebarSplitViewState',
            'timeline-details': 'timelinePanelDetailsSplitViewState',
            'timeline-split': 'timelinePanelRecorsSplitViewState',
            'timeline-view': 'timelinePanelTimelineStackSplitViewState',
            auditsSidebarWidth: 'auditsPanelSplitViewState',
            layersSidebarWidth: 'layersPanelSplitViewState',
            profilesSidebarWidth: 'profilesPanelSplitViewState',
            resourcesSidebarWidth: 'resourcesPanelSplitViewState',
        };
        const empty = {};
        for (const oldName in settingNames) {
            const newName = settingNames[oldName];
            const oldNameH = oldName + 'H';
            let newValue = null;
            const oldSetting = this.#settings.createSetting(oldName, empty);
            if (oldSetting.get() !== empty) {
                newValue = newValue || {};
                newValue.vertical = {};
                newValue.vertical.size = oldSetting.get();
                this.#removeSetting(oldSetting);
            }
            const oldSettingH = this.#settings.createSetting(oldNameH, empty);
            if (oldSettingH.get() !== empty) {
                newValue = newValue || {};
                newValue.horizontal = {};
                newValue.horizontal.size = oldSettingH.get();
                this.#removeSetting(oldSettingH);
            }
            if (newValue) {
                this.#settings.createSetting(newName, {}).set(newValue);
            }
        }
    }
    updateVersionFrom5To6() {
        const settingNames = {
            debuggerSidebarHidden: 'sourcesPanelSplitViewState',
            navigatorHidden: 'sourcesPanelNavigatorSplitViewState',
            'WebInspector.Drawer.showOnLoad': 'Inspector.drawerSplitViewState',
        };
        for (const oldName in settingNames) {
            const oldSetting = this.#settings.createSetting(oldName, null);
            if (oldSetting.get() === null) {
                this.#removeSetting(oldSetting);
                continue;
            }
            const newName = settingNames[oldName];
            const invert = oldName === 'WebInspector.Drawer.showOnLoad';
            const hidden = oldSetting.get() !== invert;
            this.#removeSetting(oldSetting);
            const showMode = hidden ? 'OnlyMain' : 'Both';
            const newSetting = this.#settings.createSetting(newName, {});
            const newValue = newSetting.get() || {};
            newValue.vertical = newValue.vertical || {};
            newValue.vertical.showMode = showMode;
            newValue.horizontal = newValue.horizontal || {};
            newValue.horizontal.showMode = showMode;
            newSetting.set(newValue);
        }
    }
    updateVersionFrom6To7() {
        const settingNames = {
            sourcesPanelNavigatorSplitViewState: 'sourcesPanelNavigatorSplitViewState',
            elementsPanelSplitViewState: 'elementsPanelSplitViewState',
            stylesPaneSplitViewState: 'stylesPaneSplitViewState',
            sourcesPanelDebuggerSidebarSplitViewState: 'sourcesPanelDebuggerSidebarSplitViewState',
        };
        const empty = {};
        for (const name in settingNames) {
            const setting = this.#settings.createSetting(name, empty);
            const value = setting.get();
            if (value === empty) {
                continue;
            }
            if (value.vertical?.size && value.vertical.size < 1) {
                value.vertical.size = 0;
            }
            if (value.horizontal?.size && value.horizontal.size < 1) {
                value.horizontal.size = 0;
            }
            setting.set(value);
        }
    }
    updateVersionFrom7To8() {
    }
    updateVersionFrom8To9() {
        const settingNames = ['skipStackFramesPattern', 'workspaceFolderExcludePattern'];
        for (let i = 0; i < settingNames.length; ++i) {
            const setting = this.#settings.createSetting(settingNames[i], '');
            let value = setting.get();
            if (!value) {
                return;
            }
            if (typeof value === 'string') {
                value = [value];
            }
            for (let j = 0; j < value.length; ++j) {
                if (typeof value[j] === 'string') {
                    value[j] = { pattern: value[j] };
                }
            }
            setting.set(value);
        }
    }
    updateVersionFrom9To10() {
        if (!window.localStorage) {
            return;
        }
        for (const key in window.localStorage) {
            if (key.startsWith('revision-history')) {
                window.localStorage.removeItem(key);
            }
        }
    }
    updateVersionFrom10To11() {
        const oldSettingName = 'customDevicePresets';
        const newSettingName = 'customEmulatedDeviceList';
        const oldSetting = this.#settings.createSetting(oldSettingName, undefined);
        const list = oldSetting.get();
        if (!Array.isArray(list)) {
            return;
        }
        const newList = [];
        for (let i = 0; i < list.length; ++i) {
            const value = list[i];
            const device = {};
            device['title'] = value['title'];
            device['type'] = 'unknown';
            device['user-agent'] = value['userAgent'];
            device['capabilities'] = [];
            if (value['touch']) {
                device['capabilities'].push('touch');
            }
            if (value['mobile']) {
                device['capabilities'].push('mobile');
            }
            device['screen'] = {};
            device['screen']['vertical'] = { width: value['width'], height: value['height'] };
            device['screen']['horizontal'] = { width: value['height'], height: value['width'] };
            device['screen']['device-pixel-ratio'] = value['deviceScaleFactor'];
            device['modes'] = [];
            device['show-by-default'] = true;
            device['show'] = 'Default';
            newList.push(device);
        }
        if (newList.length) {
            this.#settings.createSetting(newSettingName, []).set(newList);
        }
        this.#removeSetting(oldSetting);
    }
    updateVersionFrom11To12() {
        this.migrateSettingsFromLocalStorage();
    }
    updateVersionFrom12To13() {
        this.migrateSettingsFromLocalStorage();
        this.#removeSetting(this.#settings.createSetting('timelineOverviewMode', ''));
    }
    updateVersionFrom13To14() {
        const defaultValue = { throughput: -1, latency: 0 };
        this.#settings.createSetting('networkConditions', defaultValue).set(defaultValue);
    }
    updateVersionFrom14To15() {
        const setting = this.#settings.createLocalSetting('workspaceExcludedFolders', {});
        const oldValue = setting.get();
        const newValue = {};
        for (const fileSystemPath in oldValue) {
            newValue[fileSystemPath] = [];
            for (const entry of oldValue[fileSystemPath]) {
                newValue[fileSystemPath].push(entry.path);
            }
        }
        setting.set(newValue);
    }
    updateVersionFrom15To16() {
        const setting = this.#settings.createSetting('InspectorView.panelOrder', {});
        const tabOrders = setting.get();
        for (const key of Object.keys(tabOrders)) {
            tabOrders[key] = (tabOrders[key] + 1) * 10;
        }
        setting.set(tabOrders);
    }
    updateVersionFrom16To17() {
        const setting = this.#settings.createSetting('networkConditionsCustomProfiles', []);
        const oldValue = setting.get();
        const newValue = [];
        if (Array.isArray(oldValue)) {
            for (const preset of oldValue) {
                if (typeof preset.title === 'string' && typeof preset.value === 'object' &&
                    typeof preset.value.throughput === 'number' && typeof preset.value.latency === 'number') {
                    newValue.push({
                        title: preset.title,
                        value: { download: preset.value.throughput, upload: preset.value.throughput, latency: preset.value.latency },
                    });
                }
            }
        }
        setting.set(newValue);
    }
    updateVersionFrom17To18() {
        const setting = this.#settings.createLocalSetting('workspaceExcludedFolders', {});
        const oldValue = setting.get();
        const newValue = {};
        for (const oldKey in oldValue) {
            let newKey = oldKey.replace(/\\/g, '/');
            if (!newKey.startsWith('file://')) {
                if (newKey.startsWith('/')) {
                    newKey = 'file://' + newKey;
                }
                else {
                    newKey = 'file:///' + newKey;
                }
            }
            newValue[newKey] = oldValue[oldKey];
        }
        setting.set(newValue);
    }
    updateVersionFrom18To19() {
        const defaultColumns = { status: true, type: true, initiator: true, size: true, time: true };
        const visibleColumnSettings = this.#settings.createSetting('networkLogColumnsVisibility', defaultColumns);
        const visibleColumns = visibleColumnSettings.get();
        visibleColumns.name = true;
        visibleColumns.timeline = true;
        const configs = {};
        for (const columnId in visibleColumns) {
            if (!visibleColumns.hasOwnProperty(columnId)) {
                continue;
            }
            configs[columnId.toLowerCase()] = { visible: visibleColumns[columnId] };
        }
        const newSetting = this.#settings.createSetting('networkLogColumns', {});
        newSetting.set(configs);
        this.#removeSetting(visibleColumnSettings);
    }
    updateVersionFrom19To20() {
        const oldSetting = this.#settings.createSetting('InspectorView.panelOrder', {});
        const newSetting = this.#settings.createSetting('panel-tabOrder', {});
        newSetting.set(oldSetting.get());
        this.#removeSetting(oldSetting);
    }
    updateVersionFrom20To21() {
        const networkColumns = this.#settings.createSetting('networkLogColumns', {});
        const columns = networkColumns.get();
        delete columns['timeline'];
        delete columns['waterfall'];
        networkColumns.set(columns);
    }
    updateVersionFrom21To22() {
        const breakpointsSetting = this.#settings.createLocalSetting('breakpoints', []);
        const breakpoints = breakpointsSetting.get();
        for (const breakpoint of breakpoints) {
            breakpoint['url'] = breakpoint['sourceFileId'];
            delete breakpoint['sourceFileId'];
        }
        breakpointsSetting.set(breakpoints);
    }
    updateVersionFrom22To23() {
    }
    updateVersionFrom23To24() {
        const oldSetting = this.#settings.createSetting('searchInContentScripts', false);
        const newSetting = this.#settings.createSetting('searchInAnonymousAndContentScripts', false);
        newSetting.set(oldSetting.get());
        this.#removeSetting(oldSetting);
    }
    updateVersionFrom24To25() {
        const defaultColumns = { status: true, type: true, initiator: true, size: true, time: true };
        const networkLogColumnsSetting = this.#settings.createSetting('networkLogColumns', defaultColumns);
        const columns = networkLogColumnsSetting.get();
        delete columns.product;
        networkLogColumnsSetting.set(columns);
    }
    updateVersionFrom25To26() {
        const oldSetting = this.#settings.createSetting('messageURLFilters', {});
        const urls = Object.keys(oldSetting.get());
        const textFilter = urls.map(url => `-url:${url}`).join(' ');
        if (textFilter) {
            const textFilterSetting = this.#settings.createSetting('console.textFilter', '');
            const suffix = textFilterSetting.get() ? ` ${textFilterSetting.get()}` : '';
            textFilterSetting.set(`${textFilter}${suffix}`);
        }
        this.#removeSetting(oldSetting);
    }
    updateVersionFrom26To27() {
        const settings = this.#settings;
        function renameKeyInObjectSetting(settingName, from, to) {
            const setting = settings.createSetting(settingName, {});
            const value = setting.get();
            if (from in value) {
                value[to] = value[from];
                delete value[from];
                setting.set(value);
            }
        }
        function renameInStringSetting(settingName, from, to) {
            const setting = settings.createSetting(settingName, '');
            const value = setting.get();
            if (value === from) {
                setting.set(to);
            }
        }
        renameKeyInObjectSetting('panel-tabOrder', 'audits2', 'audits');
        renameKeyInObjectSetting('panel-closeableTabs', 'audits2', 'audits');
        renameInStringSetting('panel-selectedTab', 'audits2', 'audits');
    }
    updateVersionFrom27To28() {
        const setting = this.#settings.createSetting('uiTheme', 'systemPreferred');
        if (setting.get() === 'default') {
            setting.set('systemPreferred');
        }
    }
    updateVersionFrom28To29() {
        const settings = this.#settings;
        function renameKeyInObjectSetting(settingName, from, to) {
            const setting = settings.createSetting(settingName, {});
            const value = setting.get();
            if (from in value) {
                value[to] = value[from];
                delete value[from];
                setting.set(value);
            }
        }
        function renameInStringSetting(settingName, from, to) {
            const setting = settings.createSetting(settingName, '');
            const value = setting.get();
            if (value === from) {
                setting.set(to);
            }
        }
        renameKeyInObjectSetting('panel-tabOrder', 'audits', 'lighthouse');
        renameKeyInObjectSetting('panel-closeableTabs', 'audits', 'lighthouse');
        renameInStringSetting('panel-selectedTab', 'audits', 'lighthouse');
    }
    updateVersionFrom29To30() {
        const closeableTabSetting = this.#settings.createSetting('closeableTabs', {});
        const panelCloseableTabSetting = this.#settings.createSetting('panel-closeableTabs', {});
        const drawerCloseableTabSetting = this.#settings.createSetting('drawer-view-closeableTabs', {});
        const openTabsInPanel = panelCloseableTabSetting.get();
        const openTabsInDrawer = panelCloseableTabSetting.get();
        const newValue = Object.assign(openTabsInDrawer, openTabsInPanel);
        closeableTabSetting.set(newValue);
        this.#removeSetting(panelCloseableTabSetting);
        this.#removeSetting(drawerCloseableTabSetting);
    }
    updateVersionFrom30To31() {
        const recordingsSetting = this.#settings.createSetting('recorder_recordings', []);
        this.#removeSetting(recordingsSetting);
    }
    updateVersionFrom31To32() {
        const breakpointsSetting = this.#settings.createLocalSetting('breakpoints', []);
        const breakpoints = breakpointsSetting.get();
        for (const breakpoint of breakpoints) {
            breakpoint['resourceTypeName'] = 'script';
        }
        breakpointsSetting.set(breakpoints);
    }
    updateVersionFrom32To33() {
        const previouslyViewedFilesSetting = this.#settings.createLocalSetting('previouslyViewedFiles', []);
        let previouslyViewedFiles = previouslyViewedFilesSetting.get();
        previouslyViewedFiles = previouslyViewedFiles.filter((previouslyViewedFile) => 'url' in previouslyViewedFile);
        for (const previouslyViewedFile of previouslyViewedFiles) {
            previouslyViewedFile['resourceTypeName'] = 'script';
        }
        previouslyViewedFilesSetting.set(previouslyViewedFiles);
    }
    updateVersionFrom33To34() {
        const logpointPrefix = '/** DEVTOOLS_LOGPOINT */ console.log(';
        const logpointSuffix = ')';
        const breakpointsSetting = this.#settings.createLocalSetting('breakpoints', []);
        const breakpoints = breakpointsSetting.get();
        for (const breakpoint of breakpoints) {
            const isLogpoint = breakpoint.condition.startsWith(logpointPrefix) && breakpoint.condition.endsWith(logpointSuffix);
            breakpoint['isLogpoint'] = isLogpoint;
        }
        breakpointsSetting.set(breakpoints);
    }
    updateVersionFrom34To35() {
        const logpointPrefix = '/** DEVTOOLS_LOGPOINT */ console.log(';
        const logpointSuffix = ')';
        const breakpointsSetting = this.#settings.createLocalSetting('breakpoints', []);
        const breakpoints = breakpointsSetting.get();
        for (const breakpoint of breakpoints) {
            const { condition, isLogpoint } = breakpoint;
            if (isLogpoint) {
                breakpoint.condition = condition.slice(logpointPrefix.length, condition.length - logpointSuffix.length);
            }
        }
        breakpointsSetting.set(breakpoints);
    }
    updateVersionFrom35To36() {
        this.#settings.createSetting('showThirdPartyIssues', true).set(true);
    }
    updateVersionFrom36To37() {
        const updateStorage = (storage) => {
            for (const key of storage.keys()) {
                const normalizedKey = Settings.normalizeSettingName(key);
                if (normalizedKey !== key) {
                    const value = storage.get(key);
                    this.#removeSetting({ name: key, storage });
                    storage.set(normalizedKey, value);
                }
            }
        };
        updateStorage(this.#settings.globalStorage);
        updateStorage(this.#settings.syncedStorage);
        updateStorage(this.#settings.localStorage);
        for (const key of this.#settings.globalStorage.keys()) {
            if ((key.startsWith('data-grid-') && key.endsWith('-column-weights')) || key.endsWith('-tab-order') ||
                key === 'views-location-override' || key === 'closeable-tabs') {
                const setting = this.#settings.createSetting(key, {});
                setting.set(toKebabCaseKeys(setting.get()));
            }
            if (key.endsWith('-selected-tab')) {
                const setting = this.#settings.createSetting(key, '');
                setting.set(toKebabCase(setting.get()));
            }
        }
    }
    updateVersionFrom37To38() {
        const getConsoleInsightsEnabledSetting = () => {
            try {
                return this.#settings.moduleSetting('console-insights-enabled');
            }
            catch {
                return;
            }
        };
        const consoleInsightsEnabled = getConsoleInsightsEnabledSetting();
        const onboardingFinished = this.#settings.createLocalSetting('console-insights-onboarding-finished', false);
        if (consoleInsightsEnabled && consoleInsightsEnabled.get() === true && onboardingFinished.get() === false) {
            consoleInsightsEnabled.set(false);
        }
        if (consoleInsightsEnabled && consoleInsightsEnabled.get() === false) {
            onboardingFinished.set(false);
        }
    }
    updateVersionFrom38To39() {
        const PREFERRED_NETWORK_COND = 'preferred-network-condition';
        const setting = this.#settings.globalStorage.get(PREFERRED_NETWORK_COND);
        if (!setting) {
            return;
        }
        try {
            const networkSetting = JSON.parse(setting);
            if (networkSetting.title === 'Slow 3G') {
                networkSetting.title = '3G';
                networkSetting.i18nTitleKey = '3G';
                this.#settings.globalStorage.set(PREFERRED_NETWORK_COND, JSON.stringify(networkSetting));
            }
            else if (networkSetting.title === 'Fast 3G') {
                networkSetting.title = 'Slow 4G';
                networkSetting.i18nTitleKey = 'Slow 4G';
                this.#settings.globalStorage.set(PREFERRED_NETWORK_COND, JSON.stringify(networkSetting));
            }
        }
        catch {
            this.#settings.globalStorage.remove(PREFERRED_NETWORK_COND);
        }
    }
    updateVersionFrom39To40() {
        const hasCustomNetworkConditionsSetting = () => {
            try {
                this.#settings.moduleSetting('custom-network-conditions');
                return true;
            }
            catch {
                return false;
            }
        };
        if (hasCustomNetworkConditionsSetting()) {
            const conditionsSetting = this.#settings.moduleSetting('custom-network-conditions');
            const customConditions = conditionsSetting.get();
            if (customConditions?.length > 0) {
                customConditions.forEach((condition, i) => {
                    if (condition.key) {
                        return;
                    }
                    condition.key = `USER_CUSTOM_SETTING_${i + 1}`;
                });
                conditionsSetting.set(customConditions);
            }
        }
        const PREFERRED_NETWORK_COND_SETTING = 'preferred-network-condition';
        const setting = this.#settings.globalStorage.get(PREFERRED_NETWORK_COND_SETTING);
        if (!setting) {
            return;
        }
        const UI_STRING_TO_NEW_KEY = {
            'Fast 4G': 'SPEED_FAST_4G',
            'Slow 4G': 'SPEED_SLOW_4G',
            '3G': 'SPEED_3G',
            'No throttling': 'NO_THROTTLING',
            Offline: 'OFFLINE'
        };
        try {
            const networkSetting = JSON.parse(setting);
            if (networkSetting.i18nTitleKey && UI_STRING_TO_NEW_KEY.hasOwnProperty(networkSetting.i18nTitleKey)) {
                const key = UI_STRING_TO_NEW_KEY[networkSetting.i18nTitleKey];
                const newSetting = this.#settings.createSetting('active-network-condition-key', 'NO_THROTTLING');
                newSetting.set(key);
            }
        }
        finally {
            this.#settings.globalStorage.remove(PREFERRED_NETWORK_COND_SETTING);
        }
    }
    updateVersionFrom40To41() {
        if (this.#settings.syncedStorage.has('hide-network-messages')) {
            const oldNetworkSetting = this.#settings.createSetting('hide-network-messages', false, "Synced" );
            if (!this.#settings.syncedStorage.has('network-messages')) {
                const newNetworkSetting = this.#settings.createSetting('network-messages', true, "Synced" );
                newNetworkSetting.set(!oldNetworkSetting.get());
            }
            this.#removeSetting(oldNetworkSetting);
        }
        if (this.#settings.syncedStorage.has('frame-viewer-hide-chrome-window')) {
            const oldChromeFrameSetting = this.#settings.createSetting('frame-viewer-hide-chrome-window', false, "Synced" );
            if (!this.#settings.syncedStorage.has('frame-viewer-chrome-window')) {
                const newChromeFrameSetting = this.#settings.createSetting('frame-viewer-chrome-window', true, "Synced" );
                newChromeFrameSetting.set(!oldChromeFrameSetting.get());
            }
            this.#removeSetting(oldChromeFrameSetting);
        }
    }
    migrateSettingsFromLocalStorage() {
        const localSettings = new Set([
            'advancedSearchConfig',
            'breakpoints',
            'consoleHistory',
            'domBreakpoints',
            'eventListenerBreakpoints',
            'fileSystemMapping',
            'lastSelectedSourcesSidebarPaneTab',
            'previouslyViewedFiles',
            'savedURLs',
            'watchExpressions',
            'workspaceExcludedFolders',
            'xhrBreakpoints',
        ]);
        if (!window.localStorage) {
            return;
        }
        for (const key in window.localStorage) {
            if (localSettings.has(key)) {
                continue;
            }
            const value = window.localStorage[key];
            window.localStorage.removeItem(key);
            this.#settings.globalStorage.set(key, value);
        }
    }
    clearBreakpointsWhenTooMany(breakpointsSetting, maxBreakpointsCount) {
        if (breakpointsSetting.get().length > maxBreakpointsCount) {
            breakpointsSetting.set([]);
        }
    }
}
function moduleSetting(settingName) {
    return Settings.instance().moduleSetting(settingName);
}
function settingForTest(settingName) {
    return Settings.instance().settingForTest(settingName);
}

var Settings$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Deprecation: Deprecation,
	InMemoryStorage: InMemoryStorage,
	RegExpSetting: RegExpSetting,
	Setting: Setting,
	Settings: Settings,
	SettingsStorage: SettingsStorage,
	VersionController: VersionController,
	getLocalizedSettingsCategory: getLocalizedSettingsCategory,
	maybeRemoveSettingExtension: maybeRemoveSettingExtension,
	moduleSetting: moduleSetting,
	registerSettingExtension: registerSettingExtension,
	registerSettingsForTest: registerSettingsForTest,
	resetSettings: resetSettings,
	settingForTest: settingForTest
});

// Copyright 2014 The Chromium Authors
class SimpleHistoryManager {
    #entries;
    #activeEntryIndex;
    #coalescingReadonly;
    #historyDepth;
    constructor(historyDepth) {
        this.#entries = [];
        this.#activeEntryIndex = -1;
        this.#coalescingReadonly = 0;
        this.#historyDepth = historyDepth;
    }
    readOnlyLock() {
        ++this.#coalescingReadonly;
    }
    releaseReadOnlyLock() {
        --this.#coalescingReadonly;
    }
    getPreviousValidIndex() {
        if (this.empty()) {
            return -1;
        }
        let revealIndex = this.#activeEntryIndex - 1;
        while (revealIndex >= 0 && !this.#entries[revealIndex].valid()) {
            --revealIndex;
        }
        if (revealIndex < 0) {
            return -1;
        }
        return revealIndex;
    }
    getNextValidIndex() {
        let revealIndex = this.#activeEntryIndex + 1;
        while (revealIndex < this.#entries.length && !this.#entries[revealIndex].valid()) {
            ++revealIndex;
        }
        if (revealIndex >= this.#entries.length) {
            return -1;
        }
        return revealIndex;
    }
    readOnly() {
        return Boolean(this.#coalescingReadonly);
    }
    empty() {
        return !this.#entries.length;
    }
    active() {
        return this.empty() ? null : this.#entries[this.#activeEntryIndex];
    }
    push(entry) {
        if (this.readOnly()) {
            return;
        }
        if (!this.empty()) {
            this.#entries.splice(this.#activeEntryIndex + 1);
        }
        this.#entries.push(entry);
        if (this.#entries.length > this.#historyDepth) {
            this.#entries.shift();
        }
        this.#activeEntryIndex = this.#entries.length - 1;
    }
    canRollback() {
        return this.getPreviousValidIndex() >= 0;
    }
    canRollover() {
        return this.getNextValidIndex() >= 0;
    }
    rollback() {
        const revealIndex = this.getPreviousValidIndex();
        if (revealIndex === -1) {
            return false;
        }
        this.readOnlyLock();
        this.#activeEntryIndex = revealIndex;
        this.#entries[revealIndex].reveal();
        this.releaseReadOnlyLock();
        return true;
    }
    rollover() {
        const revealIndex = this.getNextValidIndex();
        if (revealIndex === -1) {
            return false;
        }
        this.readOnlyLock();
        this.#activeEntryIndex = revealIndex;
        this.#entries[revealIndex].reveal();
        this.releaseReadOnlyLock();
        return true;
    }
}

var SimpleHistoryManager$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	SimpleHistoryManager: SimpleHistoryManager
});

// Copyright 2026 The Chromium Authors
function parseSrcset(value) {
    const result = [];
    let i = 0;
    while (value.length) {
        if (i++ > 0) {
            result.push({ value: ' ', type: 0  });
        }
        value = value.trim();
        let url = '';
        let descriptor = '';
        const indexOfSpace = value.search(/\s/);
        if (indexOfSpace === -1) {
            url = value;
        }
        else if (indexOfSpace > 0 && value[indexOfSpace - 1] === ',') {
            url = value.substring(0, indexOfSpace);
        }
        else {
            url = value.substring(0, indexOfSpace);
            const indexOfComma = value.indexOf(',', indexOfSpace);
            if (indexOfComma !== -1) {
                descriptor = value.substring(indexOfSpace, indexOfComma + 1);
            }
            else {
                descriptor = value.substring(indexOfSpace);
            }
        }
        if (url) {
            if (url.endsWith(',')) {
                result.push({ value: url.substring(0, url.length - 1), type: 1  });
                result.push({ type: 0 , value: ',' });
            }
            else {
                result.push({ value: url, type: 1  });
            }
        }
        if (descriptor) {
            result.push({ type: 0 , value: descriptor });
        }
        value = value.substring(url.length + descriptor.length);
    }
    return result;
}

var Srcset = /*#__PURE__*/Object.freeze({
	__proto__: null,
	parseSrcset: parseSrcset
});

// Copyright 2015 The Chromium Authors
class StringOutputStream {
    #data = '';
    async write(chunk) {
        this.#data += chunk;
    }
    async close() {
    }
    data() {
        return this.#data;
    }
}

var StringOutputStream$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	StringOutputStream: StringOutputStream
});

// Copyright 2016 The Chromium Authors
let Trie$1 = class Trie {
    #size;
    #root;
    #edges;
    #isWord;
    #wordsInSubtree;
    #freeNodes;
    #traitImpl;
    constructor(traitImpl) {
        this.#root = 0;
        this.#traitImpl = traitImpl;
        this.clear();
    }
    static newStringTrie() {
        return new Trie({
            empty: () => '',
            append: (base, appendage) => base + appendage,
            slice: (base, start, end) => base.slice(start, end),
        });
    }
    static newArrayTrie() {
        return new Trie({
            empty: () => [],
            append: (base, appendage) => base.concat([appendage]),
            slice: (base, start, end) => base.slice(start, end),
        });
    }
    add(word) {
        let node = this.#root;
        ++this.#wordsInSubtree[this.#root];
        for (let i = 0; i < word.length; ++i) {
            const edge = word[i];
            let next = this.#edges[node].get(edge);
            if (!next) {
                if (this.#freeNodes.length) {
                    next = this.#freeNodes.pop();
                }
                else {
                    next = this.#size++;
                    this.#isWord.push(false);
                    this.#wordsInSubtree.push(0);
                    this.#edges.push(new Map());
                }
                this.#edges[node].set(edge, next);
            }
            ++this.#wordsInSubtree[next];
            node = next;
        }
        this.#isWord[node] = true;
    }
    remove(word) {
        if (!this.has(word)) {
            return false;
        }
        let node = this.#root;
        --this.#wordsInSubtree[this.#root];
        for (let i = 0; i < word.length; ++i) {
            const edge = word[i];
            const next = this.#edges[node].get(edge);
            if (!--this.#wordsInSubtree[next]) {
                this.#edges[node].delete(edge);
                this.#freeNodes.push(next);
            }
            node = next;
        }
        this.#isWord[node] = false;
        return true;
    }
    has(word) {
        let node = this.#root;
        for (let i = 0; i < word.length; ++i) {
            node = this.#edges[node].get(word[i]);
            if (!node) {
                return false;
            }
        }
        return this.#isWord[node];
    }
    words(prefix) {
        prefix = prefix ?? this.#traitImpl.empty();
        let node = this.#root;
        for (let i = 0; i < prefix.length; ++i) {
            node = this.#edges[node].get(prefix[i]);
            if (!node) {
                return [];
            }
        }
        const results = [];
        this.dfs(node, prefix, results);
        return results;
    }
    dfs(node, prefix, results) {
        if (this.#isWord[node]) {
            results.push(prefix);
        }
        const edges = this.#edges[node];
        for (const [edge, node] of edges) {
            const newPrefix = this.#traitImpl.append(prefix, edge);
            this.dfs(node, newPrefix, results);
        }
    }
    longestPrefix(word, fullWordOnly) {
        let node = this.#root;
        let wordIndex = 0;
        for (let i = 0; i < word.length; ++i) {
            node = this.#edges[node].get(word[i]);
            if (!node) {
                break;
            }
            if (!fullWordOnly || this.#isWord[node]) {
                wordIndex = i + 1;
            }
        }
        return this.#traitImpl.slice(word, 0, wordIndex);
    }
    clear() {
        this.#size = 1;
        this.#root = 0;
        this.#edges = [new Map()];
        this.#isWord = [false];
        this.#wordsInSubtree = [0];
        this.#freeNodes = [];
    }
};

var Trie$2 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Trie: Trie$1
});

// Copyright 2013 The Chromium Authors
class TextDictionary {
    words = new Map();
    index = Trie$1.newStringTrie();
    addWord(word) {
        let count = this.words.get(word) || 0;
        ++count;
        this.words.set(word, count);
        this.index.add(word);
    }
    removeWord(word) {
        let count = this.words.get(word) || 0;
        if (!count) {
            return;
        }
        if (count === 1) {
            this.words.delete(word);
            this.index.remove(word);
            return;
        }
        --count;
        this.words.set(word, count);
    }
    wordsWithPrefix(prefix) {
        return this.index.words(prefix);
    }
    hasWord(word) {
        return this.words.has(word);
    }
    wordCount(word) {
        return this.words.get(word) || 0;
    }
    reset() {
        this.words.clear();
        this.index.clear();
    }
}

var TextDictionary$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	TextDictionary: TextDictionary
});

// Copyright 2014 The Chromium Authors
class Throttler {
    #timeout;
    #isRunningProcess;
    #asSoonAsPossible;
    #process;
    #lastCompleteTime;
    #scheduler = Promise.withResolvers();
    #processTimeout;
    constructor(timeout) {
        this.#timeout = timeout;
        this.#isRunningProcess = false;
        this.#asSoonAsPossible = false;
        this.#process = null;
        this.#lastCompleteTime = 0;
    }
    #processCompleted() {
        this.#lastCompleteTime = this.#getTime();
        this.#isRunningProcess = false;
        if (this.#process) {
            this.#schedule(false);
        }
    }
    get process() {
        return this.#process;
    }
    get processCompleted() {
        return this.#process ? this.#scheduler.promise : null;
    }
    #onTimeout() {
        this.#processTimeout = undefined;
        this.#asSoonAsPossible = false;
        this.#isRunningProcess = true;
        void Promise.resolve()
            .then(this.#process)
            .catch(console.error.bind(console))
            .then(this.#processCompleted.bind(this))
            .then(this.#scheduler.resolve);
        this.#scheduler = Promise.withResolvers();
        this.#process = null;
    }
    async schedule(process, scheduling = "Default" ) {
        this.#process = process;
        const hasScheduledTasks = Boolean(this.#processTimeout) || this.#isRunningProcess;
        const okToFire = this.#getTime() - this.#lastCompleteTime > this.#timeout;
        const asSoonAsPossible = scheduling === "AsSoonAsPossible"  ||
            (scheduling === "Default"  && !hasScheduledTasks && okToFire);
        const forceTimerUpdate = asSoonAsPossible && !this.#asSoonAsPossible;
        this.#asSoonAsPossible = this.#asSoonAsPossible || asSoonAsPossible;
        this.#schedule(forceTimerUpdate);
        await this.#scheduler.promise;
    }
    #schedule(forceTimerUpdate) {
        if (this.#isRunningProcess) {
            return;
        }
        if (this.#processTimeout && !forceTimerUpdate) {
            return;
        }
        clearTimeout(this.#processTimeout);
        const timeout = this.#asSoonAsPossible ? 0 : this.#timeout;
        this.#processTimeout = setTimeout(this.#onTimeout.bind(this), timeout);
    }
    #getTime() {
        return performance.now();
    }
}

var Throttler$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Throttler: Throttler
});

// Copyright 2019 The Chromium Authors

var common = /*#__PURE__*/Object.freeze({
	__proto__: null,
	App: App,
	AppProvider: AppProvider,
	Base64: Base64,
	CharacterIdMap: CharacterIdMap$1,
	Color: Color,
	ColorConverter: ColorConverter$1,
	ColorUtils: ColorUtils,
	Console: Console$1,
	Debouncer: Debouncer,
	EventTarget: EventTarget$1,
	Gzip: Gzip,
	JavaScriptMetaData: JavaScriptMetaData,
	Lazy: Lazy,
	MapWithDefault: MapWithDefault$1,
	Mutex: Mutex$1,
	ObjectWrapper: Object$1,
	ParsedURL: ParsedURL$1,
	Progress: Progress$1,
	ResolverBase: ResolverBase$1,
	ResourceType: ResourceType$1,
	ReturnToPanel: ReturnToPanel,
	Revealer: Revealer,
	Runnable: Runnable,
	SegmentedRange: SegmentedRange$1,
	SettingRegistration: SettingRegistration,
	Settings: Settings$1,
	SimpleHistoryManager: SimpleHistoryManager$1,
	Srcset: Srcset,
	StringOutputStream: StringOutputStream$1,
	TextDictionary: TextDictionary$1,
	Throttler: Throttler$1,
	Trie: Trie$2,
	UIString: UIString
});

// Copyright 2020 The Chromium Authors
const UIStrings$18 = {
    preserveLogUponNavigation: 'Preserve log upon navigation',
    doNotPreserveLogUponNavigation: 'Do not preserve log upon navigation',
    pauseOnExceptions: 'Pause on exceptions',
    doNotPauseOnExceptions: 'Do not pause on exceptions',
    disableJavascript: 'Disable JavaScript',
    enableJavascript: 'Enable JavaScript',
    disableAsyncStackTraces: 'Disable async stack traces',
    doNotCaptureAsyncStackTraces: 'Do not capture async stack traces',
    captureAsyncStackTraces: 'Capture async stack traces',
    showRulersOnHover: 'Show rulers on hover',
    doNotShowRulersOnHover: 'Do not show rulers on hover',
    showAreaNames: 'Show area names',
    showGridNamedAreas: 'Show grid named areas',
    doNotShowGridNamedAreas: 'Do not show grid named areas',
    showTrackSizes: 'Show track sizes',
    showGridTrackSizes: 'Show grid track sizes',
    doNotShowGridTrackSizes: 'Do not show grid track sizes',
    extendGridLines: 'Extend grid lines',
    doNotExtendGridLines: 'Do not extend grid lines',
    showLineLabels: 'Show line labels',
    hideLineLabels: 'Hide line labels',
    showLineNumbers: 'Show line numbers',
    showLineNames: 'Show line names',
    showPaintFlashingRectangles: 'Show paint flashing rectangles',
    hidePaintFlashingRectangles: 'Hide paint flashing rectangles',
    showLayoutShiftRegions: 'Show layout shift regions',
    hideLayoutShiftRegions: 'Hide layout shift regions',
    highlightAdFrames: 'Highlight ad frames',
    doNotHighlightAdFrames: 'Do not highlight ad frames',
    showLayerBorders: 'Show layer borders',
    hideLayerBorders: 'Hide layer borders',
    showFramesPerSecondFpsMeter: 'Show frames per second (FPS) meter',
    hideFramesPerSecondFpsMeter: 'Hide frames per second (FPS) meter',
    showScrollPerformanceBottlenecks: 'Show scroll performance bottlenecks',
    hideScrollPerformanceBottlenecks: 'Hide scroll performance bottlenecks',
    emulateAFocusedPage: 'Emulate a focused page',
    doNotEmulateAFocusedPage: 'Do not emulate a focused page',
    doNotEmulateCssMediaType: 'Do not emulate CSS media type',
    noEmulation: 'No emulation',
    emulateCssPrintMediaType: 'Emulate CSS print media type',
    print: 'print',
    emulateCssScreenMediaType: 'Emulate CSS screen media type',
    screen: 'screen',
    query: 'query',
    emulateCssMediaType: 'Emulate CSS media type',
    doNotEmulateCss: 'Do not emulate CSS {PH1}',
    emulateCss: 'Emulate CSS {PH1}',
    emulateCssMediaFeature: 'Emulate CSS media feature {PH1}',
    doNotEmulateAnyVisionDeficiency: 'Do not emulate any vision deficiency',
    emulateBlurredVision: 'Emulate blurred vision',
    emulateReducedContrast: 'Emulate reduced contrast',
    blurredVision: 'Blurred vision',
    reducedContrast: 'Reduced contrast',
    emulateProtanopia: 'Emulate protanopia (no red)',
    protanopia: 'Protanopia (no red)',
    emulateDeuteranopia: 'Emulate deuteranopia (no green)',
    deuteranopia: 'Deuteranopia (no green)',
    emulateTritanopia: 'Emulate tritanopia (no blue)',
    tritanopia: 'Tritanopia (no blue)',
    emulateAchromatopsia: 'Emulate achromatopsia (no color)',
    achromatopsia: 'Achromatopsia (no color)',
    emulateVisionDeficiencies: 'Emulate vision deficiencies',
    emulateOsTextScale: 'Emulate OS text scale',
    doNotEmulateOsTextScale: 'Do not emulate OS text scale',
    osTextScaleEmulationNone: 'No emulation',
    osTextScaleEmulation85: '85%',
    osTextScaleEmulation100: '100% (default)',
    osTextScaleEmulation115: '115%',
    osTextScaleEmulation130: '130%',
    osTextScaleEmulation150: '150%',
    osTextScaleEmulation180: '180%',
    osTextScaleEmulation200: '200%',
    disableLocalFonts: 'Disable local fonts',
    enableLocalFonts: 'Enable local fonts',
    disableAvifFormat: 'Disable `AVIF` format',
    enableAvifFormat: 'Enable `AVIF` format',
    disableJpegXlFormat: 'Disable `JPEG XL` format',
    enableJpegXlFormat: 'Enable `JPEG XL` format',
    disableWebpFormat: 'Disable `WebP` format',
    enableWebpFormat: 'Enable `WebP` format',
    customFormatters: 'Custom formatters',
    networkRequestBlocking: 'Network request blocking',
    enableNetworkRequestBlocking: 'Enable network request blocking',
    disableNetworkRequestBlocking: 'Disable network request blocking',
    enableCache: 'Enable cache',
    disableCache: 'Disable cache while DevTools is open',
    emulateAutoDarkMode: 'Emulate auto dark mode',
    enableRemoteFileLoading: 'Allow loading remote file path resources in DevTools',
    remoteFileLoadingInfo: 'Example resource are source maps. Disabled by default for security reasons.',
    networkCacheExplanation: 'Disabling the network cache will simulate a network experience similar to a first time visitor.',
    javaScriptSourceMaps: 'JavaScript source maps',
    enableJavaScriptSourceMaps: 'Enable JavaScript source maps',
    disableJavaScriptSourceMaps: 'Disable JavaScript source maps',
    cssSourceMaps: 'CSS source maps',
    enableCssSourceMaps: 'Enable CSS source maps',
    disableCssSourceMaps: 'Disable CSS source maps',
    logXmlhttprequests: 'Log XMLHttpRequests',
};
const str_$17 = registerUIStrings('core/sdk/sdk-meta.ts', UIStrings$18);
const i18nLazyString$f = getLazilyComputedLocalizedString.bind(undefined, str_$17);
registerSettingExtension({
    category: "CONSOLE" ,
    storageType: "Synced" ,
    title: i18nLazyString$f(UIStrings$18.preserveLogUponNavigation),
    settingName: 'preserve-console-log',
    settingType: "boolean" ,
    defaultValue: false,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.preserveLogUponNavigation),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.doNotPreserveLogUponNavigation),
        },
    ],
});
registerSettingExtension({
    category: "DEBUGGER" ,
    settingName: 'pause-on-exception-enabled',
    settingType: "boolean" ,
    defaultValue: false,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.pauseOnExceptions),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.doNotPauseOnExceptions),
        },
    ],
});
registerSettingExtension({
    settingName: 'pause-on-caught-exception',
    settingType: "boolean" ,
    defaultValue: false,
});
registerSettingExtension({
    settingName: 'pause-on-uncaught-exception',
    settingType: "boolean" ,
    defaultValue: false,
});
registerSettingExtension({
    category: "DEBUGGER" ,
    title: i18nLazyString$f(UIStrings$18.disableJavascript),
    settingName: 'java-script-disabled',
    settingType: "boolean" ,
    storageType: "Session" ,
    order: 1,
    defaultValue: false,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.disableJavascript),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.enableJavascript),
        },
    ],
});
registerSettingExtension({
    category: "DEBUGGER" ,
    title: i18nLazyString$f(UIStrings$18.disableAsyncStackTraces),
    settingName: 'disable-async-stack-traces',
    settingType: "boolean" ,
    defaultValue: false,
    order: 2,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.doNotCaptureAsyncStackTraces),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.captureAsyncStackTraces),
        },
    ],
});
registerSettingExtension({
    category: "DEBUGGER" ,
    settingName: 'breakpoints-active',
    settingType: "boolean" ,
    storageType: "Session" ,
    defaultValue: true,
});
registerSettingExtension({
    category: "ELEMENTS" ,
    storageType: "Synced" ,
    title: i18nLazyString$f(UIStrings$18.showRulersOnHover),
    settingName: 'show-metrics-rulers',
    settingType: "boolean" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.showRulersOnHover),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.doNotShowRulersOnHover),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "GRID" ,
    storageType: "Synced" ,
    title: i18nLazyString$f(UIStrings$18.showAreaNames),
    settingName: 'show-grid-areas',
    settingType: "boolean" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.showGridNamedAreas),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.doNotShowGridNamedAreas),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "GRID" ,
    storageType: "Synced" ,
    title: i18nLazyString$f(UIStrings$18.showTrackSizes),
    settingName: 'show-grid-track-sizes',
    settingType: "boolean" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.showGridTrackSizes),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.doNotShowGridTrackSizes),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "GRID" ,
    storageType: "Synced" ,
    title: i18nLazyString$f(UIStrings$18.extendGridLines),
    settingName: 'extend-grid-lines',
    settingType: "boolean" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.extendGridLines),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.doNotExtendGridLines),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "GRID" ,
    storageType: "Synced" ,
    title: i18nLazyString$f(UIStrings$18.showLineLabels),
    settingName: 'show-grid-line-labels',
    settingType: "enum" ,
    options: [
        {
            title: i18nLazyString$f(UIStrings$18.hideLineLabels),
            text: i18nLazyString$f(UIStrings$18.hideLineLabels),
            value: 'none',
        },
        {
            title: i18nLazyString$f(UIStrings$18.showLineNumbers),
            text: i18nLazyString$f(UIStrings$18.showLineNumbers),
            value: 'lineNumbers',
        },
        {
            title: i18nLazyString$f(UIStrings$18.showLineNames),
            text: i18nLazyString$f(UIStrings$18.showLineNames),
            value: 'lineNames',
        },
    ],
    defaultValue: 'lineNumbers',
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'show-paint-rects',
    settingType: "boolean" ,
    storageType: "Session" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.showPaintFlashingRectangles),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.hidePaintFlashingRectangles),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'show-layout-shift-regions',
    settingType: "boolean" ,
    storageType: "Session" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.showLayoutShiftRegions),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.hideLayoutShiftRegions),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'show-ad-highlights',
    settingType: "boolean" ,
    storageType: "Session" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.highlightAdFrames),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.doNotHighlightAdFrames),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'show-debug-borders',
    settingType: "boolean" ,
    storageType: "Session" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.showLayerBorders),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.hideLayerBorders),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'show-fps-counter',
    settingType: "boolean" ,
    storageType: "Session" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.showFramesPerSecondFpsMeter),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.hideFramesPerSecondFpsMeter),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'show-scroll-bottleneck-rects',
    settingType: "boolean" ,
    storageType: "Session" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.showScrollPerformanceBottlenecks),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.hideScrollPerformanceBottlenecks),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "RENDERING" ,
    title: i18nLazyString$f(UIStrings$18.emulateAFocusedPage),
    settingName: 'emulate-page-focus',
    settingType: "boolean" ,
    storageType: "Local" ,
    defaultValue: false,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.emulateAFocusedPage),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.doNotEmulateAFocusedPage),
        },
    ],
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'emulated-css-media',
    settingType: "enum" ,
    storageType: "Session" ,
    defaultValue: '',
    options: [
        {
            title: i18nLazyString$f(UIStrings$18.doNotEmulateCssMediaType),
            text: i18nLazyString$f(UIStrings$18.noEmulation),
            value: '',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCssPrintMediaType),
            text: i18nLazyString$f(UIStrings$18.print),
            value: 'print',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCssScreenMediaType),
            text: i18nLazyString$f(UIStrings$18.screen),
            value: 'screen',
        },
    ],
    tags: [
        i18nLazyString$f(UIStrings$18.query),
    ],
    title: i18nLazyString$f(UIStrings$18.emulateCssMediaType),
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'emulated-css-media-feature-prefers-color-scheme',
    settingType: "enum" ,
    storageType: "Session" ,
    defaultValue: '',
    options: [
        {
            title: i18nLazyString$f(UIStrings$18.doNotEmulateCss, { PH1: 'prefers-color-scheme' }),
            text: i18nLazyString$f(UIStrings$18.noEmulation),
            value: '',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'prefers-color-scheme: light' }),
            text: lockedLazyString('prefers-color-scheme: light'),
            value: 'light',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'prefers-color-scheme: dark' }),
            text: lockedLazyString('prefers-color-scheme: dark'),
            value: 'dark',
        },
    ],
    tags: [
        i18nLazyString$f(UIStrings$18.query),
    ],
    title: i18nLazyString$f(UIStrings$18.emulateCssMediaFeature, { PH1: 'prefers-color-scheme' }),
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'emulated-css-media-feature-forced-colors',
    settingType: "enum" ,
    storageType: "Session" ,
    defaultValue: '',
    options: [
        {
            title: i18nLazyString$f(UIStrings$18.doNotEmulateCss, { PH1: 'forced-colors' }),
            text: i18nLazyString$f(UIStrings$18.noEmulation),
            value: '',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'forced-colors: active' }),
            text: lockedLazyString('forced-colors: active'),
            value: 'active',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'forced-colors: none' }),
            text: lockedLazyString('forced-colors: none'),
            value: 'none',
        },
    ],
    tags: [
        i18nLazyString$f(UIStrings$18.query),
    ],
    title: i18nLazyString$f(UIStrings$18.emulateCssMediaFeature, { PH1: 'forced-colors' }),
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'emulated-css-media-feature-prefers-reduced-motion',
    settingType: "enum" ,
    storageType: "Session" ,
    defaultValue: '',
    options: [
        {
            title: i18nLazyString$f(UIStrings$18.doNotEmulateCss, { PH1: 'prefers-reduced-motion' }),
            text: i18nLazyString$f(UIStrings$18.noEmulation),
            value: '',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'prefers-reduced-motion: reduce' }),
            text: lockedLazyString('prefers-reduced-motion: reduce'),
            value: 'reduce',
        },
    ],
    tags: [
        i18nLazyString$f(UIStrings$18.query),
    ],
    title: i18nLazyString$f(UIStrings$18.emulateCssMediaFeature, { PH1: 'prefers-reduced-motion' }),
});
registerSettingExtension({
    settingName: 'emulated-css-media-feature-prefers-contrast',
    settingType: "enum" ,
    storageType: "Session" ,
    defaultValue: '',
    options: [
        {
            title: i18nLazyString$f(UIStrings$18.doNotEmulateCss, { PH1: 'prefers-contrast' }),
            text: i18nLazyString$f(UIStrings$18.noEmulation),
            value: '',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'prefers-contrast: more' }),
            text: lockedLazyString('prefers-contrast: more'),
            value: 'more',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'prefers-contrast: less' }),
            text: lockedLazyString('prefers-contrast: less'),
            value: 'less',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'prefers-contrast: custom' }),
            text: lockedLazyString('prefers-contrast: custom'),
            value: 'custom',
        },
    ],
    tags: [
        i18nLazyString$f(UIStrings$18.query),
    ],
    title: i18nLazyString$f(UIStrings$18.emulateCssMediaFeature, { PH1: 'prefers-contrast' }),
});
registerSettingExtension({
    settingName: 'emulated-css-media-feature-prefers-reduced-data',
    settingType: "enum" ,
    storageType: "Session" ,
    defaultValue: '',
    options: [
        {
            title: i18nLazyString$f(UIStrings$18.doNotEmulateCss, { PH1: 'prefers-reduced-data' }),
            text: i18nLazyString$f(UIStrings$18.noEmulation),
            value: '',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'prefers-reduced-data: reduce' }),
            text: lockedLazyString('prefers-reduced-data: reduce'),
            value: 'reduce',
        },
    ],
    title: i18nLazyString$f(UIStrings$18.emulateCssMediaFeature, { PH1: 'prefers-reduced-data' }),
});
registerSettingExtension({
    settingName: 'emulated-css-media-feature-prefers-reduced-transparency',
    settingType: "enum" ,
    storageType: "Session" ,
    defaultValue: '',
    options: [
        {
            title: i18nLazyString$f(UIStrings$18.doNotEmulateCss, { PH1: 'prefers-reduced-transparency' }),
            text: i18nLazyString$f(UIStrings$18.noEmulation),
            value: '',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'prefers-reduced-transparency: reduce' }),
            text: lockedLazyString('prefers-reduced-transparency: reduce'),
            value: 'reduce',
        },
    ],
    title: i18nLazyString$f(UIStrings$18.emulateCssMediaFeature, { PH1: 'prefers-reduced-transparency' }),
});
registerSettingExtension({
    settingName: 'emulated-css-media-feature-color-gamut',
    settingType: "enum" ,
    storageType: "Session" ,
    defaultValue: '',
    options: [
        {
            title: i18nLazyString$f(UIStrings$18.doNotEmulateCss, { PH1: 'color-gamut' }),
            text: i18nLazyString$f(UIStrings$18.noEmulation),
            value: '',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'color-gamut: srgb' }),
            text: lockedLazyString('color-gamut: srgb'),
            value: 'srgb',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'color-gamut: p3' }),
            text: lockedLazyString('color-gamut: p3'),
            value: 'p3',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateCss, { PH1: 'color-gamut: rec2020' }),
            text: lockedLazyString('color-gamut: rec2020'),
            value: 'rec2020',
        },
    ],
    title: i18nLazyString$f(UIStrings$18.emulateCssMediaFeature, { PH1: 'color-gamut' }),
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'emulated-vision-deficiency',
    settingType: "enum" ,
    storageType: "Session" ,
    defaultValue: 'none',
    options: [
        {
            title: i18nLazyString$f(UIStrings$18.doNotEmulateAnyVisionDeficiency),
            text: i18nLazyString$f(UIStrings$18.noEmulation),
            value: 'none',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateBlurredVision),
            text: i18nLazyString$f(UIStrings$18.blurredVision),
            value: 'blurredVision',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateReducedContrast),
            text: i18nLazyString$f(UIStrings$18.reducedContrast),
            value: 'reducedContrast',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateProtanopia),
            text: i18nLazyString$f(UIStrings$18.protanopia),
            value: 'protanopia',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateDeuteranopia),
            text: i18nLazyString$f(UIStrings$18.deuteranopia),
            value: 'deuteranopia',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateTritanopia),
            text: i18nLazyString$f(UIStrings$18.tritanopia),
            value: 'tritanopia',
        },
        {
            title: i18nLazyString$f(UIStrings$18.emulateAchromatopsia),
            text: i18nLazyString$f(UIStrings$18.achromatopsia),
            value: 'achromatopsia',
        },
    ],
    tags: [
        i18nLazyString$f(UIStrings$18.query),
    ],
    title: i18nLazyString$f(UIStrings$18.emulateVisionDeficiencies),
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'emulated-os-text-scale',
    settingType: "enum" ,
    storageType: "Session" ,
    defaultValue: '',
    options: [
        {
            title: i18nLazyString$f(UIStrings$18.doNotEmulateOsTextScale),
            text: i18nLazyString$f(UIStrings$18.osTextScaleEmulationNone),
            value: '',
        },
        {
            title: i18nLazyString$f(UIStrings$18.osTextScaleEmulation85),
            text: i18nLazyString$f(UIStrings$18.osTextScaleEmulation85),
            value: '0.85',
        },
        {
            title: i18nLazyString$f(UIStrings$18.osTextScaleEmulation100),
            text: i18nLazyString$f(UIStrings$18.osTextScaleEmulation100),
            value: '1',
        },
        {
            title: i18nLazyString$f(UIStrings$18.osTextScaleEmulation115),
            text: i18nLazyString$f(UIStrings$18.osTextScaleEmulation115),
            value: '1.15',
        },
        {
            title: i18nLazyString$f(UIStrings$18.osTextScaleEmulation130),
            text: i18nLazyString$f(UIStrings$18.osTextScaleEmulation130),
            value: '1.3',
        },
        {
            title: i18nLazyString$f(UIStrings$18.osTextScaleEmulation150),
            text: i18nLazyString$f(UIStrings$18.osTextScaleEmulation150),
            value: '1.5',
        },
        {
            title: i18nLazyString$f(UIStrings$18.osTextScaleEmulation180),
            text: i18nLazyString$f(UIStrings$18.osTextScaleEmulation180),
            value: '1.8',
        },
        {
            title: i18nLazyString$f(UIStrings$18.osTextScaleEmulation200),
            text: i18nLazyString$f(UIStrings$18.osTextScaleEmulation200),
            value: '2',
        },
    ],
    tags: [
        i18nLazyString$f(UIStrings$18.query),
    ],
    title: i18nLazyString$f(UIStrings$18.emulateOsTextScale),
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'local-fonts-disabled',
    settingType: "boolean" ,
    storageType: "Session" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.disableLocalFonts),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.enableLocalFonts),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'avif-format-disabled',
    settingType: "boolean" ,
    storageType: "Session" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.disableAvifFormat),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.enableAvifFormat),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'jpeg-xl-format-disabled',
    settingType: "boolean" ,
    storageType: "Session" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.disableJpegXlFormat),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.enableJpegXlFormat),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "RENDERING" ,
    settingName: 'webp-format-disabled',
    settingType: "boolean" ,
    storageType: "Session" ,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.disableWebpFormat),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.enableWebpFormat),
        },
    ],
    defaultValue: false,
});
registerSettingExtension({
    category: "CONSOLE" ,
    title: i18nLazyString$f(UIStrings$18.customFormatters),
    settingName: 'custom-formatters',
    settingType: "boolean" ,
    defaultValue: false,
});
registerSettingExtension({
    category: "NETWORK" ,
    title: i18nLazyString$f(UIStrings$18.networkRequestBlocking),
    settingName: 'request-blocking-enabled',
    settingType: "boolean" ,
    storageType: "Local" ,
    defaultValue: false,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.enableNetworkRequestBlocking),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.disableNetworkRequestBlocking),
        },
    ],
});
registerSettingExtension({
    category: "NETWORK" ,
    title: i18nLazyString$f(UIStrings$18.disableCache),
    settingName: 'cache-disabled',
    settingType: "boolean" ,
    order: 0,
    defaultValue: false,
    userActionCondition: 'hasOtherClients',
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.disableCache),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.enableCache),
        },
    ],
    learnMore: {
        tooltip: i18nLazyString$f(UIStrings$18.networkCacheExplanation),
    },
});
registerSettingExtension({
    category: "RENDERING" ,
    title: i18nLazyString$f(UIStrings$18.emulateAutoDarkMode),
    settingName: 'emulate-auto-dark-mode',
    settingType: "boolean" ,
    storageType: "Session" ,
    defaultValue: false,
});
registerSettingExtension({
    category: "SOURCES" ,
    storageType: "Synced" ,
    title: i18nLazyString$f(UIStrings$18.enableRemoteFileLoading),
    settingName: 'network.enable-remote-file-loading',
    settingType: "boolean" ,
    defaultValue: false,
    learnMore: {
        tooltip: i18nLazyString$f(UIStrings$18.remoteFileLoadingInfo),
    }
});
registerSettingExtension({
    category: "SOURCES" ,
    storageType: "Synced" ,
    title: i18nLazyString$f(UIStrings$18.javaScriptSourceMaps),
    settingName: 'js-source-maps-enabled',
    settingType: "boolean" ,
    defaultValue: true,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.enableJavaScriptSourceMaps),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.disableJavaScriptSourceMaps),
        },
    ],
});
registerSettingExtension({
    category: "SOURCES" ,
    storageType: "Synced" ,
    title: i18nLazyString$f(UIStrings$18.cssSourceMaps),
    settingName: 'css-source-maps-enabled',
    settingType: "boolean" ,
    defaultValue: true,
    options: [
        {
            value: true,
            title: i18nLazyString$f(UIStrings$18.enableCssSourceMaps),
        },
        {
            value: false,
            title: i18nLazyString$f(UIStrings$18.disableCssSourceMaps),
        },
    ],
});
registerSettingExtension({
    category: "CONSOLE" ,
    storageType: "Synced" ,
    title: i18nLazyString$f(UIStrings$18.logXmlhttprequests),
    settingName: 'monitoring-xhr-enabled',
    settingType: "boolean" ,
    defaultValue: false,
});

// Copyright 2025 The Chromium Authors
registerSettingExtension({
    storageType: "Synced" ,
    settingName: 'skip-stack-frames-pattern',
    settingType: "regex" ,
    defaultValue: '/node_modules/|^node:',
});
registerSettingExtension({
    storageType: "Synced" ,
    settingName: 'skip-content-scripts',
    settingType: "boolean" ,
    defaultValue: true,
});
registerSettingExtension({
    storageType: "Synced" ,
    settingName: 'automatically-ignore-list-known-third-party-scripts',
    settingType: "boolean" ,
    defaultValue: true,
});
registerSettingExtension({
    storageType: "Synced" ,
    settingName: 'skip-anonymous-scripts',
    settingType: "boolean" ,
    defaultValue: false,
});
registerSettingExtension({
    storageType: "Synced" ,
    settingName: 'enable-ignore-listing',
    settingType: "boolean" ,
    defaultValue: true,
});

// Copyright 2015 The Chromium Authors
var Events$e;
(function (Events) {
    Events["AppendedToURL"] = "appendedToURL";
    Events["CanceledSaveURL"] = "canceledSaveURL";
    Events["ColorThemeChanged"] = "colorThemeChanged";
    Events["ContextMenuCleared"] = "contextMenuCleared";
    Events["ContextMenuItemSelected"] = "contextMenuItemSelected";
    Events["DeviceCountUpdated"] = "deviceCountUpdated";
    Events["DevicesDiscoveryConfigChanged"] = "devicesDiscoveryConfigChanged";
    Events["DevicesPortForwardingStatusChanged"] = "devicesPortForwardingStatusChanged";
    Events["DevicesUpdated"] = "devicesUpdated";
    Events["DispatchMessage"] = "dispatchMessage";
    Events["DispatchMessageChunk"] = "dispatchMessageChunk";
    Events["EnterInspectElementMode"] = "enterInspectElementMode";
    Events["EyeDropperPickedColor"] = "eyeDropperPickedColor";
    Events["FileSystemsLoaded"] = "fileSystemsLoaded";
    Events["FileSystemRemoved"] = "fileSystemRemoved";
    Events["FileSystemAdded"] = "fileSystemAdded";
    Events["FileSystemFilesChangedAddedRemoved"] = "fileSystemFilesChangedAddedRemoved";
    Events["IndexingTotalWorkCalculated"] = "indexingTotalWorkCalculated";
    Events["IndexingWorked"] = "indexingWorked";
    Events["IndexingDone"] = "indexingDone";
    Events["KeyEventUnhandled"] = "keyEventUnhandled";
    Events["ReloadInspectedPage"] = "reloadInspectedPage";
    Events["RevealSourceLine"] = "revealSourceLine";
    Events["SavedURL"] = "savedURL";
    Events["SearchCompleted"] = "searchCompleted";
    Events["SetInspectedTabId"] = "setInspectedTabId";
    Events["SetUseSoftMenu"] = "setUseSoftMenu";
    Events["ShowPanel"] = "showPanel";
})(Events$e || (Events$e = {}));
const EventDescriptors = [
    [Events$e.AppendedToURL, ['url']],
    [Events$e.CanceledSaveURL, ['url']],
    [Events$e.ColorThemeChanged, []],
    [Events$e.ContextMenuCleared, []],
    [Events$e.ContextMenuItemSelected, ['id']],
    [Events$e.DeviceCountUpdated, ['count']],
    [Events$e.DevicesDiscoveryConfigChanged, ['config']],
    [Events$e.DevicesPortForwardingStatusChanged, ['status']],
    [Events$e.DevicesUpdated, ['devices']],
    [Events$e.DispatchMessage, ['messageObject']],
    [Events$e.DispatchMessageChunk, ['messageChunk', 'messageSize']],
    [Events$e.EnterInspectElementMode, []],
    [Events$e.EyeDropperPickedColor, ['color']],
    [Events$e.FileSystemsLoaded, ['fileSystems']],
    [Events$e.FileSystemRemoved, ['fileSystemPath']],
    [Events$e.FileSystemAdded, ['errorMessage', 'fileSystem']],
    [Events$e.FileSystemFilesChangedAddedRemoved, ['changed', 'added', 'removed']],
    [Events$e.IndexingTotalWorkCalculated, , ['requestId', 'fileSystemPath', 'totalWork']],
    [Events$e.IndexingWorked, ['requestId', 'fileSystemPath', 'worked']],
    [Events$e.IndexingDone, ['requestId', 'fileSystemPath']],
    [Events$e.KeyEventUnhandled, ['event']],
    [Events$e.ReloadInspectedPage, ['hard']],
    [Events$e.RevealSourceLine, ['url', 'lineNumber', 'columnNumber']],
    [Events$e.SavedURL, ['url', 'fileSystemPath']],
    [Events$e.SearchCompleted, ['requestId', 'fileSystemPath', 'files']],
    [Events$e.SetInspectedTabId, ['tabId']],
    [Events$e.SetUseSoftMenu, ['useSoftMenu']],
    [Events$e.ShowPanel, ['panelName']],
];

// Copyright 2015 The Chromium Authors
const UIStrings$17 = {
    systemError: 'System error',
    connectionError: 'Connection error',
    certificateError: 'Certificate error',
    httpError: 'HTTP error',
    cacheError: 'Cache error',
    signedExchangeError: 'Signed Exchange error',
    ftpError: 'FTP error',
    certificateManagerError: 'Certificate manager error',
    dnsResolverError: 'DNS resolver error',
    unknownError: 'Unknown error',
    httpErrorStatusCodeSS: 'HTTP error: status code {PH1}, {PH2}',
    invalidUrl: 'Invalid URL',
    decodingDataUrlFailed: 'Decoding Data URL failed',
};
const str_$16 = registerUIStrings('core/host/ResourceLoader.ts', UIStrings$17);
const i18nString$Q = getLocalizedString.bind(undefined, str_$16);
let _lastStreamId = 0;
const _boundStreams = {};
const bindOutputStream = function (stream) {
    _boundStreams[++_lastStreamId] = stream;
    return _lastStreamId;
};
const discardOutputStream = function (id) {
    void _boundStreams[id].close();
    delete _boundStreams[id];
};
const streamWrite = function (id, chunk) {
    void _boundStreams[id].write(chunk);
};
const load = function (url, headers, callback, allowRemoteFilePaths) {
    const stream = new StringOutputStream();
    loadAsStream(url, headers, stream, mycallback, allowRemoteFilePaths);
    function mycallback(success, headers, errorDescription) {
        callback(success, headers, stream.data(), errorDescription);
    }
};
function getNetErrorCategory(netError) {
    if (netError > -100) {
        return i18nString$Q(UIStrings$17.systemError);
    }
    if (netError > -200) {
        return i18nString$Q(UIStrings$17.connectionError);
    }
    if (netError > -300) {
        return i18nString$Q(UIStrings$17.certificateError);
    }
    if (netError > -400) {
        return i18nString$Q(UIStrings$17.httpError);
    }
    if (netError > -500) {
        return i18nString$Q(UIStrings$17.cacheError);
    }
    if (netError > -600) {
        return i18nString$Q(UIStrings$17.signedExchangeError);
    }
    if (netError > -700) {
        return i18nString$Q(UIStrings$17.ftpError);
    }
    if (netError > -800) {
        return i18nString$Q(UIStrings$17.certificateManagerError);
    }
    if (netError > -900) {
        return i18nString$Q(UIStrings$17.dnsResolverError);
    }
    return i18nString$Q(UIStrings$17.unknownError);
}
function isHTTPError(netError) {
    return netError <= -300 && netError > -400;
}
function netErrorToMessage(netError, httpStatusCode, netErrorName) {
    if (netError === undefined || netErrorName === undefined) {
        return null;
    }
    if (netError !== 0) {
        if (isHTTPError(netError)) {
            return i18nString$Q(UIStrings$17.httpErrorStatusCodeSS, { PH1: String(httpStatusCode), PH2: netErrorName });
        }
        const errorCategory = getNetErrorCategory(netError);
        return `${errorCategory}: ${netErrorName}`;
    }
    return null;
}
function createErrorMessageFromResponse(response) {
    const { statusCode, netError, netErrorName, urlValid, messageOverride } = response;
    let message = '';
    const success = statusCode >= 200 && statusCode < 300;
    if (typeof messageOverride === 'string') {
        message = messageOverride;
    }
    else if (!success) {
        if (typeof netError === 'undefined') {
            if (urlValid === false) {
                message = i18nString$Q(UIStrings$17.invalidUrl);
            }
            else {
                message = i18nString$Q(UIStrings$17.unknownError);
            }
        }
        else {
            const maybeMessage = netErrorToMessage(netError, statusCode, netErrorName);
            if (maybeMessage) {
                message = maybeMessage;
            }
        }
    }
    console.assert(success === (message.length === 0));
    return { success, description: { statusCode, netError, netErrorName, urlValid, message } };
}
async function fetchToString(url) {
    try {
        const response = await fetch(url);
        return await response.text();
    }
    catch (cause) {
        throw new Error(`Failed to fetch ${url}`, { cause });
    }
}
function canBeRemoteFilePath(url) {
    try {
        const urlObject = new URL(new URL(url).toString());
        return urlObject.protocol === 'file:' && urlObject.host !== '';
    }
    catch {
        return false;
    }
}
const loadAsStream = function (url, headers, stream, callback, allowRemoteFilePaths) {
    const streamId = bindOutputStream(stream);
    const parsedURL = new ParsedURL(url);
    if (parsedURL.isDataURL()) {
        fetchToString(url).then(dataURLDecodeSuccessful).catch(dataURLDecodeFailed);
        return;
    }
    if (!allowRemoteFilePaths && canBeRemoteFilePath(url)) {
        if (callback) {
            callback( false,  {}, {
                statusCode: 400,
                netError: -20,
                netErrorName: 'net::BLOCKED_BY_CLIENT',
                message: 'Loading from a remote file path is prohibited for security reasons.',
            });
        }
        return;
    }
    const rawHeaders = [];
    if (headers) {
        for (const key in headers) {
            rawHeaders.push(key + ': ' + headers[key]);
        }
    }
    InspectorFrontendHostInstance.loadNetworkResource(url, rawHeaders.join('\r\n'), streamId, finishedCallback);
    function finishedCallback(response) {
        if (callback) {
            const { success, description } = createErrorMessageFromResponse(response);
            callback(success, response.headers || {}, description);
        }
        discardOutputStream(streamId);
    }
    function dataURLDecodeSuccessful(text) {
        streamWrite(streamId, text);
        finishedCallback(({ statusCode: 200 }));
    }
    function dataURLDecodeFailed(_xhrStatus) {
        const messageOverride = i18nString$Q(UIStrings$17.decodingDataUrlFailed);
        finishedCallback(({ statusCode: 404, messageOverride }));
    }
};

// Copyright 2025 The Chromium Authors
const UIStrings$16 = {
    devtoolsS: 'DevTools - {PH1}',
};
const str_$15 = registerUIStrings('core/host/InspectorFrontendHostStub.ts', UIStrings$16);
const i18nString$P = getLocalizedString.bind(undefined, str_$15);
const MAX_RECORDED_HISTOGRAMS_SIZE = 100;
const OVERRIDES_FILE_SYSTEM_PATH = '/overrides';
class InspectorFrontendHostStub {
    #urlsBeingSaved = new Map();
    #fileSystem = null;
    recordedCountHistograms = [];
    recordedEnumeratedHistograms = [];
    recordedPerformanceHistograms = [];
    constructor() {
        if (typeof document === 'undefined') {
            return;
        }
        function stopEventPropagation(event) {
            const zoomModifier = this.platform() === 'mac' ? event.metaKey : event.ctrlKey;
            if (zoomModifier && (event.key === '+' || event.key === '-')) {
                event.stopPropagation();
            }
        }
        document.addEventListener('keydown', event => {
            stopEventPropagation.call(this, (event));
        }, true);
    }
    platform() {
        const userAgent = navigator.userAgent;
        if (userAgent.includes('Windows NT')) {
            return 'windows';
        }
        if (userAgent.includes('Mac OS X')) {
            return 'mac';
        }
        return 'linux';
    }
    loadCompleted() {
    }
    bringToFront() {
    }
    closeWindow() {
    }
    setIsDocked(_isDocked, callback) {
        window.setTimeout(callback, 0);
    }
    showSurvey(_trigger, callback) {
        window.setTimeout(() => callback({ surveyShown: false }), 0);
    }
    canShowSurvey(_trigger, callback) {
        window.setTimeout(() => callback({ canShowSurvey: false }), 0);
    }
    setInspectedPageBounds(_bounds) {
    }
    inspectElementCompleted() {
    }
    setInjectedScriptForOrigin(_origin, _script) {
    }
    inspectedURLChanged(url) {
        if (!('document' in globalThis)) {
            return;
        }
        document.title = i18nString$P(UIStrings$16.devtoolsS, { PH1: url.replace(/^https?:\/\//, '') });
    }
    copyText(text) {
        if (text === undefined || text === null) {
            return;
        }
        void navigator.clipboard.writeText(text);
    }
    openInNewTab(url) {
        if (schemeIs(url, 'javascript:')) {
            return;
        }
        window.open(url, '_blank');
    }
    openSearchResultsInNewTab(_query) {
        Console.instance().error('Search is not enabled in hosted mode. Please inspect using chrome://inspect');
    }
    showItemInFolder(_fileSystemPath) {
        Console.instance().error('Show item in folder is not enabled in hosted mode. Please inspect using chrome://inspect');
    }
    save(url, content, _forceSaveAs, isBase64) {
        let buffer = this.#urlsBeingSaved.get(url)?.buffer;
        if (!buffer) {
            buffer = [];
            this.#urlsBeingSaved.set(url, { isBase64, buffer });
        }
        buffer.push(content);
        this.events.dispatchEventToListeners(Events$e.SavedURL, { url, fileSystemPath: url });
    }
    append(url, content) {
        const buffer = this.#urlsBeingSaved.get(url)?.buffer;
        if (buffer) {
            buffer.push(content);
            this.events.dispatchEventToListeners(Events$e.AppendedToURL, url);
        }
    }
    close(url) {
        const { isBase64, buffer } = this.#urlsBeingSaved.get(url) || { isBase64: false, buffer: [] };
        this.#urlsBeingSaved.delete(url);
        let fileName = '';
        if (url) {
            try {
                const trimmed = trimURL(url);
                fileName = removeURLFragment(trimmed);
            }
            catch {
                fileName = url;
            }
        }
        const link = document.createElement('a');
        link.download = fileName;
        let blob;
        if (isBase64) {
            const bytes = decode$1(buffer.join(''));
            blob = new Blob([bytes], { type: 'application/gzip' });
        }
        else {
            blob = new Blob(buffer, { type: 'text/plain' });
        }
        const blobUrl = URL.createObjectURL(blob);
        link.href = blobUrl;
        link.click();
        URL.revokeObjectURL(blobUrl);
    }
    sendMessageToBackend(_message) {
    }
    recordCountHistogram(histogramName, sample, min, exclusiveMax, bucketSize) {
        if (this.recordedCountHistograms.length >= MAX_RECORDED_HISTOGRAMS_SIZE) {
            this.recordedCountHistograms.shift();
        }
        this.recordedCountHistograms.push({ histogramName, sample, min, exclusiveMax, bucketSize });
    }
    recordEnumeratedHistogram(actionName, actionCode, _bucketSize) {
        if (this.recordedEnumeratedHistograms.length >= MAX_RECORDED_HISTOGRAMS_SIZE) {
            this.recordedEnumeratedHistograms.shift();
        }
        this.recordedEnumeratedHistograms.push({ actionName, actionCode });
    }
    recordPerformanceHistogram(histogramName, duration) {
        if (this.recordedPerformanceHistograms.length >= MAX_RECORDED_HISTOGRAMS_SIZE) {
            this.recordedPerformanceHistograms.shift();
        }
        this.recordedPerformanceHistograms.push({ histogramName, duration });
    }
    recordPerformanceHistogramMedium(histogramName, duration) {
        if (this.recordedPerformanceHistograms.length >= MAX_RECORDED_HISTOGRAMS_SIZE) {
            this.recordedPerformanceHistograms.shift();
        }
        this.recordedPerformanceHistograms.push({ histogramName, duration });
    }
    recordUserMetricsAction(_umaName) {
    }
    recordNewBadgeUsage(_featureName) {
    }
    connectAutomaticFileSystem(_fileSystemPath, _fileSystemUUID, _addIfMissing, callback) {
        queueMicrotask(() => callback({ success: false }));
    }
    disconnectAutomaticFileSystem(_fileSystemPath) {
    }
    requestFileSystems() {
        this.events.dispatchEventToListeners(Events$e.FileSystemsLoaded, []);
    }
    addFileSystem(_type) {
        const onFileSystem = (fs) => {
            this.#fileSystem = fs;
            const fileSystem = {
                fileSystemName: 'sandboxedRequestedFileSystem',
                fileSystemPath: OVERRIDES_FILE_SYSTEM_PATH,
                rootURL: 'filesystem:devtools://devtools/isolated/',
                type: 'overrides',
            };
            this.events.dispatchEventToListeners(Events$e.FileSystemAdded, { fileSystem });
        };
        window.webkitRequestFileSystem(window.TEMPORARY, 1024 * 1024, onFileSystem);
    }
    removeFileSystem(_fileSystemPath) {
        const removalCallback = (entries) => {
            entries.forEach(entry => {
                if (entry.isDirectory) {
                    entry.removeRecursively(() => { });
                }
                else if (entry.isFile) {
                    entry.remove(() => { });
                }
            });
        };
        if (this.#fileSystem) {
            this.#fileSystem.root.createReader().readEntries(removalCallback);
        }
        this.#fileSystem = null;
        this.events.dispatchEventToListeners(Events$e.FileSystemRemoved, OVERRIDES_FILE_SYSTEM_PATH);
    }
    isolatedFileSystem(_fileSystemId, _registeredName) {
        return this.#fileSystem;
    }
    loadNetworkResource(url, _headers, streamId, callback) {
        fetch(url)
            .then(async (result) => {
            const respBuffer = await result.arrayBuffer();
            const text = await arrayBufferToString(respBuffer);
            return text;
        })
            .then(function (text) {
            streamWrite(streamId, text);
            callback({
                statusCode: 200,
            });
        })
            .catch(function () {
            callback({
                statusCode: 404,
            });
        });
    }
    registerPreference(_name, _options) {
    }
    getPreferences(callback) {
        const prefs = {};
        for (const name in window.localStorage) {
            prefs[name] = window.localStorage[name];
        }
        callback(prefs);
    }
    getPreference(name, callback) {
        callback(window.localStorage[name]);
    }
    setPreference(name, value) {
        window.localStorage[name] = value;
    }
    removePreference(name) {
        delete window.localStorage[name];
    }
    clearPreferences() {
        window.localStorage.clear();
    }
    getSyncInformation(callback) {
        if ('getSyncInformationForTesting' in globalThis) {
            return callback(globalThis.getSyncInformationForTesting());
        }
        callback({
            isSyncActive: false,
            arePreferencesSynced: false,
        });
    }
    getHostConfig(callback) {
        const hostConfigForHostedMode = {
            devToolsVeLogging: {
                enabled: true,
            },
            thirdPartyCookieControls: {
                thirdPartyCookieMetadataEnabled: true,
                thirdPartyCookieHeuristicsEnabled: true,
                managedBlockThirdPartyCookies: 'Unset',
            },
            devToolsFlexibleLayout: {
                verticalDrawerEnabled: true,
            },
        };
        if ('hostConfigForTesting' in globalThis) {
            const { hostConfigForTesting } = globalThis;
            for (const key of Object.keys(hostConfigForTesting)) {
                const mergeEntry = (key) => {
                    if (typeof hostConfigForHostedMode[key] === 'object' && typeof hostConfigForTesting[key] === 'object') {
                        hostConfigForHostedMode[key] = { ...hostConfigForHostedMode[key], ...hostConfigForTesting[key] };
                    }
                    else {
                        hostConfigForHostedMode[key] = hostConfigForTesting[key] ?? hostConfigForHostedMode[key];
                    }
                };
                mergeEntry(key);
            }
        }
        callback(hostConfigForHostedMode);
    }
    upgradeDraggedFileSystemPermissions(_fileSystem) {
    }
    indexPath(_requestId, _fileSystemPath, _excludedFolders) {
    }
    stopIndexing(_requestId) {
    }
    searchInPath(_requestId, _fileSystemPath, _query) {
    }
    zoomFactor() {
        return 1;
    }
    zoomIn() {
    }
    zoomOut() {
    }
    resetZoom() {
    }
    setWhitelistedShortcuts(_shortcuts) {
    }
    setEyeDropperActive(_active) {
    }
    showCertificateViewer(_certChain) {
    }
    reattach(_callback) {
    }
    readyForTest() {
    }
    connectionReady() {
    }
    setOpenNewWindowForPopups(_value) {
    }
    setDevicesDiscoveryConfig(_config) {
    }
    setDevicesUpdatesEnabled(_enabled) {
    }
    openRemotePage(_browserId, _url) {
    }
    openNodeFrontend() {
    }
    showContextMenuAtPoint(_x, _y, _items, _document) {
        throw new Error('Soft context menu should be used');
    }
    isHostedMode() {
        return true;
    }
    setAddExtensionCallback(_callback) {
    }
    async initialTargetId() {
        return null;
    }
    doAidaConversation(_request, _streamId, callback) {
        callback({
            error: 'Not implemented',
        });
    }
    registerAidaClientEvent(_request, callback) {
        callback({
            error: 'Not implemented',
        });
    }
    aidaCodeComplete(_request, callback) {
        callback({
            error: 'Not implemented',
        });
    }
    dispatchHttpRequest(_request, callback) {
        callback({ error: 'Not implemented' });
    }
    recordImpression(_event) {
    }
    recordResize(_event) {
    }
    recordClick(_event) {
    }
    recordHover(_event) {
    }
    recordDrag(_event) {
    }
    recordChange(_event) {
    }
    recordKeyDown(_event) {
    }
    recordSettingAccess(_event) {
    }
    recordFunctionCall(_event) {
    }
    setChromeFlag(_flagName, _value) {
    }
    requestRestart() {
    }
}

// Copyright 2009 The Chromium Authors
let InspectorFrontendHostInstance;
class InspectorFrontendAPIImpl {
    constructor() {
        for (const descriptor of EventDescriptors) {
            this[descriptor[0]] = this.dispatch.bind(this, descriptor[0], descriptor[1], descriptor[2]);
        }
    }
    dispatch(name, signature, _runOnceLoaded, ...params) {
        if (signature.length < 2) {
            try {
                InspectorFrontendHostInstance.events.dispatchEventToListeners(name, params[0]);
            }
            catch (error) {
                console.error(error + ' ' + error.stack);
            }
            return;
        }
        const data = {};
        for (let i = 0; i < signature.length; ++i) {
            data[signature[i]] = params[i];
        }
        try {
            InspectorFrontendHostInstance.events.dispatchEventToListeners(name, data);
        }
        catch (error) {
            console.error(error + ' ' + error.stack);
        }
    }
    streamWrite(id, chunk) {
        streamWrite(id, chunk);
    }
}
function installInspectorFrontendHost(instance) {
    globalThis.InspectorFrontendHost = InspectorFrontendHostInstance = instance;
    if (!(instance instanceof InspectorFrontendHostStub)) {
        const proto = InspectorFrontendHostStub.prototype;
        for (const name of Object.getOwnPropertyNames(proto)) {
            const stub = proto[name];
            if (typeof stub !== 'function' || InspectorFrontendHostInstance[name]) {
                continue;
            }
            console.error(`Incompatible embedder: method Host.InspectorFrontendHost.${name} is missing. Using stub instead.`);
            InspectorFrontendHostInstance[name] = stub;
        }
    }
    InspectorFrontendHostInstance.events = new ObjectWrapper();
}
(function () {
    installInspectorFrontendHost(globalThis.InspectorFrontendHost ?? new InspectorFrontendHostStub());
    globalThis.InspectorFrontendAPI = new InspectorFrontendAPIImpl();
})();
function isUnderTest(prefs) {
    return Settings.hasInstance() &&
        Settings.instance().createSetting('isUnderTest', false).get();
}

// Copyright 2025 The Chromium Authors
class McpHostBindings {
    connectAutomaticFileSystem() {
    }
    disconnectAutomaticFileSystem() {
    }
    addFileSystem() {
    }
    loadCompleted() {
    }
    indexPath() {
    }
    setInspectedPageBounds() {
    }
    showCertificateViewer() {
    }
    setWhitelistedShortcuts() {
    }
    setEyeDropperActive() {
    }
    inspectElementCompleted() {
    }
    openInNewTab() {
    }
    openSearchResultsInNewTab() {
    }
    showItemInFolder() {
    }
    removeFileSystem() {
    }
    requestFileSystems() {
    }
    save() {
    }
    append() {
    }
    close() {
    }
    searchInPath() {
    }
    stopIndexing() {
    }
    bringToFront() {
    }
    closeWindow() {
    }
    copyText() {
    }
    inspectedURLChanged() {
    }
    isolatedFileSystem() {
        return null;
    }
    loadNetworkResource(urlString, _headers, streamId, callback) {
        let url;
        try {
            url = new URL$1(urlString);
        }
        catch {
            callback({
                statusCode: 404,
                urlValid: false,
            });
            return;
        }
        let contentPromise;
        if (url.protocol === 'file:') {
            contentPromise = readFile(url, { encoding: 'utf8' });
        }
        else if (url.protocol === 'http:' || url.protocol === 'https:') {
            contentPromise = fetch(url).then(response => {
                if (!response.ok) {
                    throw new Error('Fetch failed');
                }
                return response.text();
            });
        }
        else {
            callback({
                statusCode: 404,
                urlValid: false,
            });
            return;
        }
        contentPromise
            .then(content => {
            streamWrite(streamId, content);
            callback({ statusCode: 200 });
        })
            .catch(() => {
            callback({ statusCode: 404 });
        });
    }
    registerPreference() {
    }
    getPreferences() {
    }
    getPreference() {
    }
    setPreference() {
    }
    removePreference() {
    }
    clearPreferences() {
    }
    getSyncInformation() {
    }
    getHostConfig() {
    }
    upgradeDraggedFileSystemPermissions() {
    }
    platform() {
        switch (process.platform) {
            case 'darwin':
                return 'mac';
            case 'win32':
                return 'windows';
            default:
                return 'linux';
        }
    }
    recordCountHistogram() {
    }
    recordEnumeratedHistogram() {
    }
    recordPerformanceHistogram() {
    }
    recordPerformanceHistogramMedium() {
    }
    recordUserMetricsAction() {
    }
    recordNewBadgeUsage() {
    }
    sendMessageToBackend() {
    }
    setDevicesDiscoveryConfig() {
    }
    setDevicesUpdatesEnabled() {
    }
    openRemotePage() {
    }
    openNodeFrontend() {
    }
    setInjectedScriptForOrigin() {
    }
    setIsDocked() {
    }
    showSurvey() {
    }
    canShowSurvey() {
    }
    zoomFactor() {
        return 1;
    }
    zoomIn() {
    }
    zoomOut() {
    }
    resetZoom() {
    }
    showContextMenuAtPoint() {
    }
    reattach() {
    }
    readyForTest() {
    }
    connectionReady() {
    }
    setOpenNewWindowForPopups() {
    }
    isHostedMode() {
        return true;
    }
    setAddExtensionCallback() {
    }
    initialTargetId() {
        return Promise.resolve(null);
    }
    doAidaConversation(_request, _streamId, cb) {
        cb({
            error: 'Not implemented',
        });
    }
    registerAidaClientEvent(_request, cb) {
        cb({
            error: 'Not implemented',
        });
    }
    aidaCodeComplete(_request, cb) {
        cb({
            error: 'Not implemented',
        });
    }
    dispatchHttpRequest(_request, cb) {
        cb({
            error: 'Not implemented',
        });
    }
    recordImpression() {
    }
    recordResize() {
    }
    recordClick() {
    }
    recordHover() {
    }
    recordDrag() {
    }
    recordChange() {
    }
    recordKeyDown() {
    }
    recordSettingAccess() {
    }
    recordFunctionCall() {
    }
    setChromeFlag() {
    }
    requestRestart() {
    }
}

// Copyright 2025 The Chromium Authors
let connectionFactory;
class ConnectionTransport {
    static setFactory(factory) {
        connectionFactory = factory;
    }
    static getFactory() {
        return connectionFactory;
    }
}

var ConnectionTransport$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ConnectionTransport: ConnectionTransport
});

// Copyright 2025 The Chromium Authors
var CDPErrorStatus;
(function (CDPErrorStatus) {
    CDPErrorStatus[CDPErrorStatus["PARSE_ERROR"] = -32700] = "PARSE_ERROR";
    CDPErrorStatus[CDPErrorStatus["INVALID_REQUEST"] = -32600] = "INVALID_REQUEST";
    CDPErrorStatus[CDPErrorStatus["METHOD_NOT_FOUND"] = -32601] = "METHOD_NOT_FOUND";
    CDPErrorStatus[CDPErrorStatus["INVALID_PARAMS"] = -32602] = "INVALID_PARAMS";
    CDPErrorStatus[CDPErrorStatus["INTERNAL_ERROR"] = -32603] = "INTERNAL_ERROR";
    CDPErrorStatus[CDPErrorStatus["SERVER_ERROR"] = -32e3] = "SERVER_ERROR";
    CDPErrorStatus[CDPErrorStatus["SESSION_NOT_FOUND"] = -32001] = "SESSION_NOT_FOUND";
    CDPErrorStatus[CDPErrorStatus["DEVTOOLS_STUB_ERROR"] = -32015] = "DEVTOOLS_STUB_ERROR";
    CDPErrorStatus[CDPErrorStatus["DEVTOOLS_REHYDRATION_ERROR"] = -32016] = "DEVTOOLS_REHYDRATION_ERROR";
})(CDPErrorStatus || (CDPErrorStatus = {}));

var CDPConnection = /*#__PURE__*/Object.freeze({
	__proto__: null,
	get CDPErrorStatus () { return CDPErrorStatus; }
});

// Copyright 2020 The Chromium Authors
function registerCommands(inspectorBackend) {
    inspectorBackend.registerEnum("Accessibility.AXValueType", { Boolean: "boolean", Tristate: "tristate", BooleanOrUndefined: "booleanOrUndefined", Idref: "idref", IdrefList: "idrefList", Integer: "integer", Node: "node", NodeList: "nodeList", Number: "number", String: "string", ComputedString: "computedString", Token: "token", TokenList: "tokenList", DomRelation: "domRelation", Role: "role", InternalRole: "internalRole", ValueUndefined: "valueUndefined" });
    inspectorBackend.registerEnum("Accessibility.AXValueSourceType", { Attribute: "attribute", Implicit: "implicit", Style: "style", Contents: "contents", Placeholder: "placeholder", RelatedElement: "relatedElement" });
    inspectorBackend.registerEnum("Accessibility.AXValueNativeSourceType", { Description: "description", Figcaption: "figcaption", Label: "label", Labelfor: "labelfor", Labelwrapped: "labelwrapped", Legend: "legend", Rubyannotation: "rubyannotation", Tablecaption: "tablecaption", Title: "title", Other: "other" });
    inspectorBackend.registerEnum("Accessibility.AXPropertyName", { Actions: "actions", Busy: "busy", Disabled: "disabled", Editable: "editable", Focusable: "focusable", Focused: "focused", Hidden: "hidden", HiddenRoot: "hiddenRoot", Invalid: "invalid", Keyshortcuts: "keyshortcuts", Settable: "settable", Roledescription: "roledescription", Live: "live", Atomic: "atomic", Relevant: "relevant", Root: "root", Autocomplete: "autocomplete", HasPopup: "hasPopup", Level: "level", Multiselectable: "multiselectable", Orientation: "orientation", Multiline: "multiline", Readonly: "readonly", Required: "required", Valuemin: "valuemin", Valuemax: "valuemax", Valuetext: "valuetext", Checked: "checked", Expanded: "expanded", Modal: "modal", Pressed: "pressed", Selected: "selected", Activedescendant: "activedescendant", Controls: "controls", Describedby: "describedby", Details: "details", Errormessage: "errormessage", Flowto: "flowto", Labelledby: "labelledby", Owns: "owns", Url: "url", ActiveFullscreenElement: "activeFullscreenElement", ActiveModalDialog: "activeModalDialog", ActiveAriaModalDialog: "activeAriaModalDialog", AriaHiddenElement: "ariaHiddenElement", AriaHiddenSubtree: "ariaHiddenSubtree", EmptyAlt: "emptyAlt", EmptyText: "emptyText", InertElement: "inertElement", InertSubtree: "inertSubtree", LabelContainer: "labelContainer", LabelFor: "labelFor", NotRendered: "notRendered", NotVisible: "notVisible", PresentationalRole: "presentationalRole", ProbablyPresentational: "probablyPresentational", InactiveCarouselTabContent: "inactiveCarouselTabContent", Uninteresting: "uninteresting" });
    inspectorBackend.registerEvent("Accessibility.loadComplete", ["root"]);
    inspectorBackend.registerEvent("Accessibility.nodesUpdated", ["nodes"]);
    inspectorBackend.registerCommand("Accessibility.disable", [], [], "Disables the accessibility domain.");
    inspectorBackend.registerCommand("Accessibility.enable", [], [], "Enables the accessibility domain which causes `AXNodeId`s to remain consistent between method calls. This turns on accessibility for the page, which can impact performance until accessibility is disabled.");
    inspectorBackend.registerCommand("Accessibility.getPartialAXTree", [{ "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node to get the partial accessibility tree for.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node to get the partial accessibility tree for.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node wrapper to get the partial accessibility tree for.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "fetchRelatives", "type": "boolean", "optional": true, "description": "Whether to fetch this node's ancestors, siblings and children. Defaults to true.", "typeRef": null }], ["nodes"], "Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists.");
    inspectorBackend.registerCommand("Accessibility.getFullAXTree", [{ "name": "depth", "type": "number", "optional": true, "description": "The maximum depth at which descendants of the root node should be retrieved. If omitted, the full tree is returned.", "typeRef": null }, { "name": "frameId", "type": "string", "optional": true, "description": "The frame for whose document the AX tree should be retrieved. If omitted, the root frame is used.", "typeRef": "Page.FrameId" }], ["nodes"], "Fetches the entire accessibility tree for the root Document");
    inspectorBackend.registerCommand("Accessibility.getRootAXNode", [{ "name": "frameId", "type": "string", "optional": true, "description": "The frame in whose document the node resides. If omitted, the root frame is used.", "typeRef": "Page.FrameId" }], ["node"], "Fetches the root node. Requires `enable()` to have been called previously.");
    inspectorBackend.registerCommand("Accessibility.getAXNodeAndAncestors", [{ "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node to get.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node to get.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node wrapper to get.", "typeRef": "Runtime.RemoteObjectId" }], ["nodes"], "Fetches a node and all ancestors up to and including the root. Requires `enable()` to have been called previously.");
    inspectorBackend.registerCommand("Accessibility.getChildAXNodes", [{ "name": "id", "type": "string", "optional": false, "description": "", "typeRef": "Accessibility.AXNodeId" }, { "name": "frameId", "type": "string", "optional": true, "description": "The frame in whose document the node resides. If omitted, the root frame is used.", "typeRef": "Page.FrameId" }], ["nodes"], "Fetches a particular accessibility node by AXNodeId. Requires `enable()` to have been called previously.");
    inspectorBackend.registerCommand("Accessibility.queryAXTree", [{ "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node for the root to query.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node for the root to query.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node wrapper for the root to query.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "accessibleName", "type": "string", "optional": true, "description": "Find nodes with this computed name.", "typeRef": null }, { "name": "role", "type": "string", "optional": true, "description": "Find nodes with this computed role.", "typeRef": null }], ["nodes"], "Query a DOM node's accessibility subtree for accessible name and role. This command computes the name and role for all nodes in the subtree, including those that are ignored for accessibility, and returns those that match the specified name and role. If no DOM node is specified, or the DOM node does not exist, the command returns an error. If neither `accessibleName` or `role` is specified, it returns all the accessibility nodes in the subtree.");
    inspectorBackend.registerType("Accessibility.AXValueSource", [{ "name": "type", "type": "string", "optional": false, "description": "What type of source this is.", "typeRef": "Accessibility.AXValueSourceType" }, { "name": "value", "type": "object", "optional": true, "description": "The value of this property source.", "typeRef": "Accessibility.AXValue" }, { "name": "attribute", "type": "string", "optional": true, "description": "The name of the relevant attribute, if any.", "typeRef": null }, { "name": "attributeValue", "type": "object", "optional": true, "description": "The value of the relevant attribute, if any.", "typeRef": "Accessibility.AXValue" }, { "name": "superseded", "type": "boolean", "optional": true, "description": "Whether this source is superseded by a higher priority source.", "typeRef": null }, { "name": "nativeSource", "type": "string", "optional": true, "description": "The native markup source for this value, e.g. a `<label>` element.", "typeRef": "Accessibility.AXValueNativeSourceType" }, { "name": "nativeSourceValue", "type": "object", "optional": true, "description": "The value, such as a node or node list, of the native source.", "typeRef": "Accessibility.AXValue" }, { "name": "invalid", "type": "boolean", "optional": true, "description": "Whether the value for this property is invalid.", "typeRef": null }, { "name": "invalidReason", "type": "string", "optional": true, "description": "Reason for the value being invalid, if it is.", "typeRef": null }]);
    inspectorBackend.registerType("Accessibility.AXRelatedNode", [{ "name": "backendDOMNodeId", "type": "number", "optional": false, "description": "The BackendNodeId of the related DOM node.", "typeRef": "DOM.BackendNodeId" }, { "name": "idref", "type": "string", "optional": true, "description": "The IDRef value provided, if any.", "typeRef": null }, { "name": "text", "type": "string", "optional": true, "description": "The text alternative of this node in the current context.", "typeRef": null }]);
    inspectorBackend.registerType("Accessibility.AXProperty", [{ "name": "name", "type": "string", "optional": false, "description": "The name of this property.", "typeRef": "Accessibility.AXPropertyName" }, { "name": "value", "type": "object", "optional": false, "description": "The value of this property.", "typeRef": "Accessibility.AXValue" }]);
    inspectorBackend.registerType("Accessibility.AXValue", [{ "name": "type", "type": "string", "optional": false, "description": "The type of this value.", "typeRef": "Accessibility.AXValueType" }, { "name": "value", "type": "any", "optional": true, "description": "The computed value of this property.", "typeRef": null }, { "name": "relatedNodes", "type": "array", "optional": true, "description": "One or more related nodes, if applicable.", "typeRef": "Accessibility.AXRelatedNode" }, { "name": "sources", "type": "array", "optional": true, "description": "The sources which contributed to the computation of this property.", "typeRef": "Accessibility.AXValueSource" }]);
    inspectorBackend.registerType("Accessibility.AXNode", [{ "name": "nodeId", "type": "string", "optional": false, "description": "Unique identifier for this node.", "typeRef": "Accessibility.AXNodeId" }, { "name": "ignored", "type": "boolean", "optional": false, "description": "Whether this node is ignored for accessibility", "typeRef": null }, { "name": "ignoredReasons", "type": "array", "optional": true, "description": "Collection of reasons why this node is hidden.", "typeRef": "Accessibility.AXProperty" }, { "name": "role", "type": "object", "optional": true, "description": "This `Node`'s role, whether explicit or implicit.", "typeRef": "Accessibility.AXValue" }, { "name": "chromeRole", "type": "object", "optional": true, "description": "This `Node`'s Chrome raw role.", "typeRef": "Accessibility.AXValue" }, { "name": "name", "type": "object", "optional": true, "description": "The accessible name for this `Node`.", "typeRef": "Accessibility.AXValue" }, { "name": "description", "type": "object", "optional": true, "description": "The accessible description for this `Node`.", "typeRef": "Accessibility.AXValue" }, { "name": "value", "type": "object", "optional": true, "description": "The value for this `Node`.", "typeRef": "Accessibility.AXValue" }, { "name": "properties", "type": "array", "optional": true, "description": "All other properties", "typeRef": "Accessibility.AXProperty" }, { "name": "parentId", "type": "string", "optional": true, "description": "ID for this node's parent.", "typeRef": "Accessibility.AXNodeId" }, { "name": "childIds", "type": "array", "optional": true, "description": "IDs for each of this node's child nodes.", "typeRef": "Accessibility.AXNodeId" }, { "name": "backendDOMNodeId", "type": "number", "optional": true, "description": "The backend ID for the associated DOM node, if any.", "typeRef": "DOM.BackendNodeId" }, { "name": "frameId", "type": "string", "optional": true, "description": "The frame ID for the frame associated with this nodes document.", "typeRef": "Page.FrameId" }]);
    inspectorBackend.registerEnum("Animation.AnimationType", { CSSTransition: "CSSTransition", CSSAnimation: "CSSAnimation", WebAnimation: "WebAnimation" });
    inspectorBackend.registerEvent("Animation.animationCanceled", ["id"]);
    inspectorBackend.registerEvent("Animation.animationCreated", ["id"]);
    inspectorBackend.registerEvent("Animation.animationStarted", ["animation"]);
    inspectorBackend.registerEvent("Animation.animationUpdated", ["animation"]);
    inspectorBackend.registerCommand("Animation.disable", [], [], "Disables animation domain notifications.");
    inspectorBackend.registerCommand("Animation.enable", [], [], "Enables animation domain notifications.");
    inspectorBackend.registerCommand("Animation.getCurrentTime", [{ "name": "id", "type": "string", "optional": false, "description": "Id of animation.", "typeRef": null }], ["currentTime"], "Returns the current time of the an animation.");
    inspectorBackend.registerCommand("Animation.getPlaybackRate", [], ["playbackRate"], "Gets the playback rate of the document timeline.");
    inspectorBackend.registerCommand("Animation.releaseAnimations", [{ "name": "animations", "type": "array", "optional": false, "description": "List of animation ids to seek.", "typeRef": "string" }], [], "Releases a set of animations to no longer be manipulated.");
    inspectorBackend.registerCommand("Animation.resolveAnimation", [{ "name": "animationId", "type": "string", "optional": false, "description": "Animation id.", "typeRef": null }], ["remoteObject"], "Gets the remote object of the Animation.");
    inspectorBackend.registerCommand("Animation.seekAnimations", [{ "name": "animations", "type": "array", "optional": false, "description": "List of animation ids to seek.", "typeRef": "string" }, { "name": "currentTime", "type": "number", "optional": false, "description": "Set the current time of each animation.", "typeRef": null }], [], "Seek a set of animations to a particular time within each animation.");
    inspectorBackend.registerCommand("Animation.setPaused", [{ "name": "animations", "type": "array", "optional": false, "description": "Animations to set the pause state of.", "typeRef": "string" }, { "name": "paused", "type": "boolean", "optional": false, "description": "Paused state to set to.", "typeRef": null }], [], "Sets the paused state of a set of animations.");
    inspectorBackend.registerCommand("Animation.setPlaybackRate", [{ "name": "playbackRate", "type": "number", "optional": false, "description": "Playback rate for animations on page", "typeRef": null }], [], "Sets the playback rate of the document timeline.");
    inspectorBackend.registerCommand("Animation.setTiming", [{ "name": "animationId", "type": "string", "optional": false, "description": "Animation id.", "typeRef": null }, { "name": "duration", "type": "number", "optional": false, "description": "Duration of the animation.", "typeRef": null }, { "name": "delay", "type": "number", "optional": false, "description": "Delay of the animation.", "typeRef": null }], [], "Sets the timing of an animation node.");
    inspectorBackend.registerType("Animation.Animation", [{ "name": "id", "type": "string", "optional": false, "description": "`Animation`'s id.", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "`Animation`'s name.", "typeRef": null }, { "name": "pausedState", "type": "boolean", "optional": false, "description": "`Animation`'s internal paused state.", "typeRef": null }, { "name": "playState", "type": "string", "optional": false, "description": "`Animation`'s play state.", "typeRef": null }, { "name": "playbackRate", "type": "number", "optional": false, "description": "`Animation`'s playback rate.", "typeRef": null }, { "name": "startTime", "type": "number", "optional": false, "description": "`Animation`'s start time. Milliseconds for time based animations and percentage [0 - 100] for scroll driven animations (i.e. when viewOrScrollTimeline exists).", "typeRef": null }, { "name": "currentTime", "type": "number", "optional": false, "description": "`Animation`'s current time.", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "Animation type of `Animation`.", "typeRef": null }, { "name": "source", "type": "object", "optional": true, "description": "`Animation`'s source animation node.", "typeRef": "Animation.AnimationEffect" }, { "name": "cssId", "type": "string", "optional": true, "description": "A unique ID for `Animation` representing the sources that triggered this CSS animation/transition.", "typeRef": null }, { "name": "viewOrScrollTimeline", "type": "object", "optional": true, "description": "View or scroll timeline", "typeRef": "Animation.ViewOrScrollTimeline" }]);
    inspectorBackend.registerType("Animation.ViewOrScrollTimeline", [{ "name": "sourceNodeId", "type": "number", "optional": true, "description": "Scroll container node", "typeRef": "DOM.BackendNodeId" }, { "name": "startOffset", "type": "number", "optional": true, "description": "Represents the starting scroll position of the timeline as a length offset in pixels from scroll origin.", "typeRef": null }, { "name": "endOffset", "type": "number", "optional": true, "description": "Represents the ending scroll position of the timeline as a length offset in pixels from scroll origin.", "typeRef": null }, { "name": "subjectNodeId", "type": "number", "optional": true, "description": "The element whose principal box's visibility in the scrollport defined the progress of the timeline. Does not exist for animations with ScrollTimeline", "typeRef": "DOM.BackendNodeId" }, { "name": "axis", "type": "string", "optional": false, "description": "Orientation of the scroll", "typeRef": "DOM.ScrollOrientation" }]);
    inspectorBackend.registerType("Animation.AnimationEffect", [{ "name": "delay", "type": "number", "optional": false, "description": "`AnimationEffect`'s delay.", "typeRef": null }, { "name": "endDelay", "type": "number", "optional": false, "description": "`AnimationEffect`'s end delay.", "typeRef": null }, { "name": "iterationStart", "type": "number", "optional": false, "description": "`AnimationEffect`'s iteration start.", "typeRef": null }, { "name": "iterations", "type": "number", "optional": true, "description": "`AnimationEffect`'s iterations. Omitted if the value is infinite.", "typeRef": null }, { "name": "duration", "type": "number", "optional": false, "description": "`AnimationEffect`'s iteration duration. Milliseconds for time based animations and percentage [0 - 100] for scroll driven animations (i.e. when viewOrScrollTimeline exists).", "typeRef": null }, { "name": "direction", "type": "string", "optional": false, "description": "`AnimationEffect`'s playback direction.", "typeRef": null }, { "name": "fill", "type": "string", "optional": false, "description": "`AnimationEffect`'s fill mode.", "typeRef": null }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "`AnimationEffect`'s target node.", "typeRef": "DOM.BackendNodeId" }, { "name": "keyframesRule", "type": "object", "optional": true, "description": "`AnimationEffect`'s keyframes.", "typeRef": "Animation.KeyframesRule" }, { "name": "easing", "type": "string", "optional": false, "description": "`AnimationEffect`'s timing function.", "typeRef": null }]);
    inspectorBackend.registerType("Animation.KeyframesRule", [{ "name": "name", "type": "string", "optional": true, "description": "CSS keyframed animation's name.", "typeRef": null }, { "name": "keyframes", "type": "array", "optional": false, "description": "List of animation keyframes.", "typeRef": "Animation.KeyframeStyle" }]);
    inspectorBackend.registerType("Animation.KeyframeStyle", [{ "name": "offset", "type": "string", "optional": false, "description": "Keyframe's time offset.", "typeRef": null }, { "name": "easing", "type": "string", "optional": false, "description": "`AnimationEffect`'s timing function.", "typeRef": null }]);
    inspectorBackend.registerEnum("Audits.CookieExclusionReason", { ExcludeSameSiteUnspecifiedTreatedAsLax: "ExcludeSameSiteUnspecifiedTreatedAsLax", ExcludeSameSiteNoneInsecure: "ExcludeSameSiteNoneInsecure", ExcludeSameSiteLax: "ExcludeSameSiteLax", ExcludeSameSiteStrict: "ExcludeSameSiteStrict", ExcludeDomainNonASCII: "ExcludeDomainNonASCII", ExcludeThirdPartyCookieBlockedInFirstPartySet: "ExcludeThirdPartyCookieBlockedInFirstPartySet", ExcludeThirdPartyPhaseout: "ExcludeThirdPartyPhaseout", ExcludePortMismatch: "ExcludePortMismatch", ExcludeSchemeMismatch: "ExcludeSchemeMismatch" });
    inspectorBackend.registerEnum("Audits.CookieWarningReason", { WarnSameSiteUnspecifiedCrossSiteContext: "WarnSameSiteUnspecifiedCrossSiteContext", WarnSameSiteNoneInsecure: "WarnSameSiteNoneInsecure", WarnSameSiteUnspecifiedLaxAllowUnsafe: "WarnSameSiteUnspecifiedLaxAllowUnsafe", WarnSameSiteStrictLaxDowngradeStrict: "WarnSameSiteStrictLaxDowngradeStrict", WarnSameSiteStrictCrossDowngradeStrict: "WarnSameSiteStrictCrossDowngradeStrict", WarnSameSiteStrictCrossDowngradeLax: "WarnSameSiteStrictCrossDowngradeLax", WarnSameSiteLaxCrossDowngradeStrict: "WarnSameSiteLaxCrossDowngradeStrict", WarnSameSiteLaxCrossDowngradeLax: "WarnSameSiteLaxCrossDowngradeLax", WarnAttributeValueExceedsMaxSize: "WarnAttributeValueExceedsMaxSize", WarnDomainNonASCII: "WarnDomainNonASCII", WarnThirdPartyPhaseout: "WarnThirdPartyPhaseout", WarnCrossSiteRedirectDowngradeChangesInclusion: "WarnCrossSiteRedirectDowngradeChangesInclusion", WarnDeprecationTrialMetadata: "WarnDeprecationTrialMetadata", WarnThirdPartyCookieHeuristic: "WarnThirdPartyCookieHeuristic" });
    inspectorBackend.registerEnum("Audits.CookieOperation", { SetCookie: "SetCookie", ReadCookie: "ReadCookie" });
    inspectorBackend.registerEnum("Audits.InsightType", { GitHubResource: "GitHubResource", GracePeriod: "GracePeriod", Heuristics: "Heuristics" });
    inspectorBackend.registerEnum("Audits.PerformanceIssueType", { DocumentCookie: "DocumentCookie" });
    inspectorBackend.registerEnum("Audits.MixedContentResolutionStatus", { MixedContentBlocked: "MixedContentBlocked", MixedContentAutomaticallyUpgraded: "MixedContentAutomaticallyUpgraded", MixedContentWarning: "MixedContentWarning" });
    inspectorBackend.registerEnum("Audits.MixedContentResourceType", { AttributionSrc: "AttributionSrc", Audio: "Audio", Beacon: "Beacon", CSPReport: "CSPReport", Download: "Download", EventSource: "EventSource", Favicon: "Favicon", Font: "Font", Form: "Form", Frame: "Frame", Image: "Image", Import: "Import", JSON: "JSON", Manifest: "Manifest", Ping: "Ping", PluginData: "PluginData", PluginResource: "PluginResource", Prefetch: "Prefetch", Resource: "Resource", Script: "Script", ServiceWorker: "ServiceWorker", SharedWorker: "SharedWorker", SpeculationRules: "SpeculationRules", Stylesheet: "Stylesheet", Track: "Track", Video: "Video", Worker: "Worker", XMLHttpRequest: "XMLHttpRequest", XSLT: "XSLT" });
    inspectorBackend.registerEnum("Audits.BlockedByResponseReason", { CoepFrameResourceNeedsCoepHeader: "CoepFrameResourceNeedsCoepHeader", CoopSandboxedIFrameCannotNavigateToCoopPage: "CoopSandboxedIFrameCannotNavigateToCoopPage", CorpNotSameOrigin: "CorpNotSameOrigin", CorpNotSameOriginAfterDefaultedToSameOriginByCoep: "CorpNotSameOriginAfterDefaultedToSameOriginByCoep", CorpNotSameOriginAfterDefaultedToSameOriginByDip: "CorpNotSameOriginAfterDefaultedToSameOriginByDip", CorpNotSameOriginAfterDefaultedToSameOriginByCoepAndDip: "CorpNotSameOriginAfterDefaultedToSameOriginByCoepAndDip", CorpNotSameSite: "CorpNotSameSite", SRIMessageSignatureMismatch: "SRIMessageSignatureMismatch" });
    inspectorBackend.registerEnum("Audits.HeavyAdResolutionStatus", { HeavyAdBlocked: "HeavyAdBlocked", HeavyAdWarning: "HeavyAdWarning" });
    inspectorBackend.registerEnum("Audits.HeavyAdReason", { NetworkTotalLimit: "NetworkTotalLimit", CpuTotalLimit: "CpuTotalLimit", CpuPeakLimit: "CpuPeakLimit" });
    inspectorBackend.registerEnum("Audits.ContentSecurityPolicyViolationType", { KInlineViolation: "kInlineViolation", KEvalViolation: "kEvalViolation", KURLViolation: "kURLViolation", KSRIViolation: "kSRIViolation", KTrustedTypesSinkViolation: "kTrustedTypesSinkViolation", KTrustedTypesPolicyViolation: "kTrustedTypesPolicyViolation", KWasmEvalViolation: "kWasmEvalViolation" });
    inspectorBackend.registerEnum("Audits.SharedArrayBufferIssueType", { TransferIssue: "TransferIssue", CreationIssue: "CreationIssue" });
    inspectorBackend.registerEnum("Audits.AttributionReportingIssueType", { PermissionPolicyDisabled: "PermissionPolicyDisabled", UntrustworthyReportingOrigin: "UntrustworthyReportingOrigin", InsecureContext: "InsecureContext", InvalidHeader: "InvalidHeader", InvalidRegisterTriggerHeader: "InvalidRegisterTriggerHeader", SourceAndTriggerHeaders: "SourceAndTriggerHeaders", SourceIgnored: "SourceIgnored", TriggerIgnored: "TriggerIgnored", OsSourceIgnored: "OsSourceIgnored", OsTriggerIgnored: "OsTriggerIgnored", InvalidRegisterOsSourceHeader: "InvalidRegisterOsSourceHeader", InvalidRegisterOsTriggerHeader: "InvalidRegisterOsTriggerHeader", WebAndOsHeaders: "WebAndOsHeaders", NoWebOrOsSupport: "NoWebOrOsSupport", NavigationRegistrationWithoutTransientUserActivation: "NavigationRegistrationWithoutTransientUserActivation", InvalidInfoHeader: "InvalidInfoHeader", NoRegisterSourceHeader: "NoRegisterSourceHeader", NoRegisterTriggerHeader: "NoRegisterTriggerHeader", NoRegisterOsSourceHeader: "NoRegisterOsSourceHeader", NoRegisterOsTriggerHeader: "NoRegisterOsTriggerHeader", NavigationRegistrationUniqueScopeAlreadySet: "NavigationRegistrationUniqueScopeAlreadySet" });
    inspectorBackend.registerEnum("Audits.SharedDictionaryError", { UseErrorCrossOriginNoCorsRequest: "UseErrorCrossOriginNoCorsRequest", UseErrorDictionaryLoadFailure: "UseErrorDictionaryLoadFailure", UseErrorMatchingDictionaryNotUsed: "UseErrorMatchingDictionaryNotUsed", UseErrorUnexpectedContentDictionaryHeader: "UseErrorUnexpectedContentDictionaryHeader", WriteErrorCossOriginNoCorsRequest: "WriteErrorCossOriginNoCorsRequest", WriteErrorDisallowedBySettings: "WriteErrorDisallowedBySettings", WriteErrorExpiredResponse: "WriteErrorExpiredResponse", WriteErrorFeatureDisabled: "WriteErrorFeatureDisabled", WriteErrorInsufficientResources: "WriteErrorInsufficientResources", WriteErrorInvalidMatchField: "WriteErrorInvalidMatchField", WriteErrorInvalidStructuredHeader: "WriteErrorInvalidStructuredHeader", WriteErrorInvalidTTLField: "WriteErrorInvalidTTLField", WriteErrorNavigationRequest: "WriteErrorNavigationRequest", WriteErrorNoMatchField: "WriteErrorNoMatchField", WriteErrorNonIntegerTTLField: "WriteErrorNonIntegerTTLField", WriteErrorNonListMatchDestField: "WriteErrorNonListMatchDestField", WriteErrorNonSecureContext: "WriteErrorNonSecureContext", WriteErrorNonStringIdField: "WriteErrorNonStringIdField", WriteErrorNonStringInMatchDestList: "WriteErrorNonStringInMatchDestList", WriteErrorNonStringMatchField: "WriteErrorNonStringMatchField", WriteErrorNonTokenTypeField: "WriteErrorNonTokenTypeField", WriteErrorRequestAborted: "WriteErrorRequestAborted", WriteErrorShuttingDown: "WriteErrorShuttingDown", WriteErrorTooLongIdField: "WriteErrorTooLongIdField", WriteErrorUnsupportedType: "WriteErrorUnsupportedType" });
    inspectorBackend.registerEnum("Audits.SRIMessageSignatureError", { MissingSignatureHeader: "MissingSignatureHeader", MissingSignatureInputHeader: "MissingSignatureInputHeader", InvalidSignatureHeader: "InvalidSignatureHeader", InvalidSignatureInputHeader: "InvalidSignatureInputHeader", SignatureHeaderValueIsNotByteSequence: "SignatureHeaderValueIsNotByteSequence", SignatureHeaderValueIsParameterized: "SignatureHeaderValueIsParameterized", SignatureHeaderValueIsIncorrectLength: "SignatureHeaderValueIsIncorrectLength", SignatureInputHeaderMissingLabel: "SignatureInputHeaderMissingLabel", SignatureInputHeaderValueNotInnerList: "SignatureInputHeaderValueNotInnerList", SignatureInputHeaderValueMissingComponents: "SignatureInputHeaderValueMissingComponents", SignatureInputHeaderInvalidComponentType: "SignatureInputHeaderInvalidComponentType", SignatureInputHeaderInvalidComponentName: "SignatureInputHeaderInvalidComponentName", SignatureInputHeaderInvalidHeaderComponentParameter: "SignatureInputHeaderInvalidHeaderComponentParameter", SignatureInputHeaderInvalidDerivedComponentParameter: "SignatureInputHeaderInvalidDerivedComponentParameter", SignatureInputHeaderKeyIdLength: "SignatureInputHeaderKeyIdLength", SignatureInputHeaderInvalidParameter: "SignatureInputHeaderInvalidParameter", SignatureInputHeaderMissingRequiredParameters: "SignatureInputHeaderMissingRequiredParameters", ValidationFailedSignatureExpired: "ValidationFailedSignatureExpired", ValidationFailedInvalidLength: "ValidationFailedInvalidLength", ValidationFailedSignatureMismatch: "ValidationFailedSignatureMismatch", ValidationFailedIntegrityMismatch: "ValidationFailedIntegrityMismatch" });
    inspectorBackend.registerEnum("Audits.UnencodedDigestError", { MalformedDictionary: "MalformedDictionary", UnknownAlgorithm: "UnknownAlgorithm", IncorrectDigestType: "IncorrectDigestType", IncorrectDigestLength: "IncorrectDigestLength" });
    inspectorBackend.registerEnum("Audits.ConnectionAllowlistError", { InvalidHeader: "InvalidHeader", MoreThanOneList: "MoreThanOneList", ItemNotInnerList: "ItemNotInnerList", InvalidAllowlistItemType: "InvalidAllowlistItemType", ReportingEndpointNotToken: "ReportingEndpointNotToken", InvalidUrlPattern: "InvalidUrlPattern" });
    inspectorBackend.registerEnum("Audits.GenericIssueErrorType", { FormLabelForNameError: "FormLabelForNameError", FormDuplicateIdForInputError: "FormDuplicateIdForInputError", FormInputWithNoLabelError: "FormInputWithNoLabelError", FormAutocompleteAttributeEmptyError: "FormAutocompleteAttributeEmptyError", FormEmptyIdAndNameAttributesForInputError: "FormEmptyIdAndNameAttributesForInputError", FormAriaLabelledByToNonExistingIdError: "FormAriaLabelledByToNonExistingIdError", FormInputAssignedAutocompleteValueToIdOrNameAttributeError: "FormInputAssignedAutocompleteValueToIdOrNameAttributeError", FormLabelHasNeitherForNorNestedInputError: "FormLabelHasNeitherForNorNestedInputError", FormLabelForMatchesNonExistingIdError: "FormLabelForMatchesNonExistingIdError", FormInputHasWrongButWellIntendedAutocompleteValueError: "FormInputHasWrongButWellIntendedAutocompleteValueError", ResponseWasBlockedByORB: "ResponseWasBlockedByORB", NavigationEntryMarkedSkippable: "NavigationEntryMarkedSkippable", AutofillAndManualTextPolicyControlledFeaturesInfo: "AutofillAndManualTextPolicyControlledFeaturesInfo", AutofillPolicyControlledFeatureInfo: "AutofillPolicyControlledFeatureInfo", ManualTextPolicyControlledFeatureInfo: "ManualTextPolicyControlledFeatureInfo" });
    inspectorBackend.registerEnum("Audits.ClientHintIssueReason", { MetaTagAllowListInvalidOrigin: "MetaTagAllowListInvalidOrigin", MetaTagModifiedHTML: "MetaTagModifiedHTML" });
    inspectorBackend.registerEnum("Audits.FederatedAuthRequestIssueReason", { ShouldEmbargo: "ShouldEmbargo", TooManyRequests: "TooManyRequests", WellKnownHttpNotFound: "WellKnownHttpNotFound", WellKnownNoResponse: "WellKnownNoResponse", WellKnownInvalidResponse: "WellKnownInvalidResponse", WellKnownListEmpty: "WellKnownListEmpty", WellKnownInvalidContentType: "WellKnownInvalidContentType", ConfigNotInWellKnown: "ConfigNotInWellKnown", WellKnownTooBig: "WellKnownTooBig", ConfigHttpNotFound: "ConfigHttpNotFound", ConfigNoResponse: "ConfigNoResponse", ConfigInvalidResponse: "ConfigInvalidResponse", ConfigInvalidContentType: "ConfigInvalidContentType", IdpNotPotentiallyTrustworthy: "IdpNotPotentiallyTrustworthy", DisabledInSettings: "DisabledInSettings", DisabledInFlags: "DisabledInFlags", ErrorFetchingSignin: "ErrorFetchingSignin", InvalidSigninResponse: "InvalidSigninResponse", AccountsHttpNotFound: "AccountsHttpNotFound", AccountsNoResponse: "AccountsNoResponse", AccountsInvalidResponse: "AccountsInvalidResponse", AccountsListEmpty: "AccountsListEmpty", AccountsInvalidContentType: "AccountsInvalidContentType", IdTokenHttpNotFound: "IdTokenHttpNotFound", IdTokenNoResponse: "IdTokenNoResponse", IdTokenInvalidResponse: "IdTokenInvalidResponse", IdTokenIdpErrorResponse: "IdTokenIdpErrorResponse", IdTokenCrossSiteIdpErrorResponse: "IdTokenCrossSiteIdpErrorResponse", IdTokenInvalidRequest: "IdTokenInvalidRequest", IdTokenInvalidContentType: "IdTokenInvalidContentType", ErrorIdToken: "ErrorIdToken", Canceled: "Canceled", RpPageNotVisible: "RpPageNotVisible", SilentMediationFailure: "SilentMediationFailure", NotSignedInWithIdp: "NotSignedInWithIdp", MissingTransientUserActivation: "MissingTransientUserActivation", ReplacedByActiveMode: "ReplacedByActiveMode", RelyingPartyOriginIsOpaque: "RelyingPartyOriginIsOpaque", TypeNotMatching: "TypeNotMatching", UiDismissedNoEmbargo: "UiDismissedNoEmbargo", CorsError: "CorsError", SuppressedBySegmentationPlatform: "SuppressedBySegmentationPlatform" });
    inspectorBackend.registerEnum("Audits.FederatedAuthUserInfoRequestIssueReason", { NotSameOrigin: "NotSameOrigin", NotIframe: "NotIframe", NotPotentiallyTrustworthy: "NotPotentiallyTrustworthy", NoAPIPermission: "NoApiPermission", NotSignedInWithIdp: "NotSignedInWithIdp", NoAccountSharingPermission: "NoAccountSharingPermission", InvalidConfigOrWellKnown: "InvalidConfigOrWellKnown", InvalidAccountsResponse: "InvalidAccountsResponse", NoReturningUserFromFetchedAccounts: "NoReturningUserFromFetchedAccounts" });
    inspectorBackend.registerEnum("Audits.PartitioningBlobURLInfo", { BlockedCrossPartitionFetching: "BlockedCrossPartitionFetching", EnforceNoopenerForNavigation: "EnforceNoopenerForNavigation" });
    inspectorBackend.registerEnum("Audits.ElementAccessibilityIssueReason", { DisallowedSelectChild: "DisallowedSelectChild", DisallowedOptGroupChild: "DisallowedOptGroupChild", NonPhrasingContentOptionChild: "NonPhrasingContentOptionChild", InteractiveContentOptionChild: "InteractiveContentOptionChild", InteractiveContentLegendChild: "InteractiveContentLegendChild", InteractiveContentSummaryDescendant: "InteractiveContentSummaryDescendant" });
    inspectorBackend.registerEnum("Audits.StyleSheetLoadingIssueReason", { LateImportRule: "LateImportRule", RequestFailed: "RequestFailed" });
    inspectorBackend.registerEnum("Audits.PropertyRuleIssueReason", { InvalidSyntax: "InvalidSyntax", InvalidInitialValue: "InvalidInitialValue", InvalidInherits: "InvalidInherits", InvalidName: "InvalidName" });
    inspectorBackend.registerEnum("Audits.UserReidentificationIssueType", { BlockedFrameNavigation: "BlockedFrameNavigation", BlockedSubresource: "BlockedSubresource", NoisedCanvasReadback: "NoisedCanvasReadback" });
    inspectorBackend.registerEnum("Audits.PermissionElementIssueType", { InvalidType: "InvalidType", FencedFrameDisallowed: "FencedFrameDisallowed", CspFrameAncestorsMissing: "CspFrameAncestorsMissing", PermissionsPolicyBlocked: "PermissionsPolicyBlocked", PaddingRightUnsupported: "PaddingRightUnsupported", PaddingBottomUnsupported: "PaddingBottomUnsupported", InsetBoxShadowUnsupported: "InsetBoxShadowUnsupported", RequestInProgress: "RequestInProgress", UntrustedEvent: "UntrustedEvent", RegistrationFailed: "RegistrationFailed", TypeNotSupported: "TypeNotSupported", InvalidTypeActivation: "InvalidTypeActivation", SecurityChecksFailed: "SecurityChecksFailed", ActivationDisabled: "ActivationDisabled", GeolocationDeprecated: "GeolocationDeprecated", InvalidDisplayStyle: "InvalidDisplayStyle", NonOpaqueColor: "NonOpaqueColor", LowContrast: "LowContrast", FontSizeTooSmall: "FontSizeTooSmall", FontSizeTooLarge: "FontSizeTooLarge", InvalidSizeValue: "InvalidSizeValue" });
    inspectorBackend.registerEnum("Audits.InspectorIssueCode", { CookieIssue: "CookieIssue", MixedContentIssue: "MixedContentIssue", BlockedByResponseIssue: "BlockedByResponseIssue", HeavyAdIssue: "HeavyAdIssue", ContentSecurityPolicyIssue: "ContentSecurityPolicyIssue", SharedArrayBufferIssue: "SharedArrayBufferIssue", LowTextContrastIssue: "LowTextContrastIssue", CorsIssue: "CorsIssue", AttributionReportingIssue: "AttributionReportingIssue", QuirksModeIssue: "QuirksModeIssue", PartitioningBlobURLIssue: "PartitioningBlobURLIssue", NavigatorUserAgentIssue: "NavigatorUserAgentIssue", GenericIssue: "GenericIssue", DeprecationIssue: "DeprecationIssue", ClientHintIssue: "ClientHintIssue", FederatedAuthRequestIssue: "FederatedAuthRequestIssue", BounceTrackingIssue: "BounceTrackingIssue", CookieDeprecationMetadataIssue: "CookieDeprecationMetadataIssue", StylesheetLoadingIssue: "StylesheetLoadingIssue", FederatedAuthUserInfoRequestIssue: "FederatedAuthUserInfoRequestIssue", PropertyRuleIssue: "PropertyRuleIssue", SharedDictionaryIssue: "SharedDictionaryIssue", ElementAccessibilityIssue: "ElementAccessibilityIssue", SRIMessageSignatureIssue: "SRIMessageSignatureIssue", UnencodedDigestIssue: "UnencodedDigestIssue", ConnectionAllowlistIssue: "ConnectionAllowlistIssue", UserReidentificationIssue: "UserReidentificationIssue", PermissionElementIssue: "PermissionElementIssue", PerformanceIssue: "PerformanceIssue", SelectivePermissionsInterventionIssue: "SelectivePermissionsInterventionIssue" });
    inspectorBackend.registerEvent("Audits.issueAdded", ["issue"]);
    inspectorBackend.registerEnum("Audits.GetEncodedResponseRequestEncoding", { Webp: "webp", Jpeg: "jpeg", Png: "png" });
    inspectorBackend.registerCommand("Audits.getEncodedResponse", [{ "name": "requestId", "type": "string", "optional": false, "description": "Identifier of the network request to get content for.", "typeRef": "Network.RequestId" }, { "name": "encoding", "type": "string", "optional": false, "description": "The encoding to use.", "typeRef": "Audits.GetEncodedResponseRequestEncoding" }, { "name": "quality", "type": "number", "optional": true, "description": "The quality of the encoding (0-1). (defaults to 1)", "typeRef": null }, { "name": "sizeOnly", "type": "boolean", "optional": true, "description": "Whether to only return the size information (defaults to false).", "typeRef": null }], ["body", "originalSize", "encodedSize"], "Returns the response body and size if it were re-encoded with the specified settings. Only applies to images.");
    inspectorBackend.registerCommand("Audits.disable", [], [], "Disables issues domain, prevents further issues from being reported to the client.");
    inspectorBackend.registerCommand("Audits.enable", [], [], "Enables issues domain, sends the issues collected so far to the client by means of the `issueAdded` event.");
    inspectorBackend.registerCommand("Audits.checkContrast", [{ "name": "reportAAA", "type": "boolean", "optional": true, "description": "Whether to report WCAG AAA level issues. Default is false.", "typeRef": null }], [], "Runs the contrast check for the target page. Found issues are reported using Audits.issueAdded event.");
    inspectorBackend.registerCommand("Audits.checkFormsIssues", [], ["formIssues"], "Runs the form issues check for the target page. Found issues are reported using Audits.issueAdded event.");
    inspectorBackend.registerType("Audits.AffectedCookie", [{ "name": "name", "type": "string", "optional": false, "description": "The following three properties uniquely identify a cookie", "typeRef": null }, { "name": "path", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "domain", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Audits.AffectedRequest", [{ "name": "requestId", "type": "string", "optional": true, "description": "The unique request id.", "typeRef": "Network.RequestId" }, { "name": "url", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Audits.AffectedFrame", [{ "name": "frameId", "type": "string", "optional": false, "description": "", "typeRef": "Page.FrameId" }]);
    inspectorBackend.registerType("Audits.CookieIssueInsight", [{ "name": "type", "type": "string", "optional": false, "description": "", "typeRef": "Audits.InsightType" }, { "name": "tableEntryUrl", "type": "string", "optional": true, "description": "Link to table entry in third-party cookie migration readiness list.", "typeRef": null }]);
    inspectorBackend.registerType("Audits.CookieIssueDetails", [{ "name": "cookie", "type": "object", "optional": true, "description": "If AffectedCookie is not set then rawCookieLine contains the raw Set-Cookie header string. This hints at a problem where the cookie line is syntactically or semantically malformed in a way that no valid cookie could be created.", "typeRef": "Audits.AffectedCookie" }, { "name": "rawCookieLine", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "cookieWarningReasons", "type": "array", "optional": false, "description": "", "typeRef": "Audits.CookieWarningReason" }, { "name": "cookieExclusionReasons", "type": "array", "optional": false, "description": "", "typeRef": "Audits.CookieExclusionReason" }, { "name": "operation", "type": "string", "optional": false, "description": "Optionally identifies the site-for-cookies and the cookie url, which may be used by the front-end as additional context.", "typeRef": "Audits.CookieOperation" }, { "name": "siteForCookies", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "cookieUrl", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "request", "type": "object", "optional": true, "description": "", "typeRef": "Audits.AffectedRequest" }, { "name": "insight", "type": "object", "optional": true, "description": "The recommended solution to the issue.", "typeRef": "Audits.CookieIssueInsight" }]);
    inspectorBackend.registerType("Audits.PerformanceIssueDetails", [{ "name": "performanceIssueType", "type": "string", "optional": false, "description": "", "typeRef": "Audits.PerformanceIssueType" }, { "name": "sourceCodeLocation", "type": "object", "optional": true, "description": "", "typeRef": "Audits.SourceCodeLocation" }]);
    inspectorBackend.registerType("Audits.MixedContentIssueDetails", [{ "name": "resourceType", "type": "string", "optional": true, "description": "The type of resource causing the mixed content issue (css, js, iframe, form,...). Marked as optional because it is mapped to from blink::mojom::RequestContextType, which will be replaced by network::mojom::RequestDestination", "typeRef": "Audits.MixedContentResourceType" }, { "name": "resolutionStatus", "type": "string", "optional": false, "description": "The way the mixed content issue is being resolved.", "typeRef": "Audits.MixedContentResolutionStatus" }, { "name": "insecureURL", "type": "string", "optional": false, "description": "The unsafe http url causing the mixed content issue.", "typeRef": null }, { "name": "mainResourceURL", "type": "string", "optional": false, "description": "The url responsible for the call to an unsafe url.", "typeRef": null }, { "name": "request", "type": "object", "optional": true, "description": "The mixed content request. Does not always exist (e.g. for unsafe form submission urls).", "typeRef": "Audits.AffectedRequest" }, { "name": "frame", "type": "object", "optional": true, "description": "Optional because not every mixed content issue is necessarily linked to a frame.", "typeRef": "Audits.AffectedFrame" }]);
    inspectorBackend.registerType("Audits.BlockedByResponseIssueDetails", [{ "name": "request", "type": "object", "optional": false, "description": "", "typeRef": "Audits.AffectedRequest" }, { "name": "parentFrame", "type": "object", "optional": true, "description": "", "typeRef": "Audits.AffectedFrame" }, { "name": "blockedFrame", "type": "object", "optional": true, "description": "", "typeRef": "Audits.AffectedFrame" }, { "name": "reason", "type": "string", "optional": false, "description": "", "typeRef": "Audits.BlockedByResponseReason" }]);
    inspectorBackend.registerType("Audits.HeavyAdIssueDetails", [{ "name": "resolution", "type": "string", "optional": false, "description": "The resolution status, either blocking the content or warning.", "typeRef": "Audits.HeavyAdResolutionStatus" }, { "name": "reason", "type": "string", "optional": false, "description": "The reason the ad was blocked, total network or cpu or peak cpu.", "typeRef": "Audits.HeavyAdReason" }, { "name": "frame", "type": "object", "optional": false, "description": "The frame that was blocked.", "typeRef": "Audits.AffectedFrame" }]);
    inspectorBackend.registerType("Audits.SourceCodeLocation", [{ "name": "scriptId", "type": "string", "optional": true, "description": "", "typeRef": "Runtime.ScriptId" }, { "name": "url", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "lineNumber", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "columnNumber", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Audits.ContentSecurityPolicyIssueDetails", [{ "name": "blockedURL", "type": "string", "optional": true, "description": "The url not included in allowed sources.", "typeRef": null }, { "name": "violatedDirective", "type": "string", "optional": false, "description": "Specific directive that is violated, causing the CSP issue.", "typeRef": null }, { "name": "isReportOnly", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "contentSecurityPolicyViolationType", "type": "string", "optional": false, "description": "", "typeRef": "Audits.ContentSecurityPolicyViolationType" }, { "name": "frameAncestor", "type": "object", "optional": true, "description": "", "typeRef": "Audits.AffectedFrame" }, { "name": "sourceCodeLocation", "type": "object", "optional": true, "description": "", "typeRef": "Audits.SourceCodeLocation" }, { "name": "violatingNodeId", "type": "number", "optional": true, "description": "", "typeRef": "DOM.BackendNodeId" }]);
    inspectorBackend.registerType("Audits.SharedArrayBufferIssueDetails", [{ "name": "sourceCodeLocation", "type": "object", "optional": false, "description": "", "typeRef": "Audits.SourceCodeLocation" }, { "name": "isWarning", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "", "typeRef": "Audits.SharedArrayBufferIssueType" }]);
    inspectorBackend.registerType("Audits.LowTextContrastIssueDetails", [{ "name": "violatingNodeId", "type": "number", "optional": false, "description": "", "typeRef": "DOM.BackendNodeId" }, { "name": "violatingNodeSelector", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "contrastRatio", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "thresholdAA", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "thresholdAAA", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "fontSize", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "fontWeight", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Audits.CorsIssueDetails", [{ "name": "corsErrorStatus", "type": "object", "optional": false, "description": "", "typeRef": "Network.CorsErrorStatus" }, { "name": "isWarning", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "request", "type": "object", "optional": false, "description": "", "typeRef": "Audits.AffectedRequest" }, { "name": "location", "type": "object", "optional": true, "description": "", "typeRef": "Audits.SourceCodeLocation" }, { "name": "initiatorOrigin", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "resourceIPAddressSpace", "type": "string", "optional": true, "description": "", "typeRef": "Network.IPAddressSpace" }, { "name": "clientSecurityState", "type": "object", "optional": true, "description": "", "typeRef": "Network.ClientSecurityState" }]);
    inspectorBackend.registerType("Audits.AttributionReportingIssueDetails", [{ "name": "violationType", "type": "string", "optional": false, "description": "", "typeRef": "Audits.AttributionReportingIssueType" }, { "name": "request", "type": "object", "optional": true, "description": "", "typeRef": "Audits.AffectedRequest" }, { "name": "violatingNodeId", "type": "number", "optional": true, "description": "", "typeRef": "DOM.BackendNodeId" }, { "name": "invalidParameter", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Audits.QuirksModeIssueDetails", [{ "name": "isLimitedQuirksMode", "type": "boolean", "optional": false, "description": "If false, it means the document's mode is \\\"quirks\\\" instead of \\\"limited-quirks\\\".", "typeRef": null }, { "name": "documentNodeId", "type": "number", "optional": false, "description": "", "typeRef": "DOM.BackendNodeId" }, { "name": "url", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "frameId", "type": "string", "optional": false, "description": "", "typeRef": "Page.FrameId" }, { "name": "loaderId", "type": "string", "optional": false, "description": "", "typeRef": "Network.LoaderId" }]);
    inspectorBackend.registerType("Audits.NavigatorUserAgentIssueDetails", [{ "name": "url", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "location", "type": "object", "optional": true, "description": "", "typeRef": "Audits.SourceCodeLocation" }]);
    inspectorBackend.registerType("Audits.SharedDictionaryIssueDetails", [{ "name": "sharedDictionaryError", "type": "string", "optional": false, "description": "", "typeRef": "Audits.SharedDictionaryError" }, { "name": "request", "type": "object", "optional": false, "description": "", "typeRef": "Audits.AffectedRequest" }]);
    inspectorBackend.registerType("Audits.SRIMessageSignatureIssueDetails", [{ "name": "error", "type": "string", "optional": false, "description": "", "typeRef": "Audits.SRIMessageSignatureError" }, { "name": "signatureBase", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "integrityAssertions", "type": "array", "optional": false, "description": "", "typeRef": "string" }, { "name": "request", "type": "object", "optional": false, "description": "", "typeRef": "Audits.AffectedRequest" }]);
    inspectorBackend.registerType("Audits.UnencodedDigestIssueDetails", [{ "name": "error", "type": "string", "optional": false, "description": "", "typeRef": "Audits.UnencodedDigestError" }, { "name": "request", "type": "object", "optional": false, "description": "", "typeRef": "Audits.AffectedRequest" }]);
    inspectorBackend.registerType("Audits.ConnectionAllowlistIssueDetails", [{ "name": "error", "type": "string", "optional": false, "description": "", "typeRef": "Audits.ConnectionAllowlistError" }, { "name": "request", "type": "object", "optional": false, "description": "", "typeRef": "Audits.AffectedRequest" }]);
    inspectorBackend.registerType("Audits.GenericIssueDetails", [{ "name": "errorType", "type": "string", "optional": false, "description": "Issues with the same errorType are aggregated in the frontend.", "typeRef": "Audits.GenericIssueErrorType" }, { "name": "frameId", "type": "string", "optional": true, "description": "", "typeRef": "Page.FrameId" }, { "name": "violatingNodeId", "type": "number", "optional": true, "description": "", "typeRef": "DOM.BackendNodeId" }, { "name": "violatingNodeAttribute", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "request", "type": "object", "optional": true, "description": "", "typeRef": "Audits.AffectedRequest" }]);
    inspectorBackend.registerType("Audits.DeprecationIssueDetails", [{ "name": "affectedFrame", "type": "object", "optional": true, "description": "", "typeRef": "Audits.AffectedFrame" }, { "name": "sourceCodeLocation", "type": "object", "optional": false, "description": "", "typeRef": "Audits.SourceCodeLocation" }, { "name": "type", "type": "string", "optional": false, "description": "One of the deprecation names from third_party/blink/renderer/core/frame/deprecation/deprecation.json5", "typeRef": null }]);
    inspectorBackend.registerType("Audits.BounceTrackingIssueDetails", [{ "name": "trackingSites", "type": "array", "optional": false, "description": "", "typeRef": "string" }]);
    inspectorBackend.registerType("Audits.CookieDeprecationMetadataIssueDetails", [{ "name": "allowedSites", "type": "array", "optional": false, "description": "", "typeRef": "string" }, { "name": "optOutPercentage", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "isOptOutTopLevel", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "operation", "type": "string", "optional": false, "description": "", "typeRef": "Audits.CookieOperation" }]);
    inspectorBackend.registerType("Audits.FederatedAuthRequestIssueDetails", [{ "name": "federatedAuthRequestIssueReason", "type": "string", "optional": false, "description": "", "typeRef": "Audits.FederatedAuthRequestIssueReason" }]);
    inspectorBackend.registerType("Audits.FederatedAuthUserInfoRequestIssueDetails", [{ "name": "federatedAuthUserInfoRequestIssueReason", "type": "string", "optional": false, "description": "", "typeRef": "Audits.FederatedAuthUserInfoRequestIssueReason" }]);
    inspectorBackend.registerType("Audits.ClientHintIssueDetails", [{ "name": "sourceCodeLocation", "type": "object", "optional": false, "description": "", "typeRef": "Audits.SourceCodeLocation" }, { "name": "clientHintIssueReason", "type": "string", "optional": false, "description": "", "typeRef": "Audits.ClientHintIssueReason" }]);
    inspectorBackend.registerType("Audits.FailedRequestInfo", [{ "name": "url", "type": "string", "optional": false, "description": "The URL that failed to load.", "typeRef": null }, { "name": "failureMessage", "type": "string", "optional": false, "description": "The failure message for the failed request.", "typeRef": null }, { "name": "requestId", "type": "string", "optional": true, "description": "", "typeRef": "Network.RequestId" }]);
    inspectorBackend.registerType("Audits.PartitioningBlobURLIssueDetails", [{ "name": "url", "type": "string", "optional": false, "description": "The BlobURL that failed to load.", "typeRef": null }, { "name": "partitioningBlobURLInfo", "type": "string", "optional": false, "description": "Additional information about the Partitioning Blob URL issue.", "typeRef": "Audits.PartitioningBlobURLInfo" }]);
    inspectorBackend.registerType("Audits.ElementAccessibilityIssueDetails", [{ "name": "nodeId", "type": "number", "optional": false, "description": "", "typeRef": "DOM.BackendNodeId" }, { "name": "elementAccessibilityIssueReason", "type": "string", "optional": false, "description": "", "typeRef": "Audits.ElementAccessibilityIssueReason" }, { "name": "hasDisallowedAttributes", "type": "boolean", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Audits.StylesheetLoadingIssueDetails", [{ "name": "sourceCodeLocation", "type": "object", "optional": false, "description": "Source code position that referenced the failing stylesheet.", "typeRef": "Audits.SourceCodeLocation" }, { "name": "styleSheetLoadingIssueReason", "type": "string", "optional": false, "description": "Reason why the stylesheet couldn't be loaded.", "typeRef": "Audits.StyleSheetLoadingIssueReason" }, { "name": "failedRequestInfo", "type": "object", "optional": true, "description": "Contains additional info when the failure was due to a request.", "typeRef": "Audits.FailedRequestInfo" }]);
    inspectorBackend.registerType("Audits.PropertyRuleIssueDetails", [{ "name": "sourceCodeLocation", "type": "object", "optional": false, "description": "Source code position of the property rule.", "typeRef": "Audits.SourceCodeLocation" }, { "name": "propertyRuleIssueReason", "type": "string", "optional": false, "description": "Reason why the property rule was discarded.", "typeRef": "Audits.PropertyRuleIssueReason" }, { "name": "propertyValue", "type": "string", "optional": true, "description": "The value of the property rule property that failed to parse", "typeRef": null }]);
    inspectorBackend.registerType("Audits.UserReidentificationIssueDetails", [{ "name": "type", "type": "string", "optional": false, "description": "", "typeRef": "Audits.UserReidentificationIssueType" }, { "name": "request", "type": "object", "optional": true, "description": "Applies to BlockedFrameNavigation and BlockedSubresource issue types.", "typeRef": "Audits.AffectedRequest" }, { "name": "sourceCodeLocation", "type": "object", "optional": true, "description": "Applies to NoisedCanvasReadback issue type.", "typeRef": "Audits.SourceCodeLocation" }]);
    inspectorBackend.registerType("Audits.PermissionElementIssueDetails", [{ "name": "issueType", "type": "string", "optional": false, "description": "", "typeRef": "Audits.PermissionElementIssueType" }, { "name": "type", "type": "string", "optional": true, "description": "The value of the type attribute.", "typeRef": null }, { "name": "nodeId", "type": "number", "optional": true, "description": "The node ID of the <permission> element.", "typeRef": "DOM.BackendNodeId" }, { "name": "isWarning", "type": "boolean", "optional": true, "description": "True if the issue is a warning, false if it is an error.", "typeRef": null }, { "name": "permissionName", "type": "string", "optional": true, "description": "Fields for message construction: Used for messages that reference a specific permission name", "typeRef": null }, { "name": "occluderNodeInfo", "type": "string", "optional": true, "description": "Used for messages about occlusion", "typeRef": null }, { "name": "occluderParentNodeInfo", "type": "string", "optional": true, "description": "Used for messages about occluder's parent", "typeRef": null }, { "name": "disableReason", "type": "string", "optional": true, "description": "Used for messages about activation disabled reason", "typeRef": null }]);
    inspectorBackend.registerType("Audits.AdScriptIdentifier", [{ "name": "scriptId", "type": "string", "optional": false, "description": "The script's v8 identifier.", "typeRef": "Runtime.ScriptId" }, { "name": "debuggerId", "type": "string", "optional": false, "description": "v8's debugging id for the v8::Context.", "typeRef": "Runtime.UniqueDebuggerId" }, { "name": "name", "type": "string", "optional": false, "description": "The script's url (or generated name based on id if inline script).", "typeRef": null }]);
    inspectorBackend.registerType("Audits.AdAncestry", [{ "name": "adAncestryChain", "type": "array", "optional": false, "description": "The ad-script in the stack when the offending script was loaded. This is recursive down to the root script that was tagged due to the filterlist rule.", "typeRef": "Audits.AdScriptIdentifier" }, { "name": "rootScriptFilterlistRule", "type": "string", "optional": true, "description": "The filterlist rule that caused the root (last) script in `adAncestry` to be ad-tagged.", "typeRef": null }]);
    inspectorBackend.registerType("Audits.SelectivePermissionsInterventionIssueDetails", [{ "name": "apiName", "type": "string", "optional": false, "description": "Which API was intervened on.", "typeRef": null }, { "name": "adAncestry", "type": "object", "optional": false, "description": "Why the ad script using the API is considered an ad.", "typeRef": "Audits.AdAncestry" }, { "name": "stackTrace", "type": "object", "optional": true, "description": "The stack trace at the time of the intervention.", "typeRef": "Runtime.StackTrace" }]);
    inspectorBackend.registerType("Audits.InspectorIssueDetails", [{ "name": "cookieIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.CookieIssueDetails" }, { "name": "mixedContentIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.MixedContentIssueDetails" }, { "name": "blockedByResponseIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.BlockedByResponseIssueDetails" }, { "name": "heavyAdIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.HeavyAdIssueDetails" }, { "name": "contentSecurityPolicyIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.ContentSecurityPolicyIssueDetails" }, { "name": "sharedArrayBufferIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.SharedArrayBufferIssueDetails" }, { "name": "lowTextContrastIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.LowTextContrastIssueDetails" }, { "name": "corsIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.CorsIssueDetails" }, { "name": "attributionReportingIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.AttributionReportingIssueDetails" }, { "name": "quirksModeIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.QuirksModeIssueDetails" }, { "name": "partitioningBlobURLIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.PartitioningBlobURLIssueDetails" }, { "name": "navigatorUserAgentIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.NavigatorUserAgentIssueDetails" }, { "name": "genericIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.GenericIssueDetails" }, { "name": "deprecationIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.DeprecationIssueDetails" }, { "name": "clientHintIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.ClientHintIssueDetails" }, { "name": "federatedAuthRequestIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.FederatedAuthRequestIssueDetails" }, { "name": "bounceTrackingIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.BounceTrackingIssueDetails" }, { "name": "cookieDeprecationMetadataIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.CookieDeprecationMetadataIssueDetails" }, { "name": "stylesheetLoadingIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.StylesheetLoadingIssueDetails" }, { "name": "propertyRuleIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.PropertyRuleIssueDetails" }, { "name": "federatedAuthUserInfoRequestIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.FederatedAuthUserInfoRequestIssueDetails" }, { "name": "sharedDictionaryIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.SharedDictionaryIssueDetails" }, { "name": "elementAccessibilityIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.ElementAccessibilityIssueDetails" }, { "name": "sriMessageSignatureIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.SRIMessageSignatureIssueDetails" }, { "name": "unencodedDigestIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.UnencodedDigestIssueDetails" }, { "name": "connectionAllowlistIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.ConnectionAllowlistIssueDetails" }, { "name": "userReidentificationIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.UserReidentificationIssueDetails" }, { "name": "permissionElementIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.PermissionElementIssueDetails" }, { "name": "performanceIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.PerformanceIssueDetails" }, { "name": "selectivePermissionsInterventionIssueDetails", "type": "object", "optional": true, "description": "", "typeRef": "Audits.SelectivePermissionsInterventionIssueDetails" }]);
    inspectorBackend.registerType("Audits.InspectorIssue", [{ "name": "code", "type": "string", "optional": false, "description": "", "typeRef": "Audits.InspectorIssueCode" }, { "name": "details", "type": "object", "optional": false, "description": "", "typeRef": "Audits.InspectorIssueDetails" }, { "name": "issueId", "type": "string", "optional": true, "description": "A unique id for this issue. May be omitted if no other entity (e.g. exception, CDP message, etc.) is referencing this issue.", "typeRef": "Audits.IssueId" }]);
    inspectorBackend.registerEnum("Autofill.FillingStrategy", { AutocompleteAttribute: "autocompleteAttribute", AutofillInferred: "autofillInferred" });
    inspectorBackend.registerEvent("Autofill.addressFormFilled", ["filledFields", "addressUi"]);
    inspectorBackend.registerCommand("Autofill.trigger", [{ "name": "fieldId", "type": "number", "optional": false, "description": "Identifies a field that serves as an anchor for autofill.", "typeRef": "DOM.BackendNodeId" }, { "name": "frameId", "type": "string", "optional": true, "description": "Identifies the frame that field belongs to.", "typeRef": "Page.FrameId" }, { "name": "card", "type": "object", "optional": true, "description": "Credit card information to fill out the form. Credit card data is not saved.  Mutually exclusive with `address`.", "typeRef": "Autofill.CreditCard" }, { "name": "address", "type": "object", "optional": true, "description": "Address to fill out the form. Address data is not saved. Mutually exclusive with `card`.", "typeRef": "Autofill.Address" }], [], "Trigger autofill on a form identified by the fieldId. If the field and related form cannot be autofilled, returns an error.");
    inspectorBackend.registerCommand("Autofill.setAddresses", [{ "name": "addresses", "type": "array", "optional": false, "description": "", "typeRef": "Autofill.Address" }], [], "Set addresses so that developers can verify their forms implementation.");
    inspectorBackend.registerCommand("Autofill.disable", [], [], "Disables autofill domain notifications.");
    inspectorBackend.registerCommand("Autofill.enable", [], [], "Enables autofill domain notifications.");
    inspectorBackend.registerType("Autofill.CreditCard", [{ "name": "number", "type": "string", "optional": false, "description": "16-digit credit card number.", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "Name of the credit card owner.", "typeRef": null }, { "name": "expiryMonth", "type": "string", "optional": false, "description": "2-digit expiry month.", "typeRef": null }, { "name": "expiryYear", "type": "string", "optional": false, "description": "4-digit expiry year.", "typeRef": null }, { "name": "cvc", "type": "string", "optional": false, "description": "3-digit card verification code.", "typeRef": null }]);
    inspectorBackend.registerType("Autofill.AddressField", [{ "name": "name", "type": "string", "optional": false, "description": "address field name, for example GIVEN_NAME. The full list of supported field names: https://source.chromium.org/chromium/chromium/src/+/main:components/autofill/core/browser/field_types.cc;l=38", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "address field value, for example Jon Doe.", "typeRef": null }]);
    inspectorBackend.registerType("Autofill.AddressFields", [{ "name": "fields", "type": "array", "optional": false, "description": "", "typeRef": "Autofill.AddressField" }]);
    inspectorBackend.registerType("Autofill.Address", [{ "name": "fields", "type": "array", "optional": false, "description": "fields and values defining an address.", "typeRef": "Autofill.AddressField" }]);
    inspectorBackend.registerType("Autofill.AddressUI", [{ "name": "addressFields", "type": "array", "optional": false, "description": "A two dimension array containing the representation of values from an address profile.", "typeRef": "Autofill.AddressFields" }]);
    inspectorBackend.registerType("Autofill.FilledField", [{ "name": "htmlType", "type": "string", "optional": false, "description": "The type of the field, e.g text, password etc.", "typeRef": null }, { "name": "id", "type": "string", "optional": false, "description": "the html id", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "the html name", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "the field value", "typeRef": null }, { "name": "autofillType", "type": "string", "optional": false, "description": "The actual field type, e.g FAMILY_NAME", "typeRef": null }, { "name": "fillingStrategy", "type": "string", "optional": false, "description": "The filling strategy", "typeRef": "Autofill.FillingStrategy" }, { "name": "frameId", "type": "string", "optional": false, "description": "The frame the field belongs to", "typeRef": "Page.FrameId" }, { "name": "fieldId", "type": "number", "optional": false, "description": "The form field's DOM node", "typeRef": "DOM.BackendNodeId" }]);
    inspectorBackend.registerEnum("BackgroundService.ServiceName", { BackgroundFetch: "backgroundFetch", BackgroundSync: "backgroundSync", PushMessaging: "pushMessaging", Notifications: "notifications", PaymentHandler: "paymentHandler", PeriodicBackgroundSync: "periodicBackgroundSync" });
    inspectorBackend.registerEvent("BackgroundService.recordingStateChanged", ["isRecording", "service"]);
    inspectorBackend.registerEvent("BackgroundService.backgroundServiceEventReceived", ["backgroundServiceEvent"]);
    inspectorBackend.registerCommand("BackgroundService.startObserving", [{ "name": "service", "type": "string", "optional": false, "description": "", "typeRef": "BackgroundService.ServiceName" }], [], "Enables event updates for the service.");
    inspectorBackend.registerCommand("BackgroundService.stopObserving", [{ "name": "service", "type": "string", "optional": false, "description": "", "typeRef": "BackgroundService.ServiceName" }], [], "Disables event updates for the service.");
    inspectorBackend.registerCommand("BackgroundService.setRecording", [{ "name": "shouldRecord", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "service", "type": "string", "optional": false, "description": "", "typeRef": "BackgroundService.ServiceName" }], [], "Set the recording state for the service.");
    inspectorBackend.registerCommand("BackgroundService.clearEvents", [{ "name": "service", "type": "string", "optional": false, "description": "", "typeRef": "BackgroundService.ServiceName" }], [], "Clears all stored data for the service.");
    inspectorBackend.registerType("BackgroundService.EventMetadata", [{ "name": "key", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("BackgroundService.BackgroundServiceEvent", [{ "name": "timestamp", "type": "number", "optional": false, "description": "Timestamp of the event (in seconds).", "typeRef": "Network.TimeSinceEpoch" }, { "name": "origin", "type": "string", "optional": false, "description": "The origin this event belongs to.", "typeRef": null }, { "name": "serviceWorkerRegistrationId", "type": "string", "optional": false, "description": "The Service Worker ID that initiated the event.", "typeRef": "ServiceWorker.RegistrationID" }, { "name": "service", "type": "string", "optional": false, "description": "The Background Service this event belongs to.", "typeRef": "BackgroundService.ServiceName" }, { "name": "eventName", "type": "string", "optional": false, "description": "A description of the event.", "typeRef": null }, { "name": "instanceId", "type": "string", "optional": false, "description": "An identifier that groups related events together.", "typeRef": null }, { "name": "eventMetadata", "type": "array", "optional": false, "description": "A list of event-specific information.", "typeRef": "BackgroundService.EventMetadata" }, { "name": "storageKey", "type": "string", "optional": false, "description": "Storage key this event belongs to.", "typeRef": null }]);
    inspectorBackend.registerEnum("BluetoothEmulation.CentralState", { Absent: "absent", PoweredOff: "powered-off", PoweredOn: "powered-on" });
    inspectorBackend.registerEnum("BluetoothEmulation.GATTOperationType", { Connection: "connection", Discovery: "discovery" });
    inspectorBackend.registerEnum("BluetoothEmulation.CharacteristicWriteType", { WriteDefaultDeprecated: "write-default-deprecated", WriteWithResponse: "write-with-response", WriteWithoutResponse: "write-without-response" });
    inspectorBackend.registerEnum("BluetoothEmulation.CharacteristicOperationType", { Read: "read", Write: "write", SubscribeToNotifications: "subscribe-to-notifications", UnsubscribeFromNotifications: "unsubscribe-from-notifications" });
    inspectorBackend.registerEnum("BluetoothEmulation.DescriptorOperationType", { Read: "read", Write: "write" });
    inspectorBackend.registerEvent("BluetoothEmulation.gattOperationReceived", ["address", "type"]);
    inspectorBackend.registerEvent("BluetoothEmulation.characteristicOperationReceived", ["characteristicId", "type", "data", "writeType"]);
    inspectorBackend.registerEvent("BluetoothEmulation.descriptorOperationReceived", ["descriptorId", "type", "data"]);
    inspectorBackend.registerCommand("BluetoothEmulation.enable", [{ "name": "state", "type": "string", "optional": false, "description": "State of the simulated central.", "typeRef": "BluetoothEmulation.CentralState" }, { "name": "leSupported", "type": "boolean", "optional": false, "description": "If the simulated central supports low-energy.", "typeRef": null }], [], "Enable the BluetoothEmulation domain.");
    inspectorBackend.registerCommand("BluetoothEmulation.setSimulatedCentralState", [{ "name": "state", "type": "string", "optional": false, "description": "State of the simulated central.", "typeRef": "BluetoothEmulation.CentralState" }], [], "Set the state of the simulated central.");
    inspectorBackend.registerCommand("BluetoothEmulation.disable", [], [], "Disable the BluetoothEmulation domain.");
    inspectorBackend.registerCommand("BluetoothEmulation.simulatePreconnectedPeripheral", [{ "name": "address", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "manufacturerData", "type": "array", "optional": false, "description": "", "typeRef": "BluetoothEmulation.ManufacturerData" }, { "name": "knownServiceUuids", "type": "array", "optional": false, "description": "", "typeRef": "string" }], [], "Simulates a peripheral with |address|, |name| and |knownServiceUuids| that has already been connected to the system.");
    inspectorBackend.registerCommand("BluetoothEmulation.simulateAdvertisement", [{ "name": "entry", "type": "object", "optional": false, "description": "", "typeRef": "BluetoothEmulation.ScanEntry" }], [], "Simulates an advertisement packet described in |entry| being received by the central.");
    inspectorBackend.registerCommand("BluetoothEmulation.simulateGATTOperationResponse", [{ "name": "address", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "", "typeRef": "BluetoothEmulation.GATTOperationType" }, { "name": "code", "type": "number", "optional": false, "description": "", "typeRef": null }], [], "Simulates the response code from the peripheral with |address| for a GATT operation of |type|. The |code| value follows the HCI Error Codes from Bluetooth Core Specification Vol 2 Part D 1.3 List Of Error Codes.");
    inspectorBackend.registerCommand("BluetoothEmulation.simulateCharacteristicOperationResponse", [{ "name": "characteristicId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "", "typeRef": "BluetoothEmulation.CharacteristicOperationType" }, { "name": "code", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "data", "type": "string", "optional": true, "description": "", "typeRef": null }], [], "Simulates the response from the characteristic with |characteristicId| for a characteristic operation of |type|. The |code| value follows the Error Codes from Bluetooth Core Specification Vol 3 Part F 3.4.1.1 Error Response. The |data| is expected to exist when simulating a successful read operation response.");
    inspectorBackend.registerCommand("BluetoothEmulation.simulateDescriptorOperationResponse", [{ "name": "descriptorId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "", "typeRef": "BluetoothEmulation.DescriptorOperationType" }, { "name": "code", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "data", "type": "string", "optional": true, "description": "", "typeRef": null }], [], "Simulates the response from the descriptor with |descriptorId| for a descriptor operation of |type|. The |code| value follows the Error Codes from Bluetooth Core Specification Vol 3 Part F 3.4.1.1 Error Response. The |data| is expected to exist when simulating a successful read operation response.");
    inspectorBackend.registerCommand("BluetoothEmulation.addService", [{ "name": "address", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "serviceUuid", "type": "string", "optional": false, "description": "", "typeRef": null }], ["serviceId"], "Adds a service with |serviceUuid| to the peripheral with |address|.");
    inspectorBackend.registerCommand("BluetoothEmulation.removeService", [{ "name": "serviceId", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Removes the service respresented by |serviceId| from the simulated central.");
    inspectorBackend.registerCommand("BluetoothEmulation.addCharacteristic", [{ "name": "serviceId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "characteristicUuid", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "properties", "type": "object", "optional": false, "description": "", "typeRef": "BluetoothEmulation.CharacteristicProperties" }], ["characteristicId"], "Adds a characteristic with |characteristicUuid| and |properties| to the service represented by |serviceId|.");
    inspectorBackend.registerCommand("BluetoothEmulation.removeCharacteristic", [{ "name": "characteristicId", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Removes the characteristic respresented by |characteristicId| from the simulated central.");
    inspectorBackend.registerCommand("BluetoothEmulation.addDescriptor", [{ "name": "characteristicId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "descriptorUuid", "type": "string", "optional": false, "description": "", "typeRef": null }], ["descriptorId"], "Adds a descriptor with |descriptorUuid| to the characteristic respresented by |characteristicId|.");
    inspectorBackend.registerCommand("BluetoothEmulation.removeDescriptor", [{ "name": "descriptorId", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Removes the descriptor with |descriptorId| from the simulated central.");
    inspectorBackend.registerCommand("BluetoothEmulation.simulateGATTDisconnection", [{ "name": "address", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Simulates a GATT disconnection from the peripheral with |address|.");
    inspectorBackend.registerType("BluetoothEmulation.ManufacturerData", [{ "name": "key", "type": "number", "optional": false, "description": "Company identifier https://bitbucket.org/bluetooth-SIG/public/src/main/assigned_numbers/company_identifiers/company_identifiers.yaml https://usb.org/developers", "typeRef": null }, { "name": "data", "type": "string", "optional": false, "description": "Manufacturer-specific data", "typeRef": null }]);
    inspectorBackend.registerType("BluetoothEmulation.ScanRecord", [{ "name": "name", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "uuids", "type": "array", "optional": true, "description": "", "typeRef": "string" }, { "name": "appearance", "type": "number", "optional": true, "description": "Stores the external appearance description of the device.", "typeRef": null }, { "name": "txPower", "type": "number", "optional": true, "description": "Stores the transmission power of a broadcasting device.", "typeRef": null }, { "name": "manufacturerData", "type": "array", "optional": true, "description": "Key is the company identifier and the value is an array of bytes of manufacturer specific data.", "typeRef": "BluetoothEmulation.ManufacturerData" }]);
    inspectorBackend.registerType("BluetoothEmulation.ScanEntry", [{ "name": "deviceAddress", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "rssi", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "scanRecord", "type": "object", "optional": false, "description": "", "typeRef": "BluetoothEmulation.ScanRecord" }]);
    inspectorBackend.registerType("BluetoothEmulation.CharacteristicProperties", [{ "name": "broadcast", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "read", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "writeWithoutResponse", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "write", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "notify", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "indicate", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "authenticatedSignedWrites", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "extendedProperties", "type": "boolean", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerEnum("Browser.WindowState", { Normal: "normal", Minimized: "minimized", Maximized: "maximized", Fullscreen: "fullscreen" });
    inspectorBackend.registerEnum("Browser.PermissionType", { Ar: "ar", AudioCapture: "audioCapture", AutomaticFullscreen: "automaticFullscreen", BackgroundFetch: "backgroundFetch", BackgroundSync: "backgroundSync", CameraPanTiltZoom: "cameraPanTiltZoom", CapturedSurfaceControl: "capturedSurfaceControl", ClipboardReadWrite: "clipboardReadWrite", ClipboardSanitizedWrite: "clipboardSanitizedWrite", DisplayCapture: "displayCapture", DurableStorage: "durableStorage", Geolocation: "geolocation", HandTracking: "handTracking", IdleDetection: "idleDetection", KeyboardLock: "keyboardLock", LocalFonts: "localFonts", LocalNetwork: "localNetwork", LocalNetworkAccess: "localNetworkAccess", LoopbackNetwork: "loopbackNetwork", Midi: "midi", MidiSysex: "midiSysex", Nfc: "nfc", Notifications: "notifications", PaymentHandler: "paymentHandler", PeriodicBackgroundSync: "periodicBackgroundSync", PointerLock: "pointerLock", ProtectedMediaIdentifier: "protectedMediaIdentifier", Sensors: "sensors", SmartCard: "smartCard", SpeakerSelection: "speakerSelection", StorageAccess: "storageAccess", TopLevelStorageAccess: "topLevelStorageAccess", VideoCapture: "videoCapture", Vr: "vr", WakeLockScreen: "wakeLockScreen", WakeLockSystem: "wakeLockSystem", WebAppInstallation: "webAppInstallation", WebPrinting: "webPrinting", WindowManagement: "windowManagement" });
    inspectorBackend.registerEnum("Browser.PermissionSetting", { Granted: "granted", Denied: "denied", Prompt: "prompt" });
    inspectorBackend.registerEnum("Browser.BrowserCommandId", { OpenTabSearch: "openTabSearch", CloseTabSearch: "closeTabSearch", OpenGlic: "openGlic" });
    inspectorBackend.registerEnum("Browser.PrivacySandboxAPI", { BiddingAndAuctionServices: "BiddingAndAuctionServices", TrustedKeyValue: "TrustedKeyValue" });
    inspectorBackend.registerEvent("Browser.downloadWillBegin", ["frameId", "guid", "url", "suggestedFilename"]);
    inspectorBackend.registerEnum("Browser.DownloadProgressEventState", { InProgress: "inProgress", Completed: "completed", Canceled: "canceled" });
    inspectorBackend.registerEvent("Browser.downloadProgress", ["guid", "totalBytes", "receivedBytes", "state", "filePath"]);
    inspectorBackend.registerCommand("Browser.setPermission", [{ "name": "permission", "type": "object", "optional": false, "description": "Descriptor of permission to override.", "typeRef": "Browser.PermissionDescriptor" }, { "name": "setting", "type": "string", "optional": false, "description": "Setting of the permission.", "typeRef": "Browser.PermissionSetting" }, { "name": "origin", "type": "string", "optional": true, "description": "Embedding origin the permission applies to, all origins if not specified.", "typeRef": null }, { "name": "embeddedOrigin", "type": "string", "optional": true, "description": "Embedded origin the permission applies to. It is ignored unless the embedding origin is present and valid. If the embedding origin is provided but the embedded origin isn't, the embedding origin is used as the embedded origin.", "typeRef": null }, { "name": "browserContextId", "type": "string", "optional": true, "description": "Context to override. When omitted, default browser context is used.", "typeRef": "Browser.BrowserContextID" }], [], "Set permission settings for given embedding and embedded origins.");
    inspectorBackend.registerCommand("Browser.grantPermissions", [{ "name": "permissions", "type": "array", "optional": false, "description": "", "typeRef": "Browser.PermissionType" }, { "name": "origin", "type": "string", "optional": true, "description": "Origin the permission applies to, all origins if not specified.", "typeRef": null }, { "name": "browserContextId", "type": "string", "optional": true, "description": "BrowserContext to override permissions. When omitted, default browser context is used.", "typeRef": "Browser.BrowserContextID" }], [], "Grant specific permissions to the given origin and reject all others. Deprecated. Use setPermission instead.");
    inspectorBackend.registerCommand("Browser.resetPermissions", [{ "name": "browserContextId", "type": "string", "optional": true, "description": "BrowserContext to reset permissions. When omitted, default browser context is used.", "typeRef": "Browser.BrowserContextID" }], [], "Reset all permission management for all origins.");
    inspectorBackend.registerEnum("Browser.SetDownloadBehaviorRequestBehavior", { Deny: "deny", Allow: "allow", AllowAndName: "allowAndName", Default: "default" });
    inspectorBackend.registerCommand("Browser.setDownloadBehavior", [{ "name": "behavior", "type": "string", "optional": false, "description": "Whether to allow all or deny all download requests, or use default Chrome behavior if available (otherwise deny). |allowAndName| allows download and names files according to their download guids.", "typeRef": "Browser.SetDownloadBehaviorRequestBehavior" }, { "name": "browserContextId", "type": "string", "optional": true, "description": "BrowserContext to set download behavior. When omitted, default browser context is used.", "typeRef": "Browser.BrowserContextID" }, { "name": "downloadPath", "type": "string", "optional": true, "description": "The default path to save downloaded files to. This is required if behavior is set to 'allow' or 'allowAndName'.", "typeRef": null }, { "name": "eventsEnabled", "type": "boolean", "optional": true, "description": "Whether to emit download events (defaults to false).", "typeRef": null }], [], "Set the behavior when downloading a file.");
    inspectorBackend.registerCommand("Browser.cancelDownload", [{ "name": "guid", "type": "string", "optional": false, "description": "Global unique identifier of the download.", "typeRef": null }, { "name": "browserContextId", "type": "string", "optional": true, "description": "BrowserContext to perform the action in. When omitted, default browser context is used.", "typeRef": "Browser.BrowserContextID" }], [], "Cancel a download if in progress");
    inspectorBackend.registerCommand("Browser.close", [], [], "Close browser gracefully.");
    inspectorBackend.registerCommand("Browser.crash", [], [], "Crashes browser on the main thread.");
    inspectorBackend.registerCommand("Browser.crashGpuProcess", [], [], "Crashes GPU process.");
    inspectorBackend.registerCommand("Browser.getVersion", [], ["protocolVersion", "product", "revision", "userAgent", "jsVersion"], "Returns version information.");
    inspectorBackend.registerCommand("Browser.getBrowserCommandLine", [], ["arguments"], "Returns the command line switches for the browser process if, and only if --enable-automation is on the commandline.");
    inspectorBackend.registerCommand("Browser.getHistograms", [{ "name": "query", "type": "string", "optional": true, "description": "Requested substring in name. Only histograms which have query as a substring in their name are extracted. An empty or absent query returns all histograms.", "typeRef": null }, { "name": "delta", "type": "boolean", "optional": true, "description": "If true, retrieve delta since last delta call.", "typeRef": null }], ["histograms"], "Get Chrome histograms.");
    inspectorBackend.registerCommand("Browser.getHistogram", [{ "name": "name", "type": "string", "optional": false, "description": "Requested histogram name.", "typeRef": null }, { "name": "delta", "type": "boolean", "optional": true, "description": "If true, retrieve delta since last delta call.", "typeRef": null }], ["histogram"], "Get a Chrome histogram by name.");
    inspectorBackend.registerCommand("Browser.getWindowBounds", [{ "name": "windowId", "type": "number", "optional": false, "description": "Browser window id.", "typeRef": "Browser.WindowID" }], ["bounds"], "Get position and size of the browser window.");
    inspectorBackend.registerCommand("Browser.getWindowForTarget", [{ "name": "targetId", "type": "string", "optional": true, "description": "Devtools agent host id. If called as a part of the session, associated targetId is used.", "typeRef": "Target.TargetID" }], ["windowId", "bounds"], "Get the browser window that contains the devtools target.");
    inspectorBackend.registerCommand("Browser.setWindowBounds", [{ "name": "windowId", "type": "number", "optional": false, "description": "Browser window id.", "typeRef": "Browser.WindowID" }, { "name": "bounds", "type": "object", "optional": false, "description": "New window bounds. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined with 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged.", "typeRef": "Browser.Bounds" }], [], "Set position and/or size of the browser window.");
    inspectorBackend.registerCommand("Browser.setContentsSize", [{ "name": "windowId", "type": "number", "optional": false, "description": "Browser window id.", "typeRef": "Browser.WindowID" }, { "name": "width", "type": "number", "optional": true, "description": "The window contents width in DIP. Assumes current width if omitted. Must be specified if 'height' is omitted.", "typeRef": null }, { "name": "height", "type": "number", "optional": true, "description": "The window contents height in DIP. Assumes current height if omitted. Must be specified if 'width' is omitted.", "typeRef": null }], [], "Set size of the browser contents resizing browser window as necessary.");
    inspectorBackend.registerCommand("Browser.setDockTile", [{ "name": "badgeLabel", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "image", "type": "string", "optional": true, "description": "Png encoded image.", "typeRef": null }], [], "Set dock tile details, platform-specific.");
    inspectorBackend.registerCommand("Browser.executeBrowserCommand", [{ "name": "commandId", "type": "string", "optional": false, "description": "", "typeRef": "Browser.BrowserCommandId" }], [], "Invoke custom browser commands used by telemetry.");
    inspectorBackend.registerCommand("Browser.addPrivacySandboxEnrollmentOverride", [{ "name": "url", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Allows a site to use privacy sandbox features that require enrollment without the site actually being enrolled. Only supported on page targets.");
    inspectorBackend.registerCommand("Browser.addPrivacySandboxCoordinatorKeyConfig", [{ "name": "api", "type": "string", "optional": false, "description": "", "typeRef": "Browser.PrivacySandboxAPI" }, { "name": "coordinatorOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "keyConfig", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "browserContextId", "type": "string", "optional": true, "description": "BrowserContext to perform the action in. When omitted, default browser context is used.", "typeRef": "Browser.BrowserContextID" }], [], "Configures encryption keys used with a given privacy sandbox API to talk to a trusted coordinator.  Since this is intended for test automation only, coordinatorOrigin must be a .test domain. No existing coordinator configuration for the origin may exist.");
    inspectorBackend.registerType("Browser.Bounds", [{ "name": "left", "type": "number", "optional": true, "description": "The offset from the left edge of the screen to the window in pixels.", "typeRef": null }, { "name": "top", "type": "number", "optional": true, "description": "The offset from the top edge of the screen to the window in pixels.", "typeRef": null }, { "name": "width", "type": "number", "optional": true, "description": "The window width in pixels.", "typeRef": null }, { "name": "height", "type": "number", "optional": true, "description": "The window height in pixels.", "typeRef": null }, { "name": "windowState", "type": "string", "optional": true, "description": "The window state. Default to normal.", "typeRef": "Browser.WindowState" }]);
    inspectorBackend.registerType("Browser.PermissionDescriptor", [{ "name": "name", "type": "string", "optional": false, "description": "Name of permission. See https://cs.chromium.org/chromium/src/third_party/blink/renderer/modules/permissions/permission_descriptor.idl for valid permission names.", "typeRef": null }, { "name": "sysex", "type": "boolean", "optional": true, "description": "For \\\"midi\\\" permission, may also specify sysex control.", "typeRef": null }, { "name": "userVisibleOnly", "type": "boolean", "optional": true, "description": "For \\\"push\\\" permission, may specify userVisibleOnly. Note that userVisibleOnly = true is the only currently supported type.", "typeRef": null }, { "name": "allowWithoutSanitization", "type": "boolean", "optional": true, "description": "For \\\"clipboard\\\" permission, may specify allowWithoutSanitization.", "typeRef": null }, { "name": "allowWithoutGesture", "type": "boolean", "optional": true, "description": "For \\\"fullscreen\\\" permission, must specify allowWithoutGesture:true.", "typeRef": null }, { "name": "panTiltZoom", "type": "boolean", "optional": true, "description": "For \\\"camera\\\" permission, may specify panTiltZoom.", "typeRef": null }]);
    inspectorBackend.registerType("Browser.Bucket", [{ "name": "low", "type": "number", "optional": false, "description": "Minimum value (inclusive).", "typeRef": null }, { "name": "high", "type": "number", "optional": false, "description": "Maximum value (exclusive).", "typeRef": null }, { "name": "count", "type": "number", "optional": false, "description": "Number of samples.", "typeRef": null }]);
    inspectorBackend.registerType("Browser.Histogram", [{ "name": "name", "type": "string", "optional": false, "description": "Name.", "typeRef": null }, { "name": "sum", "type": "number", "optional": false, "description": "Sum of sample values.", "typeRef": null }, { "name": "count", "type": "number", "optional": false, "description": "Total number of samples.", "typeRef": null }, { "name": "buckets", "type": "array", "optional": false, "description": "Buckets.", "typeRef": "Browser.Bucket" }]);
    inspectorBackend.registerEnum("CSS.StyleSheetOrigin", { Injected: "injected", UserAgent: "user-agent", Inspector: "inspector", Regular: "regular" });
    inspectorBackend.registerEnum("CSS.CSSRuleType", { MediaRule: "MediaRule", SupportsRule: "SupportsRule", ContainerRule: "ContainerRule", LayerRule: "LayerRule", ScopeRule: "ScopeRule", StyleRule: "StyleRule", StartingStyleRule: "StartingStyleRule" });
    inspectorBackend.registerEnum("CSS.CSSMediaSource", { MediaRule: "mediaRule", ImportRule: "importRule", LinkedSheet: "linkedSheet", InlineSheet: "inlineSheet" });
    inspectorBackend.registerEnum("CSS.CSSAtRuleType", { FontFace: "font-face", FontFeatureValues: "font-feature-values", FontPaletteValues: "font-palette-values" });
    inspectorBackend.registerEnum("CSS.CSSAtRuleSubsection", { Swash: "swash", Annotation: "annotation", Ornaments: "ornaments", Stylistic: "stylistic", Styleset: "styleset", CharacterVariant: "character-variant" });
    inspectorBackend.registerEvent("CSS.fontsUpdated", ["font"]);
    inspectorBackend.registerEvent("CSS.mediaQueryResultChanged", []);
    inspectorBackend.registerEvent("CSS.styleSheetAdded", ["header"]);
    inspectorBackend.registerEvent("CSS.styleSheetChanged", ["styleSheetId"]);
    inspectorBackend.registerEvent("CSS.styleSheetRemoved", ["styleSheetId"]);
    inspectorBackend.registerEvent("CSS.computedStyleUpdated", ["nodeId"]);
    inspectorBackend.registerCommand("CSS.addRule", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "The css style sheet identifier where a new rule should be inserted.", "typeRef": "DOM.StyleSheetId" }, { "name": "ruleText", "type": "string", "optional": false, "description": "The text of a new rule.", "typeRef": null }, { "name": "location", "type": "object", "optional": false, "description": "Text position of a new rule in the target style sheet.", "typeRef": "CSS.SourceRange" }, { "name": "nodeForPropertySyntaxValidation", "type": "number", "optional": true, "description": "NodeId for the DOM node in whose context custom property declarations for registered properties should be validated. If omitted, declarations in the new rule text can only be validated statically, which may produce incorrect results if the declaration contains a var() for example.", "typeRef": "DOM.NodeId" }], ["rule"], "Inserts a new rule with the given `ruleText` in a stylesheet with given `styleSheetId`, at the position specified by `location`.");
    inspectorBackend.registerCommand("CSS.collectClassNames", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "", "typeRef": "DOM.StyleSheetId" }], ["classNames"], "Returns all class names from specified stylesheet.");
    inspectorBackend.registerCommand("CSS.createStyleSheet", [{ "name": "frameId", "type": "string", "optional": false, "description": "Identifier of the frame where \\\"via-inspector\\\" stylesheet should be created.", "typeRef": "Page.FrameId" }, { "name": "force", "type": "boolean", "optional": true, "description": "If true, creates a new stylesheet for every call. If false, returns a stylesheet previously created by a call with force=false for the frame's document if it exists or creates a new stylesheet (default: false).", "typeRef": null }], ["styleSheetId"], "Creates a new special \"via-inspector\" stylesheet in the frame with given `frameId`.");
    inspectorBackend.registerCommand("CSS.disable", [], [], "Disables the CSS agent for the given page.");
    inspectorBackend.registerCommand("CSS.enable", [], [], "Enables the CSS agent for the given page. Clients should not assume that the CSS agent has been enabled until the result of this command is received.");
    inspectorBackend.registerCommand("CSS.forcePseudoState", [{ "name": "nodeId", "type": "number", "optional": false, "description": "The element id for which to force the pseudo state.", "typeRef": "DOM.NodeId" }, { "name": "forcedPseudoClasses", "type": "array", "optional": false, "description": "Element pseudo classes to force when computing the element's style.", "typeRef": "string" }], [], "Ensures that the given node will have specified pseudo-classes whenever its style is computed by the browser.");
    inspectorBackend.registerCommand("CSS.forceStartingStyle", [{ "name": "nodeId", "type": "number", "optional": false, "description": "The element id for which to force the starting-style state.", "typeRef": "DOM.NodeId" }, { "name": "forced", "type": "boolean", "optional": false, "description": "Boolean indicating if this is on or off.", "typeRef": null }], [], "Ensures that the given node is in its starting-style state.");
    inspectorBackend.registerCommand("CSS.getBackgroundColors", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to get background colors for.", "typeRef": "DOM.NodeId" }], ["backgroundColors", "computedFontSize", "computedFontWeight"], "");
    inspectorBackend.registerCommand("CSS.getComputedStyleForNode", [{ "name": "nodeId", "type": "number", "optional": false, "description": "", "typeRef": "DOM.NodeId" }], ["computedStyle", "extraFields"], "Returns the computed style for a DOM node identified by `nodeId`.");
    inspectorBackend.registerCommand("CSS.resolveValues", [{ "name": "values", "type": "array", "optional": false, "description": "Cascade-dependent keywords (revert/revert-layer) do not work.", "typeRef": "string" }, { "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node in whose context the expression is evaluated", "typeRef": "DOM.NodeId" }, { "name": "propertyName", "type": "string", "optional": true, "description": "Only longhands and custom property names are accepted.", "typeRef": null }, { "name": "pseudoType", "type": "string", "optional": true, "description": "Pseudo element type, only works for pseudo elements that generate elements in the tree, such as ::before and ::after.", "typeRef": "DOM.PseudoType" }, { "name": "pseudoIdentifier", "type": "string", "optional": true, "description": "Pseudo element custom ident.", "typeRef": null }], ["results"], "Resolve the specified values in the context of the provided element. For example, a value of '1em' is evaluated according to the computed 'font-size' of the element and a value 'calc(1px + 2px)' will be resolved to '3px'. If the `propertyName` was specified the `values` are resolved as if they were property's declaration. If a value cannot be parsed according to the provided property syntax, the value is parsed using combined syntax as if null `propertyName` was provided. If the value cannot be resolved even then, return the provided value without any changes. Note: this function currently does not resolve CSS random() function, it returns unmodified random() function parts.`");
    inspectorBackend.registerCommand("CSS.getLonghandProperties", [{ "name": "shorthandName", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": null }], ["longhandProperties"], "");
    inspectorBackend.registerCommand("CSS.getInlineStylesForNode", [{ "name": "nodeId", "type": "number", "optional": false, "description": "", "typeRef": "DOM.NodeId" }], ["inlineStyle", "attributesStyle"], "Returns the styles defined inline (explicitly in the \"style\" attribute and implicitly, using DOM attributes) for a DOM node identified by `nodeId`.");
    inspectorBackend.registerCommand("CSS.getAnimatedStylesForNode", [{ "name": "nodeId", "type": "number", "optional": false, "description": "", "typeRef": "DOM.NodeId" }], ["animationStyles", "transitionsStyle", "inherited"], "Returns the styles coming from animations & transitions including the animation & transition styles coming from inheritance chain.");
    inspectorBackend.registerCommand("CSS.getMatchedStylesForNode", [{ "name": "nodeId", "type": "number", "optional": false, "description": "", "typeRef": "DOM.NodeId" }], ["inlineStyle", "attributesStyle", "matchedCSSRules", "pseudoElements", "inherited", "inheritedPseudoElements", "cssKeyframesRules", "cssPositionTryRules", "activePositionFallbackIndex", "cssPropertyRules", "cssPropertyRegistrations", "cssAtRules", "parentLayoutNodeId", "cssFunctionRules"], "Returns requested styles for a DOM node identified by `nodeId`.");
    inspectorBackend.registerCommand("CSS.getEnvironmentVariables", [], ["environmentVariables"], "Returns the values of the default UA-defined environment variables used in env()");
    inspectorBackend.registerCommand("CSS.getMediaQueries", [], ["medias"], "Returns all media queries parsed by the rendering engine.");
    inspectorBackend.registerCommand("CSS.getPlatformFontsForNode", [{ "name": "nodeId", "type": "number", "optional": false, "description": "", "typeRef": "DOM.NodeId" }], ["fonts"], "Requests information about platform fonts which we used to render child TextNodes in the given node.");
    inspectorBackend.registerCommand("CSS.getStyleSheetText", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "", "typeRef": "DOM.StyleSheetId" }], ["text"], "Returns the current textual content for a stylesheet.");
    inspectorBackend.registerCommand("CSS.getLayersForNode", [{ "name": "nodeId", "type": "number", "optional": false, "description": "", "typeRef": "DOM.NodeId" }], ["rootLayer"], "Returns all layers parsed by the rendering engine for the tree scope of a node. Given a DOM element identified by nodeId, getLayersForNode returns the root layer for the nearest ancestor document or shadow root. The layer root contains the full layer tree for the tree scope and their ordering.");
    inspectorBackend.registerCommand("CSS.getLocationForSelector", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "", "typeRef": "DOM.StyleSheetId" }, { "name": "selectorText", "type": "string", "optional": false, "description": "", "typeRef": null }], ["ranges"], "Given a CSS selector text and a style sheet ID, getLocationForSelector returns an array of locations of the CSS selector in the style sheet.");
    inspectorBackend.registerCommand("CSS.trackComputedStyleUpdatesForNode", [{ "name": "nodeId", "type": "number", "optional": true, "description": "", "typeRef": "DOM.NodeId" }], [], "Starts tracking the given node for the computed style updates and whenever the computed style is updated for node, it queues a `computedStyleUpdated` event with throttling. There can only be 1 node tracked for computed style updates so passing a new node id removes tracking from the previous node. Pass `undefined` to disable tracking.");
    inspectorBackend.registerCommand("CSS.trackComputedStyleUpdates", [{ "name": "propertiesToTrack", "type": "array", "optional": false, "description": "", "typeRef": "CSS.CSSComputedStyleProperty" }], [], "Starts tracking the given computed styles for updates. The specified array of properties replaces the one previously specified. Pass empty array to disable tracking. Use takeComputedStyleUpdates to retrieve the list of nodes that had properties modified. The changes to computed style properties are only tracked for nodes pushed to the front-end by the DOM agent. If no changes to the tracked properties occur after the node has been pushed to the front-end, no updates will be issued for the node.");
    inspectorBackend.registerCommand("CSS.takeComputedStyleUpdates", [], ["nodeIds"], "Polls the next batch of computed style updates.");
    inspectorBackend.registerCommand("CSS.setEffectivePropertyValueForNode", [{ "name": "nodeId", "type": "number", "optional": false, "description": "The element id for which to set property.", "typeRef": "DOM.NodeId" }, { "name": "propertyName", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Find a rule with the given active property for the given node and set the new value for this property");
    inspectorBackend.registerCommand("CSS.setPropertyRulePropertyName", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "", "typeRef": "DOM.StyleSheetId" }, { "name": "range", "type": "object", "optional": false, "description": "", "typeRef": "CSS.SourceRange" }, { "name": "propertyName", "type": "string", "optional": false, "description": "", "typeRef": null }], ["propertyName"], "Modifies the property rule property name.");
    inspectorBackend.registerCommand("CSS.setKeyframeKey", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "", "typeRef": "DOM.StyleSheetId" }, { "name": "range", "type": "object", "optional": false, "description": "", "typeRef": "CSS.SourceRange" }, { "name": "keyText", "type": "string", "optional": false, "description": "", "typeRef": null }], ["keyText"], "Modifies the keyframe rule key text.");
    inspectorBackend.registerCommand("CSS.setMediaText", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "", "typeRef": "DOM.StyleSheetId" }, { "name": "range", "type": "object", "optional": false, "description": "", "typeRef": "CSS.SourceRange" }, { "name": "text", "type": "string", "optional": false, "description": "", "typeRef": null }], ["media"], "Modifies the rule selector.");
    inspectorBackend.registerCommand("CSS.setContainerQueryText", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "", "typeRef": "DOM.StyleSheetId" }, { "name": "range", "type": "object", "optional": false, "description": "", "typeRef": "CSS.SourceRange" }, { "name": "text", "type": "string", "optional": false, "description": "", "typeRef": null }], ["containerQuery"], "Modifies the expression of a container query.");
    inspectorBackend.registerCommand("CSS.setSupportsText", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "", "typeRef": "DOM.StyleSheetId" }, { "name": "range", "type": "object", "optional": false, "description": "", "typeRef": "CSS.SourceRange" }, { "name": "text", "type": "string", "optional": false, "description": "", "typeRef": null }], ["supports"], "Modifies the expression of a supports at-rule.");
    inspectorBackend.registerCommand("CSS.setScopeText", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "", "typeRef": "DOM.StyleSheetId" }, { "name": "range", "type": "object", "optional": false, "description": "", "typeRef": "CSS.SourceRange" }, { "name": "text", "type": "string", "optional": false, "description": "", "typeRef": null }], ["scope"], "Modifies the expression of a scope at-rule.");
    inspectorBackend.registerCommand("CSS.setRuleSelector", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "", "typeRef": "DOM.StyleSheetId" }, { "name": "range", "type": "object", "optional": false, "description": "", "typeRef": "CSS.SourceRange" }, { "name": "selector", "type": "string", "optional": false, "description": "", "typeRef": null }], ["selectorList"], "Modifies the rule selector.");
    inspectorBackend.registerCommand("CSS.setStyleSheetText", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "", "typeRef": "DOM.StyleSheetId" }, { "name": "text", "type": "string", "optional": false, "description": "", "typeRef": null }], ["sourceMapURL"], "Sets the new stylesheet text.");
    inspectorBackend.registerCommand("CSS.setStyleTexts", [{ "name": "edits", "type": "array", "optional": false, "description": "", "typeRef": "CSS.StyleDeclarationEdit" }, { "name": "nodeForPropertySyntaxValidation", "type": "number", "optional": true, "description": "NodeId for the DOM node in whose context custom property declarations for registered properties should be validated. If omitted, declarations in the new rule text can only be validated statically, which may produce incorrect results if the declaration contains a var() for example.", "typeRef": "DOM.NodeId" }], ["styles"], "Applies specified style edits one after another in the given order.");
    inspectorBackend.registerCommand("CSS.startRuleUsageTracking", [], [], "Enables the selector recording.");
    inspectorBackend.registerCommand("CSS.stopRuleUsageTracking", [], ["ruleUsage"], "Stop tracking rule usage and return the list of rules that were used since last call to `takeCoverageDelta` (or since start of coverage instrumentation).");
    inspectorBackend.registerCommand("CSS.takeCoverageDelta", [], ["coverage", "timestamp"], "Obtain list of rules that became used since last call to this method (or since start of coverage instrumentation).");
    inspectorBackend.registerCommand("CSS.setLocalFontsEnabled", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "Whether rendering of local fonts is enabled.", "typeRef": null }], [], "Enables/disables rendering of local CSS fonts (enabled by default).");
    inspectorBackend.registerType("CSS.PseudoElementMatches", [{ "name": "pseudoType", "type": "string", "optional": false, "description": "Pseudo element type.", "typeRef": "DOM.PseudoType" }, { "name": "pseudoIdentifier", "type": "string", "optional": true, "description": "Pseudo element custom ident.", "typeRef": null }, { "name": "matches", "type": "array", "optional": false, "description": "Matches of CSS rules applicable to the pseudo style.", "typeRef": "CSS.RuleMatch" }]);
    inspectorBackend.registerType("CSS.CSSAnimationStyle", [{ "name": "name", "type": "string", "optional": true, "description": "The name of the animation.", "typeRef": null }, { "name": "style", "type": "object", "optional": false, "description": "The style coming from the animation.", "typeRef": "CSS.CSSStyle" }]);
    inspectorBackend.registerType("CSS.InheritedStyleEntry", [{ "name": "inlineStyle", "type": "object", "optional": true, "description": "The ancestor node's inline style, if any, in the style inheritance chain.", "typeRef": "CSS.CSSStyle" }, { "name": "matchedCSSRules", "type": "array", "optional": false, "description": "Matches of CSS rules matching the ancestor node in the style inheritance chain.", "typeRef": "CSS.RuleMatch" }]);
    inspectorBackend.registerType("CSS.InheritedAnimatedStyleEntry", [{ "name": "animationStyles", "type": "array", "optional": true, "description": "Styles coming from the animations of the ancestor, if any, in the style inheritance chain.", "typeRef": "CSS.CSSAnimationStyle" }, { "name": "transitionsStyle", "type": "object", "optional": true, "description": "The style coming from the transitions of the ancestor, if any, in the style inheritance chain.", "typeRef": "CSS.CSSStyle" }]);
    inspectorBackend.registerType("CSS.InheritedPseudoElementMatches", [{ "name": "pseudoElements", "type": "array", "optional": false, "description": "Matches of pseudo styles from the pseudos of an ancestor node.", "typeRef": "CSS.PseudoElementMatches" }]);
    inspectorBackend.registerType("CSS.RuleMatch", [{ "name": "rule", "type": "object", "optional": false, "description": "CSS rule in the match.", "typeRef": "CSS.CSSRule" }, { "name": "matchingSelectors", "type": "array", "optional": false, "description": "Matching selector indices in the rule's selectorList selectors (0-based).", "typeRef": "integer" }]);
    inspectorBackend.registerType("CSS.Value", [{ "name": "text", "type": "string", "optional": false, "description": "Value text.", "typeRef": null }, { "name": "range", "type": "object", "optional": true, "description": "Value range in the underlying resource (if available).", "typeRef": "CSS.SourceRange" }, { "name": "specificity", "type": "object", "optional": true, "description": "Specificity of the selector.", "typeRef": "CSS.Specificity" }]);
    inspectorBackend.registerType("CSS.Specificity", [{ "name": "a", "type": "number", "optional": false, "description": "The a component, which represents the number of ID selectors.", "typeRef": null }, { "name": "b", "type": "number", "optional": false, "description": "The b component, which represents the number of class selectors, attributes selectors, and pseudo-classes.", "typeRef": null }, { "name": "c", "type": "number", "optional": false, "description": "The c component, which represents the number of type selectors and pseudo-elements.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.SelectorList", [{ "name": "selectors", "type": "array", "optional": false, "description": "Selectors in the list.", "typeRef": "CSS.Value" }, { "name": "text", "type": "string", "optional": false, "description": "Rule selector text.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.CSSStyleSheetHeader", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "The stylesheet identifier.", "typeRef": "DOM.StyleSheetId" }, { "name": "frameId", "type": "string", "optional": false, "description": "Owner frame identifier.", "typeRef": "Page.FrameId" }, { "name": "sourceURL", "type": "string", "optional": false, "description": "Stylesheet resource URL. Empty if this is a constructed stylesheet created using new CSSStyleSheet() (but non-empty if this is a constructed stylesheet imported as a CSS module script).", "typeRef": null }, { "name": "sourceMapURL", "type": "string", "optional": true, "description": "URL of source map associated with the stylesheet (if any).", "typeRef": null }, { "name": "origin", "type": "string", "optional": false, "description": "Stylesheet origin.", "typeRef": "CSS.StyleSheetOrigin" }, { "name": "title", "type": "string", "optional": false, "description": "Stylesheet title.", "typeRef": null }, { "name": "ownerNode", "type": "number", "optional": true, "description": "The backend id for the owner node of the stylesheet.", "typeRef": "DOM.BackendNodeId" }, { "name": "disabled", "type": "boolean", "optional": false, "description": "Denotes whether the stylesheet is disabled.", "typeRef": null }, { "name": "hasSourceURL", "type": "boolean", "optional": true, "description": "Whether the sourceURL field value comes from the sourceURL comment.", "typeRef": null }, { "name": "isInline", "type": "boolean", "optional": false, "description": "Whether this stylesheet is created for STYLE tag by parser. This flag is not set for document.written STYLE tags.", "typeRef": null }, { "name": "isMutable", "type": "boolean", "optional": false, "description": "Whether this stylesheet is mutable. Inline stylesheets become mutable after they have been modified via CSSOM API. `<link>` element's stylesheets become mutable only if DevTools modifies them. Constructed stylesheets (new CSSStyleSheet()) are mutable immediately after creation.", "typeRef": null }, { "name": "isConstructed", "type": "boolean", "optional": false, "description": "True if this stylesheet is created through new CSSStyleSheet() or imported as a CSS module script.", "typeRef": null }, { "name": "startLine", "type": "number", "optional": false, "description": "Line offset of the stylesheet within the resource (zero based).", "typeRef": null }, { "name": "startColumn", "type": "number", "optional": false, "description": "Column offset of the stylesheet within the resource (zero based).", "typeRef": null }, { "name": "length", "type": "number", "optional": false, "description": "Size of the content (in characters).", "typeRef": null }, { "name": "endLine", "type": "number", "optional": false, "description": "Line offset of the end of the stylesheet within the resource (zero based).", "typeRef": null }, { "name": "endColumn", "type": "number", "optional": false, "description": "Column offset of the end of the stylesheet within the resource (zero based).", "typeRef": null }, { "name": "loadingFailed", "type": "boolean", "optional": true, "description": "If the style sheet was loaded from a network resource, this indicates when the resource failed to load", "typeRef": null }]);
    inspectorBackend.registerType("CSS.CSSRule", [{ "name": "styleSheetId", "type": "string", "optional": true, "description": "The css style sheet identifier (absent for user agent stylesheet and user-specified stylesheet rules) this rule came from.", "typeRef": "DOM.StyleSheetId" }, { "name": "selectorList", "type": "object", "optional": false, "description": "Rule selector data.", "typeRef": "CSS.SelectorList" }, { "name": "nestingSelectors", "type": "array", "optional": true, "description": "Array of selectors from ancestor style rules, sorted by distance from the current rule.", "typeRef": "string" }, { "name": "origin", "type": "string", "optional": false, "description": "Parent stylesheet's origin.", "typeRef": "CSS.StyleSheetOrigin" }, { "name": "style", "type": "object", "optional": false, "description": "Associated style declaration.", "typeRef": "CSS.CSSStyle" }, { "name": "originTreeScopeNodeId", "type": "number", "optional": true, "description": "The BackendNodeId of the DOM node that constitutes the origin tree scope of this rule.", "typeRef": "DOM.BackendNodeId" }, { "name": "media", "type": "array", "optional": true, "description": "Media list array (for rules involving media queries). The array enumerates media queries starting with the innermost one, going outwards.", "typeRef": "CSS.CSSMedia" }, { "name": "containerQueries", "type": "array", "optional": true, "description": "Container query list array (for rules involving container queries). The array enumerates container queries starting with the innermost one, going outwards.", "typeRef": "CSS.CSSContainerQuery" }, { "name": "supports", "type": "array", "optional": true, "description": "@supports CSS at-rule array. The array enumerates @supports at-rules starting with the innermost one, going outwards.", "typeRef": "CSS.CSSSupports" }, { "name": "layers", "type": "array", "optional": true, "description": "Cascade layer array. Contains the layer hierarchy that this rule belongs to starting with the innermost layer and going outwards.", "typeRef": "CSS.CSSLayer" }, { "name": "scopes", "type": "array", "optional": true, "description": "@scope CSS at-rule array. The array enumerates @scope at-rules starting with the innermost one, going outwards.", "typeRef": "CSS.CSSScope" }, { "name": "ruleTypes", "type": "array", "optional": true, "description": "The array keeps the types of ancestor CSSRules from the innermost going outwards.", "typeRef": "CSS.CSSRuleType" }, { "name": "startingStyles", "type": "array", "optional": true, "description": "@starting-style CSS at-rule array. The array enumerates @starting-style at-rules starting with the innermost one, going outwards.", "typeRef": "CSS.CSSStartingStyle" }]);
    inspectorBackend.registerType("CSS.RuleUsage", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "The css style sheet identifier (absent for user agent stylesheet and user-specified stylesheet rules) this rule came from.", "typeRef": "DOM.StyleSheetId" }, { "name": "startOffset", "type": "number", "optional": false, "description": "Offset of the start of the rule (including selector) from the beginning of the stylesheet.", "typeRef": null }, { "name": "endOffset", "type": "number", "optional": false, "description": "Offset of the end of the rule body from the beginning of the stylesheet.", "typeRef": null }, { "name": "used", "type": "boolean", "optional": false, "description": "Indicates whether the rule was actually used by some element in the page.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.SourceRange", [{ "name": "startLine", "type": "number", "optional": false, "description": "Start line of range.", "typeRef": null }, { "name": "startColumn", "type": "number", "optional": false, "description": "Start column of range (inclusive).", "typeRef": null }, { "name": "endLine", "type": "number", "optional": false, "description": "End line of range", "typeRef": null }, { "name": "endColumn", "type": "number", "optional": false, "description": "End column of range (exclusive).", "typeRef": null }]);
    inspectorBackend.registerType("CSS.ShorthandEntry", [{ "name": "name", "type": "string", "optional": false, "description": "Shorthand name.", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "Shorthand value.", "typeRef": null }, { "name": "important", "type": "boolean", "optional": true, "description": "Whether the property has \\\"!important\\\" annotation (implies `false` if absent).", "typeRef": null }]);
    inspectorBackend.registerType("CSS.CSSComputedStyleProperty", [{ "name": "name", "type": "string", "optional": false, "description": "Computed style property name.", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "Computed style property value.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.ComputedStyleExtraFields", [{ "name": "isAppearanceBase", "type": "boolean", "optional": false, "description": "Returns whether or not this node is being rendered with base appearance, which happens when it has its appearance property set to base/base-select or it is in the subtree of an element being rendered with base appearance.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.CSSStyle", [{ "name": "styleSheetId", "type": "string", "optional": true, "description": "The css style sheet identifier (absent for user agent stylesheet and user-specified stylesheet rules) this rule came from.", "typeRef": "DOM.StyleSheetId" }, { "name": "cssProperties", "type": "array", "optional": false, "description": "CSS properties in the style.", "typeRef": "CSS.CSSProperty" }, { "name": "shorthandEntries", "type": "array", "optional": false, "description": "Computed values for all shorthands found in the style.", "typeRef": "CSS.ShorthandEntry" }, { "name": "cssText", "type": "string", "optional": true, "description": "Style declaration text (if available).", "typeRef": null }, { "name": "range", "type": "object", "optional": true, "description": "Style declaration range in the enclosing stylesheet (if available).", "typeRef": "CSS.SourceRange" }]);
    inspectorBackend.registerType("CSS.CSSProperty", [{ "name": "name", "type": "string", "optional": false, "description": "The property name.", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "The property value.", "typeRef": null }, { "name": "important", "type": "boolean", "optional": true, "description": "Whether the property has \\\"!important\\\" annotation (implies `false` if absent).", "typeRef": null }, { "name": "implicit", "type": "boolean", "optional": true, "description": "Whether the property is implicit (implies `false` if absent).", "typeRef": null }, { "name": "text", "type": "string", "optional": true, "description": "The full property text as specified in the style.", "typeRef": null }, { "name": "parsedOk", "type": "boolean", "optional": true, "description": "Whether the property is understood by the browser (implies `true` if absent).", "typeRef": null }, { "name": "disabled", "type": "boolean", "optional": true, "description": "Whether the property is disabled by the user (present for source-based properties only).", "typeRef": null }, { "name": "range", "type": "object", "optional": true, "description": "The entire property range in the enclosing style declaration (if available).", "typeRef": "CSS.SourceRange" }, { "name": "longhandProperties", "type": "array", "optional": true, "description": "Parsed longhand components of this property if it is a shorthand. This field will be empty if the given property is not a shorthand.", "typeRef": "CSS.CSSProperty" }]);
    inspectorBackend.registerType("CSS.CSSMedia", [{ "name": "text", "type": "string", "optional": false, "description": "Media query text.", "typeRef": null }, { "name": "source", "type": "string", "optional": false, "description": "Source of the media query: \\\"mediaRule\\\" if specified by a @media rule, \\\"importRule\\\" if specified by an @import rule, \\\"linkedSheet\\\" if specified by a \\\"media\\\" attribute in a linked stylesheet's LINK tag, \\\"inlineSheet\\\" if specified by a \\\"media\\\" attribute in an inline stylesheet's STYLE tag.", "typeRef": null }, { "name": "sourceURL", "type": "string", "optional": true, "description": "URL of the document containing the media query description.", "typeRef": null }, { "name": "range", "type": "object", "optional": true, "description": "The associated rule (@media or @import) header range in the enclosing stylesheet (if available).", "typeRef": "CSS.SourceRange" }, { "name": "styleSheetId", "type": "string", "optional": true, "description": "Identifier of the stylesheet containing this object (if exists).", "typeRef": "DOM.StyleSheetId" }, { "name": "mediaList", "type": "array", "optional": true, "description": "Array of media queries.", "typeRef": "CSS.MediaQuery" }]);
    inspectorBackend.registerType("CSS.MediaQuery", [{ "name": "expressions", "type": "array", "optional": false, "description": "Array of media query expressions.", "typeRef": "CSS.MediaQueryExpression" }, { "name": "active", "type": "boolean", "optional": false, "description": "Whether the media query condition is satisfied.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.MediaQueryExpression", [{ "name": "value", "type": "number", "optional": false, "description": "Media query expression value.", "typeRef": null }, { "name": "unit", "type": "string", "optional": false, "description": "Media query expression units.", "typeRef": null }, { "name": "feature", "type": "string", "optional": false, "description": "Media query expression feature.", "typeRef": null }, { "name": "valueRange", "type": "object", "optional": true, "description": "The associated range of the value text in the enclosing stylesheet (if available).", "typeRef": "CSS.SourceRange" }, { "name": "computedLength", "type": "number", "optional": true, "description": "Computed length of media query expression (if applicable).", "typeRef": null }]);
    inspectorBackend.registerType("CSS.CSSContainerQuery", [{ "name": "text", "type": "string", "optional": false, "description": "Container query text.", "typeRef": null }, { "name": "range", "type": "object", "optional": true, "description": "The associated rule header range in the enclosing stylesheet (if available).", "typeRef": "CSS.SourceRange" }, { "name": "styleSheetId", "type": "string", "optional": true, "description": "Identifier of the stylesheet containing this object (if exists).", "typeRef": "DOM.StyleSheetId" }, { "name": "name", "type": "string", "optional": true, "description": "Optional name for the container.", "typeRef": null }, { "name": "physicalAxes", "type": "string", "optional": true, "description": "Optional physical axes queried for the container.", "typeRef": "DOM.PhysicalAxes" }, { "name": "logicalAxes", "type": "string", "optional": true, "description": "Optional logical axes queried for the container.", "typeRef": "DOM.LogicalAxes" }, { "name": "queriesScrollState", "type": "boolean", "optional": true, "description": "true if the query contains scroll-state() queries.", "typeRef": null }, { "name": "queriesAnchored", "type": "boolean", "optional": true, "description": "true if the query contains anchored() queries.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.CSSSupports", [{ "name": "text", "type": "string", "optional": false, "description": "Supports rule text.", "typeRef": null }, { "name": "active", "type": "boolean", "optional": false, "description": "Whether the supports condition is satisfied.", "typeRef": null }, { "name": "range", "type": "object", "optional": true, "description": "The associated rule header range in the enclosing stylesheet (if available).", "typeRef": "CSS.SourceRange" }, { "name": "styleSheetId", "type": "string", "optional": true, "description": "Identifier of the stylesheet containing this object (if exists).", "typeRef": "DOM.StyleSheetId" }]);
    inspectorBackend.registerType("CSS.CSSScope", [{ "name": "text", "type": "string", "optional": false, "description": "Scope rule text.", "typeRef": null }, { "name": "range", "type": "object", "optional": true, "description": "The associated rule header range in the enclosing stylesheet (if available).", "typeRef": "CSS.SourceRange" }, { "name": "styleSheetId", "type": "string", "optional": true, "description": "Identifier of the stylesheet containing this object (if exists).", "typeRef": "DOM.StyleSheetId" }]);
    inspectorBackend.registerType("CSS.CSSLayer", [{ "name": "text", "type": "string", "optional": false, "description": "Layer name.", "typeRef": null }, { "name": "range", "type": "object", "optional": true, "description": "The associated rule header range in the enclosing stylesheet (if available).", "typeRef": "CSS.SourceRange" }, { "name": "styleSheetId", "type": "string", "optional": true, "description": "Identifier of the stylesheet containing this object (if exists).", "typeRef": "DOM.StyleSheetId" }]);
    inspectorBackend.registerType("CSS.CSSStartingStyle", [{ "name": "range", "type": "object", "optional": true, "description": "The associated rule header range in the enclosing stylesheet (if available).", "typeRef": "CSS.SourceRange" }, { "name": "styleSheetId", "type": "string", "optional": true, "description": "Identifier of the stylesheet containing this object (if exists).", "typeRef": "DOM.StyleSheetId" }]);
    inspectorBackend.registerType("CSS.CSSLayerData", [{ "name": "name", "type": "string", "optional": false, "description": "Layer name.", "typeRef": null }, { "name": "subLayers", "type": "array", "optional": true, "description": "Direct sub-layers", "typeRef": "CSS.CSSLayerData" }, { "name": "order", "type": "number", "optional": false, "description": "Layer order. The order determines the order of the layer in the cascade order. A higher number has higher priority in the cascade order.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.PlatformFontUsage", [{ "name": "familyName", "type": "string", "optional": false, "description": "Font's family name reported by platform.", "typeRef": null }, { "name": "postScriptName", "type": "string", "optional": false, "description": "Font's PostScript name reported by platform.", "typeRef": null }, { "name": "isCustomFont", "type": "boolean", "optional": false, "description": "Indicates if the font was downloaded or resolved locally.", "typeRef": null }, { "name": "glyphCount", "type": "number", "optional": false, "description": "Amount of glyphs that were rendered with this font.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.FontVariationAxis", [{ "name": "tag", "type": "string", "optional": false, "description": "The font-variation-setting tag (a.k.a. \\\"axis tag\\\").", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "Human-readable variation name in the default language (normally, \\\"en\\\").", "typeRef": null }, { "name": "minValue", "type": "number", "optional": false, "description": "The minimum value (inclusive) the font supports for this tag.", "typeRef": null }, { "name": "maxValue", "type": "number", "optional": false, "description": "The maximum value (inclusive) the font supports for this tag.", "typeRef": null }, { "name": "defaultValue", "type": "number", "optional": false, "description": "The default value.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.FontFace", [{ "name": "fontFamily", "type": "string", "optional": false, "description": "The font-family.", "typeRef": null }, { "name": "fontStyle", "type": "string", "optional": false, "description": "The font-style.", "typeRef": null }, { "name": "fontVariant", "type": "string", "optional": false, "description": "The font-variant.", "typeRef": null }, { "name": "fontWeight", "type": "string", "optional": false, "description": "The font-weight.", "typeRef": null }, { "name": "fontStretch", "type": "string", "optional": false, "description": "The font-stretch.", "typeRef": null }, { "name": "fontDisplay", "type": "string", "optional": false, "description": "The font-display.", "typeRef": null }, { "name": "unicodeRange", "type": "string", "optional": false, "description": "The unicode-range.", "typeRef": null }, { "name": "src", "type": "string", "optional": false, "description": "The src.", "typeRef": null }, { "name": "platformFontFamily", "type": "string", "optional": false, "description": "The resolved platform font family", "typeRef": null }, { "name": "fontVariationAxes", "type": "array", "optional": true, "description": "Available variation settings (a.k.a. \\\"axes\\\").", "typeRef": "CSS.FontVariationAxis" }]);
    inspectorBackend.registerType("CSS.CSSTryRule", [{ "name": "styleSheetId", "type": "string", "optional": true, "description": "The css style sheet identifier (absent for user agent stylesheet and user-specified stylesheet rules) this rule came from.", "typeRef": "DOM.StyleSheetId" }, { "name": "origin", "type": "string", "optional": false, "description": "Parent stylesheet's origin.", "typeRef": "CSS.StyleSheetOrigin" }, { "name": "style", "type": "object", "optional": false, "description": "Associated style declaration.", "typeRef": "CSS.CSSStyle" }]);
    inspectorBackend.registerType("CSS.CSSPositionTryRule", [{ "name": "name", "type": "object", "optional": false, "description": "The prelude dashed-ident name", "typeRef": "CSS.Value" }, { "name": "styleSheetId", "type": "string", "optional": true, "description": "The css style sheet identifier (absent for user agent stylesheet and user-specified stylesheet rules) this rule came from.", "typeRef": "DOM.StyleSheetId" }, { "name": "origin", "type": "string", "optional": false, "description": "Parent stylesheet's origin.", "typeRef": "CSS.StyleSheetOrigin" }, { "name": "style", "type": "object", "optional": false, "description": "Associated style declaration.", "typeRef": "CSS.CSSStyle" }, { "name": "active", "type": "boolean", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("CSS.CSSKeyframesRule", [{ "name": "animationName", "type": "object", "optional": false, "description": "Animation name.", "typeRef": "CSS.Value" }, { "name": "keyframes", "type": "array", "optional": false, "description": "List of keyframes.", "typeRef": "CSS.CSSKeyframeRule" }]);
    inspectorBackend.registerType("CSS.CSSPropertyRegistration", [{ "name": "propertyName", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "initialValue", "type": "object", "optional": true, "description": "", "typeRef": "CSS.Value" }, { "name": "inherits", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "syntax", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("CSS.CSSAtRule", [{ "name": "type", "type": "string", "optional": false, "description": "Type of at-rule.", "typeRef": null }, { "name": "subsection", "type": "string", "optional": true, "description": "Subsection of font-feature-values, if this is a subsection.", "typeRef": null }, { "name": "name", "type": "object", "optional": true, "description": "LINT_SKIP.ThenChange(//third_party/blink/renderer/core/inspector/inspector_style_sheet.cc:FontVariantAlternatesFeatureType,//third_party/blink/renderer/core/inspector/inspector_css_agent.cc:FontVariantAlternatesFeatureType) Associated name, if applicable.", "typeRef": "CSS.Value" }, { "name": "styleSheetId", "type": "string", "optional": true, "description": "The css style sheet identifier (absent for user agent stylesheet and user-specified stylesheet rules) this rule came from.", "typeRef": "DOM.StyleSheetId" }, { "name": "origin", "type": "string", "optional": false, "description": "Parent stylesheet's origin.", "typeRef": "CSS.StyleSheetOrigin" }, { "name": "style", "type": "object", "optional": false, "description": "Associated style declaration.", "typeRef": "CSS.CSSStyle" }]);
    inspectorBackend.registerType("CSS.CSSPropertyRule", [{ "name": "styleSheetId", "type": "string", "optional": true, "description": "The css style sheet identifier (absent for user agent stylesheet and user-specified stylesheet rules) this rule came from.", "typeRef": "DOM.StyleSheetId" }, { "name": "origin", "type": "string", "optional": false, "description": "Parent stylesheet's origin.", "typeRef": "CSS.StyleSheetOrigin" }, { "name": "propertyName", "type": "object", "optional": false, "description": "Associated property name.", "typeRef": "CSS.Value" }, { "name": "style", "type": "object", "optional": false, "description": "Associated style declaration.", "typeRef": "CSS.CSSStyle" }]);
    inspectorBackend.registerType("CSS.CSSFunctionParameter", [{ "name": "name", "type": "string", "optional": false, "description": "The parameter name.", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "The parameter type.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.CSSFunctionConditionNode", [{ "name": "media", "type": "object", "optional": true, "description": "Media query for this conditional block. Only one type of condition should be set.", "typeRef": "CSS.CSSMedia" }, { "name": "containerQueries", "type": "object", "optional": true, "description": "Container query for this conditional block. Only one type of condition should be set.", "typeRef": "CSS.CSSContainerQuery" }, { "name": "supports", "type": "object", "optional": true, "description": "@supports CSS at-rule condition. Only one type of condition should be set.", "typeRef": "CSS.CSSSupports" }, { "name": "children", "type": "array", "optional": false, "description": "Block body.", "typeRef": "CSS.CSSFunctionNode" }, { "name": "conditionText", "type": "string", "optional": false, "description": "The condition text.", "typeRef": null }]);
    inspectorBackend.registerType("CSS.CSSFunctionNode", [{ "name": "condition", "type": "object", "optional": true, "description": "A conditional block. If set, style should not be set.", "typeRef": "CSS.CSSFunctionConditionNode" }, { "name": "style", "type": "object", "optional": true, "description": "Values set by this node. If set, condition should not be set.", "typeRef": "CSS.CSSStyle" }]);
    inspectorBackend.registerType("CSS.CSSFunctionRule", [{ "name": "name", "type": "object", "optional": false, "description": "Name of the function.", "typeRef": "CSS.Value" }, { "name": "styleSheetId", "type": "string", "optional": true, "description": "The css style sheet identifier (absent for user agent stylesheet and user-specified stylesheet rules) this rule came from.", "typeRef": "DOM.StyleSheetId" }, { "name": "origin", "type": "string", "optional": false, "description": "Parent stylesheet's origin.", "typeRef": "CSS.StyleSheetOrigin" }, { "name": "parameters", "type": "array", "optional": false, "description": "List of parameters.", "typeRef": "CSS.CSSFunctionParameter" }, { "name": "children", "type": "array", "optional": false, "description": "Function body.", "typeRef": "CSS.CSSFunctionNode" }]);
    inspectorBackend.registerType("CSS.CSSKeyframeRule", [{ "name": "styleSheetId", "type": "string", "optional": true, "description": "The css style sheet identifier (absent for user agent stylesheet and user-specified stylesheet rules) this rule came from.", "typeRef": "DOM.StyleSheetId" }, { "name": "origin", "type": "string", "optional": false, "description": "Parent stylesheet's origin.", "typeRef": "CSS.StyleSheetOrigin" }, { "name": "keyText", "type": "object", "optional": false, "description": "Associated key text.", "typeRef": "CSS.Value" }, { "name": "style", "type": "object", "optional": false, "description": "Associated style declaration.", "typeRef": "CSS.CSSStyle" }]);
    inspectorBackend.registerType("CSS.StyleDeclarationEdit", [{ "name": "styleSheetId", "type": "string", "optional": false, "description": "The css style sheet identifier.", "typeRef": "DOM.StyleSheetId" }, { "name": "range", "type": "object", "optional": false, "description": "The range of the style text in the enclosing stylesheet.", "typeRef": "CSS.SourceRange" }, { "name": "text", "type": "string", "optional": false, "description": "New style text.", "typeRef": null }]);
    inspectorBackend.registerEnum("CacheStorage.CachedResponseType", { Basic: "basic", Cors: "cors", Default: "default", Error: "error", OpaqueResponse: "opaqueResponse", OpaqueRedirect: "opaqueRedirect" });
    inspectorBackend.registerCommand("CacheStorage.deleteCache", [{ "name": "cacheId", "type": "string", "optional": false, "description": "Id of cache for deletion.", "typeRef": "CacheStorage.CacheId" }], [], "Deletes a cache.");
    inspectorBackend.registerCommand("CacheStorage.deleteEntry", [{ "name": "cacheId", "type": "string", "optional": false, "description": "Id of cache where the entry will be deleted.", "typeRef": "CacheStorage.CacheId" }, { "name": "request", "type": "string", "optional": false, "description": "URL spec of the request.", "typeRef": null }], [], "Deletes a cache entry.");
    inspectorBackend.registerCommand("CacheStorage.requestCacheNames", [{ "name": "securityOrigin", "type": "string", "optional": true, "description": "At least and at most one of securityOrigin, storageKey, storageBucket must be specified. Security origin.", "typeRef": null }, { "name": "storageKey", "type": "string", "optional": true, "description": "Storage key.", "typeRef": null }, { "name": "storageBucket", "type": "object", "optional": true, "description": "Storage bucket. If not specified, it uses the default bucket.", "typeRef": "Storage.StorageBucket" }], ["caches"], "Requests cache names.");
    inspectorBackend.registerCommand("CacheStorage.requestCachedResponse", [{ "name": "cacheId", "type": "string", "optional": false, "description": "Id of cache that contains the entry.", "typeRef": "CacheStorage.CacheId" }, { "name": "requestURL", "type": "string", "optional": false, "description": "URL spec of the request.", "typeRef": null }, { "name": "requestHeaders", "type": "array", "optional": false, "description": "headers of the request.", "typeRef": "CacheStorage.Header" }], ["response"], "Fetches cache entry.");
    inspectorBackend.registerCommand("CacheStorage.requestEntries", [{ "name": "cacheId", "type": "string", "optional": false, "description": "ID of cache to get entries from.", "typeRef": "CacheStorage.CacheId" }, { "name": "skipCount", "type": "number", "optional": true, "description": "Number of records to skip.", "typeRef": null }, { "name": "pageSize", "type": "number", "optional": true, "description": "Number of records to fetch.", "typeRef": null }, { "name": "pathFilter", "type": "string", "optional": true, "description": "If present, only return the entries containing this substring in the path", "typeRef": null }], ["cacheDataEntries", "returnCount"], "Requests data from cache.");
    inspectorBackend.registerType("CacheStorage.DataEntry", [{ "name": "requestURL", "type": "string", "optional": false, "description": "Request URL.", "typeRef": null }, { "name": "requestMethod", "type": "string", "optional": false, "description": "Request method.", "typeRef": null }, { "name": "requestHeaders", "type": "array", "optional": false, "description": "Request headers", "typeRef": "CacheStorage.Header" }, { "name": "responseTime", "type": "number", "optional": false, "description": "Number of seconds since epoch.", "typeRef": null }, { "name": "responseStatus", "type": "number", "optional": false, "description": "HTTP response status code.", "typeRef": null }, { "name": "responseStatusText", "type": "string", "optional": false, "description": "HTTP response status text.", "typeRef": null }, { "name": "responseType", "type": "string", "optional": false, "description": "HTTP response type", "typeRef": "CacheStorage.CachedResponseType" }, { "name": "responseHeaders", "type": "array", "optional": false, "description": "Response headers", "typeRef": "CacheStorage.Header" }]);
    inspectorBackend.registerType("CacheStorage.Cache", [{ "name": "cacheId", "type": "string", "optional": false, "description": "An opaque unique id of the cache.", "typeRef": "CacheStorage.CacheId" }, { "name": "securityOrigin", "type": "string", "optional": false, "description": "Security origin of the cache.", "typeRef": null }, { "name": "storageKey", "type": "string", "optional": false, "description": "Storage key of the cache.", "typeRef": null }, { "name": "storageBucket", "type": "object", "optional": true, "description": "Storage bucket of the cache.", "typeRef": "Storage.StorageBucket" }, { "name": "cacheName", "type": "string", "optional": false, "description": "The name of the cache.", "typeRef": null }]);
    inspectorBackend.registerType("CacheStorage.Header", [{ "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("CacheStorage.CachedResponse", [{ "name": "body", "type": "string", "optional": false, "description": "Entry content, base64-encoded.", "typeRef": null }]);
    inspectorBackend.registerEvent("Cast.sinksUpdated", ["sinks"]);
    inspectorBackend.registerEvent("Cast.issueUpdated", ["issueMessage"]);
    inspectorBackend.registerCommand("Cast.enable", [{ "name": "presentationUrl", "type": "string", "optional": true, "description": "", "typeRef": null }], [], "Starts observing for sinks that can be used for tab mirroring, and if set, sinks compatible with |presentationUrl| as well. When sinks are found, a |sinksUpdated| event is fired. Also starts observing for issue messages. When an issue is added or removed, an |issueUpdated| event is fired.");
    inspectorBackend.registerCommand("Cast.disable", [], [], "Stops observing for sinks and issues.");
    inspectorBackend.registerCommand("Cast.setSinkToUse", [{ "name": "sinkName", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Sets a sink to be used when the web page requests the browser to choose a sink via Presentation API, Remote Playback API, or Cast SDK.");
    inspectorBackend.registerCommand("Cast.startDesktopMirroring", [{ "name": "sinkName", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Starts mirroring the desktop to the sink.");
    inspectorBackend.registerCommand("Cast.startTabMirroring", [{ "name": "sinkName", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Starts mirroring the tab to the sink.");
    inspectorBackend.registerCommand("Cast.stopCasting", [{ "name": "sinkName", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Stops the active Cast session on the sink.");
    inspectorBackend.registerType("Cast.Sink", [{ "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "id", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "session", "type": "string", "optional": true, "description": "Text describing the current session. Present only if there is an active session on the sink.", "typeRef": null }]);
    inspectorBackend.registerEnum("DOM.PseudoType", { FirstLine: "first-line", FirstLetter: "first-letter", Checkmark: "checkmark", Before: "before", After: "after", PickerIcon: "picker-icon", InterestHint: "interest-hint", Marker: "marker", Backdrop: "backdrop", Column: "column", Selection: "selection", SearchText: "search-text", TargetText: "target-text", SpellingError: "spelling-error", GrammarError: "grammar-error", Highlight: "highlight", FirstLineInherited: "first-line-inherited", ScrollMarker: "scroll-marker", ScrollMarkerGroup: "scroll-marker-group", ScrollButton: "scroll-button", Scrollbar: "scrollbar", ScrollbarThumb: "scrollbar-thumb", ScrollbarButton: "scrollbar-button", ScrollbarTrack: "scrollbar-track", ScrollbarTrackPiece: "scrollbar-track-piece", ScrollbarCorner: "scrollbar-corner", Resizer: "resizer", InputListButton: "input-list-button", ViewTransition: "view-transition", ViewTransitionGroup: "view-transition-group", ViewTransitionImagePair: "view-transition-image-pair", ViewTransitionGroupChildren: "view-transition-group-children", ViewTransitionOld: "view-transition-old", ViewTransitionNew: "view-transition-new", Placeholder: "placeholder", FileSelectorButton: "file-selector-button", DetailsContent: "details-content", Picker: "picker", PermissionIcon: "permission-icon", OverscrollAreaParent: "overscroll-area-parent" });
    inspectorBackend.registerEnum("DOM.ShadowRootType", { UserAgent: "user-agent", Open: "open", Closed: "closed" });
    inspectorBackend.registerEnum("DOM.CompatibilityMode", { QuirksMode: "QuirksMode", LimitedQuirksMode: "LimitedQuirksMode", NoQuirksMode: "NoQuirksMode" });
    inspectorBackend.registerEnum("DOM.PhysicalAxes", { Horizontal: "Horizontal", Vertical: "Vertical", Both: "Both" });
    inspectorBackend.registerEnum("DOM.LogicalAxes", { Inline: "Inline", Block: "Block", Both: "Both" });
    inspectorBackend.registerEnum("DOM.ScrollOrientation", { Horizontal: "horizontal", Vertical: "vertical" });
    inspectorBackend.registerEvent("DOM.attributeModified", ["nodeId", "name", "value"]);
    inspectorBackend.registerEvent("DOM.adoptedStyleSheetsModified", ["nodeId", "adoptedStyleSheets"]);
    inspectorBackend.registerEvent("DOM.attributeRemoved", ["nodeId", "name"]);
    inspectorBackend.registerEvent("DOM.characterDataModified", ["nodeId", "characterData"]);
    inspectorBackend.registerEvent("DOM.childNodeCountUpdated", ["nodeId", "childNodeCount"]);
    inspectorBackend.registerEvent("DOM.childNodeInserted", ["parentNodeId", "previousNodeId", "node"]);
    inspectorBackend.registerEvent("DOM.childNodeRemoved", ["parentNodeId", "nodeId"]);
    inspectorBackend.registerEvent("DOM.distributedNodesUpdated", ["insertionPointId", "distributedNodes"]);
    inspectorBackend.registerEvent("DOM.documentUpdated", []);
    inspectorBackend.registerEvent("DOM.inlineStyleInvalidated", ["nodeIds"]);
    inspectorBackend.registerEvent("DOM.pseudoElementAdded", ["parentId", "pseudoElement"]);
    inspectorBackend.registerEvent("DOM.topLayerElementsUpdated", []);
    inspectorBackend.registerEvent("DOM.scrollableFlagUpdated", ["nodeId", "isScrollable"]);
    inspectorBackend.registerEvent("DOM.adRelatedStateUpdated", ["nodeId", "isAdRelated"]);
    inspectorBackend.registerEvent("DOM.affectedByStartingStylesFlagUpdated", ["nodeId", "affectedByStartingStyles"]);
    inspectorBackend.registerEvent("DOM.pseudoElementRemoved", ["parentId", "pseudoElementId"]);
    inspectorBackend.registerEvent("DOM.setChildNodes", ["parentId", "nodes"]);
    inspectorBackend.registerEvent("DOM.shadowRootPopped", ["hostId", "rootId"]);
    inspectorBackend.registerEvent("DOM.shadowRootPushed", ["hostId", "root"]);
    inspectorBackend.registerCommand("DOM.collectClassNamesFromSubtree", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to collect class names.", "typeRef": "DOM.NodeId" }], ["classNames"], "Collects class names for the node with given id and all of it's child nodes.");
    inspectorBackend.registerCommand("DOM.copyTo", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to copy.", "typeRef": "DOM.NodeId" }, { "name": "targetNodeId", "type": "number", "optional": false, "description": "Id of the element to drop the copy into.", "typeRef": "DOM.NodeId" }, { "name": "insertBeforeNodeId", "type": "number", "optional": true, "description": "Drop the copy before this node (if absent, the copy becomes the last child of `targetNodeId`).", "typeRef": "DOM.NodeId" }], ["nodeId"], "Creates a deep copy of the specified node and places it into the target container before the given anchor.");
    inspectorBackend.registerCommand("DOM.describeNode", [{ "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node wrapper.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "depth", "type": "number", "optional": true, "description": "The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0.", "typeRef": null }, { "name": "pierce", "type": "boolean", "optional": true, "description": "Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false).", "typeRef": null }], ["node"], "Describes node given its id, does not require domain to be enabled. Does not start tracking any objects, can be used for automation.");
    inspectorBackend.registerCommand("DOM.scrollIntoViewIfNeeded", [{ "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node wrapper.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "rect", "type": "object", "optional": true, "description": "The rect to be scrolled into view, relative to the node's border box, in CSS pixels. When omitted, center of the node will be used, similar to Element.scrollIntoView.", "typeRef": "DOM.Rect" }], [], "Scrolls the specified rect of the given node into view if not already visible. Note: exactly one between nodeId, backendNodeId and objectId should be passed to identify the node.");
    inspectorBackend.registerCommand("DOM.disable", [], [], "Disables DOM agent for the given page.");
    inspectorBackend.registerCommand("DOM.discardSearchResults", [{ "name": "searchId", "type": "string", "optional": false, "description": "Unique search session identifier.", "typeRef": null }], [], "Discards search results from the session with the given id. `getSearchResults` should no longer be called for that search.");
    inspectorBackend.registerEnum("DOM.EnableRequestIncludeWhitespace", { None: "none", All: "all" });
    inspectorBackend.registerCommand("DOM.enable", [{ "name": "includeWhitespace", "type": "string", "optional": true, "description": "Whether to include whitespaces in the children array of returned Nodes.", "typeRef": "DOM.EnableRequestIncludeWhitespace" }], [], "Enables DOM agent for the given page.");
    inspectorBackend.registerCommand("DOM.focus", [{ "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node wrapper.", "typeRef": "Runtime.RemoteObjectId" }], [], "Focuses the given element.");
    inspectorBackend.registerCommand("DOM.getAttributes", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to retrieve attributes for.", "typeRef": "DOM.NodeId" }], ["attributes"], "Returns attributes for the specified node.");
    inspectorBackend.registerCommand("DOM.getBoxModel", [{ "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node wrapper.", "typeRef": "Runtime.RemoteObjectId" }], ["model"], "Returns boxes for the given node.");
    inspectorBackend.registerCommand("DOM.getContentQuads", [{ "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node wrapper.", "typeRef": "Runtime.RemoteObjectId" }], ["quads"], "Returns quads that describe node position on the page. This method might return multiple quads for inline nodes.");
    inspectorBackend.registerCommand("DOM.getDocument", [{ "name": "depth", "type": "number", "optional": true, "description": "The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0.", "typeRef": null }, { "name": "pierce", "type": "boolean", "optional": true, "description": "Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false).", "typeRef": null }], ["root"], "Returns the root DOM node (and optionally the subtree) to the caller. Implicitly enables the DOM domain events for the current target.");
    inspectorBackend.registerCommand("DOM.getFlattenedDocument", [{ "name": "depth", "type": "number", "optional": true, "description": "The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0.", "typeRef": null }, { "name": "pierce", "type": "boolean", "optional": true, "description": "Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false).", "typeRef": null }], ["nodes"], "Returns the root DOM node (and optionally the subtree) to the caller. Deprecated, as it is not designed to work well with the rest of the DOM agent. Use DOMSnapshot.captureSnapshot instead.");
    inspectorBackend.registerCommand("DOM.getNodesForSubtreeByStyle", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Node ID pointing to the root of a subtree.", "typeRef": "DOM.NodeId" }, { "name": "computedStyles", "type": "array", "optional": false, "description": "The style to filter nodes by (includes nodes if any of properties matches).", "typeRef": "DOM.CSSComputedStyleProperty" }, { "name": "pierce", "type": "boolean", "optional": true, "description": "Whether or not iframes and shadow roots in the same target should be traversed when returning the results (default is false).", "typeRef": null }], ["nodeIds"], "Finds nodes with a given computed style in a subtree.");
    inspectorBackend.registerCommand("DOM.getNodeForLocation", [{ "name": "x", "type": "number", "optional": false, "description": "X coordinate.", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Y coordinate.", "typeRef": null }, { "name": "includeUserAgentShadowDOM", "type": "boolean", "optional": true, "description": "False to skip to the nearest non-UA shadow root ancestor (default: false).", "typeRef": null }, { "name": "ignorePointerEventsNone", "type": "boolean", "optional": true, "description": "Whether to ignore pointer-events: none on elements and hit test them.", "typeRef": null }], ["backendNodeId", "frameId", "nodeId"], "Returns node id at given location. Depending on whether DOM domain is enabled, nodeId is either returned or not.");
    inspectorBackend.registerCommand("DOM.getOuterHTML", [{ "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node wrapper.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "includeShadowDOM", "type": "boolean", "optional": true, "description": "Include all shadow roots. Equals to false if not specified.", "typeRef": null }], ["outerHTML"], "Returns node's HTML markup.");
    inspectorBackend.registerCommand("DOM.getRelayoutBoundary", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node.", "typeRef": "DOM.NodeId" }], ["nodeId"], "Returns the id of the nearest ancestor that is a relayout boundary.");
    inspectorBackend.registerCommand("DOM.getSearchResults", [{ "name": "searchId", "type": "string", "optional": false, "description": "Unique search session identifier.", "typeRef": null }, { "name": "fromIndex", "type": "number", "optional": false, "description": "Start index of the search result to be returned.", "typeRef": null }, { "name": "toIndex", "type": "number", "optional": false, "description": "End index of the search result to be returned.", "typeRef": null }], ["nodeIds"], "Returns search results from given `fromIndex` to given `toIndex` from the search with the given identifier.");
    inspectorBackend.registerCommand("DOM.hideHighlight", [], [], "Hides any highlight.");
    inspectorBackend.registerCommand("DOM.highlightNode", [], [], "Highlights DOM node.");
    inspectorBackend.registerCommand("DOM.highlightRect", [], [], "Highlights given rectangle.");
    inspectorBackend.registerCommand("DOM.markUndoableState", [], [], "Marks last undoable state.");
    inspectorBackend.registerCommand("DOM.moveTo", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to move.", "typeRef": "DOM.NodeId" }, { "name": "targetNodeId", "type": "number", "optional": false, "description": "Id of the element to drop the moved node into.", "typeRef": "DOM.NodeId" }, { "name": "insertBeforeNodeId", "type": "number", "optional": true, "description": "Drop node before this one (if absent, the moved node becomes the last child of `targetNodeId`).", "typeRef": "DOM.NodeId" }], ["nodeId"], "Moves node into the new container, places it before the given anchor.");
    inspectorBackend.registerCommand("DOM.performSearch", [{ "name": "query", "type": "string", "optional": false, "description": "Plain text or query selector or XPath search query.", "typeRef": null }, { "name": "includeUserAgentShadowDOM", "type": "boolean", "optional": true, "description": "True to search in user agent shadow DOM.", "typeRef": null }], ["searchId", "resultCount"], "Searches for a given string in the DOM tree. Use `getSearchResults` to access search results or `cancelSearch` to end this search session.");
    inspectorBackend.registerCommand("DOM.pushNodeByPathToFrontend", [{ "name": "path", "type": "string", "optional": false, "description": "Path to node in the proprietary format.", "typeRef": null }], ["nodeId"], "Requests that the node is sent to the caller given its path. // FIXME, use XPath");
    inspectorBackend.registerCommand("DOM.pushNodesByBackendIdsToFrontend", [{ "name": "backendNodeIds", "type": "array", "optional": false, "description": "The array of backend node ids.", "typeRef": "DOM.BackendNodeId" }], ["nodeIds"], "Requests that a batch of nodes is sent to the caller given their backend node ids.");
    inspectorBackend.registerCommand("DOM.querySelector", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to query upon.", "typeRef": "DOM.NodeId" }, { "name": "selector", "type": "string", "optional": false, "description": "Selector string.", "typeRef": null }], ["nodeId"], "Executes `querySelector` on a given node.");
    inspectorBackend.registerCommand("DOM.querySelectorAll", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to query upon.", "typeRef": "DOM.NodeId" }, { "name": "selector", "type": "string", "optional": false, "description": "Selector string.", "typeRef": null }], ["nodeIds"], "Executes `querySelectorAll` on a given node.");
    inspectorBackend.registerCommand("DOM.getTopLayerElements", [], ["nodeIds"], "Returns NodeIds of current top layer elements. Top layer is rendered closest to the user within a viewport, therefore its elements always appear on top of all other content.");
    inspectorBackend.registerEnum("DOM.GetElementByRelationRequestRelation", { PopoverTarget: "PopoverTarget", InterestTarget: "InterestTarget", CommandFor: "CommandFor" });
    inspectorBackend.registerCommand("DOM.getElementByRelation", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node from which to query the relation.", "typeRef": "DOM.NodeId" }, { "name": "relation", "type": "string", "optional": false, "description": "Type of relation to get.", "typeRef": "DOM.GetElementByRelationRequestRelation" }], ["nodeId"], "Returns the NodeId of the matched element according to certain relations.");
    inspectorBackend.registerCommand("DOM.redo", [], [], "Re-does the last undone action.");
    inspectorBackend.registerCommand("DOM.removeAttribute", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the element to remove attribute from.", "typeRef": "DOM.NodeId" }, { "name": "name", "type": "string", "optional": false, "description": "Name of the attribute to remove.", "typeRef": null }], [], "Removes attribute with given name from an element with given id.");
    inspectorBackend.registerCommand("DOM.removeNode", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to remove.", "typeRef": "DOM.NodeId" }], [], "Removes node with given id.");
    inspectorBackend.registerCommand("DOM.requestChildNodes", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to get children for.", "typeRef": "DOM.NodeId" }, { "name": "depth", "type": "number", "optional": true, "description": "The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0.", "typeRef": null }, { "name": "pierce", "type": "boolean", "optional": true, "description": "Whether or not iframes and shadow roots should be traversed when returning the sub-tree (default is false).", "typeRef": null }], [], "Requests that children of the node with given id are returned to the caller in form of `setChildNodes` events where not only immediate children are retrieved, but all children down to the specified depth.");
    inspectorBackend.registerCommand("DOM.requestNode", [{ "name": "objectId", "type": "string", "optional": false, "description": "JavaScript object id to convert into node.", "typeRef": "Runtime.RemoteObjectId" }], ["nodeId"], "Requests that the node is sent to the caller given the JavaScript node object reference. All nodes that form the path from the node to the root are also sent to the client as a series of `setChildNodes` notifications.");
    inspectorBackend.registerCommand("DOM.resolveNode", [{ "name": "nodeId", "type": "number", "optional": true, "description": "Id of the node to resolve.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Backend identifier of the node to resolve.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects.", "typeRef": null }, { "name": "executionContextId", "type": "number", "optional": true, "description": "Execution context in which to resolve the node.", "typeRef": "Runtime.ExecutionContextId" }], ["object"], "Resolves the JavaScript node object for a given NodeId or BackendNodeId.");
    inspectorBackend.registerCommand("DOM.setAttributeValue", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the element to set attribute for.", "typeRef": "DOM.NodeId" }, { "name": "name", "type": "string", "optional": false, "description": "Attribute name.", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "Attribute value.", "typeRef": null }], [], "Sets attribute for an element with given id.");
    inspectorBackend.registerCommand("DOM.setAttributesAsText", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the element to set attributes for.", "typeRef": "DOM.NodeId" }, { "name": "text", "type": "string", "optional": false, "description": "Text with a number of attributes. Will parse this text using HTML parser.", "typeRef": null }, { "name": "name", "type": "string", "optional": true, "description": "Attribute name to replace with new attributes derived from text in case text parsed successfully.", "typeRef": null }], [], "Sets attributes on element with given id. This method is useful when user edits some existing attribute value and types in several attribute name/value pairs.");
    inspectorBackend.registerCommand("DOM.setFileInputFiles", [{ "name": "files", "type": "array", "optional": false, "description": "Array of file paths to set.", "typeRef": "string" }, { "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node wrapper.", "typeRef": "Runtime.RemoteObjectId" }], [], "Sets files for the given file input element.");
    inspectorBackend.registerCommand("DOM.setNodeStackTracesEnabled", [{ "name": "enable", "type": "boolean", "optional": false, "description": "Enable or disable.", "typeRef": null }], [], "Sets if stack traces should be captured for Nodes. See `Node.getNodeStackTraces`. Default is disabled.");
    inspectorBackend.registerCommand("DOM.getNodeStackTraces", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to get stack traces for.", "typeRef": "DOM.NodeId" }], ["creation"], "Gets stack traces associated with a Node. As of now, only provides stack trace for Node creation.");
    inspectorBackend.registerCommand("DOM.getFileInfo", [{ "name": "objectId", "type": "string", "optional": false, "description": "JavaScript object id of the node wrapper.", "typeRef": "Runtime.RemoteObjectId" }], ["path"], "Returns file information for the given File wrapper.");
    inspectorBackend.registerCommand("DOM.getDetachedDomNodes", [], ["detachedNodes"], "Returns list of detached nodes");
    inspectorBackend.registerCommand("DOM.setInspectedNode", [{ "name": "nodeId", "type": "number", "optional": false, "description": "DOM node id to be accessible by means of $x command line API.", "typeRef": "DOM.NodeId" }], [], "Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions).");
    inspectorBackend.registerCommand("DOM.setNodeName", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to set name for.", "typeRef": "DOM.NodeId" }, { "name": "name", "type": "string", "optional": false, "description": "New node's name.", "typeRef": null }], ["nodeId"], "Sets node name for a node with given id.");
    inspectorBackend.registerCommand("DOM.setNodeValue", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to set value for.", "typeRef": "DOM.NodeId" }, { "name": "value", "type": "string", "optional": false, "description": "New node's value.", "typeRef": null }], [], "Sets node value for a node with given id.");
    inspectorBackend.registerCommand("DOM.setOuterHTML", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to set markup for.", "typeRef": "DOM.NodeId" }, { "name": "outerHTML", "type": "string", "optional": false, "description": "Outer HTML markup to set.", "typeRef": null }], [], "Sets node HTML markup, returns new node id.");
    inspectorBackend.registerCommand("DOM.undo", [], [], "Undoes the last performed action.");
    inspectorBackend.registerCommand("DOM.getFrameOwner", [{ "name": "frameId", "type": "string", "optional": false, "description": "", "typeRef": "Page.FrameId" }], ["backendNodeId", "nodeId"], "Returns iframe node that owns iframe with the given domain.");
    inspectorBackend.registerCommand("DOM.getContainerForNode", [{ "name": "nodeId", "type": "number", "optional": false, "description": "", "typeRef": "DOM.NodeId" }, { "name": "containerName", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "physicalAxes", "type": "string", "optional": true, "description": "", "typeRef": "DOM.PhysicalAxes" }, { "name": "logicalAxes", "type": "string", "optional": true, "description": "", "typeRef": "DOM.LogicalAxes" }, { "name": "queriesScrollState", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "queriesAnchored", "type": "boolean", "optional": true, "description": "", "typeRef": null }], ["nodeId"], "Returns the query container of the given node based on container query conditions: containerName, physical and logical axes, and whether it queries scroll-state or anchored elements. If no axes are provided and queriesScrollState is false, the style container is returned, which is the direct parent or the closest element with a matching container-name.");
    inspectorBackend.registerCommand("DOM.getQueryingDescendantsForContainer", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the container node to find querying descendants from.", "typeRef": "DOM.NodeId" }], ["nodeIds"], "Returns the descendants of a container query container that have container queries against this container.");
    inspectorBackend.registerCommand("DOM.getAnchorElement", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the positioned element from which to find the anchor.", "typeRef": "DOM.NodeId" }, { "name": "anchorSpecifier", "type": "string", "optional": true, "description": "An optional anchor specifier, as defined in https://www.w3.org/TR/css-anchor-position-1/#anchor-specifier. If not provided, it will return the implicit anchor element for the given positioned element.", "typeRef": null }], ["nodeId"], "Returns the target anchor element of the given anchor query according to https://www.w3.org/TR/css-anchor-position-1/#target.");
    inspectorBackend.registerCommand("DOM.forceShowPopover", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the popover HTMLElement", "typeRef": "DOM.NodeId" }, { "name": "enable", "type": "boolean", "optional": false, "description": "If true, opens the popover and keeps it open. If false, closes the popover if it was previously force-opened.", "typeRef": null }], ["nodeIds"], "When enabling, this API force-opens the popover identified by nodeId and keeps it open until disabled.");
    inspectorBackend.registerType("DOM.BackendNode", [{ "name": "nodeType", "type": "number", "optional": false, "description": "`Node`'s nodeType.", "typeRef": null }, { "name": "nodeName", "type": "string", "optional": false, "description": "`Node`'s nodeName.", "typeRef": null }, { "name": "backendNodeId", "type": "number", "optional": false, "description": "", "typeRef": "DOM.BackendNodeId" }]);
    inspectorBackend.registerType("DOM.Node", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Node identifier that is passed into the rest of the DOM messages as the `nodeId`. Backend will only push node with given `id` once. It is aware of all requested nodes and will only fire DOM events for nodes known to the client.", "typeRef": "DOM.NodeId" }, { "name": "parentId", "type": "number", "optional": true, "description": "The id of the parent node if any.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": false, "description": "The BackendNodeId for this node.", "typeRef": "DOM.BackendNodeId" }, { "name": "nodeType", "type": "number", "optional": false, "description": "`Node`'s nodeType.", "typeRef": null }, { "name": "nodeName", "type": "string", "optional": false, "description": "`Node`'s nodeName.", "typeRef": null }, { "name": "localName", "type": "string", "optional": false, "description": "`Node`'s localName.", "typeRef": null }, { "name": "nodeValue", "type": "string", "optional": false, "description": "`Node`'s nodeValue.", "typeRef": null }, { "name": "childNodeCount", "type": "number", "optional": true, "description": "Child count for `Container` nodes.", "typeRef": null }, { "name": "children", "type": "array", "optional": true, "description": "Child nodes of this node when requested with children.", "typeRef": "DOM.Node" }, { "name": "attributes", "type": "array", "optional": true, "description": "Attributes of the `Element` node in the form of flat array `[name1, value1, name2, value2]`.", "typeRef": "string" }, { "name": "documentURL", "type": "string", "optional": true, "description": "Document URL that `Document` or `FrameOwner` node points to.", "typeRef": null }, { "name": "baseURL", "type": "string", "optional": true, "description": "Base URL that `Document` or `FrameOwner` node uses for URL completion.", "typeRef": null }, { "name": "publicId", "type": "string", "optional": true, "description": "`DocumentType`'s publicId.", "typeRef": null }, { "name": "systemId", "type": "string", "optional": true, "description": "`DocumentType`'s systemId.", "typeRef": null }, { "name": "internalSubset", "type": "string", "optional": true, "description": "`DocumentType`'s internalSubset.", "typeRef": null }, { "name": "xmlVersion", "type": "string", "optional": true, "description": "`Document`'s XML version in case of XML documents.", "typeRef": null }, { "name": "name", "type": "string", "optional": true, "description": "`Attr`'s name.", "typeRef": null }, { "name": "value", "type": "string", "optional": true, "description": "`Attr`'s value.", "typeRef": null }, { "name": "pseudoType", "type": "string", "optional": true, "description": "Pseudo element type for this node.", "typeRef": "DOM.PseudoType" }, { "name": "pseudoIdentifier", "type": "string", "optional": true, "description": "Pseudo element identifier for this node. Only present if there is a valid pseudoType.", "typeRef": null }, { "name": "shadowRootType", "type": "string", "optional": true, "description": "Shadow root type.", "typeRef": "DOM.ShadowRootType" }, { "name": "frameId", "type": "string", "optional": true, "description": "Frame ID for frame owner elements.", "typeRef": "Page.FrameId" }, { "name": "contentDocument", "type": "object", "optional": true, "description": "Content document for frame owner elements.", "typeRef": "DOM.Node" }, { "name": "shadowRoots", "type": "array", "optional": true, "description": "Shadow root list for given element host.", "typeRef": "DOM.Node" }, { "name": "templateContent", "type": "object", "optional": true, "description": "Content document fragment for template elements.", "typeRef": "DOM.Node" }, { "name": "pseudoElements", "type": "array", "optional": true, "description": "Pseudo elements associated with this node.", "typeRef": "DOM.Node" }, { "name": "importedDocument", "type": "object", "optional": true, "description": "Deprecated, as the HTML Imports API has been removed (crbug.com/937746). This property used to return the imported document for the HTMLImport links. The property is always undefined now.", "typeRef": "DOM.Node" }, { "name": "distributedNodes", "type": "array", "optional": true, "description": "Distributed nodes for given insertion point.", "typeRef": "DOM.BackendNode" }, { "name": "isSVG", "type": "boolean", "optional": true, "description": "Whether the node is SVG.", "typeRef": null }, { "name": "compatibilityMode", "type": "string", "optional": true, "description": "", "typeRef": "DOM.CompatibilityMode" }, { "name": "assignedSlot", "type": "object", "optional": true, "description": "", "typeRef": "DOM.BackendNode" }, { "name": "isScrollable", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "affectedByStartingStyles", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "adoptedStyleSheets", "type": "array", "optional": true, "description": "", "typeRef": "DOM.StyleSheetId" }, { "name": "isAdRelated", "type": "boolean", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("DOM.DetachedElementInfo", [{ "name": "treeNode", "type": "object", "optional": false, "description": "", "typeRef": "DOM.Node" }, { "name": "retainedNodeIds", "type": "array", "optional": false, "description": "", "typeRef": "DOM.NodeId" }]);
    inspectorBackend.registerType("DOM.RGBA", [{ "name": "r", "type": "number", "optional": false, "description": "The red component, in the [0-255] range.", "typeRef": null }, { "name": "g", "type": "number", "optional": false, "description": "The green component, in the [0-255] range.", "typeRef": null }, { "name": "b", "type": "number", "optional": false, "description": "The blue component, in the [0-255] range.", "typeRef": null }, { "name": "a", "type": "number", "optional": true, "description": "The alpha component, in the [0-1] range (default: 1).", "typeRef": null }]);
    inspectorBackend.registerType("DOM.Quad", [{ "name": "Quad", "type": "array", "optional": false, "description": "An array of quad vertices, x immediately followed by y for each point, points clock-wise.", "typeRef": "number" }]);
    inspectorBackend.registerType("DOM.BoxModel", [{ "name": "content", "type": "array", "optional": false, "description": "Content box", "typeRef": "DOM.Quad" }, { "name": "padding", "type": "array", "optional": false, "description": "Padding box", "typeRef": "DOM.Quad" }, { "name": "border", "type": "array", "optional": false, "description": "Border box", "typeRef": "DOM.Quad" }, { "name": "margin", "type": "array", "optional": false, "description": "Margin box", "typeRef": "DOM.Quad" }, { "name": "width", "type": "number", "optional": false, "description": "Node width", "typeRef": null }, { "name": "height", "type": "number", "optional": false, "description": "Node height", "typeRef": null }, { "name": "shapeOutside", "type": "object", "optional": true, "description": "Shape outside coordinates", "typeRef": "DOM.ShapeOutsideInfo" }]);
    inspectorBackend.registerType("DOM.ShapeOutsideInfo", [{ "name": "bounds", "type": "array", "optional": false, "description": "Shape bounds", "typeRef": "DOM.Quad" }, { "name": "shape", "type": "array", "optional": false, "description": "Shape coordinate details", "typeRef": "any" }, { "name": "marginShape", "type": "array", "optional": false, "description": "Margin shape bounds", "typeRef": "any" }]);
    inspectorBackend.registerType("DOM.Rect", [{ "name": "x", "type": "number", "optional": false, "description": "X coordinate", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Y coordinate", "typeRef": null }, { "name": "width", "type": "number", "optional": false, "description": "Rectangle width", "typeRef": null }, { "name": "height", "type": "number", "optional": false, "description": "Rectangle height", "typeRef": null }]);
    inspectorBackend.registerType("DOM.CSSComputedStyleProperty", [{ "name": "name", "type": "string", "optional": false, "description": "Computed style property name.", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "Computed style property value.", "typeRef": null }]);
    inspectorBackend.registerEnum("DOMDebugger.DOMBreakpointType", { SubtreeModified: "subtree-modified", AttributeModified: "attribute-modified", NodeRemoved: "node-removed" });
    inspectorBackend.registerEnum("DOMDebugger.CSPViolationType", { TrustedtypeSinkViolation: "trustedtype-sink-violation", TrustedtypePolicyViolation: "trustedtype-policy-violation" });
    inspectorBackend.registerCommand("DOMDebugger.getEventListeners", [{ "name": "objectId", "type": "string", "optional": false, "description": "Identifier of the object to return listeners for.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "depth", "type": "number", "optional": true, "description": "The maximum depth at which Node children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0.", "typeRef": null }, { "name": "pierce", "type": "boolean", "optional": true, "description": "Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false). Reports listeners for all contexts if pierce is enabled.", "typeRef": null }], ["listeners"], "Returns event listeners of the given object.");
    inspectorBackend.registerCommand("DOMDebugger.removeDOMBreakpoint", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Identifier of the node to remove breakpoint from.", "typeRef": "DOM.NodeId" }, { "name": "type", "type": "string", "optional": false, "description": "Type of the breakpoint to remove.", "typeRef": "DOMDebugger.DOMBreakpointType" }], [], "Removes DOM breakpoint that was set using `setDOMBreakpoint`.");
    inspectorBackend.registerCommand("DOMDebugger.removeEventListenerBreakpoint", [{ "name": "eventName", "type": "string", "optional": false, "description": "Event name.", "typeRef": null }, { "name": "targetName", "type": "string", "optional": true, "description": "EventTarget interface name.", "typeRef": null }], [], "Removes breakpoint on particular DOM event.");
    inspectorBackend.registerCommand("DOMDebugger.removeInstrumentationBreakpoint", [{ "name": "eventName", "type": "string", "optional": false, "description": "Instrumentation name to stop on.", "typeRef": null }], [], "Removes breakpoint on particular native event.");
    inspectorBackend.registerCommand("DOMDebugger.removeXHRBreakpoint", [{ "name": "url", "type": "string", "optional": false, "description": "Resource URL substring.", "typeRef": null }], [], "Removes breakpoint from XMLHttpRequest.");
    inspectorBackend.registerCommand("DOMDebugger.setBreakOnCSPViolation", [{ "name": "violationTypes", "type": "array", "optional": false, "description": "CSP Violations to stop upon.", "typeRef": "DOMDebugger.CSPViolationType" }], [], "Sets breakpoint on particular CSP violations.");
    inspectorBackend.registerCommand("DOMDebugger.setDOMBreakpoint", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Identifier of the node to set breakpoint on.", "typeRef": "DOM.NodeId" }, { "name": "type", "type": "string", "optional": false, "description": "Type of the operation to stop upon.", "typeRef": "DOMDebugger.DOMBreakpointType" }], [], "Sets breakpoint on particular operation with DOM.");
    inspectorBackend.registerCommand("DOMDebugger.setEventListenerBreakpoint", [{ "name": "eventName", "type": "string", "optional": false, "description": "DOM Event name to stop on (any DOM event will do).", "typeRef": null }, { "name": "targetName", "type": "string", "optional": true, "description": "EventTarget interface name to stop on. If equal to `\\\"*\\\"` or not provided, will stop on any EventTarget.", "typeRef": null }], [], "Sets breakpoint on particular DOM event.");
    inspectorBackend.registerCommand("DOMDebugger.setInstrumentationBreakpoint", [{ "name": "eventName", "type": "string", "optional": false, "description": "Instrumentation name to stop on.", "typeRef": null }], [], "Sets breakpoint on particular native event.");
    inspectorBackend.registerCommand("DOMDebugger.setXHRBreakpoint", [{ "name": "url", "type": "string", "optional": false, "description": "Resource URL substring. All XHRs having this substring in the URL will get stopped upon.", "typeRef": null }], [], "Sets breakpoint on XMLHttpRequest.");
    inspectorBackend.registerType("DOMDebugger.EventListener", [{ "name": "type", "type": "string", "optional": false, "description": "`EventListener`'s type.", "typeRef": null }, { "name": "useCapture", "type": "boolean", "optional": false, "description": "`EventListener`'s useCapture.", "typeRef": null }, { "name": "passive", "type": "boolean", "optional": false, "description": "`EventListener`'s passive flag.", "typeRef": null }, { "name": "once", "type": "boolean", "optional": false, "description": "`EventListener`'s once flag.", "typeRef": null }, { "name": "scriptId", "type": "string", "optional": false, "description": "Script id of the handler code.", "typeRef": "Runtime.ScriptId" }, { "name": "lineNumber", "type": "number", "optional": false, "description": "Line number in the script (0-based).", "typeRef": null }, { "name": "columnNumber", "type": "number", "optional": false, "description": "Column number in the script (0-based).", "typeRef": null }, { "name": "handler", "type": "object", "optional": true, "description": "Event handler function value.", "typeRef": "Runtime.RemoteObject" }, { "name": "originalHandler", "type": "object", "optional": true, "description": "Event original handler function value.", "typeRef": "Runtime.RemoteObject" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Node the listener is added to (if any).", "typeRef": "DOM.BackendNodeId" }]);
    inspectorBackend.registerCommand("DOMSnapshot.disable", [], [], "Disables DOM snapshot agent for the given page.");
    inspectorBackend.registerCommand("DOMSnapshot.enable", [], [], "Enables DOM snapshot agent for the given page.");
    inspectorBackend.registerCommand("DOMSnapshot.getSnapshot", [{ "name": "computedStyleWhitelist", "type": "array", "optional": false, "description": "Whitelist of computed styles to return.", "typeRef": "string" }, { "name": "includeEventListeners", "type": "boolean", "optional": true, "description": "Whether or not to retrieve details of DOM listeners (default false).", "typeRef": null }, { "name": "includePaintOrder", "type": "boolean", "optional": true, "description": "Whether to determine and include the paint order index of LayoutTreeNodes (default false).", "typeRef": null }, { "name": "includeUserAgentShadowTree", "type": "boolean", "optional": true, "description": "Whether to include UA shadow tree in the snapshot (default false).", "typeRef": null }], ["domNodes", "layoutTreeNodes", "computedStyles"], "Returns a document snapshot, including the full DOM tree of the root node (including iframes, template contents, and imported documents) in a flattened array, as well as layout and white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is flattened.");
    inspectorBackend.registerCommand("DOMSnapshot.captureSnapshot", [{ "name": "computedStyles", "type": "array", "optional": false, "description": "Whitelist of computed styles to return.", "typeRef": "string" }, { "name": "includePaintOrder", "type": "boolean", "optional": true, "description": "Whether to include layout object paint orders into the snapshot.", "typeRef": null }, { "name": "includeDOMRects", "type": "boolean", "optional": true, "description": "Whether to include DOM rectangles (offsetRects, clientRects, scrollRects) into the snapshot", "typeRef": null }, { "name": "includeBlendedBackgroundColors", "type": "boolean", "optional": true, "description": "Whether to include blended background colors in the snapshot (default: false). Blended background color is achieved by blending background colors of all elements that overlap with the current element.", "typeRef": null }, { "name": "includeTextColorOpacities", "type": "boolean", "optional": true, "description": "Whether to include text color opacity in the snapshot (default: false). An element might have the opacity property set that affects the text color of the element. The final text color opacity is computed based on the opacity of all overlapping elements.", "typeRef": null }], ["documents", "strings"], "Returns a document snapshot, including the full DOM tree of the root node (including iframes, template contents, and imported documents) in a flattened array, as well as layout and white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is flattened.");
    inspectorBackend.registerType("DOMSnapshot.DOMNode", [{ "name": "nodeType", "type": "number", "optional": false, "description": "`Node`'s nodeType.", "typeRef": null }, { "name": "nodeName", "type": "string", "optional": false, "description": "`Node`'s nodeName.", "typeRef": null }, { "name": "nodeValue", "type": "string", "optional": false, "description": "`Node`'s nodeValue.", "typeRef": null }, { "name": "textValue", "type": "string", "optional": true, "description": "Only set for textarea elements, contains the text value.", "typeRef": null }, { "name": "inputValue", "type": "string", "optional": true, "description": "Only set for input elements, contains the input's associated text value.", "typeRef": null }, { "name": "inputChecked", "type": "boolean", "optional": true, "description": "Only set for radio and checkbox input elements, indicates if the element has been checked", "typeRef": null }, { "name": "optionSelected", "type": "boolean", "optional": true, "description": "Only set for option elements, indicates if the element has been selected", "typeRef": null }, { "name": "backendNodeId", "type": "number", "optional": false, "description": "`Node`'s id, corresponds to DOM.Node.backendNodeId.", "typeRef": "DOM.BackendNodeId" }, { "name": "childNodeIndexes", "type": "array", "optional": true, "description": "The indexes of the node's child nodes in the `domNodes` array returned by `getSnapshot`, if any.", "typeRef": "integer" }, { "name": "attributes", "type": "array", "optional": true, "description": "Attributes of an `Element` node.", "typeRef": "DOMSnapshot.NameValue" }, { "name": "pseudoElementIndexes", "type": "array", "optional": true, "description": "Indexes of pseudo elements associated with this node in the `domNodes` array returned by `getSnapshot`, if any.", "typeRef": "integer" }, { "name": "layoutNodeIndex", "type": "number", "optional": true, "description": "The index of the node's related layout tree node in the `layoutTreeNodes` array returned by `getSnapshot`, if any.", "typeRef": null }, { "name": "documentURL", "type": "string", "optional": true, "description": "Document URL that `Document` or `FrameOwner` node points to.", "typeRef": null }, { "name": "baseURL", "type": "string", "optional": true, "description": "Base URL that `Document` or `FrameOwner` node uses for URL completion.", "typeRef": null }, { "name": "contentLanguage", "type": "string", "optional": true, "description": "Only set for documents, contains the document's content language.", "typeRef": null }, { "name": "documentEncoding", "type": "string", "optional": true, "description": "Only set for documents, contains the document's character set encoding.", "typeRef": null }, { "name": "publicId", "type": "string", "optional": true, "description": "`DocumentType` node's publicId.", "typeRef": null }, { "name": "systemId", "type": "string", "optional": true, "description": "`DocumentType` node's systemId.", "typeRef": null }, { "name": "frameId", "type": "string", "optional": true, "description": "Frame ID for frame owner elements and also for the document node.", "typeRef": "Page.FrameId" }, { "name": "contentDocumentIndex", "type": "number", "optional": true, "description": "The index of a frame owner element's content document in the `domNodes` array returned by `getSnapshot`, if any.", "typeRef": null }, { "name": "pseudoType", "type": "string", "optional": true, "description": "Type of a pseudo element node.", "typeRef": "DOM.PseudoType" }, { "name": "shadowRootType", "type": "string", "optional": true, "description": "Shadow root type.", "typeRef": "DOM.ShadowRootType" }, { "name": "isClickable", "type": "boolean", "optional": true, "description": "Whether this DOM node responds to mouse clicks. This includes nodes that have had click event listeners attached via JavaScript as well as anchor tags that naturally navigate when clicked.", "typeRef": null }, { "name": "eventListeners", "type": "array", "optional": true, "description": "Details of the node's event listeners, if any.", "typeRef": "DOMDebugger.EventListener" }, { "name": "currentSourceURL", "type": "string", "optional": true, "description": "The selected url for nodes with a srcset attribute.", "typeRef": null }, { "name": "originURL", "type": "string", "optional": true, "description": "The url of the script (if any) that generates this node.", "typeRef": null }, { "name": "scrollOffsetX", "type": "number", "optional": true, "description": "Scroll offsets, set when this node is a Document.", "typeRef": null }, { "name": "scrollOffsetY", "type": "number", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("DOMSnapshot.InlineTextBox", [{ "name": "boundingBox", "type": "object", "optional": false, "description": "The bounding box in document coordinates. Note that scroll offset of the document is ignored.", "typeRef": "DOM.Rect" }, { "name": "startCharacterIndex", "type": "number", "optional": false, "description": "The starting index in characters, for this post layout textbox substring. Characters that would be represented as a surrogate pair in UTF-16 have length 2.", "typeRef": null }, { "name": "numCharacters", "type": "number", "optional": false, "description": "The number of characters in this post layout textbox substring. Characters that would be represented as a surrogate pair in UTF-16 have length 2.", "typeRef": null }]);
    inspectorBackend.registerType("DOMSnapshot.LayoutTreeNode", [{ "name": "domNodeIndex", "type": "number", "optional": false, "description": "The index of the related DOM node in the `domNodes` array returned by `getSnapshot`.", "typeRef": null }, { "name": "boundingBox", "type": "object", "optional": false, "description": "The bounding box in document coordinates. Note that scroll offset of the document is ignored.", "typeRef": "DOM.Rect" }, { "name": "layoutText", "type": "string", "optional": true, "description": "Contents of the LayoutText, if any.", "typeRef": null }, { "name": "inlineTextNodes", "type": "array", "optional": true, "description": "The post-layout inline text nodes, if any.", "typeRef": "DOMSnapshot.InlineTextBox" }, { "name": "styleIndex", "type": "number", "optional": true, "description": "Index into the `computedStyles` array returned by `getSnapshot`.", "typeRef": null }, { "name": "paintOrder", "type": "number", "optional": true, "description": "Global paint order index, which is determined by the stacking order of the nodes. Nodes that are painted together will have the same index. Only provided if includePaintOrder in getSnapshot was true.", "typeRef": null }, { "name": "isStackingContext", "type": "boolean", "optional": true, "description": "Set to true to indicate the element begins a new stacking context.", "typeRef": null }]);
    inspectorBackend.registerType("DOMSnapshot.ComputedStyle", [{ "name": "properties", "type": "array", "optional": false, "description": "Name/value pairs of computed style properties.", "typeRef": "DOMSnapshot.NameValue" }]);
    inspectorBackend.registerType("DOMSnapshot.NameValue", [{ "name": "name", "type": "string", "optional": false, "description": "Attribute/property name.", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "Attribute/property value.", "typeRef": null }]);
    inspectorBackend.registerType("DOMSnapshot.ArrayOfStrings", [{ "name": "ArrayOfStrings", "type": "array", "optional": false, "description": "Index of the string in the strings table.", "typeRef": "DOMSnapshot.StringIndex" }]);
    inspectorBackend.registerType("DOMSnapshot.RareStringData", [{ "name": "index", "type": "array", "optional": false, "description": "", "typeRef": "integer" }, { "name": "value", "type": "array", "optional": false, "description": "", "typeRef": "DOMSnapshot.StringIndex" }]);
    inspectorBackend.registerType("DOMSnapshot.RareBooleanData", [{ "name": "index", "type": "array", "optional": false, "description": "", "typeRef": "integer" }]);
    inspectorBackend.registerType("DOMSnapshot.RareIntegerData", [{ "name": "index", "type": "array", "optional": false, "description": "", "typeRef": "integer" }, { "name": "value", "type": "array", "optional": false, "description": "", "typeRef": "integer" }]);
    inspectorBackend.registerType("DOMSnapshot.Rectangle", [{ "name": "Rectangle", "type": "array", "optional": false, "description": "", "typeRef": "number" }]);
    inspectorBackend.registerType("DOMSnapshot.DocumentSnapshot", [{ "name": "documentURL", "type": "number", "optional": false, "description": "Document URL that `Document` or `FrameOwner` node points to.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "title", "type": "number", "optional": false, "description": "Document title.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "baseURL", "type": "number", "optional": false, "description": "Base URL that `Document` or `FrameOwner` node uses for URL completion.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "contentLanguage", "type": "number", "optional": false, "description": "Contains the document's content language.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "encodingName", "type": "number", "optional": false, "description": "Contains the document's character set encoding.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "publicId", "type": "number", "optional": false, "description": "`DocumentType` node's publicId.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "systemId", "type": "number", "optional": false, "description": "`DocumentType` node's systemId.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "frameId", "type": "number", "optional": false, "description": "Frame ID for frame owner elements and also for the document node.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "nodes", "type": "object", "optional": false, "description": "A table with dom nodes.", "typeRef": "DOMSnapshot.NodeTreeSnapshot" }, { "name": "layout", "type": "object", "optional": false, "description": "The nodes in the layout tree.", "typeRef": "DOMSnapshot.LayoutTreeSnapshot" }, { "name": "textBoxes", "type": "object", "optional": false, "description": "The post-layout inline text nodes.", "typeRef": "DOMSnapshot.TextBoxSnapshot" }, { "name": "scrollOffsetX", "type": "number", "optional": true, "description": "Horizontal scroll offset.", "typeRef": null }, { "name": "scrollOffsetY", "type": "number", "optional": true, "description": "Vertical scroll offset.", "typeRef": null }, { "name": "contentWidth", "type": "number", "optional": true, "description": "Document content width.", "typeRef": null }, { "name": "contentHeight", "type": "number", "optional": true, "description": "Document content height.", "typeRef": null }]);
    inspectorBackend.registerType("DOMSnapshot.NodeTreeSnapshot", [{ "name": "parentIndex", "type": "array", "optional": true, "description": "Parent node index.", "typeRef": "integer" }, { "name": "nodeType", "type": "array", "optional": true, "description": "`Node`'s nodeType.", "typeRef": "integer" }, { "name": "shadowRootType", "type": "object", "optional": true, "description": "Type of the shadow root the `Node` is in. String values are equal to the `ShadowRootType` enum.", "typeRef": "DOMSnapshot.RareStringData" }, { "name": "nodeName", "type": "array", "optional": true, "description": "`Node`'s nodeName.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "nodeValue", "type": "array", "optional": true, "description": "`Node`'s nodeValue.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "backendNodeId", "type": "array", "optional": true, "description": "`Node`'s id, corresponds to DOM.Node.backendNodeId.", "typeRef": "DOM.BackendNodeId" }, { "name": "attributes", "type": "array", "optional": true, "description": "Attributes of an `Element` node. Flatten name, value pairs.", "typeRef": "DOMSnapshot.ArrayOfStrings" }, { "name": "textValue", "type": "object", "optional": true, "description": "Only set for textarea elements, contains the text value.", "typeRef": "DOMSnapshot.RareStringData" }, { "name": "inputValue", "type": "object", "optional": true, "description": "Only set for input elements, contains the input's associated text value.", "typeRef": "DOMSnapshot.RareStringData" }, { "name": "inputChecked", "type": "object", "optional": true, "description": "Only set for radio and checkbox input elements, indicates if the element has been checked", "typeRef": "DOMSnapshot.RareBooleanData" }, { "name": "optionSelected", "type": "object", "optional": true, "description": "Only set for option elements, indicates if the element has been selected", "typeRef": "DOMSnapshot.RareBooleanData" }, { "name": "contentDocumentIndex", "type": "object", "optional": true, "description": "The index of the document in the list of the snapshot documents.", "typeRef": "DOMSnapshot.RareIntegerData" }, { "name": "pseudoType", "type": "object", "optional": true, "description": "Type of a pseudo element node.", "typeRef": "DOMSnapshot.RareStringData" }, { "name": "pseudoIdentifier", "type": "object", "optional": true, "description": "Pseudo element identifier for this node. Only present if there is a valid pseudoType.", "typeRef": "DOMSnapshot.RareStringData" }, { "name": "isClickable", "type": "object", "optional": true, "description": "Whether this DOM node responds to mouse clicks. This includes nodes that have had click event listeners attached via JavaScript as well as anchor tags that naturally navigate when clicked.", "typeRef": "DOMSnapshot.RareBooleanData" }, { "name": "currentSourceURL", "type": "object", "optional": true, "description": "The selected url for nodes with a srcset attribute.", "typeRef": "DOMSnapshot.RareStringData" }, { "name": "originURL", "type": "object", "optional": true, "description": "The url of the script (if any) that generates this node.", "typeRef": "DOMSnapshot.RareStringData" }]);
    inspectorBackend.registerType("DOMSnapshot.LayoutTreeSnapshot", [{ "name": "nodeIndex", "type": "array", "optional": false, "description": "Index of the corresponding node in the `NodeTreeSnapshot` array returned by `captureSnapshot`.", "typeRef": "integer" }, { "name": "styles", "type": "array", "optional": false, "description": "Array of indexes specifying computed style strings, filtered according to the `computedStyles` parameter passed to `captureSnapshot`.", "typeRef": "DOMSnapshot.ArrayOfStrings" }, { "name": "bounds", "type": "array", "optional": false, "description": "The absolute position bounding box.", "typeRef": "DOMSnapshot.Rectangle" }, { "name": "text", "type": "array", "optional": false, "description": "Contents of the LayoutText, if any.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "stackingContexts", "type": "object", "optional": false, "description": "Stacking context information.", "typeRef": "DOMSnapshot.RareBooleanData" }, { "name": "paintOrders", "type": "array", "optional": true, "description": "Global paint order index, which is determined by the stacking order of the nodes. Nodes that are painted together will have the same index. Only provided if includePaintOrder in captureSnapshot was true.", "typeRef": "integer" }, { "name": "offsetRects", "type": "array", "optional": true, "description": "The offset rect of nodes. Only available when includeDOMRects is set to true", "typeRef": "DOMSnapshot.Rectangle" }, { "name": "scrollRects", "type": "array", "optional": true, "description": "The scroll rect of nodes. Only available when includeDOMRects is set to true", "typeRef": "DOMSnapshot.Rectangle" }, { "name": "clientRects", "type": "array", "optional": true, "description": "The client rect of nodes. Only available when includeDOMRects is set to true", "typeRef": "DOMSnapshot.Rectangle" }, { "name": "blendedBackgroundColors", "type": "array", "optional": true, "description": "The list of background colors that are blended with colors of overlapping elements.", "typeRef": "DOMSnapshot.StringIndex" }, { "name": "textColorOpacities", "type": "array", "optional": true, "description": "The list of computed text opacities.", "typeRef": "number" }]);
    inspectorBackend.registerType("DOMSnapshot.TextBoxSnapshot", [{ "name": "layoutIndex", "type": "array", "optional": false, "description": "Index of the layout tree node that owns this box collection.", "typeRef": "integer" }, { "name": "bounds", "type": "array", "optional": false, "description": "The absolute position bounding box.", "typeRef": "DOMSnapshot.Rectangle" }, { "name": "start", "type": "array", "optional": false, "description": "The starting index in characters, for this post layout textbox substring. Characters that would be represented as a surrogate pair in UTF-16 have length 2.", "typeRef": "integer" }, { "name": "length", "type": "array", "optional": false, "description": "The number of characters in this post layout textbox substring. Characters that would be represented as a surrogate pair in UTF-16 have length 2.", "typeRef": "integer" }]);
    inspectorBackend.registerEvent("DOMStorage.domStorageItemAdded", ["storageId", "key", "newValue"]);
    inspectorBackend.registerEvent("DOMStorage.domStorageItemRemoved", ["storageId", "key"]);
    inspectorBackend.registerEvent("DOMStorage.domStorageItemUpdated", ["storageId", "key", "oldValue", "newValue"]);
    inspectorBackend.registerEvent("DOMStorage.domStorageItemsCleared", ["storageId"]);
    inspectorBackend.registerCommand("DOMStorage.clear", [{ "name": "storageId", "type": "object", "optional": false, "description": "", "typeRef": "DOMStorage.StorageId" }], [], "");
    inspectorBackend.registerCommand("DOMStorage.disable", [], [], "Disables storage tracking, prevents storage events from being sent to the client.");
    inspectorBackend.registerCommand("DOMStorage.enable", [], [], "Enables storage tracking, storage events will now be delivered to the client.");
    inspectorBackend.registerCommand("DOMStorage.getDOMStorageItems", [{ "name": "storageId", "type": "object", "optional": false, "description": "", "typeRef": "DOMStorage.StorageId" }], ["entries"], "");
    inspectorBackend.registerCommand("DOMStorage.removeDOMStorageItem", [{ "name": "storageId", "type": "object", "optional": false, "description": "", "typeRef": "DOMStorage.StorageId" }, { "name": "key", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("DOMStorage.setDOMStorageItem", [{ "name": "storageId", "type": "object", "optional": false, "description": "", "typeRef": "DOMStorage.StorageId" }, { "name": "key", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerType("DOMStorage.StorageId", [{ "name": "securityOrigin", "type": "string", "optional": true, "description": "Security origin for the storage.", "typeRef": null }, { "name": "storageKey", "type": "string", "optional": true, "description": "Represents a key by which DOM Storage keys its CachedStorageAreas", "typeRef": "DOMStorage.SerializedStorageKey" }, { "name": "isLocalStorage", "type": "boolean", "optional": false, "description": "Whether the storage is local storage (not session storage).", "typeRef": null }]);
    inspectorBackend.registerType("DOMStorage.Item", [{ "name": "Item", "type": "array", "optional": false, "description": "DOM Storage item.", "typeRef": "string" }]);
    inspectorBackend.registerEvent("DeviceAccess.deviceRequestPrompted", ["id", "devices"]);
    inspectorBackend.registerCommand("DeviceAccess.enable", [], [], "Enable events in this domain.");
    inspectorBackend.registerCommand("DeviceAccess.disable", [], [], "Disable events in this domain.");
    inspectorBackend.registerCommand("DeviceAccess.selectPrompt", [{ "name": "id", "type": "string", "optional": false, "description": "", "typeRef": "DeviceAccess.RequestId" }, { "name": "deviceId", "type": "string", "optional": false, "description": "", "typeRef": "DeviceAccess.DeviceId" }], [], "Select a device in response to a DeviceAccess.deviceRequestPrompted event.");
    inspectorBackend.registerCommand("DeviceAccess.cancelPrompt", [{ "name": "id", "type": "string", "optional": false, "description": "", "typeRef": "DeviceAccess.RequestId" }], [], "Cancel a prompt in response to a DeviceAccess.deviceRequestPrompted event.");
    inspectorBackend.registerType("DeviceAccess.PromptDevice", [{ "name": "id", "type": "string", "optional": false, "description": "", "typeRef": "DeviceAccess.DeviceId" }, { "name": "name", "type": "string", "optional": false, "description": "Display name as it appears in a device request user prompt.", "typeRef": null }]);
    inspectorBackend.registerCommand("DeviceOrientation.clearDeviceOrientationOverride", [], [], "Clears the overridden Device Orientation.");
    inspectorBackend.registerCommand("DeviceOrientation.setDeviceOrientationOverride", [{ "name": "alpha", "type": "number", "optional": false, "description": "Mock alpha", "typeRef": null }, { "name": "beta", "type": "number", "optional": false, "description": "Mock beta", "typeRef": null }, { "name": "gamma", "type": "number", "optional": false, "description": "Mock gamma", "typeRef": null }], [], "Overrides the Device Orientation.");
    inspectorBackend.registerEnum("Emulation.ScreenOrientationType", { PortraitPrimary: "portraitPrimary", PortraitSecondary: "portraitSecondary", LandscapePrimary: "landscapePrimary", LandscapeSecondary: "landscapeSecondary" });
    inspectorBackend.registerEnum("Emulation.DisplayFeatureOrientation", { Vertical: "vertical", Horizontal: "horizontal" });
    inspectorBackend.registerEnum("Emulation.DevicePostureType", { Continuous: "continuous", Folded: "folded" });
    inspectorBackend.registerEnum("Emulation.VirtualTimePolicy", { Advance: "advance", Pause: "pause", PauseIfNetworkFetchesPending: "pauseIfNetworkFetchesPending" });
    inspectorBackend.registerEnum("Emulation.SensorType", { AbsoluteOrientation: "absolute-orientation", Accelerometer: "accelerometer", AmbientLight: "ambient-light", Gravity: "gravity", Gyroscope: "gyroscope", LinearAcceleration: "linear-acceleration", Magnetometer: "magnetometer", RelativeOrientation: "relative-orientation" });
    inspectorBackend.registerEnum("Emulation.PressureSource", { Cpu: "cpu" });
    inspectorBackend.registerEnum("Emulation.PressureState", { Nominal: "nominal", Fair: "fair", Serious: "serious", Critical: "critical" });
    inspectorBackend.registerEnum("Emulation.DisabledImageType", { Avif: "avif", Jxl: "jxl", Webp: "webp" });
    inspectorBackend.registerEvent("Emulation.virtualTimeBudgetExpired", []);
    inspectorBackend.registerEvent("Emulation.screenOrientationLockChanged", ["locked", "orientation"]);
    inspectorBackend.registerCommand("Emulation.canEmulate", [], ["result"], "Tells whether emulation is supported.");
    inspectorBackend.registerCommand("Emulation.clearDeviceMetricsOverride", [], [], "Clears the overridden device metrics.");
    inspectorBackend.registerCommand("Emulation.clearGeolocationOverride", [], [], "Clears the overridden Geolocation Position and Error.");
    inspectorBackend.registerCommand("Emulation.resetPageScaleFactor", [], [], "Requests that page scale factor is reset to initial values.");
    inspectorBackend.registerCommand("Emulation.setFocusEmulationEnabled", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "Whether to enable to disable focus emulation.", "typeRef": null }], [], "Enables or disables simulating a focused and active page.");
    inspectorBackend.registerCommand("Emulation.setAutoDarkModeOverride", [{ "name": "enabled", "type": "boolean", "optional": true, "description": "Whether to enable or disable automatic dark mode. If not specified, any existing override will be cleared.", "typeRef": null }], [], "Automatically render all web contents using a dark theme.");
    inspectorBackend.registerCommand("Emulation.setCPUThrottlingRate", [{ "name": "rate", "type": "number", "optional": false, "description": "Throttling rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).", "typeRef": null }], [], "Enables CPU throttling to emulate slow CPUs.");
    inspectorBackend.registerCommand("Emulation.setDefaultBackgroundColorOverride", [{ "name": "color", "type": "object", "optional": true, "description": "RGBA of the default background color. If not specified, any existing override will be cleared.", "typeRef": "DOM.RGBA" }], [], "Sets or clears an override of the default background color of the frame. This override is used if the content does not specify one.");
    inspectorBackend.registerCommand("Emulation.setSafeAreaInsetsOverride", [{ "name": "insets", "type": "object", "optional": false, "description": "", "typeRef": "Emulation.SafeAreaInsets" }], [], "Overrides the values for env(safe-area-inset-*) and env(safe-area-max-inset-*). Unset values will cause the respective variables to be undefined, even if previously overridden.");
    inspectorBackend.registerEnum("Emulation.SetDeviceMetricsOverrideRequestScrollbarType", { Overlay: "overlay", Default: "default" });
    inspectorBackend.registerCommand("Emulation.setDeviceMetricsOverride", [{ "name": "width", "type": "number", "optional": false, "description": "Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override.", "typeRef": null }, { "name": "height", "type": "number", "optional": false, "description": "Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override.", "typeRef": null }, { "name": "deviceScaleFactor", "type": "number", "optional": false, "description": "Overriding device scale factor value. 0 disables the override.", "typeRef": null }, { "name": "mobile", "type": "boolean", "optional": false, "description": "Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text autosizing and more.", "typeRef": null }, { "name": "scale", "type": "number", "optional": true, "description": "Scale to apply to resulting view image.", "typeRef": null }, { "name": "screenWidth", "type": "number", "optional": true, "description": "Overriding screen width value in pixels (minimum 0, maximum 10000000).", "typeRef": null }, { "name": "screenHeight", "type": "number", "optional": true, "description": "Overriding screen height value in pixels (minimum 0, maximum 10000000).", "typeRef": null }, { "name": "positionX", "type": "number", "optional": true, "description": "Overriding view X position on screen in pixels (minimum 0, maximum 10000000).", "typeRef": null }, { "name": "positionY", "type": "number", "optional": true, "description": "Overriding view Y position on screen in pixels (minimum 0, maximum 10000000).", "typeRef": null }, { "name": "dontSetVisibleSize", "type": "boolean", "optional": true, "description": "Do not set visible view size, rely upon explicit setVisibleSize call.", "typeRef": null }, { "name": "screenOrientation", "type": "object", "optional": true, "description": "Screen orientation override.", "typeRef": "Emulation.ScreenOrientation" }, { "name": "viewport", "type": "object", "optional": true, "description": "If set, the visible area of the page will be overridden to this viewport. This viewport change is not observed by the page, e.g. viewport-relative elements do not change positions.", "typeRef": "Page.Viewport" }, { "name": "displayFeature", "type": "object", "optional": true, "description": "If set, the display feature of a multi-segment screen. If not set, multi-segment support is turned-off. Deprecated, use Emulation.setDisplayFeaturesOverride.", "typeRef": "Emulation.DisplayFeature" }, { "name": "devicePosture", "type": "object", "optional": true, "description": "If set, the posture of a foldable device. If not set the posture is set to continuous. Deprecated, use Emulation.setDevicePostureOverride.", "typeRef": "Emulation.DevicePosture" }, { "name": "scrollbarType", "type": "string", "optional": true, "description": "Scrollbar type. Default: `default`.", "typeRef": "Emulation.SetDeviceMetricsOverrideRequestScrollbarType" }], [], "Overrides the values of device screen dimensions (window.screen.width, window.screen.height, window.innerWidth, window.innerHeight, and \"device-width\"/\"device-height\"-related CSS media query results).");
    inspectorBackend.registerCommand("Emulation.setDevicePostureOverride", [{ "name": "posture", "type": "object", "optional": false, "description": "", "typeRef": "Emulation.DevicePosture" }], [], "Start reporting the given posture value to the Device Posture API. This override can also be set in setDeviceMetricsOverride().");
    inspectorBackend.registerCommand("Emulation.clearDevicePostureOverride", [], [], "Clears a device posture override set with either setDeviceMetricsOverride() or setDevicePostureOverride() and starts using posture information from the platform again. Does nothing if no override is set.");
    inspectorBackend.registerCommand("Emulation.setDisplayFeaturesOverride", [{ "name": "features", "type": "array", "optional": false, "description": "", "typeRef": "Emulation.DisplayFeature" }], [], "Start using the given display features to pupulate the Viewport Segments API. This override can also be set in setDeviceMetricsOverride().");
    inspectorBackend.registerCommand("Emulation.clearDisplayFeaturesOverride", [], [], "Clears the display features override set with either setDeviceMetricsOverride() or setDisplayFeaturesOverride() and starts using display features from the platform again. Does nothing if no override is set.");
    inspectorBackend.registerCommand("Emulation.setScrollbarsHidden", [{ "name": "hidden", "type": "boolean", "optional": false, "description": "Whether scrollbars should be always hidden.", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("Emulation.setDocumentCookieDisabled", [{ "name": "disabled", "type": "boolean", "optional": false, "description": "Whether document.coookie API should be disabled.", "typeRef": null }], [], "");
    inspectorBackend.registerEnum("Emulation.SetEmitTouchEventsForMouseRequestConfiguration", { Mobile: "mobile", Desktop: "desktop" });
    inspectorBackend.registerCommand("Emulation.setEmitTouchEventsForMouse", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "Whether touch emulation based on mouse input should be enabled.", "typeRef": null }, { "name": "configuration", "type": "string", "optional": true, "description": "Touch/gesture events configuration. Default: current platform.", "typeRef": "Emulation.SetEmitTouchEventsForMouseRequestConfiguration" }], [], "");
    inspectorBackend.registerCommand("Emulation.setEmulatedMedia", [{ "name": "media", "type": "string", "optional": true, "description": "Media type to emulate. Empty string disables the override.", "typeRef": null }, { "name": "features", "type": "array", "optional": true, "description": "Media features to emulate.", "typeRef": "Emulation.MediaFeature" }], [], "Emulates the given media type or media feature for CSS media queries.");
    inspectorBackend.registerEnum("Emulation.SetEmulatedVisionDeficiencyRequestType", { None: "none", BlurredVision: "blurredVision", ReducedContrast: "reducedContrast", Achromatopsia: "achromatopsia", Deuteranopia: "deuteranopia", Protanopia: "protanopia", Tritanopia: "tritanopia" });
    inspectorBackend.registerCommand("Emulation.setEmulatedVisionDeficiency", [{ "name": "type", "type": "string", "optional": false, "description": "Vision deficiency to emulate. Order: best-effort emulations come first, followed by any physiologically accurate emulations for medically recognized color vision deficiencies.", "typeRef": "Emulation.SetEmulatedVisionDeficiencyRequestType" }], [], "Emulates the given vision deficiency.");
    inspectorBackend.registerCommand("Emulation.setEmulatedOSTextScale", [{ "name": "scale", "type": "number", "optional": true, "description": "", "typeRef": null }], [], "Emulates the given OS text scale.");
    inspectorBackend.registerCommand("Emulation.setGeolocationOverride", [{ "name": "latitude", "type": "number", "optional": true, "description": "Mock latitude", "typeRef": null }, { "name": "longitude", "type": "number", "optional": true, "description": "Mock longitude", "typeRef": null }, { "name": "accuracy", "type": "number", "optional": true, "description": "Mock accuracy", "typeRef": null }, { "name": "altitude", "type": "number", "optional": true, "description": "Mock altitude", "typeRef": null }, { "name": "altitudeAccuracy", "type": "number", "optional": true, "description": "Mock altitudeAccuracy", "typeRef": null }, { "name": "heading", "type": "number", "optional": true, "description": "Mock heading", "typeRef": null }, { "name": "speed", "type": "number", "optional": true, "description": "Mock speed", "typeRef": null }], [], "Overrides the Geolocation Position or Error. Omitting latitude, longitude or accuracy emulates position unavailable.");
    inspectorBackend.registerCommand("Emulation.getOverriddenSensorInformation", [{ "name": "type", "type": "string", "optional": false, "description": "", "typeRef": "Emulation.SensorType" }], ["requestedSamplingFrequency"], "");
    inspectorBackend.registerCommand("Emulation.setSensorOverrideEnabled", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "", "typeRef": "Emulation.SensorType" }, { "name": "metadata", "type": "object", "optional": true, "description": "", "typeRef": "Emulation.SensorMetadata" }], [], "Overrides a platform sensor of a given type. If |enabled| is true, calls to Sensor.start() will use a virtual sensor as backend rather than fetching data from a real hardware sensor. Otherwise, existing virtual sensor-backend Sensor objects will fire an error event and new calls to Sensor.start() will attempt to use a real sensor instead.");
    inspectorBackend.registerCommand("Emulation.setSensorOverrideReadings", [{ "name": "type", "type": "string", "optional": false, "description": "", "typeRef": "Emulation.SensorType" }, { "name": "reading", "type": "object", "optional": false, "description": "", "typeRef": "Emulation.SensorReading" }], [], "Updates the sensor readings reported by a sensor type previously overridden by setSensorOverrideEnabled.");
    inspectorBackend.registerCommand("Emulation.setPressureSourceOverrideEnabled", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "source", "type": "string", "optional": false, "description": "", "typeRef": "Emulation.PressureSource" }, { "name": "metadata", "type": "object", "optional": true, "description": "", "typeRef": "Emulation.PressureMetadata" }], [], "Overrides a pressure source of a given type, as used by the Compute Pressure API, so that updates to PressureObserver.observe() are provided via setPressureStateOverride instead of being retrieved from platform-provided telemetry data.");
    inspectorBackend.registerCommand("Emulation.setPressureStateOverride", [{ "name": "source", "type": "string", "optional": false, "description": "", "typeRef": "Emulation.PressureSource" }, { "name": "state", "type": "string", "optional": false, "description": "", "typeRef": "Emulation.PressureState" }], [], "TODO: OBSOLETE: To remove when setPressureDataOverride is merged. Provides a given pressure state that will be processed and eventually be delivered to PressureObserver users. |source| must have been previously overridden by setPressureSourceOverrideEnabled.");
    inspectorBackend.registerCommand("Emulation.setPressureDataOverride", [{ "name": "source", "type": "string", "optional": false, "description": "", "typeRef": "Emulation.PressureSource" }, { "name": "state", "type": "string", "optional": false, "description": "", "typeRef": "Emulation.PressureState" }, { "name": "ownContributionEstimate", "type": "number", "optional": true, "description": "", "typeRef": null }], [], "Provides a given pressure data set that will be processed and eventually be delivered to PressureObserver users. |source| must have been previously overridden by setPressureSourceOverrideEnabled.");
    inspectorBackend.registerCommand("Emulation.setIdleOverride", [{ "name": "isUserActive", "type": "boolean", "optional": false, "description": "Mock isUserActive", "typeRef": null }, { "name": "isScreenUnlocked", "type": "boolean", "optional": false, "description": "Mock isScreenUnlocked", "typeRef": null }], [], "Overrides the Idle state.");
    inspectorBackend.registerCommand("Emulation.clearIdleOverride", [], [], "Clears Idle state overrides.");
    inspectorBackend.registerCommand("Emulation.setNavigatorOverrides", [{ "name": "platform", "type": "string", "optional": false, "description": "The platform navigator.platform should return.", "typeRef": null }], [], "Overrides value returned by the javascript navigator object.");
    inspectorBackend.registerCommand("Emulation.setPageScaleFactor", [{ "name": "pageScaleFactor", "type": "number", "optional": false, "description": "Page scale factor.", "typeRef": null }], [], "Sets a specified page scale factor.");
    inspectorBackend.registerCommand("Emulation.setScriptExecutionDisabled", [{ "name": "value", "type": "boolean", "optional": false, "description": "Whether script execution should be disabled in the page.", "typeRef": null }], [], "Switches script execution in the page.");
    inspectorBackend.registerCommand("Emulation.setTouchEmulationEnabled", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "Whether the touch event emulation should be enabled.", "typeRef": null }, { "name": "maxTouchPoints", "type": "number", "optional": true, "description": "Maximum touch points supported. Defaults to one.", "typeRef": null }], [], "Enables touch on platforms which do not support them.");
    inspectorBackend.registerCommand("Emulation.setVirtualTimePolicy", [{ "name": "policy", "type": "string", "optional": false, "description": "", "typeRef": "Emulation.VirtualTimePolicy" }, { "name": "budget", "type": "number", "optional": true, "description": "If set, after this many virtual milliseconds have elapsed virtual time will be paused and a virtualTimeBudgetExpired event is sent.", "typeRef": null }, { "name": "maxVirtualTimeTaskStarvationCount", "type": "number", "optional": true, "description": "If set this specifies the maximum number of tasks that can be run before virtual is forced forwards to prevent deadlock.", "typeRef": null }, { "name": "initialVirtualTime", "type": "number", "optional": true, "description": "If set, base::Time::Now will be overridden to initially return this value.", "typeRef": "Network.TimeSinceEpoch" }], ["virtualTimeTicksBase"], "Turns on virtual time for all frames (replacing real-time with a synthetic time source) and sets the current virtual time policy.  Note this supersedes any previous time budget.");
    inspectorBackend.registerCommand("Emulation.setLocaleOverride", [{ "name": "locale", "type": "string", "optional": true, "description": "ICU style C locale (e.g. \\\"en_US\\\"). If not specified or empty, disables the override and restores default host system locale.", "typeRef": null }], [], "Overrides default host system locale with the specified one.");
    inspectorBackend.registerCommand("Emulation.setTimezoneOverride", [{ "name": "timezoneId", "type": "string", "optional": false, "description": "The timezone identifier. List of supported timezones: https://source.chromium.org/chromium/chromium/deps/icu.git/+/faee8bc70570192d82d2978a71e2a615788597d1:source/data/misc/metaZones.txt If empty, disables the override and restores default host system timezone.", "typeRef": null }], [], "Overrides default host system timezone with the specified one.");
    inspectorBackend.registerCommand("Emulation.setVisibleSize", [{ "name": "width", "type": "number", "optional": false, "description": "Frame width (DIP).", "typeRef": null }, { "name": "height", "type": "number", "optional": false, "description": "Frame height (DIP).", "typeRef": null }], [], "Resizes the frame/viewport of the page. Note that this does not affect the frame's container (e.g. browser window). Can be used to produce screenshots of the specified size. Not supported on Android.");
    inspectorBackend.registerCommand("Emulation.setDisabledImageTypes", [{ "name": "imageTypes", "type": "array", "optional": false, "description": "Image types to disable.", "typeRef": "Emulation.DisabledImageType" }], [], "");
    inspectorBackend.registerCommand("Emulation.setDataSaverOverride", [{ "name": "dataSaverEnabled", "type": "boolean", "optional": true, "description": "Override value. Omitting the parameter disables the override.", "typeRef": null }], [], "Override the value of navigator.connection.saveData");
    inspectorBackend.registerCommand("Emulation.setHardwareConcurrencyOverride", [{ "name": "hardwareConcurrency", "type": "number", "optional": false, "description": "Hardware concurrency to report", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("Emulation.setUserAgentOverride", [{ "name": "userAgent", "type": "string", "optional": false, "description": "User agent to use.", "typeRef": null }, { "name": "acceptLanguage", "type": "string", "optional": true, "description": "Browser language to emulate.", "typeRef": null }, { "name": "platform", "type": "string", "optional": true, "description": "The platform navigator.platform should return.", "typeRef": null }, { "name": "userAgentMetadata", "type": "object", "optional": true, "description": "To be sent in Sec-CH-UA-* headers and returned in navigator.userAgentData", "typeRef": "Emulation.UserAgentMetadata" }], [], "Allows overriding user agent with the given string. `userAgentMetadata` must be set for Client Hint headers to be sent.");
    inspectorBackend.registerCommand("Emulation.setAutomationOverride", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "Whether the override should be enabled.", "typeRef": null }], [], "Allows overriding the automation flag.");
    inspectorBackend.registerCommand("Emulation.setSmallViewportHeightDifferenceOverride", [{ "name": "difference", "type": "number", "optional": false, "description": "This will cause an element of size 100svh to be `difference` pixels smaller than an element of size 100lvh.", "typeRef": null }], [], "Allows overriding the difference between the small and large viewport sizes, which determine the value of the `svh` and `lvh` unit, respectively. Only supported for top-level frames.");
    inspectorBackend.registerCommand("Emulation.getScreenInfos", [], ["screenInfos"], "Returns device's screen configuration. In headful mode, the physical screens configuration is returned, whereas in headless mode, a virtual headless screen configuration is provided instead.");
    inspectorBackend.registerCommand("Emulation.addScreen", [{ "name": "left", "type": "number", "optional": false, "description": "Offset of the left edge of the screen in pixels.", "typeRef": null }, { "name": "top", "type": "number", "optional": false, "description": "Offset of the top edge of the screen in pixels.", "typeRef": null }, { "name": "width", "type": "number", "optional": false, "description": "The width of the screen in pixels.", "typeRef": null }, { "name": "height", "type": "number", "optional": false, "description": "The height of the screen in pixels.", "typeRef": null }, { "name": "workAreaInsets", "type": "object", "optional": true, "description": "Specifies the screen's work area. Default is entire screen.", "typeRef": "Emulation.WorkAreaInsets" }, { "name": "devicePixelRatio", "type": "number", "optional": true, "description": "Specifies the screen's device pixel ratio. Default is 1.", "typeRef": null }, { "name": "rotation", "type": "number", "optional": true, "description": "Specifies the screen's rotation angle. Available values are 0, 90, 180 and 270. Default is 0.", "typeRef": null }, { "name": "colorDepth", "type": "number", "optional": true, "description": "Specifies the screen's color depth in bits. Default is 24.", "typeRef": null }, { "name": "label", "type": "string", "optional": true, "description": "Specifies the descriptive label for the screen. Default is none.", "typeRef": null }, { "name": "isInternal", "type": "boolean", "optional": true, "description": "Indicates whether the screen is internal to the device or external, attached to the device. Default is false.", "typeRef": null }], ["screenInfo"], "Add a new screen to the device. Only supported in headless mode.");
    inspectorBackend.registerCommand("Emulation.removeScreen", [{ "name": "screenId", "type": "string", "optional": false, "description": "", "typeRef": "Emulation.ScreenId" }], [], "Remove screen from the device. Only supported in headless mode.");
    inspectorBackend.registerCommand("Emulation.setPrimaryScreen", [{ "name": "screenId", "type": "string", "optional": false, "description": "", "typeRef": "Emulation.ScreenId" }], [], "Set primary screen. Only supported in headless mode. Note that this changes the coordinate system origin to the top-left of the new primary screen, updating the bounds and work areas of all existing screens accordingly.");
    inspectorBackend.registerType("Emulation.SafeAreaInsets", [{ "name": "top", "type": "number", "optional": true, "description": "Overrides safe-area-inset-top.", "typeRef": null }, { "name": "topMax", "type": "number", "optional": true, "description": "Overrides safe-area-max-inset-top.", "typeRef": null }, { "name": "left", "type": "number", "optional": true, "description": "Overrides safe-area-inset-left.", "typeRef": null }, { "name": "leftMax", "type": "number", "optional": true, "description": "Overrides safe-area-max-inset-left.", "typeRef": null }, { "name": "bottom", "type": "number", "optional": true, "description": "Overrides safe-area-inset-bottom.", "typeRef": null }, { "name": "bottomMax", "type": "number", "optional": true, "description": "Overrides safe-area-max-inset-bottom.", "typeRef": null }, { "name": "right", "type": "number", "optional": true, "description": "Overrides safe-area-inset-right.", "typeRef": null }, { "name": "rightMax", "type": "number", "optional": true, "description": "Overrides safe-area-max-inset-right.", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.ScreenOrientation", [{ "name": "type", "type": "string", "optional": false, "description": "Orientation type.", "typeRef": null }, { "name": "angle", "type": "number", "optional": false, "description": "Orientation angle.", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.DisplayFeature", [{ "name": "orientation", "type": "string", "optional": false, "description": "Orientation of a display feature in relation to screen", "typeRef": null }, { "name": "offset", "type": "number", "optional": false, "description": "The offset from the screen origin in either the x (for vertical orientation) or y (for horizontal orientation) direction.", "typeRef": null }, { "name": "maskLength", "type": "number", "optional": false, "description": "A display feature may mask content such that it is not physically displayed - this length along with the offset describes this area. A display feature that only splits content will have a 0 mask_length.", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.DevicePosture", [{ "name": "type", "type": "string", "optional": false, "description": "Current posture of the device", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.MediaFeature", [{ "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.UserAgentBrandVersion", [{ "name": "brand", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "version", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.UserAgentMetadata", [{ "name": "brands", "type": "array", "optional": true, "description": "Brands appearing in Sec-CH-UA.", "typeRef": "Emulation.UserAgentBrandVersion" }, { "name": "fullVersionList", "type": "array", "optional": true, "description": "Brands appearing in Sec-CH-UA-Full-Version-List.", "typeRef": "Emulation.UserAgentBrandVersion" }, { "name": "fullVersion", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "platform", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "platformVersion", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "architecture", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "model", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "mobile", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "bitness", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "wow64", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "formFactors", "type": "array", "optional": true, "description": "Used to specify User Agent form-factor values. See https://wicg.github.io/ua-client-hints/#sec-ch-ua-form-factors", "typeRef": "string" }]);
    inspectorBackend.registerType("Emulation.SensorMetadata", [{ "name": "available", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "minimumFrequency", "type": "number", "optional": true, "description": "", "typeRef": null }, { "name": "maximumFrequency", "type": "number", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.SensorReadingSingle", [{ "name": "value", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.SensorReadingXYZ", [{ "name": "x", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "z", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.SensorReadingQuaternion", [{ "name": "x", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "z", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "w", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.SensorReading", [{ "name": "single", "type": "object", "optional": true, "description": "", "typeRef": "Emulation.SensorReadingSingle" }, { "name": "xyz", "type": "object", "optional": true, "description": "", "typeRef": "Emulation.SensorReadingXYZ" }, { "name": "quaternion", "type": "object", "optional": true, "description": "", "typeRef": "Emulation.SensorReadingQuaternion" }]);
    inspectorBackend.registerType("Emulation.PressureMetadata", [{ "name": "available", "type": "boolean", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.WorkAreaInsets", [{ "name": "top", "type": "number", "optional": true, "description": "Work area top inset in pixels. Default is 0;", "typeRef": null }, { "name": "left", "type": "number", "optional": true, "description": "Work area left inset in pixels. Default is 0;", "typeRef": null }, { "name": "bottom", "type": "number", "optional": true, "description": "Work area bottom inset in pixels. Default is 0;", "typeRef": null }, { "name": "right", "type": "number", "optional": true, "description": "Work area right inset in pixels. Default is 0;", "typeRef": null }]);
    inspectorBackend.registerType("Emulation.ScreenInfo", [{ "name": "left", "type": "number", "optional": false, "description": "Offset of the left edge of the screen.", "typeRef": null }, { "name": "top", "type": "number", "optional": false, "description": "Offset of the top edge of the screen.", "typeRef": null }, { "name": "width", "type": "number", "optional": false, "description": "Width of the screen.", "typeRef": null }, { "name": "height", "type": "number", "optional": false, "description": "Height of the screen.", "typeRef": null }, { "name": "availLeft", "type": "number", "optional": false, "description": "Offset of the left edge of the available screen area.", "typeRef": null }, { "name": "availTop", "type": "number", "optional": false, "description": "Offset of the top edge of the available screen area.", "typeRef": null }, { "name": "availWidth", "type": "number", "optional": false, "description": "Width of the available screen area.", "typeRef": null }, { "name": "availHeight", "type": "number", "optional": false, "description": "Height of the available screen area.", "typeRef": null }, { "name": "devicePixelRatio", "type": "number", "optional": false, "description": "Specifies the screen's device pixel ratio.", "typeRef": null }, { "name": "orientation", "type": "object", "optional": false, "description": "Specifies the screen's orientation.", "typeRef": "Emulation.ScreenOrientation" }, { "name": "colorDepth", "type": "number", "optional": false, "description": "Specifies the screen's color depth in bits.", "typeRef": null }, { "name": "isExtended", "type": "boolean", "optional": false, "description": "Indicates whether the device has multiple screens.", "typeRef": null }, { "name": "isInternal", "type": "boolean", "optional": false, "description": "Indicates whether the screen is internal to the device or external, attached to the device.", "typeRef": null }, { "name": "isPrimary", "type": "boolean", "optional": false, "description": "Indicates whether the screen is set as the the operating system primary screen.", "typeRef": null }, { "name": "label", "type": "string", "optional": false, "description": "Specifies the descriptive label for the screen.", "typeRef": null }, { "name": "id", "type": "string", "optional": false, "description": "Specifies the unique identifier of the screen.", "typeRef": "Emulation.ScreenId" }]);
    inspectorBackend.registerCommand("EventBreakpoints.setInstrumentationBreakpoint", [{ "name": "eventName", "type": "string", "optional": false, "description": "Instrumentation name to stop on.", "typeRef": null }], [], "Sets breakpoint on particular native event.");
    inspectorBackend.registerCommand("EventBreakpoints.removeInstrumentationBreakpoint", [{ "name": "eventName", "type": "string", "optional": false, "description": "Instrumentation name to stop on.", "typeRef": null }], [], "Removes breakpoint on particular native event.");
    inspectorBackend.registerCommand("EventBreakpoints.disable", [], [], "Removes all breakpoints");
    inspectorBackend.registerEnum("Extensions.StorageArea", { Session: "session", Local: "local", Sync: "sync", Managed: "managed" });
    inspectorBackend.registerCommand("Extensions.triggerAction", [{ "name": "id", "type": "string", "optional": false, "description": "Extension id.", "typeRef": null }, { "name": "targetId", "type": "string", "optional": false, "description": "A tab target ID to trigger the default extension action on.", "typeRef": null }], [], "Runs an extension default action. Available if the client is connected using the --remote-debugging-pipe flag and the --enable-unsafe-extension-debugging flag is set.");
    inspectorBackend.registerCommand("Extensions.loadUnpacked", [{ "name": "path", "type": "string", "optional": false, "description": "Absolute file path.", "typeRef": null }, { "name": "enableInIncognito", "type": "boolean", "optional": true, "description": "Enable the extension in incognito", "typeRef": null }], ["id"], "Installs an unpacked extension from the filesystem similar to --load-extension CLI flags. Returns extension ID once the extension has been installed. Available if the client is connected using the --remote-debugging-pipe flag and the --enable-unsafe-extension-debugging flag is set.");
    inspectorBackend.registerCommand("Extensions.getExtensions", [], ["extensions"], "Gets a list of all unpacked extensions. Available if the client is connected using the --remote-debugging-pipe flag and the --enable-unsafe-extension-debugging flag is set.");
    inspectorBackend.registerCommand("Extensions.uninstall", [{ "name": "id", "type": "string", "optional": false, "description": "Extension id.", "typeRef": null }], [], "Uninstalls an unpacked extension (others not supported) from the profile. Available if the client is connected using the --remote-debugging-pipe flag and the --enable-unsafe-extension-debugging.");
    inspectorBackend.registerCommand("Extensions.getStorageItems", [{ "name": "id", "type": "string", "optional": false, "description": "ID of extension.", "typeRef": null }, { "name": "storageArea", "type": "string", "optional": false, "description": "StorageArea to retrieve data from.", "typeRef": "Extensions.StorageArea" }, { "name": "keys", "type": "array", "optional": true, "description": "Keys to retrieve.", "typeRef": "string" }], ["data"], "Gets data from extension storage in the given `storageArea`. If `keys` is specified, these are used to filter the result.");
    inspectorBackend.registerCommand("Extensions.removeStorageItems", [{ "name": "id", "type": "string", "optional": false, "description": "ID of extension.", "typeRef": null }, { "name": "storageArea", "type": "string", "optional": false, "description": "StorageArea to remove data from.", "typeRef": "Extensions.StorageArea" }, { "name": "keys", "type": "array", "optional": false, "description": "Keys to remove.", "typeRef": "string" }], [], "Removes `keys` from extension storage in the given `storageArea`.");
    inspectorBackend.registerCommand("Extensions.clearStorageItems", [{ "name": "id", "type": "string", "optional": false, "description": "ID of extension.", "typeRef": null }, { "name": "storageArea", "type": "string", "optional": false, "description": "StorageArea to remove data from.", "typeRef": "Extensions.StorageArea" }], [], "Clears extension storage in the given `storageArea`.");
    inspectorBackend.registerCommand("Extensions.setStorageItems", [{ "name": "id", "type": "string", "optional": false, "description": "ID of extension.", "typeRef": null }, { "name": "storageArea", "type": "string", "optional": false, "description": "StorageArea to set data in.", "typeRef": "Extensions.StorageArea" }, { "name": "values", "type": "object", "optional": false, "description": "Values to set.", "typeRef": null }], [], "Sets `values` in extension storage in the given `storageArea`. The provided `values` will be merged with existing values in the storage area.");
    inspectorBackend.registerType("Extensions.ExtensionInfo", [{ "name": "id", "type": "string", "optional": false, "description": "Extension id.", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "Extension name.", "typeRef": null }, { "name": "version", "type": "string", "optional": false, "description": "Extension version.", "typeRef": null }, { "name": "path", "type": "string", "optional": false, "description": "The path from which the extension was loaded.", "typeRef": null }, { "name": "enabled", "type": "boolean", "optional": false, "description": "Extension enabled status.", "typeRef": null }]);
    inspectorBackend.registerEnum("FedCm.LoginState", { SignIn: "SignIn", SignUp: "SignUp" });
    inspectorBackend.registerEnum("FedCm.DialogType", { AccountChooser: "AccountChooser", AutoReauthn: "AutoReauthn", ConfirmIdpLogin: "ConfirmIdpLogin", Error: "Error" });
    inspectorBackend.registerEnum("FedCm.DialogButton", { ConfirmIdpLoginContinue: "ConfirmIdpLoginContinue", ErrorGotIt: "ErrorGotIt", ErrorMoreDetails: "ErrorMoreDetails" });
    inspectorBackend.registerEnum("FedCm.AccountUrlType", { TermsOfService: "TermsOfService", PrivacyPolicy: "PrivacyPolicy" });
    inspectorBackend.registerEvent("FedCm.dialogShown", ["dialogId", "dialogType", "accounts", "title", "subtitle"]);
    inspectorBackend.registerEvent("FedCm.dialogClosed", ["dialogId"]);
    inspectorBackend.registerCommand("FedCm.enable", [{ "name": "disableRejectionDelay", "type": "boolean", "optional": true, "description": "Allows callers to disable the promise rejection delay that would normally happen, if this is unimportant to what's being tested. (step 4 of https://fedidcg.github.io/FedCM/#browser-api-rp-sign-in)", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("FedCm.disable", [], [], "");
    inspectorBackend.registerCommand("FedCm.selectAccount", [{ "name": "dialogId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "accountIndex", "type": "number", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("FedCm.clickDialogButton", [{ "name": "dialogId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "dialogButton", "type": "string", "optional": false, "description": "", "typeRef": "FedCm.DialogButton" }], [], "");
    inspectorBackend.registerCommand("FedCm.openUrl", [{ "name": "dialogId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "accountIndex", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "accountUrlType", "type": "string", "optional": false, "description": "", "typeRef": "FedCm.AccountUrlType" }], [], "");
    inspectorBackend.registerCommand("FedCm.dismissDialog", [{ "name": "dialogId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "triggerCooldown", "type": "boolean", "optional": true, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("FedCm.resetCooldown", [], [], "Resets the cooldown time, if any, to allow the next FedCM call to show a dialog even if one was recently dismissed by the user.");
    inspectorBackend.registerType("FedCm.Account", [{ "name": "accountId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "email", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "givenName", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "pictureUrl", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "idpConfigUrl", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "idpLoginUrl", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "loginState", "type": "string", "optional": false, "description": "", "typeRef": "FedCm.LoginState" }, { "name": "termsOfServiceUrl", "type": "string", "optional": true, "description": "These two are only set if the loginState is signUp", "typeRef": null }, { "name": "privacyPolicyUrl", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerEnum("Fetch.RequestStage", { Request: "Request", Response: "Response" });
    inspectorBackend.registerEnum("Fetch.AuthChallengeSource", { Server: "Server", Proxy: "Proxy" });
    inspectorBackend.registerEnum("Fetch.AuthChallengeResponseResponse", { Default: "Default", CancelAuth: "CancelAuth", ProvideCredentials: "ProvideCredentials" });
    inspectorBackend.registerEvent("Fetch.requestPaused", ["requestId", "request", "frameId", "resourceType", "responseErrorReason", "responseStatusCode", "responseStatusText", "responseHeaders", "networkId", "redirectedRequestId"]);
    inspectorBackend.registerEvent("Fetch.authRequired", ["requestId", "request", "frameId", "resourceType", "authChallenge"]);
    inspectorBackend.registerCommand("Fetch.disable", [], [], "Disables the fetch domain.");
    inspectorBackend.registerCommand("Fetch.enable", [{ "name": "patterns", "type": "array", "optional": true, "description": "If specified, only requests matching any of these patterns will produce fetchRequested event and will be paused until clients response. If not set, all requests will be affected.", "typeRef": "Fetch.RequestPattern" }, { "name": "handleAuthRequests", "type": "boolean", "optional": true, "description": "If true, authRequired events will be issued and requests will be paused expecting a call to continueWithAuth.", "typeRef": null }], [], "Enables issuing of requestPaused events. A request will be paused until client calls one of failRequest, fulfillRequest or continueRequest/continueWithAuth.");
    inspectorBackend.registerCommand("Fetch.failRequest", [{ "name": "requestId", "type": "string", "optional": false, "description": "An id the client received in requestPaused event.", "typeRef": "Fetch.RequestId" }, { "name": "errorReason", "type": "string", "optional": false, "description": "Causes the request to fail with the given reason.", "typeRef": "Network.ErrorReason" }], [], "Causes the request to fail with specified reason.");
    inspectorBackend.registerCommand("Fetch.fulfillRequest", [{ "name": "requestId", "type": "string", "optional": false, "description": "An id the client received in requestPaused event.", "typeRef": "Fetch.RequestId" }, { "name": "responseCode", "type": "number", "optional": false, "description": "An HTTP response code.", "typeRef": null }, { "name": "responseHeaders", "type": "array", "optional": true, "description": "Response headers.", "typeRef": "Fetch.HeaderEntry" }, { "name": "binaryResponseHeaders", "type": "string", "optional": true, "description": "Alternative way of specifying response headers as a \\0-separated series of name: value pairs. Prefer the above method unless you need to represent some non-UTF8 values that can't be transmitted over the protocol as text.", "typeRef": null }, { "name": "body", "type": "string", "optional": true, "description": "A response body. If absent, original response body will be used if the request is intercepted at the response stage and empty body will be used if the request is intercepted at the request stage.", "typeRef": null }, { "name": "responsePhrase", "type": "string", "optional": true, "description": "A textual representation of responseCode. If absent, a standard phrase matching responseCode is used.", "typeRef": null }], [], "Provides response to the request.");
    inspectorBackend.registerCommand("Fetch.continueRequest", [{ "name": "requestId", "type": "string", "optional": false, "description": "An id the client received in requestPaused event.", "typeRef": "Fetch.RequestId" }, { "name": "url", "type": "string", "optional": true, "description": "If set, the request url will be modified in a way that's not observable by page.", "typeRef": null }, { "name": "method", "type": "string", "optional": true, "description": "If set, the request method is overridden.", "typeRef": null }, { "name": "postData", "type": "string", "optional": true, "description": "If set, overrides the post data in the request.", "typeRef": null }, { "name": "headers", "type": "array", "optional": true, "description": "If set, overrides the request headers. Note that the overrides do not extend to subsequent redirect hops, if a redirect happens. Another override may be applied to a different request produced by a redirect.", "typeRef": "Fetch.HeaderEntry" }, { "name": "interceptResponse", "type": "boolean", "optional": true, "description": "If set, overrides response interception behavior for this request.", "typeRef": null }], [], "Continues the request, optionally modifying some of its parameters.");
    inspectorBackend.registerCommand("Fetch.continueWithAuth", [{ "name": "requestId", "type": "string", "optional": false, "description": "An id the client received in authRequired event.", "typeRef": "Fetch.RequestId" }, { "name": "authChallengeResponse", "type": "object", "optional": false, "description": "Response to  with an authChallenge.", "typeRef": "Fetch.AuthChallengeResponse" }], [], "Continues a request supplying authChallengeResponse following authRequired event.");
    inspectorBackend.registerCommand("Fetch.continueResponse", [{ "name": "requestId", "type": "string", "optional": false, "description": "An id the client received in requestPaused event.", "typeRef": "Fetch.RequestId" }, { "name": "responseCode", "type": "number", "optional": true, "description": "An HTTP response code. If absent, original response code will be used.", "typeRef": null }, { "name": "responsePhrase", "type": "string", "optional": true, "description": "A textual representation of responseCode. If absent, a standard phrase matching responseCode is used.", "typeRef": null }, { "name": "responseHeaders", "type": "array", "optional": true, "description": "Response headers. If absent, original response headers will be used.", "typeRef": "Fetch.HeaderEntry" }, { "name": "binaryResponseHeaders", "type": "string", "optional": true, "description": "Alternative way of specifying response headers as a \\0-separated series of name: value pairs. Prefer the above method unless you need to represent some non-UTF8 values that can't be transmitted over the protocol as text.", "typeRef": null }], [], "Continues loading of the paused response, optionally modifying the response headers. If either responseCode or headers are modified, all of them must be present.");
    inspectorBackend.registerCommand("Fetch.getResponseBody", [{ "name": "requestId", "type": "string", "optional": false, "description": "Identifier for the intercepted request to get body for.", "typeRef": "Fetch.RequestId" }], ["body", "base64Encoded"], "Causes the body of the response to be received from the server and returned as a single string. May only be issued for a request that is paused in the Response stage and is mutually exclusive with takeResponseBodyForInterceptionAsStream. Calling other methods that affect the request or disabling fetch domain before body is received results in an undefined behavior. Note that the response body is not available for redirects. Requests paused in the _redirect received_ state may be differentiated by `responseCode` and presence of `location` response header, see comments to `requestPaused` for details.");
    inspectorBackend.registerCommand("Fetch.takeResponseBodyAsStream", [{ "name": "requestId", "type": "string", "optional": false, "description": "", "typeRef": "Fetch.RequestId" }], ["stream"], "Returns a handle to the stream representing the response body. The request must be paused in the HeadersReceived stage. Note that after this command the request can't be continued as is -- client either needs to cancel it or to provide the response body. The stream only supports sequential read, IO.read will fail if the position is specified. This method is mutually exclusive with getResponseBody. Calling other methods that affect the request or disabling fetch domain before body is received results in an undefined behavior.");
    inspectorBackend.registerType("Fetch.RequestPattern", [{ "name": "urlPattern", "type": "string", "optional": true, "description": "Wildcards (`'*'` -> zero or more, `'?'` -> exactly one) are allowed. Escape character is backslash. Omitting is equivalent to `\\\"*\\\"`.", "typeRef": null }, { "name": "resourceType", "type": "string", "optional": true, "description": "If set, only requests for matching resource types will be intercepted.", "typeRef": "Network.ResourceType" }, { "name": "requestStage", "type": "string", "optional": true, "description": "Stage at which to begin intercepting requests. Default is Request.", "typeRef": "Fetch.RequestStage" }]);
    inspectorBackend.registerType("Fetch.HeaderEntry", [{ "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Fetch.AuthChallenge", [{ "name": "source", "type": "string", "optional": true, "description": "Source of the authentication challenge.", "typeRef": null }, { "name": "origin", "type": "string", "optional": false, "description": "Origin of the challenger.", "typeRef": null }, { "name": "scheme", "type": "string", "optional": false, "description": "The authentication scheme used, such as basic or digest", "typeRef": null }, { "name": "realm", "type": "string", "optional": false, "description": "The realm of the challenge. May be empty.", "typeRef": null }]);
    inspectorBackend.registerType("Fetch.AuthChallengeResponse", [{ "name": "response", "type": "string", "optional": false, "description": "The decision on what to do in response to the authorization challenge.  Default means deferring to the default behavior of the net stack, which will likely either the Cancel authentication or display a popup dialog box.", "typeRef": null }, { "name": "username", "type": "string", "optional": true, "description": "The username to provide, possibly empty. Should only be set if response is ProvideCredentials.", "typeRef": null }, { "name": "password", "type": "string", "optional": true, "description": "The password to provide, possibly empty. Should only be set if response is ProvideCredentials.", "typeRef": null }]);
    inspectorBackend.registerCommand("FileSystem.getDirectory", [{ "name": "bucketFileSystemLocator", "type": "object", "optional": false, "description": "", "typeRef": "FileSystem.BucketFileSystemLocator" }], ["directory"], "");
    inspectorBackend.registerType("FileSystem.File", [{ "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "lastModified", "type": "number", "optional": false, "description": "Timestamp", "typeRef": "Network.TimeSinceEpoch" }, { "name": "size", "type": "number", "optional": false, "description": "Size in bytes", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("FileSystem.Directory", [{ "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "nestedDirectories", "type": "array", "optional": false, "description": "", "typeRef": "string" }, { "name": "nestedFiles", "type": "array", "optional": false, "description": "Files that are directly nested under this directory.", "typeRef": "FileSystem.File" }]);
    inspectorBackend.registerType("FileSystem.BucketFileSystemLocator", [{ "name": "storageKey", "type": "string", "optional": false, "description": "Storage key", "typeRef": "Storage.SerializedStorageKey" }, { "name": "bucketName", "type": "string", "optional": true, "description": "Bucket name. Not passing a `bucketName` will retrieve the default Bucket. (https://developer.mozilla.org/en-US/docs/Web/API/Storage_API#storage_buckets)", "typeRef": null }, { "name": "pathComponents", "type": "array", "optional": false, "description": "Path to the directory using each path component as an array item.", "typeRef": "string" }]);
    inspectorBackend.registerEnum("HeadlessExperimental.ScreenshotParamsFormat", { Jpeg: "jpeg", Png: "png", Webp: "webp" });
    inspectorBackend.registerCommand("HeadlessExperimental.beginFrame", [{ "name": "frameTimeTicks", "type": "number", "optional": true, "description": "Timestamp of this BeginFrame in Renderer TimeTicks (milliseconds of uptime). If not set, the current time will be used.", "typeRef": null }, { "name": "interval", "type": "number", "optional": true, "description": "The interval between BeginFrames that is reported to the compositor, in milliseconds. Defaults to a 60 frames/second interval, i.e. about 16.666 milliseconds.", "typeRef": null }, { "name": "noDisplayUpdates", "type": "boolean", "optional": true, "description": "Whether updates should not be committed and drawn onto the display. False by default. If true, only side effects of the BeginFrame will be run, such as layout and animations, but any visual updates may not be visible on the display or in screenshots.", "typeRef": null }, { "name": "screenshot", "type": "object", "optional": true, "description": "If set, a screenshot of the frame will be captured and returned in the response. Otherwise, no screenshot will be captured. Note that capturing a screenshot can fail, for example, during renderer initialization. In such a case, no screenshot data will be returned.", "typeRef": "HeadlessExperimental.ScreenshotParams" }], ["hasDamage", "screenshotData"], "Sends a BeginFrame to the target and returns when the frame was completed. Optionally captures a screenshot from the resulting frame. Requires that the target was created with enabled BeginFrameControl. Designed for use with --run-all-compositor-stages-before-draw, see also https://goo.gle/chrome-headless-rendering for more background.");
    inspectorBackend.registerCommand("HeadlessExperimental.disable", [], [], "Disables headless events for the target.");
    inspectorBackend.registerCommand("HeadlessExperimental.enable", [], [], "Enables headless events for the target.");
    inspectorBackend.registerType("HeadlessExperimental.ScreenshotParams", [{ "name": "format", "type": "string", "optional": true, "description": "Image compression format (defaults to png).", "typeRef": null }, { "name": "quality", "type": "number", "optional": true, "description": "Compression quality from range [0..100] (jpeg and webp only).", "typeRef": null }, { "name": "optimizeForSpeed", "type": "boolean", "optional": true, "description": "Optimize image encoding for speed, not for resulting size (defaults to false)", "typeRef": null }]);
    inspectorBackend.registerCommand("IO.close", [{ "name": "handle", "type": "string", "optional": false, "description": "Handle of the stream to close.", "typeRef": "IO.StreamHandle" }], [], "Close the stream, discard any temporary backing storage.");
    inspectorBackend.registerCommand("IO.read", [{ "name": "handle", "type": "string", "optional": false, "description": "Handle of the stream to read.", "typeRef": "IO.StreamHandle" }, { "name": "offset", "type": "number", "optional": true, "description": "Seek to the specified offset before reading (if not specified, proceed with offset following the last read). Some types of streams may only support sequential reads.", "typeRef": null }, { "name": "size", "type": "number", "optional": true, "description": "Maximum number of bytes to read (left upon the agent discretion if not specified).", "typeRef": null }], ["base64Encoded", "data", "eof"], "Read a chunk of the stream");
    inspectorBackend.registerCommand("IO.resolveBlob", [{ "name": "objectId", "type": "string", "optional": false, "description": "Object id of a Blob object wrapper.", "typeRef": "Runtime.RemoteObjectId" }], ["uuid"], "Return UUID of Blob object specified by a remote object id.");
    inspectorBackend.registerEnum("IndexedDB.KeyType", { Number: "number", String: "string", Date: "date", Array: "array" });
    inspectorBackend.registerEnum("IndexedDB.KeyPathType", { Null: "null", String: "string", Array: "array" });
    inspectorBackend.registerCommand("IndexedDB.clearObjectStore", [{ "name": "securityOrigin", "type": "string", "optional": true, "description": "At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin.", "typeRef": null }, { "name": "storageKey", "type": "string", "optional": true, "description": "Storage key.", "typeRef": null }, { "name": "storageBucket", "type": "object", "optional": true, "description": "Storage bucket. If not specified, it uses the default bucket.", "typeRef": "Storage.StorageBucket" }, { "name": "databaseName", "type": "string", "optional": false, "description": "Database name.", "typeRef": null }, { "name": "objectStoreName", "type": "string", "optional": false, "description": "Object store name.", "typeRef": null }], [], "Clears all entries from an object store.");
    inspectorBackend.registerCommand("IndexedDB.deleteDatabase", [{ "name": "securityOrigin", "type": "string", "optional": true, "description": "At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin.", "typeRef": null }, { "name": "storageKey", "type": "string", "optional": true, "description": "Storage key.", "typeRef": null }, { "name": "storageBucket", "type": "object", "optional": true, "description": "Storage bucket. If not specified, it uses the default bucket.", "typeRef": "Storage.StorageBucket" }, { "name": "databaseName", "type": "string", "optional": false, "description": "Database name.", "typeRef": null }], [], "Deletes a database.");
    inspectorBackend.registerCommand("IndexedDB.deleteObjectStoreEntries", [{ "name": "securityOrigin", "type": "string", "optional": true, "description": "At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin.", "typeRef": null }, { "name": "storageKey", "type": "string", "optional": true, "description": "Storage key.", "typeRef": null }, { "name": "storageBucket", "type": "object", "optional": true, "description": "Storage bucket. If not specified, it uses the default bucket.", "typeRef": "Storage.StorageBucket" }, { "name": "databaseName", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "objectStoreName", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "keyRange", "type": "object", "optional": false, "description": "Range of entry keys to delete", "typeRef": "IndexedDB.KeyRange" }], [], "Delete a range of entries from an object store");
    inspectorBackend.registerCommand("IndexedDB.disable", [], [], "Disables events from backend.");
    inspectorBackend.registerCommand("IndexedDB.enable", [], [], "Enables events from backend.");
    inspectorBackend.registerCommand("IndexedDB.requestData", [{ "name": "securityOrigin", "type": "string", "optional": true, "description": "At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin.", "typeRef": null }, { "name": "storageKey", "type": "string", "optional": true, "description": "Storage key.", "typeRef": null }, { "name": "storageBucket", "type": "object", "optional": true, "description": "Storage bucket. If not specified, it uses the default bucket.", "typeRef": "Storage.StorageBucket" }, { "name": "databaseName", "type": "string", "optional": false, "description": "Database name.", "typeRef": null }, { "name": "objectStoreName", "type": "string", "optional": false, "description": "Object store name.", "typeRef": null }, { "name": "indexName", "type": "string", "optional": true, "description": "Index name. If not specified, it performs an object store data request.", "typeRef": null }, { "name": "skipCount", "type": "number", "optional": false, "description": "Number of records to skip.", "typeRef": null }, { "name": "pageSize", "type": "number", "optional": false, "description": "Number of records to fetch.", "typeRef": null }, { "name": "keyRange", "type": "object", "optional": true, "description": "Key range.", "typeRef": "IndexedDB.KeyRange" }], ["objectStoreDataEntries", "hasMore"], "Requests data from object store or index.");
    inspectorBackend.registerCommand("IndexedDB.getMetadata", [{ "name": "securityOrigin", "type": "string", "optional": true, "description": "At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin.", "typeRef": null }, { "name": "storageKey", "type": "string", "optional": true, "description": "Storage key.", "typeRef": null }, { "name": "storageBucket", "type": "object", "optional": true, "description": "Storage bucket. If not specified, it uses the default bucket.", "typeRef": "Storage.StorageBucket" }, { "name": "databaseName", "type": "string", "optional": false, "description": "Database name.", "typeRef": null }, { "name": "objectStoreName", "type": "string", "optional": false, "description": "Object store name.", "typeRef": null }], ["entriesCount", "keyGeneratorValue"], "Gets metadata of an object store.");
    inspectorBackend.registerCommand("IndexedDB.requestDatabase", [{ "name": "securityOrigin", "type": "string", "optional": true, "description": "At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin.", "typeRef": null }, { "name": "storageKey", "type": "string", "optional": true, "description": "Storage key.", "typeRef": null }, { "name": "storageBucket", "type": "object", "optional": true, "description": "Storage bucket. If not specified, it uses the default bucket.", "typeRef": "Storage.StorageBucket" }, { "name": "databaseName", "type": "string", "optional": false, "description": "Database name.", "typeRef": null }], ["databaseWithObjectStores"], "Requests database with given name in given frame.");
    inspectorBackend.registerCommand("IndexedDB.requestDatabaseNames", [{ "name": "securityOrigin", "type": "string", "optional": true, "description": "At least and at most one of securityOrigin, storageKey, or storageBucket must be specified. Security origin.", "typeRef": null }, { "name": "storageKey", "type": "string", "optional": true, "description": "Storage key.", "typeRef": null }, { "name": "storageBucket", "type": "object", "optional": true, "description": "Storage bucket. If not specified, it uses the default bucket.", "typeRef": "Storage.StorageBucket" }], ["databaseNames"], "Requests database names for given security origin.");
    inspectorBackend.registerType("IndexedDB.DatabaseWithObjectStores", [{ "name": "name", "type": "string", "optional": false, "description": "Database name.", "typeRef": null }, { "name": "version", "type": "number", "optional": false, "description": "Database version (type is not 'integer', as the standard requires the version number to be 'unsigned long long')", "typeRef": null }, { "name": "objectStores", "type": "array", "optional": false, "description": "Object stores in this database.", "typeRef": "IndexedDB.ObjectStore" }]);
    inspectorBackend.registerType("IndexedDB.ObjectStore", [{ "name": "name", "type": "string", "optional": false, "description": "Object store name.", "typeRef": null }, { "name": "keyPath", "type": "object", "optional": false, "description": "Object store key path.", "typeRef": "IndexedDB.KeyPath" }, { "name": "autoIncrement", "type": "boolean", "optional": false, "description": "If true, object store has auto increment flag set.", "typeRef": null }, { "name": "indexes", "type": "array", "optional": false, "description": "Indexes in this object store.", "typeRef": "IndexedDB.ObjectStoreIndex" }]);
    inspectorBackend.registerType("IndexedDB.ObjectStoreIndex", [{ "name": "name", "type": "string", "optional": false, "description": "Index name.", "typeRef": null }, { "name": "keyPath", "type": "object", "optional": false, "description": "Index key path.", "typeRef": "IndexedDB.KeyPath" }, { "name": "unique", "type": "boolean", "optional": false, "description": "If true, index is unique.", "typeRef": null }, { "name": "multiEntry", "type": "boolean", "optional": false, "description": "If true, index allows multiple entries for a key.", "typeRef": null }]);
    inspectorBackend.registerType("IndexedDB.Key", [{ "name": "type", "type": "string", "optional": false, "description": "Key type.", "typeRef": null }, { "name": "number", "type": "number", "optional": true, "description": "Number value.", "typeRef": null }, { "name": "string", "type": "string", "optional": true, "description": "String value.", "typeRef": null }, { "name": "date", "type": "number", "optional": true, "description": "Date value.", "typeRef": null }, { "name": "array", "type": "array", "optional": true, "description": "Array value.", "typeRef": "IndexedDB.Key" }]);
    inspectorBackend.registerType("IndexedDB.KeyRange", [{ "name": "lower", "type": "object", "optional": true, "description": "Lower bound.", "typeRef": "IndexedDB.Key" }, { "name": "upper", "type": "object", "optional": true, "description": "Upper bound.", "typeRef": "IndexedDB.Key" }, { "name": "lowerOpen", "type": "boolean", "optional": false, "description": "If true lower bound is open.", "typeRef": null }, { "name": "upperOpen", "type": "boolean", "optional": false, "description": "If true upper bound is open.", "typeRef": null }]);
    inspectorBackend.registerType("IndexedDB.DataEntry", [{ "name": "key", "type": "object", "optional": false, "description": "Key object.", "typeRef": "Runtime.RemoteObject" }, { "name": "primaryKey", "type": "object", "optional": false, "description": "Primary key object.", "typeRef": "Runtime.RemoteObject" }, { "name": "value", "type": "object", "optional": false, "description": "Value object.", "typeRef": "Runtime.RemoteObject" }]);
    inspectorBackend.registerType("IndexedDB.KeyPath", [{ "name": "type", "type": "string", "optional": false, "description": "Key path type.", "typeRef": null }, { "name": "string", "type": "string", "optional": true, "description": "String value.", "typeRef": null }, { "name": "array", "type": "array", "optional": true, "description": "Array value.", "typeRef": "string" }]);
    inspectorBackend.registerEnum("Input.GestureSourceType", { Default: "default", Touch: "touch", Mouse: "mouse" });
    inspectorBackend.registerEnum("Input.MouseButton", { None: "none", Left: "left", Middle: "middle", Right: "right", Back: "back", Forward: "forward" });
    inspectorBackend.registerEvent("Input.dragIntercepted", ["data"]);
    inspectorBackend.registerEnum("Input.DispatchDragEventRequestType", { DragEnter: "dragEnter", DragOver: "dragOver", Drop: "drop", DragCancel: "dragCancel" });
    inspectorBackend.registerCommand("Input.dispatchDragEvent", [{ "name": "type", "type": "string", "optional": false, "description": "Type of the drag event.", "typeRef": "Input.DispatchDragEventRequestType" }, { "name": "x", "type": "number", "optional": false, "description": "X coordinate of the event relative to the main frame's viewport in CSS pixels.", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport.", "typeRef": null }, { "name": "data", "type": "object", "optional": false, "description": "", "typeRef": "Input.DragData" }, { "name": "modifiers", "type": "number", "optional": true, "description": "Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0).", "typeRef": null }], [], "Dispatches a drag event into the page.");
    inspectorBackend.registerEnum("Input.DispatchKeyEventRequestType", { KeyDown: "keyDown", KeyUp: "keyUp", RawKeyDown: "rawKeyDown", Char: "char" });
    inspectorBackend.registerCommand("Input.dispatchKeyEvent", [{ "name": "type", "type": "string", "optional": false, "description": "Type of the key event.", "typeRef": "Input.DispatchKeyEventRequestType" }, { "name": "modifiers", "type": "number", "optional": true, "description": "Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0).", "typeRef": null }, { "name": "timestamp", "type": "number", "optional": true, "description": "Time at which the event occurred.", "typeRef": "Input.TimeSinceEpoch" }, { "name": "text", "type": "string", "optional": true, "description": "Text as generated by processing a virtual key code with a keyboard layout. Not needed for for `keyUp` and `rawKeyDown` events (default: \\\"\\\")", "typeRef": null }, { "name": "unmodifiedText", "type": "string", "optional": true, "description": "Text that would have been generated by the keyboard if no modifiers were pressed (except for shift). Useful for shortcut (accelerator) key handling (default: \\\"\\\").", "typeRef": null }, { "name": "keyIdentifier", "type": "string", "optional": true, "description": "Unique key identifier (e.g., 'U+0041') (default: \\\"\\\").", "typeRef": null }, { "name": "code", "type": "string", "optional": true, "description": "Unique DOM defined string value for each physical key (e.g., 'KeyA') (default: \\\"\\\").", "typeRef": null }, { "name": "key", "type": "string", "optional": true, "description": "Unique DOM defined string value describing the meaning of the key in the context of active modifiers, keyboard layout, etc (e.g., 'AltGr') (default: \\\"\\\").", "typeRef": null }, { "name": "windowsVirtualKeyCode", "type": "number", "optional": true, "description": "Windows virtual key code (default: 0).", "typeRef": null }, { "name": "nativeVirtualKeyCode", "type": "number", "optional": true, "description": "Native virtual key code (default: 0).", "typeRef": null }, { "name": "autoRepeat", "type": "boolean", "optional": true, "description": "Whether the event was generated from auto repeat (default: false).", "typeRef": null }, { "name": "isKeypad", "type": "boolean", "optional": true, "description": "Whether the event was generated from the keypad (default: false).", "typeRef": null }, { "name": "isSystemKey", "type": "boolean", "optional": true, "description": "Whether the event was a system key event (default: false).", "typeRef": null }, { "name": "location", "type": "number", "optional": true, "description": "Whether the event was from the left or right side of the keyboard. 1=Left, 2=Right (default: 0).", "typeRef": null }, { "name": "commands", "type": "array", "optional": true, "description": "Editing commands to send with the key event (e.g., 'selectAll') (default: []). These are related to but not equal the command names used in `document.execCommand` and NSStandardKeyBindingResponding. See https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/commands/editor_command_names.h for valid command names.", "typeRef": "string" }], [], "Dispatches a key event to the page.");
    inspectorBackend.registerCommand("Input.insertText", [{ "name": "text", "type": "string", "optional": false, "description": "The text to insert.", "typeRef": null }], [], "This method emulates inserting text that doesn't come from a key press, for example an emoji keyboard or an IME.");
    inspectorBackend.registerCommand("Input.imeSetComposition", [{ "name": "text", "type": "string", "optional": false, "description": "The text to insert", "typeRef": null }, { "name": "selectionStart", "type": "number", "optional": false, "description": "selection start", "typeRef": null }, { "name": "selectionEnd", "type": "number", "optional": false, "description": "selection end", "typeRef": null }, { "name": "replacementStart", "type": "number", "optional": true, "description": "replacement start", "typeRef": null }, { "name": "replacementEnd", "type": "number", "optional": true, "description": "replacement end", "typeRef": null }], [], "This method sets the current candidate text for IME. Use imeCommitComposition to commit the final text. Use imeSetComposition with empty string as text to cancel composition.");
    inspectorBackend.registerEnum("Input.DispatchMouseEventRequestType", { MousePressed: "mousePressed", MouseReleased: "mouseReleased", MouseMoved: "mouseMoved", MouseWheel: "mouseWheel" });
    inspectorBackend.registerEnum("Input.DispatchMouseEventRequestPointerType", { Mouse: "mouse", Pen: "pen" });
    inspectorBackend.registerCommand("Input.dispatchMouseEvent", [{ "name": "type", "type": "string", "optional": false, "description": "Type of the mouse event.", "typeRef": "Input.DispatchMouseEventRequestType" }, { "name": "x", "type": "number", "optional": false, "description": "X coordinate of the event relative to the main frame's viewport in CSS pixels.", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport.", "typeRef": null }, { "name": "modifiers", "type": "number", "optional": true, "description": "Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0).", "typeRef": null }, { "name": "timestamp", "type": "number", "optional": true, "description": "Time at which the event occurred.", "typeRef": "Input.TimeSinceEpoch" }, { "name": "button", "type": "string", "optional": true, "description": "Mouse button (default: \\\"none\\\").", "typeRef": "Input.MouseButton" }, { "name": "buttons", "type": "number", "optional": true, "description": "A number indicating which buttons are pressed on the mouse when a mouse event is triggered. Left=1, Right=2, Middle=4, Back=8, Forward=16, None=0.", "typeRef": null }, { "name": "clickCount", "type": "number", "optional": true, "description": "Number of times the mouse button was clicked (default: 0).", "typeRef": null }, { "name": "force", "type": "number", "optional": true, "description": "The normalized pressure, which has a range of [0,1] (default: 0).", "typeRef": null }, { "name": "tangentialPressure", "type": "number", "optional": true, "description": "The normalized tangential pressure, which has a range of [-1,1] (default: 0).", "typeRef": null }, { "name": "tiltX", "type": "number", "optional": true, "description": "The plane angle between the Y-Z plane and the plane containing both the stylus axis and the Y axis, in degrees of the range [-90,90], a positive tiltX is to the right (default: 0).", "typeRef": null }, { "name": "tiltY", "type": "number", "optional": true, "description": "The plane angle between the X-Z plane and the plane containing both the stylus axis and the X axis, in degrees of the range [-90,90], a positive tiltY is towards the user (default: 0).", "typeRef": null }, { "name": "twist", "type": "number", "optional": true, "description": "The clockwise rotation of a pen stylus around its own major axis, in degrees in the range [0,359] (default: 0).", "typeRef": null }, { "name": "deltaX", "type": "number", "optional": true, "description": "X delta in CSS pixels for mouse wheel event (default: 0).", "typeRef": null }, { "name": "deltaY", "type": "number", "optional": true, "description": "Y delta in CSS pixels for mouse wheel event (default: 0).", "typeRef": null }, { "name": "pointerType", "type": "string", "optional": true, "description": "Pointer type (default: \\\"mouse\\\").", "typeRef": "Input.DispatchMouseEventRequestPointerType" }], [], "Dispatches a mouse event to the page.");
    inspectorBackend.registerEnum("Input.DispatchTouchEventRequestType", { TouchStart: "touchStart", TouchEnd: "touchEnd", TouchMove: "touchMove", TouchCancel: "touchCancel" });
    inspectorBackend.registerCommand("Input.dispatchTouchEvent", [{ "name": "type", "type": "string", "optional": false, "description": "Type of the touch event. TouchEnd and TouchCancel must not contain any touch points, while TouchStart and TouchMove must contains at least one.", "typeRef": "Input.DispatchTouchEventRequestType" }, { "name": "touchPoints", "type": "array", "optional": false, "description": "Active touch points on the touch device. One event per any changed point (compared to previous touch event in a sequence) is generated, emulating pressing/moving/releasing points one by one.", "typeRef": "Input.TouchPoint" }, { "name": "modifiers", "type": "number", "optional": true, "description": "Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0).", "typeRef": null }, { "name": "timestamp", "type": "number", "optional": true, "description": "Time at which the event occurred.", "typeRef": "Input.TimeSinceEpoch" }], [], "Dispatches a touch event to the page.");
    inspectorBackend.registerCommand("Input.cancelDragging", [], [], "Cancels any active dragging in the page.");
    inspectorBackend.registerEnum("Input.EmulateTouchFromMouseEventRequestType", { MousePressed: "mousePressed", MouseReleased: "mouseReleased", MouseMoved: "mouseMoved", MouseWheel: "mouseWheel" });
    inspectorBackend.registerCommand("Input.emulateTouchFromMouseEvent", [{ "name": "type", "type": "string", "optional": false, "description": "Type of the mouse event.", "typeRef": "Input.EmulateTouchFromMouseEventRequestType" }, { "name": "x", "type": "number", "optional": false, "description": "X coordinate of the mouse pointer in DIP.", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Y coordinate of the mouse pointer in DIP.", "typeRef": null }, { "name": "button", "type": "string", "optional": false, "description": "Mouse button. Only \\\"none\\\", \\\"left\\\", \\\"right\\\" are supported.", "typeRef": "Input.MouseButton" }, { "name": "timestamp", "type": "number", "optional": true, "description": "Time at which the event occurred (default: current time).", "typeRef": "Input.TimeSinceEpoch" }, { "name": "deltaX", "type": "number", "optional": true, "description": "X delta in DIP for mouse wheel event (default: 0).", "typeRef": null }, { "name": "deltaY", "type": "number", "optional": true, "description": "Y delta in DIP for mouse wheel event (default: 0).", "typeRef": null }, { "name": "modifiers", "type": "number", "optional": true, "description": "Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0).", "typeRef": null }, { "name": "clickCount", "type": "number", "optional": true, "description": "Number of times the mouse button was clicked (default: 0).", "typeRef": null }], [], "Emulates touch event from the mouse event parameters.");
    inspectorBackend.registerCommand("Input.setIgnoreInputEvents", [{ "name": "ignore", "type": "boolean", "optional": false, "description": "Ignores input events processing when set to true.", "typeRef": null }], [], "Ignores input events (useful while auditing page).");
    inspectorBackend.registerCommand("Input.setInterceptDrags", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "Prevents default drag and drop behavior and instead emits `Input.dragIntercepted` events. Drag and drop behavior can be directly controlled via `Input.dispatchDragEvent`.");
    inspectorBackend.registerCommand("Input.synthesizePinchGesture", [{ "name": "x", "type": "number", "optional": false, "description": "X coordinate of the start of the gesture in CSS pixels.", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Y coordinate of the start of the gesture in CSS pixels.", "typeRef": null }, { "name": "scaleFactor", "type": "number", "optional": false, "description": "Relative scale factor after zooming (>1.0 zooms in, <1.0 zooms out).", "typeRef": null }, { "name": "relativeSpeed", "type": "number", "optional": true, "description": "Relative pointer speed in pixels per second (default: 800).", "typeRef": null }, { "name": "gestureSourceType", "type": "string", "optional": true, "description": "Which type of input events to be generated (default: 'default', which queries the platform for the preferred input type).", "typeRef": "Input.GestureSourceType" }], [], "Synthesizes a pinch gesture over a time period by issuing appropriate touch events.");
    inspectorBackend.registerCommand("Input.synthesizeScrollGesture", [{ "name": "x", "type": "number", "optional": false, "description": "X coordinate of the start of the gesture in CSS pixels.", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Y coordinate of the start of the gesture in CSS pixels.", "typeRef": null }, { "name": "xDistance", "type": "number", "optional": true, "description": "The distance to scroll along the X axis (positive to scroll left).", "typeRef": null }, { "name": "yDistance", "type": "number", "optional": true, "description": "The distance to scroll along the Y axis (positive to scroll up).", "typeRef": null }, { "name": "xOverscroll", "type": "number", "optional": true, "description": "The number of additional pixels to scroll back along the X axis, in addition to the given distance.", "typeRef": null }, { "name": "yOverscroll", "type": "number", "optional": true, "description": "The number of additional pixels to scroll back along the Y axis, in addition to the given distance.", "typeRef": null }, { "name": "preventFling", "type": "boolean", "optional": true, "description": "Prevent fling (default: true).", "typeRef": null }, { "name": "speed", "type": "number", "optional": true, "description": "Swipe speed in pixels per second (default: 800).", "typeRef": null }, { "name": "gestureSourceType", "type": "string", "optional": true, "description": "Which type of input events to be generated (default: 'default', which queries the platform for the preferred input type).", "typeRef": "Input.GestureSourceType" }, { "name": "repeatCount", "type": "number", "optional": true, "description": "The number of times to repeat the gesture (default: 0).", "typeRef": null }, { "name": "repeatDelayMs", "type": "number", "optional": true, "description": "The number of milliseconds delay between each repeat. (default: 250).", "typeRef": null }, { "name": "interactionMarkerName", "type": "string", "optional": true, "description": "The name of the interaction markers to generate, if not empty (default: \\\"\\\").", "typeRef": null }], [], "Synthesizes a scroll gesture over a time period by issuing appropriate touch events.");
    inspectorBackend.registerCommand("Input.synthesizeTapGesture", [{ "name": "x", "type": "number", "optional": false, "description": "X coordinate of the start of the gesture in CSS pixels.", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Y coordinate of the start of the gesture in CSS pixels.", "typeRef": null }, { "name": "duration", "type": "number", "optional": true, "description": "Duration between touchdown and touchup events in ms (default: 50).", "typeRef": null }, { "name": "tapCount", "type": "number", "optional": true, "description": "Number of times to perform the tap (e.g. 2 for double tap, default: 1).", "typeRef": null }, { "name": "gestureSourceType", "type": "string", "optional": true, "description": "Which type of input events to be generated (default: 'default', which queries the platform for the preferred input type).", "typeRef": "Input.GestureSourceType" }], [], "Synthesizes a tap gesture over a time period by issuing appropriate touch events.");
    inspectorBackend.registerType("Input.TouchPoint", [{ "name": "x", "type": "number", "optional": false, "description": "X coordinate of the event relative to the main frame's viewport in CSS pixels.", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport.", "typeRef": null }, { "name": "radiusX", "type": "number", "optional": true, "description": "X radius of the touch area (default: 1.0).", "typeRef": null }, { "name": "radiusY", "type": "number", "optional": true, "description": "Y radius of the touch area (default: 1.0).", "typeRef": null }, { "name": "rotationAngle", "type": "number", "optional": true, "description": "Rotation angle (default: 0.0).", "typeRef": null }, { "name": "force", "type": "number", "optional": true, "description": "Force (default: 1.0).", "typeRef": null }, { "name": "tangentialPressure", "type": "number", "optional": true, "description": "The normalized tangential pressure, which has a range of [-1,1] (default: 0).", "typeRef": null }, { "name": "tiltX", "type": "number", "optional": true, "description": "The plane angle between the Y-Z plane and the plane containing both the stylus axis and the Y axis, in degrees of the range [-90,90], a positive tiltX is to the right (default: 0)", "typeRef": null }, { "name": "tiltY", "type": "number", "optional": true, "description": "The plane angle between the X-Z plane and the plane containing both the stylus axis and the X axis, in degrees of the range [-90,90], a positive tiltY is towards the user (default: 0).", "typeRef": null }, { "name": "twist", "type": "number", "optional": true, "description": "The clockwise rotation of a pen stylus around its own major axis, in degrees in the range [0,359] (default: 0).", "typeRef": null }, { "name": "id", "type": "number", "optional": true, "description": "Identifier used to track touch sources between events, must be unique within an event.", "typeRef": null }]);
    inspectorBackend.registerType("Input.DragDataItem", [{ "name": "mimeType", "type": "string", "optional": false, "description": "Mime type of the dragged data.", "typeRef": null }, { "name": "data", "type": "string", "optional": false, "description": "Depending of the value of `mimeType`, it contains the dragged link, text, HTML markup or any other data.", "typeRef": null }, { "name": "title", "type": "string", "optional": true, "description": "Title associated with a link. Only valid when `mimeType` == \\\"text/uri-list\\\".", "typeRef": null }, { "name": "baseURL", "type": "string", "optional": true, "description": "Stores the base URL for the contained markup. Only valid when `mimeType` == \\\"text/html\\\".", "typeRef": null }]);
    inspectorBackend.registerType("Input.DragData", [{ "name": "items", "type": "array", "optional": false, "description": "", "typeRef": "Input.DragDataItem" }, { "name": "files", "type": "array", "optional": true, "description": "List of filenames that should be included when dropping", "typeRef": "string" }, { "name": "dragOperationsMask", "type": "number", "optional": false, "description": "Bit field representing allowed drag operations. Copy = 1, Link = 2, Move = 16", "typeRef": null }]);
    inspectorBackend.registerEvent("Inspector.detached", ["reason"]);
    inspectorBackend.registerEvent("Inspector.targetCrashed", []);
    inspectorBackend.registerEvent("Inspector.targetReloadedAfterCrash", []);
    inspectorBackend.registerEvent("Inspector.workerScriptLoaded", []);
    inspectorBackend.registerCommand("Inspector.disable", [], [], "Disables inspector domain notifications.");
    inspectorBackend.registerCommand("Inspector.enable", [], [], "Enables inspector domain notifications.");
    inspectorBackend.registerEnum("LayerTree.ScrollRectType", { RepaintsOnScroll: "RepaintsOnScroll", TouchEventHandler: "TouchEventHandler", WheelEventHandler: "WheelEventHandler" });
    inspectorBackend.registerEvent("LayerTree.layerPainted", ["layerId", "clip"]);
    inspectorBackend.registerEvent("LayerTree.layerTreeDidChange", ["layers"]);
    inspectorBackend.registerCommand("LayerTree.compositingReasons", [{ "name": "layerId", "type": "string", "optional": false, "description": "The id of the layer for which we want to get the reasons it was composited.", "typeRef": "LayerTree.LayerId" }], ["compositingReasons", "compositingReasonIds"], "Provides the reasons why the given layer was composited.");
    inspectorBackend.registerCommand("LayerTree.disable", [], [], "Disables compositing tree inspection.");
    inspectorBackend.registerCommand("LayerTree.enable", [], [], "Enables compositing tree inspection.");
    inspectorBackend.registerCommand("LayerTree.loadSnapshot", [{ "name": "tiles", "type": "array", "optional": false, "description": "An array of tiles composing the snapshot.", "typeRef": "LayerTree.PictureTile" }], ["snapshotId"], "Returns the snapshot identifier.");
    inspectorBackend.registerCommand("LayerTree.makeSnapshot", [{ "name": "layerId", "type": "string", "optional": false, "description": "The id of the layer.", "typeRef": "LayerTree.LayerId" }], ["snapshotId"], "Returns the layer snapshot identifier.");
    inspectorBackend.registerCommand("LayerTree.profileSnapshot", [{ "name": "snapshotId", "type": "string", "optional": false, "description": "The id of the layer snapshot.", "typeRef": "LayerTree.SnapshotId" }, { "name": "minRepeatCount", "type": "number", "optional": true, "description": "The maximum number of times to replay the snapshot (1, if not specified).", "typeRef": null }, { "name": "minDuration", "type": "number", "optional": true, "description": "The minimum duration (in seconds) to replay the snapshot.", "typeRef": null }, { "name": "clipRect", "type": "object", "optional": true, "description": "The clip rectangle to apply when replaying the snapshot.", "typeRef": "DOM.Rect" }], ["timings"], "");
    inspectorBackend.registerCommand("LayerTree.releaseSnapshot", [{ "name": "snapshotId", "type": "string", "optional": false, "description": "The id of the layer snapshot.", "typeRef": "LayerTree.SnapshotId" }], [], "Releases layer snapshot captured by the back-end.");
    inspectorBackend.registerCommand("LayerTree.replaySnapshot", [{ "name": "snapshotId", "type": "string", "optional": false, "description": "The id of the layer snapshot.", "typeRef": "LayerTree.SnapshotId" }, { "name": "fromStep", "type": "number", "optional": true, "description": "The first step to replay from (replay from the very start if not specified).", "typeRef": null }, { "name": "toStep", "type": "number", "optional": true, "description": "The last step to replay to (replay till the end if not specified).", "typeRef": null }, { "name": "scale", "type": "number", "optional": true, "description": "The scale to apply while replaying (defaults to 1).", "typeRef": null }], ["dataURL"], "Replays the layer snapshot and returns the resulting bitmap.");
    inspectorBackend.registerCommand("LayerTree.snapshotCommandLog", [{ "name": "snapshotId", "type": "string", "optional": false, "description": "The id of the layer snapshot.", "typeRef": "LayerTree.SnapshotId" }], ["commandLog"], "Replays the layer snapshot and returns canvas log.");
    inspectorBackend.registerType("LayerTree.ScrollRect", [{ "name": "rect", "type": "object", "optional": false, "description": "Rectangle itself.", "typeRef": "DOM.Rect" }, { "name": "type", "type": "string", "optional": false, "description": "Reason for rectangle to force scrolling on the main thread", "typeRef": null }]);
    inspectorBackend.registerType("LayerTree.StickyPositionConstraint", [{ "name": "stickyBoxRect", "type": "object", "optional": false, "description": "Layout rectangle of the sticky element before being shifted", "typeRef": "DOM.Rect" }, { "name": "containingBlockRect", "type": "object", "optional": false, "description": "Layout rectangle of the containing block of the sticky element", "typeRef": "DOM.Rect" }, { "name": "nearestLayerShiftingStickyBox", "type": "string", "optional": true, "description": "The nearest sticky layer that shifts the sticky box", "typeRef": "LayerTree.LayerId" }, { "name": "nearestLayerShiftingContainingBlock", "type": "string", "optional": true, "description": "The nearest sticky layer that shifts the containing block", "typeRef": "LayerTree.LayerId" }]);
    inspectorBackend.registerType("LayerTree.PictureTile", [{ "name": "x", "type": "number", "optional": false, "description": "Offset from owning layer left boundary", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Offset from owning layer top boundary", "typeRef": null }, { "name": "picture", "type": "string", "optional": false, "description": "Base64-encoded snapshot data.", "typeRef": null }]);
    inspectorBackend.registerType("LayerTree.Layer", [{ "name": "layerId", "type": "string", "optional": false, "description": "The unique id for this layer.", "typeRef": "LayerTree.LayerId" }, { "name": "parentLayerId", "type": "string", "optional": true, "description": "The id of parent (not present for root).", "typeRef": "LayerTree.LayerId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "The backend id for the node associated with this layer.", "typeRef": "DOM.BackendNodeId" }, { "name": "offsetX", "type": "number", "optional": false, "description": "Offset from parent layer, X coordinate.", "typeRef": null }, { "name": "offsetY", "type": "number", "optional": false, "description": "Offset from parent layer, Y coordinate.", "typeRef": null }, { "name": "width", "type": "number", "optional": false, "description": "Layer width.", "typeRef": null }, { "name": "height", "type": "number", "optional": false, "description": "Layer height.", "typeRef": null }, { "name": "transform", "type": "array", "optional": true, "description": "Transformation matrix for layer, default is identity matrix", "typeRef": "number" }, { "name": "anchorX", "type": "number", "optional": true, "description": "Transform anchor point X, absent if no transform specified", "typeRef": null }, { "name": "anchorY", "type": "number", "optional": true, "description": "Transform anchor point Y, absent if no transform specified", "typeRef": null }, { "name": "anchorZ", "type": "number", "optional": true, "description": "Transform anchor point Z, absent if no transform specified", "typeRef": null }, { "name": "paintCount", "type": "number", "optional": false, "description": "Indicates how many time this layer has painted.", "typeRef": null }, { "name": "drawsContent", "type": "boolean", "optional": false, "description": "Indicates whether this layer hosts any content, rather than being used for transform/scrolling purposes only.", "typeRef": null }, { "name": "invisible", "type": "boolean", "optional": true, "description": "Set if layer is not visible.", "typeRef": null }, { "name": "scrollRects", "type": "array", "optional": true, "description": "Rectangles scrolling on main thread only.", "typeRef": "LayerTree.ScrollRect" }, { "name": "stickyPositionConstraint", "type": "object", "optional": true, "description": "Sticky position constraint information", "typeRef": "LayerTree.StickyPositionConstraint" }]);
    inspectorBackend.registerType("LayerTree.PaintProfile", [{ "name": "PaintProfile", "type": "array", "optional": false, "description": "Array of timings, one per paint step.", "typeRef": "number" }]);
    inspectorBackend.registerEnum("Log.LogEntrySource", { XML: "xml", Javascript: "javascript", Network: "network", Storage: "storage", Appcache: "appcache", Rendering: "rendering", Security: "security", Deprecation: "deprecation", Worker: "worker", Violation: "violation", Intervention: "intervention", Recommendation: "recommendation", Other: "other" });
    inspectorBackend.registerEnum("Log.LogEntryLevel", { Verbose: "verbose", Info: "info", Warning: "warning", Error: "error" });
    inspectorBackend.registerEnum("Log.LogEntryCategory", { Cors: "cors" });
    inspectorBackend.registerEnum("Log.ViolationSettingName", { LongTask: "longTask", LongLayout: "longLayout", BlockedEvent: "blockedEvent", BlockedParser: "blockedParser", DiscouragedAPIUse: "discouragedAPIUse", Handler: "handler", RecurringHandler: "recurringHandler" });
    inspectorBackend.registerEvent("Log.entryAdded", ["entry"]);
    inspectorBackend.registerCommand("Log.clear", [], [], "Clears the log.");
    inspectorBackend.registerCommand("Log.disable", [], [], "Disables log domain, prevents further log entries from being reported to the client.");
    inspectorBackend.registerCommand("Log.enable", [], [], "Enables log domain, sends the entries collected so far to the client by means of the `entryAdded` notification.");
    inspectorBackend.registerCommand("Log.startViolationsReport", [{ "name": "config", "type": "array", "optional": false, "description": "Configuration for violations.", "typeRef": "Log.ViolationSetting" }], [], "start violation reporting.");
    inspectorBackend.registerCommand("Log.stopViolationsReport", [], [], "Stop violation reporting.");
    inspectorBackend.registerType("Log.LogEntry", [{ "name": "source", "type": "string", "optional": false, "description": "Log entry source.", "typeRef": null }, { "name": "level", "type": "string", "optional": false, "description": "Log entry severity.", "typeRef": null }, { "name": "text", "type": "string", "optional": false, "description": "Logged text.", "typeRef": null }, { "name": "category", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "timestamp", "type": "number", "optional": false, "description": "Timestamp when this entry was added.", "typeRef": "Runtime.Timestamp" }, { "name": "url", "type": "string", "optional": true, "description": "URL of the resource if known.", "typeRef": null }, { "name": "lineNumber", "type": "number", "optional": true, "description": "Line number in the resource.", "typeRef": null }, { "name": "stackTrace", "type": "object", "optional": true, "description": "JavaScript stack trace.", "typeRef": "Runtime.StackTrace" }, { "name": "networkRequestId", "type": "string", "optional": true, "description": "Identifier of the network request associated with this entry.", "typeRef": "Network.RequestId" }, { "name": "workerId", "type": "string", "optional": true, "description": "Identifier of the worker associated with this entry.", "typeRef": null }, { "name": "args", "type": "array", "optional": true, "description": "Call arguments.", "typeRef": "Runtime.RemoteObject" }]);
    inspectorBackend.registerType("Log.ViolationSetting", [{ "name": "name", "type": "string", "optional": false, "description": "Violation type.", "typeRef": null }, { "name": "threshold", "type": "number", "optional": false, "description": "Time threshold to trigger upon.", "typeRef": null }]);
    inspectorBackend.registerEnum("Media.PlayerMessageLevel", { Error: "error", Warning: "warning", Info: "info", Debug: "debug" });
    inspectorBackend.registerEvent("Media.playerPropertiesChanged", ["playerId", "properties"]);
    inspectorBackend.registerEvent("Media.playerEventsAdded", ["playerId", "events"]);
    inspectorBackend.registerEvent("Media.playerMessagesLogged", ["playerId", "messages"]);
    inspectorBackend.registerEvent("Media.playerErrorsRaised", ["playerId", "errors"]);
    inspectorBackend.registerEvent("Media.playerCreated", ["player"]);
    inspectorBackend.registerCommand("Media.enable", [], [], "Enables the Media domain");
    inspectorBackend.registerCommand("Media.disable", [], [], "Disables the Media domain.");
    inspectorBackend.registerType("Media.PlayerMessage", [{ "name": "level", "type": "string", "optional": false, "description": "Keep in sync with MediaLogMessageLevel We are currently keeping the message level 'error' separate from the PlayerError type because right now they represent different things, this one being a DVLOG(ERROR) style log message that gets printed based on what log level is selected in the UI, and the other is a representation of a media::PipelineStatus object. Soon however we're going to be moving away from using PipelineStatus for errors and introducing a new error type which should hopefully let us integrate the error log level into the PlayerError type.", "typeRef": null }, { "name": "message", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Media.PlayerProperty", [{ "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Media.PlayerEvent", [{ "name": "timestamp", "type": "number", "optional": false, "description": "", "typeRef": "Media.Timestamp" }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Media.PlayerErrorSourceLocation", [{ "name": "file", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "line", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Media.PlayerError", [{ "name": "errorType", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "code", "type": "number", "optional": false, "description": "Code is the numeric enum entry for a specific set of error codes, such as PipelineStatusCodes in media/base/pipeline_status.h", "typeRef": null }, { "name": "stack", "type": "array", "optional": false, "description": "A trace of where this error was caused / where it passed through.", "typeRef": "Media.PlayerErrorSourceLocation" }, { "name": "cause", "type": "array", "optional": false, "description": "Errors potentially have a root cause error, ie, a DecoderError might be caused by an WindowsError", "typeRef": "Media.PlayerError" }, { "name": "data", "type": "object", "optional": false, "description": "Extra data attached to an error, such as an HRESULT, Video Codec, etc.", "typeRef": null }]);
    inspectorBackend.registerType("Media.Player", [{ "name": "playerId", "type": "string", "optional": false, "description": "", "typeRef": "Media.PlayerId" }, { "name": "domNodeId", "type": "number", "optional": true, "description": "", "typeRef": "DOM.BackendNodeId" }]);
    inspectorBackend.registerEnum("Memory.PressureLevel", { Moderate: "moderate", Critical: "critical" });
    inspectorBackend.registerCommand("Memory.getDOMCounters", [], ["documents", "nodes", "jsEventListeners"], "Retruns current DOM object counters.");
    inspectorBackend.registerCommand("Memory.getDOMCountersForLeakDetection", [], ["counters"], "Retruns DOM object counters after preparing renderer for leak detection.");
    inspectorBackend.registerCommand("Memory.prepareForLeakDetection", [], [], "Prepares for leak detection by terminating workers, stopping spellcheckers, dropping non-essential internal caches, running garbage collections, etc.");
    inspectorBackend.registerCommand("Memory.forciblyPurgeJavaScriptMemory", [], [], "Simulate OomIntervention by purging V8 memory.");
    inspectorBackend.registerCommand("Memory.setPressureNotificationsSuppressed", [{ "name": "suppressed", "type": "boolean", "optional": false, "description": "If true, memory pressure notifications will be suppressed.", "typeRef": null }], [], "Enable/disable suppressing memory pressure notifications in all processes.");
    inspectorBackend.registerCommand("Memory.simulatePressureNotification", [{ "name": "level", "type": "string", "optional": false, "description": "Memory pressure level of the notification.", "typeRef": "Memory.PressureLevel" }], [], "Simulate a memory pressure notification in all processes.");
    inspectorBackend.registerCommand("Memory.startSampling", [{ "name": "samplingInterval", "type": "number", "optional": true, "description": "Average number of bytes between samples.", "typeRef": null }, { "name": "suppressRandomness", "type": "boolean", "optional": true, "description": "Do not randomize intervals between samples.", "typeRef": null }], [], "Start collecting native memory profile.");
    inspectorBackend.registerCommand("Memory.stopSampling", [], [], "Stop collecting native memory profile.");
    inspectorBackend.registerCommand("Memory.getAllTimeSamplingProfile", [], ["profile"], "Retrieve native memory allocations profile collected since renderer process startup.");
    inspectorBackend.registerCommand("Memory.getBrowserSamplingProfile", [], ["profile"], "Retrieve native memory allocations profile collected since browser process startup.");
    inspectorBackend.registerCommand("Memory.getSamplingProfile", [], ["profile"], "Retrieve native memory allocations profile collected since last `startSampling` call.");
    inspectorBackend.registerType("Memory.SamplingProfileNode", [{ "name": "size", "type": "number", "optional": false, "description": "Size of the sampled allocation.", "typeRef": null }, { "name": "total", "type": "number", "optional": false, "description": "Total bytes attributed to this sample.", "typeRef": null }, { "name": "stack", "type": "array", "optional": false, "description": "Execution stack at the point of allocation.", "typeRef": "string" }]);
    inspectorBackend.registerType("Memory.SamplingProfile", [{ "name": "samples", "type": "array", "optional": false, "description": "", "typeRef": "Memory.SamplingProfileNode" }, { "name": "modules", "type": "array", "optional": false, "description": "", "typeRef": "Memory.Module" }]);
    inspectorBackend.registerType("Memory.Module", [{ "name": "name", "type": "string", "optional": false, "description": "Name of the module.", "typeRef": null }, { "name": "uuid", "type": "string", "optional": false, "description": "UUID of the module.", "typeRef": null }, { "name": "baseAddress", "type": "string", "optional": false, "description": "Base address where the module is loaded into memory. Encoded as a decimal or hexadecimal (0x prefixed) string.", "typeRef": null }, { "name": "size", "type": "number", "optional": false, "description": "Size of the module in bytes.", "typeRef": null }]);
    inspectorBackend.registerType("Memory.DOMCounter", [{ "name": "name", "type": "string", "optional": false, "description": "Object name. Note: object names should be presumed volatile and clients should not expect the returned names to be consistent across runs.", "typeRef": null }, { "name": "count", "type": "number", "optional": false, "description": "Object count.", "typeRef": null }]);
    inspectorBackend.registerEnum("Network.ResourceType", { Document: "Document", Stylesheet: "Stylesheet", Image: "Image", Media: "Media", Font: "Font", Script: "Script", TextTrack: "TextTrack", XHR: "XHR", Fetch: "Fetch", Prefetch: "Prefetch", EventSource: "EventSource", WebSocket: "WebSocket", Manifest: "Manifest", SignedExchange: "SignedExchange", Ping: "Ping", CSPViolationReport: "CSPViolationReport", Preflight: "Preflight", FedCM: "FedCM", Other: "Other" });
    inspectorBackend.registerEnum("Network.ErrorReason", { Failed: "Failed", Aborted: "Aborted", TimedOut: "TimedOut", AccessDenied: "AccessDenied", ConnectionClosed: "ConnectionClosed", ConnectionReset: "ConnectionReset", ConnectionRefused: "ConnectionRefused", ConnectionAborted: "ConnectionAborted", ConnectionFailed: "ConnectionFailed", NameNotResolved: "NameNotResolved", InternetDisconnected: "InternetDisconnected", AddressUnreachable: "AddressUnreachable", BlockedByClient: "BlockedByClient", BlockedByResponse: "BlockedByResponse" });
    inspectorBackend.registerEnum("Network.ConnectionType", { None: "none", Cellular2g: "cellular2g", Cellular3g: "cellular3g", Cellular4g: "cellular4g", Bluetooth: "bluetooth", Ethernet: "ethernet", Wifi: "wifi", Wimax: "wimax", Other: "other" });
    inspectorBackend.registerEnum("Network.CookieSameSite", { Strict: "Strict", Lax: "Lax", None: "None" });
    inspectorBackend.registerEnum("Network.CookiePriority", { Low: "Low", Medium: "Medium", High: "High" });
    inspectorBackend.registerEnum("Network.CookieSourceScheme", { Unset: "Unset", NonSecure: "NonSecure", Secure: "Secure" });
    inspectorBackend.registerEnum("Network.ResourcePriority", { VeryLow: "VeryLow", Low: "Low", Medium: "Medium", High: "High", VeryHigh: "VeryHigh" });
    inspectorBackend.registerEnum("Network.RenderBlockingBehavior", { Blocking: "Blocking", InBodyParserBlocking: "InBodyParserBlocking", NonBlocking: "NonBlocking", NonBlockingDynamic: "NonBlockingDynamic", PotentiallyBlocking: "PotentiallyBlocking" });
    inspectorBackend.registerEnum("Network.RequestReferrerPolicy", { UnsafeUrl: "unsafe-url", NoReferrerWhenDowngrade: "no-referrer-when-downgrade", NoReferrer: "no-referrer", Origin: "origin", OriginWhenCrossOrigin: "origin-when-cross-origin", SameOrigin: "same-origin", StrictOrigin: "strict-origin", StrictOriginWhenCrossOrigin: "strict-origin-when-cross-origin" });
    inspectorBackend.registerEnum("Network.CertificateTransparencyCompliance", { Unknown: "unknown", NotCompliant: "not-compliant", Compliant: "compliant" });
    inspectorBackend.registerEnum("Network.BlockedReason", { Other: "other", Csp: "csp", MixedContent: "mixed-content", Origin: "origin", Inspector: "inspector", Integrity: "integrity", SubresourceFilter: "subresource-filter", ContentType: "content-type", CoepFrameResourceNeedsCoepHeader: "coep-frame-resource-needs-coep-header", CoopSandboxedIframeCannotNavigateToCoopPage: "coop-sandboxed-iframe-cannot-navigate-to-coop-page", CorpNotSameOrigin: "corp-not-same-origin", CorpNotSameOriginAfterDefaultedToSameOriginByCoep: "corp-not-same-origin-after-defaulted-to-same-origin-by-coep", CorpNotSameOriginAfterDefaultedToSameOriginByDip: "corp-not-same-origin-after-defaulted-to-same-origin-by-dip", CorpNotSameOriginAfterDefaultedToSameOriginByCoepAndDip: "corp-not-same-origin-after-defaulted-to-same-origin-by-coep-and-dip", CorpNotSameSite: "corp-not-same-site", SriMessageSignatureMismatch: "sri-message-signature-mismatch" });
    inspectorBackend.registerEnum("Network.CorsError", { DisallowedByMode: "DisallowedByMode", InvalidResponse: "InvalidResponse", WildcardOriginNotAllowed: "WildcardOriginNotAllowed", MissingAllowOriginHeader: "MissingAllowOriginHeader", MultipleAllowOriginValues: "MultipleAllowOriginValues", InvalidAllowOriginValue: "InvalidAllowOriginValue", AllowOriginMismatch: "AllowOriginMismatch", InvalidAllowCredentials: "InvalidAllowCredentials", CorsDisabledScheme: "CorsDisabledScheme", PreflightInvalidStatus: "PreflightInvalidStatus", PreflightDisallowedRedirect: "PreflightDisallowedRedirect", PreflightWildcardOriginNotAllowed: "PreflightWildcardOriginNotAllowed", PreflightMissingAllowOriginHeader: "PreflightMissingAllowOriginHeader", PreflightMultipleAllowOriginValues: "PreflightMultipleAllowOriginValues", PreflightInvalidAllowOriginValue: "PreflightInvalidAllowOriginValue", PreflightAllowOriginMismatch: "PreflightAllowOriginMismatch", PreflightInvalidAllowCredentials: "PreflightInvalidAllowCredentials", PreflightMissingAllowExternal: "PreflightMissingAllowExternal", PreflightInvalidAllowExternal: "PreflightInvalidAllowExternal", InvalidAllowMethodsPreflightResponse: "InvalidAllowMethodsPreflightResponse", InvalidAllowHeadersPreflightResponse: "InvalidAllowHeadersPreflightResponse", MethodDisallowedByPreflightResponse: "MethodDisallowedByPreflightResponse", HeaderDisallowedByPreflightResponse: "HeaderDisallowedByPreflightResponse", RedirectContainsCredentials: "RedirectContainsCredentials", InsecureLocalNetwork: "InsecureLocalNetwork", InvalidLocalNetworkAccess: "InvalidLocalNetworkAccess", NoCorsRedirectModeNotFollow: "NoCorsRedirectModeNotFollow", LocalNetworkAccessPermissionDenied: "LocalNetworkAccessPermissionDenied" });
    inspectorBackend.registerEnum("Network.ServiceWorkerResponseSource", { CacheStorage: "cache-storage", HttpCache: "http-cache", FallbackCode: "fallback-code", Network: "network" });
    inspectorBackend.registerEnum("Network.TrustTokenParamsRefreshPolicy", { UseCached: "UseCached", Refresh: "Refresh" });
    inspectorBackend.registerEnum("Network.TrustTokenOperationType", { Issuance: "Issuance", Redemption: "Redemption", Signing: "Signing" });
    inspectorBackend.registerEnum("Network.AlternateProtocolUsage", { AlternativeJobWonWithoutRace: "alternativeJobWonWithoutRace", AlternativeJobWonRace: "alternativeJobWonRace", MainJobWonRace: "mainJobWonRace", MappingMissing: "mappingMissing", Broken: "broken", DnsAlpnH3JobWonWithoutRace: "dnsAlpnH3JobWonWithoutRace", DnsAlpnH3JobWonRace: "dnsAlpnH3JobWonRace", UnspecifiedReason: "unspecifiedReason" });
    inspectorBackend.registerEnum("Network.ServiceWorkerRouterSource", { Network: "network", Cache: "cache", FetchEvent: "fetch-event", RaceNetworkAndFetchHandler: "race-network-and-fetch-handler", RaceNetworkAndCache: "race-network-and-cache" });
    inspectorBackend.registerEnum("Network.InitiatorType", { Parser: "parser", Script: "script", Preload: "preload", SignedExchange: "SignedExchange", Preflight: "preflight", FedCM: "FedCM", Other: "other" });
    inspectorBackend.registerEnum("Network.SetCookieBlockedReason", { SecureOnly: "SecureOnly", SameSiteStrict: "SameSiteStrict", SameSiteLax: "SameSiteLax", SameSiteUnspecifiedTreatedAsLax: "SameSiteUnspecifiedTreatedAsLax", SameSiteNoneInsecure: "SameSiteNoneInsecure", UserPreferences: "UserPreferences", ThirdPartyPhaseout: "ThirdPartyPhaseout", ThirdPartyBlockedInFirstPartySet: "ThirdPartyBlockedInFirstPartySet", SyntaxError: "SyntaxError", SchemeNotSupported: "SchemeNotSupported", OverwriteSecure: "OverwriteSecure", InvalidDomain: "InvalidDomain", InvalidPrefix: "InvalidPrefix", UnknownError: "UnknownError", SchemefulSameSiteStrict: "SchemefulSameSiteStrict", SchemefulSameSiteLax: "SchemefulSameSiteLax", SchemefulSameSiteUnspecifiedTreatedAsLax: "SchemefulSameSiteUnspecifiedTreatedAsLax", NameValuePairExceedsMaxSize: "NameValuePairExceedsMaxSize", DisallowedCharacter: "DisallowedCharacter", NoCookieContent: "NoCookieContent" });
    inspectorBackend.registerEnum("Network.CookieBlockedReason", { SecureOnly: "SecureOnly", NotOnPath: "NotOnPath", DomainMismatch: "DomainMismatch", SameSiteStrict: "SameSiteStrict", SameSiteLax: "SameSiteLax", SameSiteUnspecifiedTreatedAsLax: "SameSiteUnspecifiedTreatedAsLax", SameSiteNoneInsecure: "SameSiteNoneInsecure", UserPreferences: "UserPreferences", ThirdPartyPhaseout: "ThirdPartyPhaseout", ThirdPartyBlockedInFirstPartySet: "ThirdPartyBlockedInFirstPartySet", UnknownError: "UnknownError", SchemefulSameSiteStrict: "SchemefulSameSiteStrict", SchemefulSameSiteLax: "SchemefulSameSiteLax", SchemefulSameSiteUnspecifiedTreatedAsLax: "SchemefulSameSiteUnspecifiedTreatedAsLax", NameValuePairExceedsMaxSize: "NameValuePairExceedsMaxSize", PortMismatch: "PortMismatch", SchemeMismatch: "SchemeMismatch", AnonymousContext: "AnonymousContext" });
    inspectorBackend.registerEnum("Network.CookieExemptionReason", { None: "None", UserSetting: "UserSetting", TPCDMetadata: "TPCDMetadata", TPCDDeprecationTrial: "TPCDDeprecationTrial", TopLevelTPCDDeprecationTrial: "TopLevelTPCDDeprecationTrial", TPCDHeuristics: "TPCDHeuristics", EnterprisePolicy: "EnterprisePolicy", StorageAccess: "StorageAccess", TopLevelStorageAccess: "TopLevelStorageAccess", Scheme: "Scheme", SameSiteNoneCookiesInSandbox: "SameSiteNoneCookiesInSandbox" });
    inspectorBackend.registerEnum("Network.AuthChallengeSource", { Server: "Server", Proxy: "Proxy" });
    inspectorBackend.registerEnum("Network.AuthChallengeResponseResponse", { Default: "Default", CancelAuth: "CancelAuth", ProvideCredentials: "ProvideCredentials" });
    inspectorBackend.registerEnum("Network.InterceptionStage", { Request: "Request", HeadersReceived: "HeadersReceived" });
    inspectorBackend.registerEnum("Network.SignedExchangeErrorField", { SignatureSig: "signatureSig", SignatureIntegrity: "signatureIntegrity", SignatureCertUrl: "signatureCertUrl", SignatureCertSha256: "signatureCertSha256", SignatureValidityUrl: "signatureValidityUrl", SignatureTimestamps: "signatureTimestamps" });
    inspectorBackend.registerEnum("Network.ContentEncoding", { Deflate: "deflate", Gzip: "gzip", Br: "br", Zstd: "zstd" });
    inspectorBackend.registerEnum("Network.DirectSocketDnsQueryType", { Ipv4: "ipv4", Ipv6: "ipv6" });
    inspectorBackend.registerEnum("Network.LocalNetworkAccessRequestPolicy", { Allow: "Allow", BlockFromInsecureToMorePrivate: "BlockFromInsecureToMorePrivate", WarnFromInsecureToMorePrivate: "WarnFromInsecureToMorePrivate", PermissionBlock: "PermissionBlock", PermissionWarn: "PermissionWarn" });
    inspectorBackend.registerEnum("Network.IPAddressSpace", { Loopback: "Loopback", Local: "Local", Public: "Public", Unknown: "Unknown" });
    inspectorBackend.registerEnum("Network.CrossOriginOpenerPolicyValue", { SameOrigin: "SameOrigin", SameOriginAllowPopups: "SameOriginAllowPopups", RestrictProperties: "RestrictProperties", UnsafeNone: "UnsafeNone", SameOriginPlusCoep: "SameOriginPlusCoep", RestrictPropertiesPlusCoep: "RestrictPropertiesPlusCoep", NoopenerAllowPopups: "NoopenerAllowPopups" });
    inspectorBackend.registerEnum("Network.CrossOriginEmbedderPolicyValue", { None: "None", Credentialless: "Credentialless", RequireCorp: "RequireCorp" });
    inspectorBackend.registerEnum("Network.ContentSecurityPolicySource", { HTTP: "HTTP", Meta: "Meta" });
    inspectorBackend.registerEnum("Network.ReportStatus", { Queued: "Queued", Pending: "Pending", MarkedForRemoval: "MarkedForRemoval", Success: "Success" });
    inspectorBackend.registerEnum("Network.DeviceBoundSessionWithUsageUsage", { NotInScope: "NotInScope", InScopeRefreshNotYetNeeded: "InScopeRefreshNotYetNeeded", InScopeRefreshNotAllowed: "InScopeRefreshNotAllowed", ProactiveRefreshNotPossible: "ProactiveRefreshNotPossible", ProactiveRefreshAttempted: "ProactiveRefreshAttempted", Deferred: "Deferred" });
    inspectorBackend.registerEnum("Network.DeviceBoundSessionUrlRuleRuleType", { Exclude: "Exclude", Include: "Include" });
    inspectorBackend.registerEnum("Network.DeviceBoundSessionFetchResult", { Success: "Success", KeyError: "KeyError", SigningError: "SigningError", ServerRequestedTermination: "ServerRequestedTermination", InvalidSessionId: "InvalidSessionId", InvalidChallenge: "InvalidChallenge", TooManyChallenges: "TooManyChallenges", InvalidFetcherUrl: "InvalidFetcherUrl", InvalidRefreshUrl: "InvalidRefreshUrl", TransientHttpError: "TransientHttpError", ScopeOriginSameSiteMismatch: "ScopeOriginSameSiteMismatch", RefreshUrlSameSiteMismatch: "RefreshUrlSameSiteMismatch", MismatchedSessionId: "MismatchedSessionId", MissingScope: "MissingScope", NoCredentials: "NoCredentials", SubdomainRegistrationWellKnownUnavailable: "SubdomainRegistrationWellKnownUnavailable", SubdomainRegistrationUnauthorized: "SubdomainRegistrationUnauthorized", SubdomainRegistrationWellKnownMalformed: "SubdomainRegistrationWellKnownMalformed", SessionProviderWellKnownUnavailable: "SessionProviderWellKnownUnavailable", RelyingPartyWellKnownUnavailable: "RelyingPartyWellKnownUnavailable", FederatedKeyThumbprintMismatch: "FederatedKeyThumbprintMismatch", InvalidFederatedSessionUrl: "InvalidFederatedSessionUrl", InvalidFederatedKey: "InvalidFederatedKey", TooManyRelyingOriginLabels: "TooManyRelyingOriginLabels", BoundCookieSetForbidden: "BoundCookieSetForbidden", NetError: "NetError", ProxyError: "ProxyError", EmptySessionConfig: "EmptySessionConfig", InvalidCredentialsConfig: "InvalidCredentialsConfig", InvalidCredentialsType: "InvalidCredentialsType", InvalidCredentialsEmptyName: "InvalidCredentialsEmptyName", InvalidCredentialsCookie: "InvalidCredentialsCookie", PersistentHttpError: "PersistentHttpError", RegistrationAttemptedChallenge: "RegistrationAttemptedChallenge", InvalidScopeOrigin: "InvalidScopeOrigin", ScopeOriginContainsPath: "ScopeOriginContainsPath", RefreshInitiatorNotString: "RefreshInitiatorNotString", RefreshInitiatorInvalidHostPattern: "RefreshInitiatorInvalidHostPattern", InvalidScopeSpecification: "InvalidScopeSpecification", MissingScopeSpecificationType: "MissingScopeSpecificationType", EmptyScopeSpecificationDomain: "EmptyScopeSpecificationDomain", EmptyScopeSpecificationPath: "EmptyScopeSpecificationPath", InvalidScopeSpecificationType: "InvalidScopeSpecificationType", InvalidScopeIncludeSite: "InvalidScopeIncludeSite", MissingScopeIncludeSite: "MissingScopeIncludeSite", FederatedNotAuthorizedByProvider: "FederatedNotAuthorizedByProvider", FederatedNotAuthorizedByRelyingParty: "FederatedNotAuthorizedByRelyingParty", SessionProviderWellKnownMalformed: "SessionProviderWellKnownMalformed", SessionProviderWellKnownHasProviderOrigin: "SessionProviderWellKnownHasProviderOrigin", RelyingPartyWellKnownMalformed: "RelyingPartyWellKnownMalformed", RelyingPartyWellKnownHasRelyingOrigins: "RelyingPartyWellKnownHasRelyingOrigins", InvalidFederatedSessionProviderSessionMissing: "InvalidFederatedSessionProviderSessionMissing", InvalidFederatedSessionWrongProviderOrigin: "InvalidFederatedSessionWrongProviderOrigin", InvalidCredentialsCookieCreationTime: "InvalidCredentialsCookieCreationTime", InvalidCredentialsCookieName: "InvalidCredentialsCookieName", InvalidCredentialsCookieParsing: "InvalidCredentialsCookieParsing", InvalidCredentialsCookieUnpermittedAttribute: "InvalidCredentialsCookieUnpermittedAttribute", InvalidCredentialsCookieInvalidDomain: "InvalidCredentialsCookieInvalidDomain", InvalidCredentialsCookiePrefix: "InvalidCredentialsCookiePrefix", InvalidScopeRulePath: "InvalidScopeRulePath", InvalidScopeRuleHostPattern: "InvalidScopeRuleHostPattern", ScopeRuleOriginScopedHostPatternMismatch: "ScopeRuleOriginScopedHostPatternMismatch", ScopeRuleSiteScopedHostPatternMismatch: "ScopeRuleSiteScopedHostPatternMismatch", SigningQuotaExceeded: "SigningQuotaExceeded", InvalidConfigJson: "InvalidConfigJson", InvalidFederatedSessionProviderFailedToRestoreKey: "InvalidFederatedSessionProviderFailedToRestoreKey", FailedToUnwrapKey: "FailedToUnwrapKey", SessionDeletedDuringRefresh: "SessionDeletedDuringRefresh" });
    inspectorBackend.registerEnum("Network.RefreshEventDetailsRefreshResult", { Refreshed: "Refreshed", InitializedService: "InitializedService", Unreachable: "Unreachable", ServerError: "ServerError", RefreshQuotaExceeded: "RefreshQuotaExceeded", FatalError: "FatalError", SigningQuotaExceeded: "SigningQuotaExceeded" });
    inspectorBackend.registerEnum("Network.TerminationEventDetailsDeletionReason", { Expired: "Expired", FailedToRestoreKey: "FailedToRestoreKey", FailedToUnwrapKey: "FailedToUnwrapKey", StoragePartitionCleared: "StoragePartitionCleared", ClearBrowsingData: "ClearBrowsingData", ServerRequested: "ServerRequested", InvalidSessionParams: "InvalidSessionParams", RefreshFatalError: "RefreshFatalError" });
    inspectorBackend.registerEnum("Network.ChallengeEventDetailsChallengeResult", { Success: "Success", NoSessionId: "NoSessionId", NoSessionMatch: "NoSessionMatch", CantSetBoundCookie: "CantSetBoundCookie" });
    inspectorBackend.registerEvent("Network.dataReceived", ["requestId", "timestamp", "dataLength", "encodedDataLength", "data"]);
    inspectorBackend.registerEvent("Network.eventSourceMessageReceived", ["requestId", "timestamp", "eventName", "eventId", "data"]);
    inspectorBackend.registerEvent("Network.loadingFailed", ["requestId", "timestamp", "type", "errorText", "canceled", "blockedReason", "corsErrorStatus"]);
    inspectorBackend.registerEvent("Network.loadingFinished", ["requestId", "timestamp", "encodedDataLength"]);
    inspectorBackend.registerEvent("Network.requestIntercepted", ["interceptionId", "request", "frameId", "resourceType", "isNavigationRequest", "isDownload", "redirectUrl", "authChallenge", "responseErrorReason", "responseStatusCode", "responseHeaders", "requestId"]);
    inspectorBackend.registerEvent("Network.requestServedFromCache", ["requestId"]);
    inspectorBackend.registerEvent("Network.requestWillBeSent", ["requestId", "loaderId", "documentURL", "request", "timestamp", "wallTime", "initiator", "redirectHasExtraInfo", "redirectResponse", "type", "frameId", "hasUserGesture", "renderBlockingBehavior"]);
    inspectorBackend.registerEvent("Network.resourceChangedPriority", ["requestId", "newPriority", "timestamp"]);
    inspectorBackend.registerEvent("Network.signedExchangeReceived", ["requestId", "info"]);
    inspectorBackend.registerEvent("Network.responseReceived", ["requestId", "loaderId", "timestamp", "type", "response", "hasExtraInfo", "frameId"]);
    inspectorBackend.registerEvent("Network.webSocketClosed", ["requestId", "timestamp"]);
    inspectorBackend.registerEvent("Network.webSocketCreated", ["requestId", "url", "initiator"]);
    inspectorBackend.registerEvent("Network.webSocketFrameError", ["requestId", "timestamp", "errorMessage"]);
    inspectorBackend.registerEvent("Network.webSocketFrameReceived", ["requestId", "timestamp", "response"]);
    inspectorBackend.registerEvent("Network.webSocketFrameSent", ["requestId", "timestamp", "response"]);
    inspectorBackend.registerEvent("Network.webSocketHandshakeResponseReceived", ["requestId", "timestamp", "response"]);
    inspectorBackend.registerEvent("Network.webSocketWillSendHandshakeRequest", ["requestId", "timestamp", "wallTime", "request"]);
    inspectorBackend.registerEvent("Network.webTransportCreated", ["transportId", "url", "timestamp", "initiator"]);
    inspectorBackend.registerEvent("Network.webTransportConnectionEstablished", ["transportId", "timestamp"]);
    inspectorBackend.registerEvent("Network.webTransportClosed", ["transportId", "timestamp"]);
    inspectorBackend.registerEvent("Network.directTCPSocketCreated", ["identifier", "remoteAddr", "remotePort", "options", "timestamp", "initiator"]);
    inspectorBackend.registerEvent("Network.directTCPSocketOpened", ["identifier", "remoteAddr", "remotePort", "timestamp", "localAddr", "localPort"]);
    inspectorBackend.registerEvent("Network.directTCPSocketAborted", ["identifier", "errorMessage", "timestamp"]);
    inspectorBackend.registerEvent("Network.directTCPSocketClosed", ["identifier", "timestamp"]);
    inspectorBackend.registerEvent("Network.directTCPSocketChunkSent", ["identifier", "data", "timestamp"]);
    inspectorBackend.registerEvent("Network.directTCPSocketChunkReceived", ["identifier", "data", "timestamp"]);
    inspectorBackend.registerEvent("Network.directUDPSocketJoinedMulticastGroup", ["identifier", "IPAddress"]);
    inspectorBackend.registerEvent("Network.directUDPSocketLeftMulticastGroup", ["identifier", "IPAddress"]);
    inspectorBackend.registerEvent("Network.directUDPSocketCreated", ["identifier", "options", "timestamp", "initiator"]);
    inspectorBackend.registerEvent("Network.directUDPSocketOpened", ["identifier", "localAddr", "localPort", "timestamp", "remoteAddr", "remotePort"]);
    inspectorBackend.registerEvent("Network.directUDPSocketAborted", ["identifier", "errorMessage", "timestamp"]);
    inspectorBackend.registerEvent("Network.directUDPSocketClosed", ["identifier", "timestamp"]);
    inspectorBackend.registerEvent("Network.directUDPSocketChunkSent", ["identifier", "message", "timestamp"]);
    inspectorBackend.registerEvent("Network.directUDPSocketChunkReceived", ["identifier", "message", "timestamp"]);
    inspectorBackend.registerEvent("Network.requestWillBeSentExtraInfo", ["requestId", "associatedCookies", "headers", "connectTiming", "deviceBoundSessionUsages", "clientSecurityState", "siteHasCookieInOtherPartition", "appliedNetworkConditionsId"]);
    inspectorBackend.registerEvent("Network.responseReceivedExtraInfo", ["requestId", "blockedCookies", "headers", "resourceIPAddressSpace", "statusCode", "headersText", "cookiePartitionKey", "cookiePartitionKeyOpaque", "exemptedCookies"]);
    inspectorBackend.registerEvent("Network.responseReceivedEarlyHints", ["requestId", "headers"]);
    inspectorBackend.registerEnum("Network.TrustTokenOperationDoneEventStatus", { Ok: "Ok", InvalidArgument: "InvalidArgument", MissingIssuerKeys: "MissingIssuerKeys", FailedPrecondition: "FailedPrecondition", ResourceExhausted: "ResourceExhausted", AlreadyExists: "AlreadyExists", ResourceLimited: "ResourceLimited", Unauthorized: "Unauthorized", BadResponse: "BadResponse", InternalError: "InternalError", UnknownError: "UnknownError", FulfilledLocally: "FulfilledLocally", SiteIssuerLimit: "SiteIssuerLimit" });
    inspectorBackend.registerEvent("Network.trustTokenOperationDone", ["status", "type", "requestId", "topLevelOrigin", "issuerOrigin", "issuedTokenCount"]);
    inspectorBackend.registerEvent("Network.policyUpdated", []);
    inspectorBackend.registerEvent("Network.reportingApiReportAdded", ["report"]);
    inspectorBackend.registerEvent("Network.reportingApiReportUpdated", ["report"]);
    inspectorBackend.registerEvent("Network.reportingApiEndpointsChangedForOrigin", ["origin", "endpoints"]);
    inspectorBackend.registerEvent("Network.deviceBoundSessionsAdded", ["sessions"]);
    inspectorBackend.registerEvent("Network.deviceBoundSessionEventOccurred", ["eventId", "site", "succeeded", "sessionId", "creationEventDetails", "refreshEventDetails", "terminationEventDetails", "challengeEventDetails"]);
    inspectorBackend.registerCommand("Network.setAcceptedEncodings", [{ "name": "encodings", "type": "array", "optional": false, "description": "List of accepted content encodings.", "typeRef": "Network.ContentEncoding" }], [], "Sets a list of content encodings that will be accepted. Empty list means no encoding is accepted.");
    inspectorBackend.registerCommand("Network.clearAcceptedEncodingsOverride", [], [], "Clears accepted encodings set by setAcceptedEncodings");
    inspectorBackend.registerCommand("Network.canClearBrowserCache", [], ["result"], "Tells whether clearing browser cache is supported.");
    inspectorBackend.registerCommand("Network.canClearBrowserCookies", [], ["result"], "Tells whether clearing browser cookies is supported.");
    inspectorBackend.registerCommand("Network.canEmulateNetworkConditions", [], ["result"], "Tells whether emulation of network conditions is supported.");
    inspectorBackend.registerCommand("Network.clearBrowserCache", [], [], "Clears browser cache.");
    inspectorBackend.registerCommand("Network.clearBrowserCookies", [], [], "Clears browser cookies.");
    inspectorBackend.registerCommand("Network.continueInterceptedRequest", [{ "name": "interceptionId", "type": "string", "optional": false, "description": "", "typeRef": "Network.InterceptionId" }, { "name": "errorReason", "type": "string", "optional": true, "description": "If set this causes the request to fail with the given reason. Passing `Aborted` for requests marked with `isNavigationRequest` also cancels the navigation. Must not be set in response to an authChallenge.", "typeRef": "Network.ErrorReason" }, { "name": "rawResponse", "type": "string", "optional": true, "description": "If set the requests completes using with the provided base64 encoded raw response, including HTTP status line and headers etc... Must not be set in response to an authChallenge.", "typeRef": null }, { "name": "url", "type": "string", "optional": true, "description": "If set the request url will be modified in a way that's not observable by page. Must not be set in response to an authChallenge.", "typeRef": null }, { "name": "method", "type": "string", "optional": true, "description": "If set this allows the request method to be overridden. Must not be set in response to an authChallenge.", "typeRef": null }, { "name": "postData", "type": "string", "optional": true, "description": "If set this allows postData to be set. Must not be set in response to an authChallenge.", "typeRef": null }, { "name": "headers", "type": "object", "optional": true, "description": "If set this allows the request headers to be changed. Must not be set in response to an authChallenge.", "typeRef": "Network.Headers" }, { "name": "authChallengeResponse", "type": "object", "optional": true, "description": "Response to a requestIntercepted with an authChallenge. Must not be set otherwise.", "typeRef": "Network.AuthChallengeResponse" }], [], "Response to Network.requestIntercepted which either modifies the request to continue with any modifications, or blocks it, or completes it with the provided response bytes. If a network fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted event will be sent with the same InterceptionId. Deprecated, use Fetch.continueRequest, Fetch.fulfillRequest and Fetch.failRequest instead.");
    inspectorBackend.registerCommand("Network.deleteCookies", [{ "name": "name", "type": "string", "optional": false, "description": "Name of the cookies to remove.", "typeRef": null }, { "name": "url", "type": "string", "optional": true, "description": "If specified, deletes all the cookies with the given name where domain and path match provided URL.", "typeRef": null }, { "name": "domain", "type": "string", "optional": true, "description": "If specified, deletes only cookies with the exact domain.", "typeRef": null }, { "name": "path", "type": "string", "optional": true, "description": "If specified, deletes only cookies with the exact path.", "typeRef": null }, { "name": "partitionKey", "type": "object", "optional": true, "description": "If specified, deletes only cookies with the the given name and partitionKey where all partition key attributes match the cookie partition key attribute.", "typeRef": "Network.CookiePartitionKey" }], [], "Deletes browser cookies with matching name and url or domain/path/partitionKey pair.");
    inspectorBackend.registerCommand("Network.disable", [], [], "Disables network tracking, prevents network events from being sent to the client.");
    inspectorBackend.registerCommand("Network.emulateNetworkConditions", [{ "name": "offline", "type": "boolean", "optional": false, "description": "True to emulate internet disconnection.", "typeRef": null }, { "name": "latency", "type": "number", "optional": false, "description": "Minimum latency from request sent to response headers received (ms).", "typeRef": null }, { "name": "downloadThroughput", "type": "number", "optional": false, "description": "Maximal aggregated download throughput (bytes/sec). -1 disables download throttling.", "typeRef": null }, { "name": "uploadThroughput", "type": "number", "optional": false, "description": "Maximal aggregated upload throughput (bytes/sec).  -1 disables upload throttling.", "typeRef": null }, { "name": "connectionType", "type": "string", "optional": true, "description": "Connection type if known.", "typeRef": "Network.ConnectionType" }, { "name": "packetLoss", "type": "number", "optional": true, "description": "WebRTC packet loss (percent, 0-100). 0 disables packet loss emulation, 100 drops all the packets.", "typeRef": null }, { "name": "packetQueueLength", "type": "number", "optional": true, "description": "WebRTC packet queue length (packet). 0 removes any queue length limitations.", "typeRef": null }, { "name": "packetReordering", "type": "boolean", "optional": true, "description": "WebRTC packetReordering feature.", "typeRef": null }], [], "Activates emulation of network conditions. This command is deprecated in favor of the emulateNetworkConditionsByRule and overrideNetworkState commands, which can be used together to the same effect.");
    inspectorBackend.registerCommand("Network.emulateNetworkConditionsByRule", [{ "name": "offline", "type": "boolean", "optional": false, "description": "True to emulate internet disconnection.", "typeRef": null }, { "name": "matchedNetworkConditions", "type": "array", "optional": false, "description": "Configure conditions for matching requests. If multiple entries match a request, the first entry wins.  Global conditions can be configured by leaving the urlPattern for the conditions empty. These global conditions are also applied for throttling of p2p connections.", "typeRef": "Network.NetworkConditions" }], ["ruleIds"], "Activates emulation of network conditions for individual requests using URL match patterns. Unlike the deprecated Network.emulateNetworkConditions this method does not affect `navigator` state. Use Network.overrideNetworkState to explicitly modify `navigator` behavior.");
    inspectorBackend.registerCommand("Network.overrideNetworkState", [{ "name": "offline", "type": "boolean", "optional": false, "description": "True to emulate internet disconnection.", "typeRef": null }, { "name": "latency", "type": "number", "optional": false, "description": "Minimum latency from request sent to response headers received (ms).", "typeRef": null }, { "name": "downloadThroughput", "type": "number", "optional": false, "description": "Maximal aggregated download throughput (bytes/sec). -1 disables download throttling.", "typeRef": null }, { "name": "uploadThroughput", "type": "number", "optional": false, "description": "Maximal aggregated upload throughput (bytes/sec).  -1 disables upload throttling.", "typeRef": null }, { "name": "connectionType", "type": "string", "optional": true, "description": "Connection type if known.", "typeRef": "Network.ConnectionType" }], [], "Override the state of navigator.onLine and navigator.connection.");
    inspectorBackend.registerCommand("Network.enable", [{ "name": "maxTotalBufferSize", "type": "number", "optional": true, "description": "Buffer size in bytes to use when preserving network payloads (XHRs, etc). This is the maximum number of bytes that will be collected by this DevTools session.", "typeRef": null }, { "name": "maxResourceBufferSize", "type": "number", "optional": true, "description": "Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc).", "typeRef": null }, { "name": "maxPostDataSize", "type": "number", "optional": true, "description": "Longest post body size (in bytes) that would be included in requestWillBeSent notification", "typeRef": null }, { "name": "reportDirectSocketTraffic", "type": "boolean", "optional": true, "description": "Whether DirectSocket chunk send/receive events should be reported.", "typeRef": null }, { "name": "enableDurableMessages", "type": "boolean", "optional": true, "description": "Enable storing response bodies outside of renderer, so that these survive a cross-process navigation. Requires maxTotalBufferSize to be set. Currently defaults to false. This field is being deprecated in favor of the dedicated configureDurableMessages command, due to the possibility of deadlocks when awaiting Network.enable before issuing Runtime.runIfWaitingForDebugger.", "typeRef": null }], [], "Enables network tracking, network events will now be delivered to the client.");
    inspectorBackend.registerCommand("Network.configureDurableMessages", [{ "name": "maxTotalBufferSize", "type": "number", "optional": true, "description": "Buffer size in bytes to use when preserving network payloads (XHRs, etc).", "typeRef": null }, { "name": "maxResourceBufferSize", "type": "number", "optional": true, "description": "Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc).", "typeRef": null }], [], "Configures storing response bodies outside of renderer, so that these survive a cross-process navigation. If maxTotalBufferSize is not set, durable messages are disabled.");
    inspectorBackend.registerCommand("Network.getAllCookies", [], ["cookies"], "Returns all browser cookies. Depending on the backend support, will return detailed cookie information in the `cookies` field. Deprecated. Use Storage.getCookies instead.");
    inspectorBackend.registerCommand("Network.getCertificate", [{ "name": "origin", "type": "string", "optional": false, "description": "Origin to get certificate for.", "typeRef": null }], ["tableNames"], "Returns the DER-encoded certificate.");
    inspectorBackend.registerCommand("Network.getCookies", [{ "name": "urls", "type": "array", "optional": true, "description": "The list of URLs for which applicable cookies will be fetched. If not specified, it's assumed to be set to the list containing the URLs of the page and all of its subframes.", "typeRef": "string" }], ["cookies"], "Returns all browser cookies for the current URL. Depending on the backend support, will return detailed cookie information in the `cookies` field.");
    inspectorBackend.registerCommand("Network.getResponseBody", [{ "name": "requestId", "type": "string", "optional": false, "description": "Identifier of the network request to get content for.", "typeRef": "Network.RequestId" }], ["body", "base64Encoded"], "Returns content served for the given request.");
    inspectorBackend.registerCommand("Network.getRequestPostData", [{ "name": "requestId", "type": "string", "optional": false, "description": "Identifier of the network request to get content for.", "typeRef": "Network.RequestId" }], ["postData", "base64Encoded"], "Returns post data sent with the request. Returns an error when no data was sent with the request.");
    inspectorBackend.registerCommand("Network.getResponseBodyForInterception", [{ "name": "interceptionId", "type": "string", "optional": false, "description": "Identifier for the intercepted request to get body for.", "typeRef": "Network.InterceptionId" }], ["body", "base64Encoded"], "Returns content served for the given currently intercepted request.");
    inspectorBackend.registerCommand("Network.takeResponseBodyForInterceptionAsStream", [{ "name": "interceptionId", "type": "string", "optional": false, "description": "", "typeRef": "Network.InterceptionId" }], ["stream"], "Returns a handle to the stream representing the response body. Note that after this command, the intercepted request can't be continued as is -- you either need to cancel it or to provide the response body. The stream only supports sequential read, IO.read will fail if the position is specified.");
    inspectorBackend.registerCommand("Network.replayXHR", [{ "name": "requestId", "type": "string", "optional": false, "description": "Identifier of XHR to replay.", "typeRef": "Network.RequestId" }], [], "This method sends a new XMLHttpRequest which is identical to the original one. The following parameters should be identical: method, url, async, request body, extra headers, withCredentials attribute, user, password.");
    inspectorBackend.registerCommand("Network.searchInResponseBody", [{ "name": "requestId", "type": "string", "optional": false, "description": "Identifier of the network response to search.", "typeRef": "Network.RequestId" }, { "name": "query", "type": "string", "optional": false, "description": "String to search for.", "typeRef": null }, { "name": "caseSensitive", "type": "boolean", "optional": true, "description": "If true, search is case sensitive.", "typeRef": null }, { "name": "isRegex", "type": "boolean", "optional": true, "description": "If true, treats string parameter as regex.", "typeRef": null }], ["result"], "Searches for given string in response content.");
    inspectorBackend.registerCommand("Network.setBlockedURLs", [{ "name": "urlPatterns", "type": "array", "optional": true, "description": "Patterns to match in the order in which they are given. These patterns also take precedence over any wildcard patterns defined in `urls`.", "typeRef": "Network.BlockPattern" }, { "name": "urls", "type": "array", "optional": true, "description": "URL patterns to block. Wildcards ('*') are allowed.", "typeRef": "string" }], [], "Blocks URLs from loading.");
    inspectorBackend.registerCommand("Network.setBypassServiceWorker", [{ "name": "bypass", "type": "boolean", "optional": false, "description": "Bypass service worker and load from network.", "typeRef": null }], [], "Toggles ignoring of service worker for each request.");
    inspectorBackend.registerCommand("Network.setCacheDisabled", [{ "name": "cacheDisabled", "type": "boolean", "optional": false, "description": "Cache disabled state.", "typeRef": null }], [], "Toggles ignoring cache for each request. If `true`, cache will not be used.");
    inspectorBackend.registerCommand("Network.setCookie", [{ "name": "name", "type": "string", "optional": false, "description": "Cookie name.", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "Cookie value.", "typeRef": null }, { "name": "url", "type": "string", "optional": true, "description": "The request-URI to associate with the setting of the cookie. This value can affect the default domain, path, source port, and source scheme values of the created cookie.", "typeRef": null }, { "name": "domain", "type": "string", "optional": true, "description": "Cookie domain.", "typeRef": null }, { "name": "path", "type": "string", "optional": true, "description": "Cookie path.", "typeRef": null }, { "name": "secure", "type": "boolean", "optional": true, "description": "True if cookie is secure.", "typeRef": null }, { "name": "httpOnly", "type": "boolean", "optional": true, "description": "True if cookie is http-only.", "typeRef": null }, { "name": "sameSite", "type": "string", "optional": true, "description": "Cookie SameSite type.", "typeRef": "Network.CookieSameSite" }, { "name": "expires", "type": "number", "optional": true, "description": "Cookie expiration date, session cookie if not set", "typeRef": "Network.TimeSinceEpoch" }, { "name": "priority", "type": "string", "optional": true, "description": "Cookie Priority type.", "typeRef": "Network.CookiePriority" }, { "name": "sourceScheme", "type": "string", "optional": true, "description": "Cookie source scheme type.", "typeRef": "Network.CookieSourceScheme" }, { "name": "sourcePort", "type": "number", "optional": true, "description": "Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port. An unspecified port value allows protocol clients to emulate legacy cookie scope for the port. This is a temporary ability and it will be removed in the future.", "typeRef": null }, { "name": "partitionKey", "type": "object", "optional": true, "description": "Cookie partition key. If not set, the cookie will be set as not partitioned.", "typeRef": "Network.CookiePartitionKey" }], ["success"], "Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.");
    inspectorBackend.registerCommand("Network.setCookies", [{ "name": "cookies", "type": "array", "optional": false, "description": "Cookies to be set.", "typeRef": "Network.CookieParam" }], [], "Sets given cookies.");
    inspectorBackend.registerCommand("Network.setExtraHTTPHeaders", [{ "name": "headers", "type": "object", "optional": false, "description": "Map with extra HTTP headers.", "typeRef": "Network.Headers" }], [], "Specifies whether to always send extra HTTP headers with the requests from this page.");
    inspectorBackend.registerCommand("Network.setAttachDebugStack", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "Whether to attach a page script stack for debugging purpose.", "typeRef": null }], [], "Specifies whether to attach a page script stack id in requests");
    inspectorBackend.registerCommand("Network.setRequestInterception", [{ "name": "patterns", "type": "array", "optional": false, "description": "Requests matching any of these patterns will be forwarded and wait for the corresponding continueInterceptedRequest call.", "typeRef": "Network.RequestPattern" }], [], "Sets the requests to intercept that match the provided patterns and optionally resource types. Deprecated, please use Fetch.enable instead.");
    inspectorBackend.registerCommand("Network.setUserAgentOverride", [{ "name": "userAgent", "type": "string", "optional": false, "description": "User agent to use.", "typeRef": null }, { "name": "acceptLanguage", "type": "string", "optional": true, "description": "Browser language to emulate.", "typeRef": null }, { "name": "platform", "type": "string", "optional": true, "description": "The platform navigator.platform should return.", "typeRef": null }, { "name": "userAgentMetadata", "type": "object", "optional": true, "description": "To be sent in Sec-CH-UA-* headers and returned in navigator.userAgentData", "typeRef": "Emulation.UserAgentMetadata" }], [], "Allows overriding user agent with the given string.");
    inspectorBackend.registerCommand("Network.streamResourceContent", [{ "name": "requestId", "type": "string", "optional": false, "description": "Identifier of the request to stream.", "typeRef": "Network.RequestId" }], ["bufferedData"], "Enables streaming of the response for the given requestId. If enabled, the dataReceived event contains the data that was received during streaming.");
    inspectorBackend.registerCommand("Network.getSecurityIsolationStatus", [{ "name": "frameId", "type": "string", "optional": true, "description": "If no frameId is provided, the status of the target is provided.", "typeRef": "Page.FrameId" }], ["status"], "Returns information about the COEP/COOP isolation status.");
    inspectorBackend.registerCommand("Network.enableReportingApi", [{ "name": "enable", "type": "boolean", "optional": false, "description": "Whether to enable or disable events for the Reporting API", "typeRef": null }], [], "Enables tracking for the Reporting API, events generated by the Reporting API will now be delivered to the client. Enabling triggers 'reportingApiReportAdded' for all existing reports.");
    inspectorBackend.registerCommand("Network.enableDeviceBoundSessions", [{ "name": "enable", "type": "boolean", "optional": false, "description": "Whether to enable or disable events.", "typeRef": null }], [], "Sets up tracking device bound sessions and fetching of initial set of sessions.");
    inspectorBackend.registerCommand("Network.fetchSchemefulSite", [{ "name": "origin", "type": "string", "optional": false, "description": "The URL origin.", "typeRef": null }], ["schemefulSite"], "Fetches the schemeful site for a specific origin.");
    inspectorBackend.registerCommand("Network.loadNetworkResource", [{ "name": "frameId", "type": "string", "optional": true, "description": "Frame id to get the resource for. Mandatory for frame targets, and should be omitted for worker targets.", "typeRef": "Page.FrameId" }, { "name": "url", "type": "string", "optional": false, "description": "URL of the resource to get content for.", "typeRef": null }, { "name": "options", "type": "object", "optional": false, "description": "Options for the request.", "typeRef": "Network.LoadNetworkResourceOptions" }], ["resource"], "Fetches the resource and returns the content.");
    inspectorBackend.registerCommand("Network.setCookieControls", [{ "name": "enableThirdPartyCookieRestriction", "type": "boolean", "optional": false, "description": "Whether 3pc restriction is enabled.", "typeRef": null }, { "name": "disableThirdPartyCookieMetadata", "type": "boolean", "optional": false, "description": "Whether 3pc grace period exception should be enabled; false by default.", "typeRef": null }, { "name": "disableThirdPartyCookieHeuristics", "type": "boolean", "optional": false, "description": "Whether 3pc heuristics exceptions should be enabled; false by default.", "typeRef": null }], [], "Sets Controls for third-party cookie access Page reload is required before the new cookie behavior will be observed");
    inspectorBackend.registerType("Network.ResourceTiming", [{ "name": "requestTime", "type": "number", "optional": false, "description": "Timing's requestTime is a baseline in seconds, while the other numbers are ticks in milliseconds relatively to this requestTime.", "typeRef": null }, { "name": "proxyStart", "type": "number", "optional": false, "description": "Started resolving proxy.", "typeRef": null }, { "name": "proxyEnd", "type": "number", "optional": false, "description": "Finished resolving proxy.", "typeRef": null }, { "name": "dnsStart", "type": "number", "optional": false, "description": "Started DNS address resolve.", "typeRef": null }, { "name": "dnsEnd", "type": "number", "optional": false, "description": "Finished DNS address resolve.", "typeRef": null }, { "name": "connectStart", "type": "number", "optional": false, "description": "Started connecting to the remote host.", "typeRef": null }, { "name": "connectEnd", "type": "number", "optional": false, "description": "Connected to the remote host.", "typeRef": null }, { "name": "sslStart", "type": "number", "optional": false, "description": "Started SSL handshake.", "typeRef": null }, { "name": "sslEnd", "type": "number", "optional": false, "description": "Finished SSL handshake.", "typeRef": null }, { "name": "workerStart", "type": "number", "optional": false, "description": "Started running ServiceWorker.", "typeRef": null }, { "name": "workerReady", "type": "number", "optional": false, "description": "Finished Starting ServiceWorker.", "typeRef": null }, { "name": "workerFetchStart", "type": "number", "optional": false, "description": "Started fetch event.", "typeRef": null }, { "name": "workerRespondWithSettled", "type": "number", "optional": false, "description": "Settled fetch event respondWith promise.", "typeRef": null }, { "name": "workerRouterEvaluationStart", "type": "number", "optional": true, "description": "Started ServiceWorker static routing source evaluation.", "typeRef": null }, { "name": "workerCacheLookupStart", "type": "number", "optional": true, "description": "Started cache lookup when the source was evaluated to `cache`.", "typeRef": null }, { "name": "sendStart", "type": "number", "optional": false, "description": "Started sending request.", "typeRef": null }, { "name": "sendEnd", "type": "number", "optional": false, "description": "Finished sending request.", "typeRef": null }, { "name": "pushStart", "type": "number", "optional": false, "description": "Time the server started pushing request.", "typeRef": null }, { "name": "pushEnd", "type": "number", "optional": false, "description": "Time the server finished pushing request.", "typeRef": null }, { "name": "receiveHeadersStart", "type": "number", "optional": false, "description": "Started receiving response headers.", "typeRef": null }, { "name": "receiveHeadersEnd", "type": "number", "optional": false, "description": "Finished receiving response headers.", "typeRef": null }]);
    inspectorBackend.registerType("Network.PostDataEntry", [{ "name": "bytes", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Network.Request", [{ "name": "url", "type": "string", "optional": false, "description": "Request URL (without fragment).", "typeRef": null }, { "name": "urlFragment", "type": "string", "optional": true, "description": "Fragment of the requested URL starting with hash, if present.", "typeRef": null }, { "name": "method", "type": "string", "optional": false, "description": "HTTP request method.", "typeRef": null }, { "name": "headers", "type": "object", "optional": false, "description": "HTTP request headers.", "typeRef": "Network.Headers" }, { "name": "postData", "type": "string", "optional": true, "description": "HTTP POST request data. Use postDataEntries instead.", "typeRef": null }, { "name": "hasPostData", "type": "boolean", "optional": true, "description": "True when the request has POST data. Note that postData might still be omitted when this flag is true when the data is too long.", "typeRef": null }, { "name": "postDataEntries", "type": "array", "optional": true, "description": "Request body elements (post data broken into individual entries).", "typeRef": "Network.PostDataEntry" }, { "name": "mixedContentType", "type": "string", "optional": true, "description": "The mixed content type of the request.", "typeRef": "Security.MixedContentType" }, { "name": "initialPriority", "type": "string", "optional": false, "description": "Priority of the resource request at the time request is sent.", "typeRef": "Network.ResourcePriority" }, { "name": "referrerPolicy", "type": "string", "optional": false, "description": "The referrer policy of the request, as defined in https://www.w3.org/TR/referrer-policy/", "typeRef": null }, { "name": "isLinkPreload", "type": "boolean", "optional": true, "description": "Whether is loaded via link preload.", "typeRef": null }, { "name": "trustTokenParams", "type": "object", "optional": true, "description": "Set for requests when the TrustToken API is used. Contains the parameters passed by the developer (e.g. via \\\"fetch\\\") as understood by the backend.", "typeRef": "Network.TrustTokenParams" }, { "name": "isSameSite", "type": "boolean", "optional": true, "description": "True if this resource request is considered to be the 'same site' as the request corresponding to the main frame.", "typeRef": null }, { "name": "isAdRelated", "type": "boolean", "optional": true, "description": "True when the resource request is ad-related.", "typeRef": null }]);
    inspectorBackend.registerType("Network.SignedCertificateTimestamp", [{ "name": "status", "type": "string", "optional": false, "description": "Validation status.", "typeRef": null }, { "name": "origin", "type": "string", "optional": false, "description": "Origin.", "typeRef": null }, { "name": "logDescription", "type": "string", "optional": false, "description": "Log name / description.", "typeRef": null }, { "name": "logId", "type": "string", "optional": false, "description": "Log ID.", "typeRef": null }, { "name": "timestamp", "type": "number", "optional": false, "description": "Issuance date. Unlike TimeSinceEpoch, this contains the number of milliseconds since January 1, 1970, UTC, not the number of seconds.", "typeRef": null }, { "name": "hashAlgorithm", "type": "string", "optional": false, "description": "Hash algorithm.", "typeRef": null }, { "name": "signatureAlgorithm", "type": "string", "optional": false, "description": "Signature algorithm.", "typeRef": null }, { "name": "signatureData", "type": "string", "optional": false, "description": "Signature data.", "typeRef": null }]);
    inspectorBackend.registerType("Network.SecurityDetails", [{ "name": "protocol", "type": "string", "optional": false, "description": "Protocol name (e.g. \\\"TLS 1.2\\\" or \\\"QUIC\\\").", "typeRef": null }, { "name": "keyExchange", "type": "string", "optional": false, "description": "Key Exchange used by the connection, or the empty string if not applicable.", "typeRef": null }, { "name": "keyExchangeGroup", "type": "string", "optional": true, "description": "(EC)DH group used by the connection, if applicable.", "typeRef": null }, { "name": "cipher", "type": "string", "optional": false, "description": "Cipher name.", "typeRef": null }, { "name": "mac", "type": "string", "optional": true, "description": "TLS MAC. Note that AEAD ciphers do not have separate MACs.", "typeRef": null }, { "name": "certificateId", "type": "number", "optional": false, "description": "Certificate ID value.", "typeRef": "Security.CertificateId" }, { "name": "subjectName", "type": "string", "optional": false, "description": "Certificate subject name.", "typeRef": null }, { "name": "sanList", "type": "array", "optional": false, "description": "Subject Alternative Name (SAN) DNS names and IP addresses.", "typeRef": "string" }, { "name": "issuer", "type": "string", "optional": false, "description": "Name of the issuing CA.", "typeRef": null }, { "name": "validFrom", "type": "number", "optional": false, "description": "Certificate valid from date.", "typeRef": "Network.TimeSinceEpoch" }, { "name": "validTo", "type": "number", "optional": false, "description": "Certificate valid to (expiration) date", "typeRef": "Network.TimeSinceEpoch" }, { "name": "signedCertificateTimestampList", "type": "array", "optional": false, "description": "List of signed certificate timestamps (SCTs).", "typeRef": "Network.SignedCertificateTimestamp" }, { "name": "certificateTransparencyCompliance", "type": "string", "optional": false, "description": "Whether the request complied with Certificate Transparency policy", "typeRef": "Network.CertificateTransparencyCompliance" }, { "name": "serverSignatureAlgorithm", "type": "number", "optional": true, "description": "The signature algorithm used by the server in the TLS server signature, represented as a TLS SignatureScheme code point. Omitted if not applicable or not known.", "typeRef": null }, { "name": "encryptedClientHello", "type": "boolean", "optional": false, "description": "Whether the connection used Encrypted ClientHello", "typeRef": null }]);
    inspectorBackend.registerType("Network.CorsErrorStatus", [{ "name": "corsError", "type": "string", "optional": false, "description": "", "typeRef": "Network.CorsError" }, { "name": "failedParameter", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Network.TrustTokenParams", [{ "name": "operation", "type": "string", "optional": false, "description": "", "typeRef": "Network.TrustTokenOperationType" }, { "name": "refreshPolicy", "type": "string", "optional": false, "description": "Only set for \\\"token-redemption\\\" operation and determine whether to request a fresh SRR or use a still valid cached SRR.", "typeRef": null }, { "name": "issuers", "type": "array", "optional": true, "description": "Origins of issuers from whom to request tokens or redemption records.", "typeRef": "string" }]);
    inspectorBackend.registerType("Network.ServiceWorkerRouterInfo", [{ "name": "ruleIdMatched", "type": "number", "optional": true, "description": "ID of the rule matched. If there is a matched rule, this field will be set, otherwiser no value will be set.", "typeRef": null }, { "name": "matchedSourceType", "type": "string", "optional": true, "description": "The router source of the matched rule. If there is a matched rule, this field will be set, otherwise no value will be set.", "typeRef": "Network.ServiceWorkerRouterSource" }, { "name": "actualSourceType", "type": "string", "optional": true, "description": "The actual router source used.", "typeRef": "Network.ServiceWorkerRouterSource" }]);
    inspectorBackend.registerType("Network.Response", [{ "name": "url", "type": "string", "optional": false, "description": "Response URL. This URL can be different from CachedResource.url in case of redirect.", "typeRef": null }, { "name": "status", "type": "number", "optional": false, "description": "HTTP response status code.", "typeRef": null }, { "name": "statusText", "type": "string", "optional": false, "description": "HTTP response status text.", "typeRef": null }, { "name": "headers", "type": "object", "optional": false, "description": "HTTP response headers.", "typeRef": "Network.Headers" }, { "name": "headersText", "type": "string", "optional": true, "description": "HTTP response headers text. This has been replaced by the headers in Network.responseReceivedExtraInfo.", "typeRef": null }, { "name": "mimeType", "type": "string", "optional": false, "description": "Resource mimeType as determined by the browser.", "typeRef": null }, { "name": "charset", "type": "string", "optional": false, "description": "Resource charset as determined by the browser (if applicable).", "typeRef": null }, { "name": "requestHeaders", "type": "object", "optional": true, "description": "Refined HTTP request headers that were actually transmitted over the network.", "typeRef": "Network.Headers" }, { "name": "requestHeadersText", "type": "string", "optional": true, "description": "HTTP request headers text. This has been replaced by the headers in Network.requestWillBeSentExtraInfo.", "typeRef": null }, { "name": "connectionReused", "type": "boolean", "optional": false, "description": "Specifies whether physical connection was actually reused for this request.", "typeRef": null }, { "name": "connectionId", "type": "number", "optional": false, "description": "Physical connection id that was actually used for this request.", "typeRef": null }, { "name": "remoteIPAddress", "type": "string", "optional": true, "description": "Remote IP address.", "typeRef": null }, { "name": "remotePort", "type": "number", "optional": true, "description": "Remote port.", "typeRef": null }, { "name": "fromDiskCache", "type": "boolean", "optional": true, "description": "Specifies that the request was served from the disk cache.", "typeRef": null }, { "name": "fromServiceWorker", "type": "boolean", "optional": true, "description": "Specifies that the request was served from the ServiceWorker.", "typeRef": null }, { "name": "fromPrefetchCache", "type": "boolean", "optional": true, "description": "Specifies that the request was served from the prefetch cache.", "typeRef": null }, { "name": "fromEarlyHints", "type": "boolean", "optional": true, "description": "Specifies that the request was served from the prefetch cache.", "typeRef": null }, { "name": "serviceWorkerRouterInfo", "type": "object", "optional": true, "description": "Information about how ServiceWorker Static Router API was used. If this field is set with `matchedSourceType` field, a matching rule is found. If this field is set without `matchedSource`, no matching rule is found. Otherwise, the API is not used.", "typeRef": "Network.ServiceWorkerRouterInfo" }, { "name": "encodedDataLength", "type": "number", "optional": false, "description": "Total number of bytes received for this request so far.", "typeRef": null }, { "name": "timing", "type": "object", "optional": true, "description": "Timing information for the given request.", "typeRef": "Network.ResourceTiming" }, { "name": "serviceWorkerResponseSource", "type": "string", "optional": true, "description": "Response source of response from ServiceWorker.", "typeRef": "Network.ServiceWorkerResponseSource" }, { "name": "responseTime", "type": "number", "optional": true, "description": "The time at which the returned response was generated.", "typeRef": "Network.TimeSinceEpoch" }, { "name": "cacheStorageCacheName", "type": "string", "optional": true, "description": "Cache Storage Cache Name.", "typeRef": null }, { "name": "protocol", "type": "string", "optional": true, "description": "Protocol used to fetch this request.", "typeRef": null }, { "name": "alternateProtocolUsage", "type": "string", "optional": true, "description": "The reason why Chrome uses a specific transport protocol for HTTP semantics.", "typeRef": "Network.AlternateProtocolUsage" }, { "name": "securityState", "type": "string", "optional": false, "description": "Security state of the request resource.", "typeRef": "Security.SecurityState" }, { "name": "securityDetails", "type": "object", "optional": true, "description": "Security details for the request.", "typeRef": "Network.SecurityDetails" }]);
    inspectorBackend.registerType("Network.WebSocketRequest", [{ "name": "headers", "type": "object", "optional": false, "description": "HTTP request headers.", "typeRef": "Network.Headers" }]);
    inspectorBackend.registerType("Network.WebSocketResponse", [{ "name": "status", "type": "number", "optional": false, "description": "HTTP response status code.", "typeRef": null }, { "name": "statusText", "type": "string", "optional": false, "description": "HTTP response status text.", "typeRef": null }, { "name": "headers", "type": "object", "optional": false, "description": "HTTP response headers.", "typeRef": "Network.Headers" }, { "name": "headersText", "type": "string", "optional": true, "description": "HTTP response headers text.", "typeRef": null }, { "name": "requestHeaders", "type": "object", "optional": true, "description": "HTTP request headers.", "typeRef": "Network.Headers" }, { "name": "requestHeadersText", "type": "string", "optional": true, "description": "HTTP request headers text.", "typeRef": null }]);
    inspectorBackend.registerType("Network.WebSocketFrame", [{ "name": "opcode", "type": "number", "optional": false, "description": "WebSocket message opcode.", "typeRef": null }, { "name": "mask", "type": "boolean", "optional": false, "description": "WebSocket message mask.", "typeRef": null }, { "name": "payloadData", "type": "string", "optional": false, "description": "WebSocket message payload data. If the opcode is 1, this is a text message and payloadData is a UTF-8 string. If the opcode isn't 1, then payloadData is a base64 encoded string representing binary data.", "typeRef": null }]);
    inspectorBackend.registerType("Network.CachedResource", [{ "name": "url", "type": "string", "optional": false, "description": "Resource URL. This is the url of the original network request.", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "Type of this resource.", "typeRef": "Network.ResourceType" }, { "name": "response", "type": "object", "optional": true, "description": "Cached response data.", "typeRef": "Network.Response" }, { "name": "bodySize", "type": "number", "optional": false, "description": "Cached response body size.", "typeRef": null }]);
    inspectorBackend.registerType("Network.Initiator", [{ "name": "type", "type": "string", "optional": false, "description": "Type of this initiator.", "typeRef": null }, { "name": "stack", "type": "object", "optional": true, "description": "Initiator JavaScript stack trace, set for Script only. Requires the Debugger domain to be enabled.", "typeRef": "Runtime.StackTrace" }, { "name": "url", "type": "string", "optional": true, "description": "Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type.", "typeRef": null }, { "name": "lineNumber", "type": "number", "optional": true, "description": "Initiator line number, set for Parser type or for Script type (when script is importing module) (0-based).", "typeRef": null }, { "name": "columnNumber", "type": "number", "optional": true, "description": "Initiator column number, set for Parser type or for Script type (when script is importing module) (0-based).", "typeRef": null }, { "name": "requestId", "type": "string", "optional": true, "description": "Set if another request triggered this request (e.g. preflight).", "typeRef": "Network.RequestId" }]);
    inspectorBackend.registerType("Network.CookiePartitionKey", [{ "name": "topLevelSite", "type": "string", "optional": false, "description": "The site of the top-level URL the browser was visiting at the start of the request to the endpoint that set the cookie.", "typeRef": null }, { "name": "hasCrossSiteAncestor", "type": "boolean", "optional": false, "description": "Indicates if the cookie has any ancestors that are cross-site to the topLevelSite.", "typeRef": null }]);
    inspectorBackend.registerType("Network.Cookie", [{ "name": "name", "type": "string", "optional": false, "description": "Cookie name.", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "Cookie value.", "typeRef": null }, { "name": "domain", "type": "string", "optional": false, "description": "Cookie domain.", "typeRef": null }, { "name": "path", "type": "string", "optional": false, "description": "Cookie path.", "typeRef": null }, { "name": "expires", "type": "number", "optional": false, "description": "Cookie expiration date as the number of seconds since the UNIX epoch. The value is set to -1 if the expiry date is not set. The value can be null for values that cannot be represented in JSON (\u00b1Inf).", "typeRef": null }, { "name": "size", "type": "number", "optional": false, "description": "Cookie size.", "typeRef": null }, { "name": "httpOnly", "type": "boolean", "optional": false, "description": "True if cookie is http-only.", "typeRef": null }, { "name": "secure", "type": "boolean", "optional": false, "description": "True if cookie is secure.", "typeRef": null }, { "name": "session", "type": "boolean", "optional": false, "description": "True in case of session cookie.", "typeRef": null }, { "name": "sameSite", "type": "string", "optional": true, "description": "Cookie SameSite type.", "typeRef": "Network.CookieSameSite" }, { "name": "priority", "type": "string", "optional": false, "description": "Cookie Priority", "typeRef": "Network.CookiePriority" }, { "name": "sourceScheme", "type": "string", "optional": false, "description": "Cookie source scheme type.", "typeRef": "Network.CookieSourceScheme" }, { "name": "sourcePort", "type": "number", "optional": false, "description": "Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port. An unspecified port value allows protocol clients to emulate legacy cookie scope for the port. This is a temporary ability and it will be removed in the future.", "typeRef": null }, { "name": "partitionKey", "type": "object", "optional": true, "description": "Cookie partition key.", "typeRef": "Network.CookiePartitionKey" }, { "name": "partitionKeyOpaque", "type": "boolean", "optional": true, "description": "True if cookie partition key is opaque.", "typeRef": null }]);
    inspectorBackend.registerType("Network.BlockedSetCookieWithReason", [{ "name": "blockedReasons", "type": "array", "optional": false, "description": "The reason(s) this cookie was blocked.", "typeRef": "Network.SetCookieBlockedReason" }, { "name": "cookieLine", "type": "string", "optional": false, "description": "The string representing this individual cookie as it would appear in the header. This is not the entire \\\"cookie\\\" or \\\"set-cookie\\\" header which could have multiple cookies.", "typeRef": null }, { "name": "cookie", "type": "object", "optional": true, "description": "The cookie object which represents the cookie which was not stored. It is optional because sometimes complete cookie information is not available, such as in the case of parsing errors.", "typeRef": "Network.Cookie" }]);
    inspectorBackend.registerType("Network.ExemptedSetCookieWithReason", [{ "name": "exemptionReason", "type": "string", "optional": false, "description": "The reason the cookie was exempted.", "typeRef": "Network.CookieExemptionReason" }, { "name": "cookieLine", "type": "string", "optional": false, "description": "The string representing this individual cookie as it would appear in the header.", "typeRef": null }, { "name": "cookie", "type": "object", "optional": false, "description": "The cookie object representing the cookie.", "typeRef": "Network.Cookie" }]);
    inspectorBackend.registerType("Network.AssociatedCookie", [{ "name": "cookie", "type": "object", "optional": false, "description": "The cookie object representing the cookie which was not sent.", "typeRef": "Network.Cookie" }, { "name": "blockedReasons", "type": "array", "optional": false, "description": "The reason(s) the cookie was blocked. If empty means the cookie is included.", "typeRef": "Network.CookieBlockedReason" }, { "name": "exemptionReason", "type": "string", "optional": true, "description": "The reason the cookie should have been blocked by 3PCD but is exempted. A cookie could only have at most one exemption reason.", "typeRef": "Network.CookieExemptionReason" }]);
    inspectorBackend.registerType("Network.CookieParam", [{ "name": "name", "type": "string", "optional": false, "description": "Cookie name.", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "Cookie value.", "typeRef": null }, { "name": "url", "type": "string", "optional": true, "description": "The request-URI to associate with the setting of the cookie. This value can affect the default domain, path, source port, and source scheme values of the created cookie.", "typeRef": null }, { "name": "domain", "type": "string", "optional": true, "description": "Cookie domain.", "typeRef": null }, { "name": "path", "type": "string", "optional": true, "description": "Cookie path.", "typeRef": null }, { "name": "secure", "type": "boolean", "optional": true, "description": "True if cookie is secure.", "typeRef": null }, { "name": "httpOnly", "type": "boolean", "optional": true, "description": "True if cookie is http-only.", "typeRef": null }, { "name": "sameSite", "type": "string", "optional": true, "description": "Cookie SameSite type.", "typeRef": "Network.CookieSameSite" }, { "name": "expires", "type": "number", "optional": true, "description": "Cookie expiration date, session cookie if not set", "typeRef": "Network.TimeSinceEpoch" }, { "name": "priority", "type": "string", "optional": true, "description": "Cookie Priority.", "typeRef": "Network.CookiePriority" }, { "name": "sourceScheme", "type": "string", "optional": true, "description": "Cookie source scheme type.", "typeRef": "Network.CookieSourceScheme" }, { "name": "sourcePort", "type": "number", "optional": true, "description": "Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port. An unspecified port value allows protocol clients to emulate legacy cookie scope for the port. This is a temporary ability and it will be removed in the future.", "typeRef": null }, { "name": "partitionKey", "type": "object", "optional": true, "description": "Cookie partition key. If not set, the cookie will be set as not partitioned.", "typeRef": "Network.CookiePartitionKey" }]);
    inspectorBackend.registerType("Network.AuthChallenge", [{ "name": "source", "type": "string", "optional": true, "description": "Source of the authentication challenge.", "typeRef": null }, { "name": "origin", "type": "string", "optional": false, "description": "Origin of the challenger.", "typeRef": null }, { "name": "scheme", "type": "string", "optional": false, "description": "The authentication scheme used, such as basic or digest", "typeRef": null }, { "name": "realm", "type": "string", "optional": false, "description": "The realm of the challenge. May be empty.", "typeRef": null }]);
    inspectorBackend.registerType("Network.AuthChallengeResponse", [{ "name": "response", "type": "string", "optional": false, "description": "The decision on what to do in response to the authorization challenge.  Default means deferring to the default behavior of the net stack, which will likely either the Cancel authentication or display a popup dialog box.", "typeRef": null }, { "name": "username", "type": "string", "optional": true, "description": "The username to provide, possibly empty. Should only be set if response is ProvideCredentials.", "typeRef": null }, { "name": "password", "type": "string", "optional": true, "description": "The password to provide, possibly empty. Should only be set if response is ProvideCredentials.", "typeRef": null }]);
    inspectorBackend.registerType("Network.RequestPattern", [{ "name": "urlPattern", "type": "string", "optional": true, "description": "Wildcards (`'*'` -> zero or more, `'?'` -> exactly one) are allowed. Escape character is backslash. Omitting is equivalent to `\\\"*\\\"`.", "typeRef": null }, { "name": "resourceType", "type": "string", "optional": true, "description": "If set, only requests for matching resource types will be intercepted.", "typeRef": "Network.ResourceType" }, { "name": "interceptionStage", "type": "string", "optional": true, "description": "Stage at which to begin intercepting requests. Default is Request.", "typeRef": "Network.InterceptionStage" }]);
    inspectorBackend.registerType("Network.SignedExchangeSignature", [{ "name": "label", "type": "string", "optional": false, "description": "Signed exchange signature label.", "typeRef": null }, { "name": "signature", "type": "string", "optional": false, "description": "The hex string of signed exchange signature.", "typeRef": null }, { "name": "integrity", "type": "string", "optional": false, "description": "Signed exchange signature integrity.", "typeRef": null }, { "name": "certUrl", "type": "string", "optional": true, "description": "Signed exchange signature cert Url.", "typeRef": null }, { "name": "certSha256", "type": "string", "optional": true, "description": "The hex string of signed exchange signature cert sha256.", "typeRef": null }, { "name": "validityUrl", "type": "string", "optional": false, "description": "Signed exchange signature validity Url.", "typeRef": null }, { "name": "date", "type": "number", "optional": false, "description": "Signed exchange signature date.", "typeRef": null }, { "name": "expires", "type": "number", "optional": false, "description": "Signed exchange signature expires.", "typeRef": null }, { "name": "certificates", "type": "array", "optional": true, "description": "The encoded certificates.", "typeRef": "string" }]);
    inspectorBackend.registerType("Network.SignedExchangeHeader", [{ "name": "requestUrl", "type": "string", "optional": false, "description": "Signed exchange request URL.", "typeRef": null }, { "name": "responseCode", "type": "number", "optional": false, "description": "Signed exchange response code.", "typeRef": null }, { "name": "responseHeaders", "type": "object", "optional": false, "description": "Signed exchange response headers.", "typeRef": "Network.Headers" }, { "name": "signatures", "type": "array", "optional": false, "description": "Signed exchange response signature.", "typeRef": "Network.SignedExchangeSignature" }, { "name": "headerIntegrity", "type": "string", "optional": false, "description": "Signed exchange header integrity hash in the form of `sha256-<base64-hash-value>`.", "typeRef": null }]);
    inspectorBackend.registerType("Network.SignedExchangeError", [{ "name": "message", "type": "string", "optional": false, "description": "Error message.", "typeRef": null }, { "name": "signatureIndex", "type": "number", "optional": true, "description": "The index of the signature which caused the error.", "typeRef": null }, { "name": "errorField", "type": "string", "optional": true, "description": "The field which caused the error.", "typeRef": "Network.SignedExchangeErrorField" }]);
    inspectorBackend.registerType("Network.SignedExchangeInfo", [{ "name": "outerResponse", "type": "object", "optional": false, "description": "The outer response of signed HTTP exchange which was received from network.", "typeRef": "Network.Response" }, { "name": "hasExtraInfo", "type": "boolean", "optional": false, "description": "Whether network response for the signed exchange was accompanied by extra headers.", "typeRef": null }, { "name": "header", "type": "object", "optional": true, "description": "Information about the signed exchange header.", "typeRef": "Network.SignedExchangeHeader" }, { "name": "securityDetails", "type": "object", "optional": true, "description": "Security details for the signed exchange header.", "typeRef": "Network.SecurityDetails" }, { "name": "errors", "type": "array", "optional": true, "description": "Errors occurred while handling the signed exchange.", "typeRef": "Network.SignedExchangeError" }]);
    inspectorBackend.registerType("Network.NetworkConditions", [{ "name": "urlPattern", "type": "string", "optional": false, "description": "Only matching requests will be affected by these conditions. Patterns use the URLPattern constructor string syntax (https://urlpattern.spec.whatwg.org/) and must be absolute. If the pattern is empty, all requests are matched (including p2p connections).", "typeRef": null }, { "name": "latency", "type": "number", "optional": false, "description": "Minimum latency from request sent to response headers received (ms).", "typeRef": null }, { "name": "downloadThroughput", "type": "number", "optional": false, "description": "Maximal aggregated download throughput (bytes/sec). -1 disables download throttling.", "typeRef": null }, { "name": "uploadThroughput", "type": "number", "optional": false, "description": "Maximal aggregated upload throughput (bytes/sec).  -1 disables upload throttling.", "typeRef": null }, { "name": "connectionType", "type": "string", "optional": true, "description": "Connection type if known.", "typeRef": "Network.ConnectionType" }, { "name": "packetLoss", "type": "number", "optional": true, "description": "WebRTC packet loss (percent, 0-100). 0 disables packet loss emulation, 100 drops all the packets.", "typeRef": null }, { "name": "packetQueueLength", "type": "number", "optional": true, "description": "WebRTC packet queue length (packet). 0 removes any queue length limitations.", "typeRef": null }, { "name": "packetReordering", "type": "boolean", "optional": true, "description": "WebRTC packetReordering feature.", "typeRef": null }]);
    inspectorBackend.registerType("Network.BlockPattern", [{ "name": "urlPattern", "type": "string", "optional": false, "description": "URL pattern to match. Patterns use the URLPattern constructor string syntax (https://urlpattern.spec.whatwg.org/) and must be absolute. Example: `*://*:*/*.css`.", "typeRef": null }, { "name": "block", "type": "boolean", "optional": false, "description": "Whether or not to block the pattern. If false, a matching request will not be blocked even if it matches a later `BlockPattern`.", "typeRef": null }]);
    inspectorBackend.registerType("Network.DirectTCPSocketOptions", [{ "name": "noDelay", "type": "boolean", "optional": false, "description": "TCP_NODELAY option", "typeRef": null }, { "name": "keepAliveDelay", "type": "number", "optional": true, "description": "Expected to be unsigned integer.", "typeRef": null }, { "name": "sendBufferSize", "type": "number", "optional": true, "description": "Expected to be unsigned integer.", "typeRef": null }, { "name": "receiveBufferSize", "type": "number", "optional": true, "description": "Expected to be unsigned integer.", "typeRef": null }, { "name": "dnsQueryType", "type": "string", "optional": true, "description": "", "typeRef": "Network.DirectSocketDnsQueryType" }]);
    inspectorBackend.registerType("Network.DirectUDPSocketOptions", [{ "name": "remoteAddr", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "remotePort", "type": "number", "optional": true, "description": "Unsigned int 16.", "typeRef": null }, { "name": "localAddr", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "localPort", "type": "number", "optional": true, "description": "Unsigned int 16.", "typeRef": null }, { "name": "dnsQueryType", "type": "string", "optional": true, "description": "", "typeRef": "Network.DirectSocketDnsQueryType" }, { "name": "sendBufferSize", "type": "number", "optional": true, "description": "Expected to be unsigned integer.", "typeRef": null }, { "name": "receiveBufferSize", "type": "number", "optional": true, "description": "Expected to be unsigned integer.", "typeRef": null }, { "name": "multicastLoopback", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "multicastTimeToLive", "type": "number", "optional": true, "description": "Unsigned int 8.", "typeRef": null }, { "name": "multicastAllowAddressSharing", "type": "boolean", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Network.DirectUDPMessage", [{ "name": "data", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "remoteAddr", "type": "string", "optional": true, "description": "Null for connected mode.", "typeRef": null }, { "name": "remotePort", "type": "number", "optional": true, "description": "Null for connected mode. Expected to be unsigned integer.", "typeRef": null }]);
    inspectorBackend.registerType("Network.ConnectTiming", [{ "name": "requestTime", "type": "number", "optional": false, "description": "Timing's requestTime is a baseline in seconds, while the other numbers are ticks in milliseconds relatively to this requestTime. Matches ResourceTiming's requestTime for the same request (but not for redirected requests).", "typeRef": null }]);
    inspectorBackend.registerType("Network.ClientSecurityState", [{ "name": "initiatorIsSecureContext", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "initiatorIPAddressSpace", "type": "string", "optional": false, "description": "", "typeRef": "Network.IPAddressSpace" }, { "name": "localNetworkAccessRequestPolicy", "type": "string", "optional": false, "description": "", "typeRef": "Network.LocalNetworkAccessRequestPolicy" }]);
    inspectorBackend.registerType("Network.CrossOriginOpenerPolicyStatus", [{ "name": "value", "type": "string", "optional": false, "description": "", "typeRef": "Network.CrossOriginOpenerPolicyValue" }, { "name": "reportOnlyValue", "type": "string", "optional": false, "description": "", "typeRef": "Network.CrossOriginOpenerPolicyValue" }, { "name": "reportingEndpoint", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "reportOnlyReportingEndpoint", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Network.CrossOriginEmbedderPolicyStatus", [{ "name": "value", "type": "string", "optional": false, "description": "", "typeRef": "Network.CrossOriginEmbedderPolicyValue" }, { "name": "reportOnlyValue", "type": "string", "optional": false, "description": "", "typeRef": "Network.CrossOriginEmbedderPolicyValue" }, { "name": "reportingEndpoint", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "reportOnlyReportingEndpoint", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Network.ContentSecurityPolicyStatus", [{ "name": "effectiveDirectives", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "isEnforced", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "source", "type": "string", "optional": false, "description": "", "typeRef": "Network.ContentSecurityPolicySource" }]);
    inspectorBackend.registerType("Network.SecurityIsolationStatus", [{ "name": "coop", "type": "object", "optional": true, "description": "", "typeRef": "Network.CrossOriginOpenerPolicyStatus" }, { "name": "coep", "type": "object", "optional": true, "description": "", "typeRef": "Network.CrossOriginEmbedderPolicyStatus" }, { "name": "csp", "type": "array", "optional": true, "description": "", "typeRef": "Network.ContentSecurityPolicyStatus" }]);
    inspectorBackend.registerType("Network.ReportingApiReport", [{ "name": "id", "type": "string", "optional": false, "description": "", "typeRef": "Network.ReportId" }, { "name": "initiatorUrl", "type": "string", "optional": false, "description": "The URL of the document that triggered the report.", "typeRef": null }, { "name": "destination", "type": "string", "optional": false, "description": "The name of the endpoint group that should be used to deliver the report.", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "The type of the report (specifies the set of data that is contained in the report body).", "typeRef": null }, { "name": "timestamp", "type": "number", "optional": false, "description": "When the report was generated.", "typeRef": "Network.TimeSinceEpoch" }, { "name": "depth", "type": "number", "optional": false, "description": "How many uploads deep the related request was.", "typeRef": null }, { "name": "completedAttempts", "type": "number", "optional": false, "description": "The number of delivery attempts made so far, not including an active attempt.", "typeRef": null }, { "name": "body", "type": "object", "optional": false, "description": "", "typeRef": null }, { "name": "status", "type": "string", "optional": false, "description": "", "typeRef": "Network.ReportStatus" }]);
    inspectorBackend.registerType("Network.ReportingApiEndpoint", [{ "name": "url", "type": "string", "optional": false, "description": "The URL of the endpoint to which reports may be delivered.", "typeRef": null }, { "name": "groupName", "type": "string", "optional": false, "description": "Name of the endpoint group.", "typeRef": null }]);
    inspectorBackend.registerType("Network.DeviceBoundSessionKey", [{ "name": "site", "type": "string", "optional": false, "description": "The site the session is set up for.", "typeRef": null }, { "name": "id", "type": "string", "optional": false, "description": "The id of the session.", "typeRef": null }]);
    inspectorBackend.registerType("Network.DeviceBoundSessionWithUsage", [{ "name": "sessionKey", "type": "object", "optional": false, "description": "The key for the session.", "typeRef": "Network.DeviceBoundSessionKey" }, { "name": "usage", "type": "string", "optional": false, "description": "How the session was used (or not used).", "typeRef": null }]);
    inspectorBackend.registerType("Network.DeviceBoundSessionCookieCraving", [{ "name": "name", "type": "string", "optional": false, "description": "The name of the craving.", "typeRef": null }, { "name": "domain", "type": "string", "optional": false, "description": "The domain of the craving.", "typeRef": null }, { "name": "path", "type": "string", "optional": false, "description": "The path of the craving.", "typeRef": null }, { "name": "secure", "type": "boolean", "optional": false, "description": "The `Secure` attribute of the craving attributes.", "typeRef": null }, { "name": "httpOnly", "type": "boolean", "optional": false, "description": "The `HttpOnly` attribute of the craving attributes.", "typeRef": null }, { "name": "sameSite", "type": "string", "optional": true, "description": "The `SameSite` attribute of the craving attributes.", "typeRef": "Network.CookieSameSite" }]);
    inspectorBackend.registerType("Network.DeviceBoundSessionUrlRule", [{ "name": "ruleType", "type": "string", "optional": false, "description": "See comments on `net::device_bound_sessions::SessionInclusionRules::UrlRule::rule_type`.", "typeRef": null }, { "name": "hostPattern", "type": "string", "optional": false, "description": "See comments on `net::device_bound_sessions::SessionInclusionRules::UrlRule::host_pattern`.", "typeRef": null }, { "name": "pathPrefix", "type": "string", "optional": false, "description": "See comments on `net::device_bound_sessions::SessionInclusionRules::UrlRule::path_prefix`.", "typeRef": null }]);
    inspectorBackend.registerType("Network.DeviceBoundSessionInclusionRules", [{ "name": "origin", "type": "string", "optional": false, "description": "See comments on `net::device_bound_sessions::SessionInclusionRules::origin_`.", "typeRef": null }, { "name": "includeSite", "type": "boolean", "optional": false, "description": "Whether the whole site is included. See comments on `net::device_bound_sessions::SessionInclusionRules::include_site_` for more details; this boolean is true if that value is populated.", "typeRef": null }, { "name": "urlRules", "type": "array", "optional": false, "description": "See comments on `net::device_bound_sessions::SessionInclusionRules::url_rules_`.", "typeRef": "Network.DeviceBoundSessionUrlRule" }]);
    inspectorBackend.registerType("Network.DeviceBoundSession", [{ "name": "key", "type": "object", "optional": false, "description": "The site and session ID of the session.", "typeRef": "Network.DeviceBoundSessionKey" }, { "name": "refreshUrl", "type": "string", "optional": false, "description": "See comments on `net::device_bound_sessions::Session::refresh_url_`.", "typeRef": null }, { "name": "inclusionRules", "type": "object", "optional": false, "description": "See comments on `net::device_bound_sessions::Session::inclusion_rules_`.", "typeRef": "Network.DeviceBoundSessionInclusionRules" }, { "name": "cookieCravings", "type": "array", "optional": false, "description": "See comments on `net::device_bound_sessions::Session::cookie_cravings_`.", "typeRef": "Network.DeviceBoundSessionCookieCraving" }, { "name": "expiryDate", "type": "number", "optional": false, "description": "See comments on `net::device_bound_sessions::Session::expiry_date_`.", "typeRef": "Network.TimeSinceEpoch" }, { "name": "cachedChallenge", "type": "string", "optional": true, "description": "See comments on `net::device_bound_sessions::Session::cached_challenge__`.", "typeRef": null }, { "name": "allowedRefreshInitiators", "type": "array", "optional": false, "description": "See comments on `net::device_bound_sessions::Session::allowed_refresh_initiators_`.", "typeRef": "string" }]);
    inspectorBackend.registerType("Network.DeviceBoundSessionFailedRequest", [{ "name": "requestUrl", "type": "string", "optional": false, "description": "The failed request URL.", "typeRef": null }, { "name": "netError", "type": "string", "optional": true, "description": "The net error of the response if it was not OK.", "typeRef": null }, { "name": "responseError", "type": "number", "optional": true, "description": "The response code if the net error was OK and the response code was not 200.", "typeRef": null }, { "name": "responseErrorBody", "type": "string", "optional": true, "description": "The body of the response if the net error was OK, the response code was not 200, and the response body was not empty.", "typeRef": null }]);
    inspectorBackend.registerType("Network.CreationEventDetails", [{ "name": "fetchResult", "type": "string", "optional": false, "description": "The result of the fetch attempt.", "typeRef": "Network.DeviceBoundSessionFetchResult" }, { "name": "newSession", "type": "object", "optional": true, "description": "The session if there was a newly created session. This is populated for all successful creation events.", "typeRef": "Network.DeviceBoundSession" }, { "name": "failedRequest", "type": "object", "optional": true, "description": "Details about a failed device bound session network request if there was one.", "typeRef": "Network.DeviceBoundSessionFailedRequest" }]);
    inspectorBackend.registerType("Network.RefreshEventDetails", [{ "name": "refreshResult", "type": "string", "optional": false, "description": "The result of a refresh.", "typeRef": null }, { "name": "fetchResult", "type": "string", "optional": true, "description": "If there was a fetch attempt, the result of that.", "typeRef": "Network.DeviceBoundSessionFetchResult" }, { "name": "newSession", "type": "object", "optional": true, "description": "The session display if there was a newly created session. This is populated for any refresh event that modifies the session config.", "typeRef": "Network.DeviceBoundSession" }, { "name": "wasFullyProactiveRefresh", "type": "boolean", "optional": false, "description": "See comments on `net::device_bound_sessions::RefreshEventResult::was_fully_proactive_refresh`.", "typeRef": null }, { "name": "failedRequest", "type": "object", "optional": true, "description": "Details about a failed device bound session network request if there was one.", "typeRef": "Network.DeviceBoundSessionFailedRequest" }]);
    inspectorBackend.registerType("Network.TerminationEventDetails", [{ "name": "deletionReason", "type": "string", "optional": false, "description": "The reason for a session being deleted.", "typeRef": null }]);
    inspectorBackend.registerType("Network.ChallengeEventDetails", [{ "name": "challengeResult", "type": "string", "optional": false, "description": "The result of a challenge.", "typeRef": null }, { "name": "challenge", "type": "string", "optional": false, "description": "The challenge set.", "typeRef": null }]);
    inspectorBackend.registerType("Network.LoadNetworkResourcePageResult", [{ "name": "success", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "netError", "type": "number", "optional": true, "description": "Optional values used for error reporting.", "typeRef": null }, { "name": "netErrorName", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "httpStatusCode", "type": "number", "optional": true, "description": "", "typeRef": null }, { "name": "stream", "type": "string", "optional": true, "description": "If successful, one of the following two fields holds the result.", "typeRef": "IO.StreamHandle" }, { "name": "headers", "type": "object", "optional": true, "description": "Response headers.", "typeRef": "Network.Headers" }]);
    inspectorBackend.registerType("Network.LoadNetworkResourceOptions", [{ "name": "disableCache", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "includeCredentials", "type": "boolean", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerEnum("Overlay.LineStylePattern", { Dashed: "dashed", Dotted: "dotted" });
    inspectorBackend.registerEnum("Overlay.ContrastAlgorithm", { Aa: "aa", Aaa: "aaa", Apca: "apca" });
    inspectorBackend.registerEnum("Overlay.ColorFormat", { Rgb: "rgb", Hsl: "hsl", Hwb: "hwb", Hex: "hex" });
    inspectorBackend.registerEnum("Overlay.InspectMode", { SearchForNode: "searchForNode", SearchForUAShadowDOM: "searchForUAShadowDOM", CaptureAreaScreenshot: "captureAreaScreenshot", None: "none" });
    inspectorBackend.registerEvent("Overlay.inspectNodeRequested", ["backendNodeId"]);
    inspectorBackend.registerEvent("Overlay.nodeHighlightRequested", ["nodeId"]);
    inspectorBackend.registerEvent("Overlay.screenshotRequested", ["viewport"]);
    inspectorBackend.registerEvent("Overlay.inspectPanelShowRequested", ["backendNodeId"]);
    inspectorBackend.registerEvent("Overlay.inspectedElementWindowRestored", ["backendNodeId"]);
    inspectorBackend.registerEvent("Overlay.inspectModeCanceled", []);
    inspectorBackend.registerCommand("Overlay.disable", [], [], "Disables domain notifications.");
    inspectorBackend.registerCommand("Overlay.enable", [], [], "Enables domain notifications.");
    inspectorBackend.registerCommand("Overlay.getHighlightObjectForTest", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to get highlight object for.", "typeRef": "DOM.NodeId" }, { "name": "includeDistance", "type": "boolean", "optional": true, "description": "Whether to include distance info.", "typeRef": null }, { "name": "includeStyle", "type": "boolean", "optional": true, "description": "Whether to include style info.", "typeRef": null }, { "name": "colorFormat", "type": "string", "optional": true, "description": "The color format to get config with (default: hex).", "typeRef": "Overlay.ColorFormat" }, { "name": "showAccessibilityInfo", "type": "boolean", "optional": true, "description": "Whether to show accessibility info (default: true).", "typeRef": null }], ["highlight"], "For testing.");
    inspectorBackend.registerCommand("Overlay.getGridHighlightObjectsForTest", [{ "name": "nodeIds", "type": "array", "optional": false, "description": "Ids of the node to get highlight object for.", "typeRef": "DOM.NodeId" }], ["highlights"], "For Persistent Grid testing.");
    inspectorBackend.registerCommand("Overlay.getSourceOrderHighlightObjectForTest", [{ "name": "nodeId", "type": "number", "optional": false, "description": "Id of the node to highlight.", "typeRef": "DOM.NodeId" }], ["highlight"], "For Source Order Viewer testing.");
    inspectorBackend.registerCommand("Overlay.hideHighlight", [], [], "Hides any highlight.");
    inspectorBackend.registerCommand("Overlay.highlightFrame", [{ "name": "frameId", "type": "string", "optional": false, "description": "Identifier of the frame to highlight.", "typeRef": "Page.FrameId" }, { "name": "contentColor", "type": "object", "optional": true, "description": "The content box highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "contentOutlineColor", "type": "object", "optional": true, "description": "The content box highlight outline color (default: transparent).", "typeRef": "DOM.RGBA" }], [], "Highlights owner element of the frame with given id. Deprecated: Doesn't work reliably and cannot be fixed due to process separation (the owner node might be in a different process). Determine the owner node in the client and use highlightNode.");
    inspectorBackend.registerCommand("Overlay.highlightNode", [{ "name": "highlightConfig", "type": "object", "optional": false, "description": "A descriptor for the highlight appearance.", "typeRef": "Overlay.HighlightConfig" }, { "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node to highlight.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node to highlight.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node to be highlighted.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "selector", "type": "string", "optional": true, "description": "Selectors to highlight relevant nodes.", "typeRef": null }], [], "Highlights DOM node with given id or with the given JavaScript object wrapper. Either nodeId or objectId must be specified.");
    inspectorBackend.registerCommand("Overlay.highlightQuad", [{ "name": "quad", "type": "array", "optional": false, "description": "Quad to highlight", "typeRef": "DOM.Quad" }, { "name": "color", "type": "object", "optional": true, "description": "The highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "outlineColor", "type": "object", "optional": true, "description": "The highlight outline color (default: transparent).", "typeRef": "DOM.RGBA" }], [], "Highlights given quad. Coordinates are absolute with respect to the main frame viewport.");
    inspectorBackend.registerCommand("Overlay.highlightRect", [{ "name": "x", "type": "number", "optional": false, "description": "X coordinate", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Y coordinate", "typeRef": null }, { "name": "width", "type": "number", "optional": false, "description": "Rectangle width", "typeRef": null }, { "name": "height", "type": "number", "optional": false, "description": "Rectangle height", "typeRef": null }, { "name": "color", "type": "object", "optional": true, "description": "The highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "outlineColor", "type": "object", "optional": true, "description": "The highlight outline color (default: transparent).", "typeRef": "DOM.RGBA" }], [], "Highlights given rectangle. Coordinates are absolute with respect to the main frame viewport. Issue: the method does not handle device pixel ratio (DPR) correctly. The coordinates currently have to be adjusted by the client if DPR is not 1 (see crbug.com/437807128).");
    inspectorBackend.registerCommand("Overlay.highlightSourceOrder", [{ "name": "sourceOrderConfig", "type": "object", "optional": false, "description": "A descriptor for the appearance of the overlay drawing.", "typeRef": "Overlay.SourceOrderConfig" }, { "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node to highlight.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node to highlight.", "typeRef": "DOM.BackendNodeId" }, { "name": "objectId", "type": "string", "optional": true, "description": "JavaScript object id of the node to be highlighted.", "typeRef": "Runtime.RemoteObjectId" }], [], "Highlights the source order of the children of the DOM node with given id or with the given JavaScript object wrapper. Either nodeId or objectId must be specified.");
    inspectorBackend.registerCommand("Overlay.setInspectMode", [{ "name": "mode", "type": "string", "optional": false, "description": "Set an inspection mode.", "typeRef": "Overlay.InspectMode" }, { "name": "highlightConfig", "type": "object", "optional": true, "description": "A descriptor for the highlight appearance of hovered-over nodes. May be omitted if `enabled == false`.", "typeRef": "Overlay.HighlightConfig" }], [], "Enters the 'inspect' mode. In this mode, elements that user is hovering over are highlighted. Backend then generates 'inspectNodeRequested' event upon element selection.");
    inspectorBackend.registerCommand("Overlay.setShowAdHighlights", [{ "name": "show", "type": "boolean", "optional": false, "description": "True for showing ad highlights", "typeRef": null }], [], "Highlights owner element of all frames detected to be ads.");
    inspectorBackend.registerCommand("Overlay.setPausedInDebuggerMessage", [{ "name": "message", "type": "string", "optional": true, "description": "The message to display, also triggers resume and step over controls.", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("Overlay.setShowDebugBorders", [{ "name": "show", "type": "boolean", "optional": false, "description": "True for showing debug borders", "typeRef": null }], [], "Requests that backend shows debug borders on layers");
    inspectorBackend.registerCommand("Overlay.setShowFPSCounter", [{ "name": "show", "type": "boolean", "optional": false, "description": "True for showing the FPS counter", "typeRef": null }], [], "Requests that backend shows the FPS counter");
    inspectorBackend.registerCommand("Overlay.setShowGridOverlays", [{ "name": "gridNodeHighlightConfigs", "type": "array", "optional": false, "description": "An array of node identifiers and descriptors for the highlight appearance.", "typeRef": "Overlay.GridNodeHighlightConfig" }], [], "Highlight multiple elements with the CSS Grid overlay.");
    inspectorBackend.registerCommand("Overlay.setShowFlexOverlays", [{ "name": "flexNodeHighlightConfigs", "type": "array", "optional": false, "description": "An array of node identifiers and descriptors for the highlight appearance.", "typeRef": "Overlay.FlexNodeHighlightConfig" }], [], "");
    inspectorBackend.registerCommand("Overlay.setShowScrollSnapOverlays", [{ "name": "scrollSnapHighlightConfigs", "type": "array", "optional": false, "description": "An array of node identifiers and descriptors for the highlight appearance.", "typeRef": "Overlay.ScrollSnapHighlightConfig" }], [], "");
    inspectorBackend.registerCommand("Overlay.setShowContainerQueryOverlays", [{ "name": "containerQueryHighlightConfigs", "type": "array", "optional": false, "description": "An array of node identifiers and descriptors for the highlight appearance.", "typeRef": "Overlay.ContainerQueryHighlightConfig" }], [], "");
    inspectorBackend.registerCommand("Overlay.setShowInspectedElementAnchor", [{ "name": "inspectedElementAnchorConfig", "type": "object", "optional": false, "description": "Node identifier for which to show an anchor for.", "typeRef": "Overlay.InspectedElementAnchorConfig" }], [], "");
    inspectorBackend.registerCommand("Overlay.setShowPaintRects", [{ "name": "result", "type": "boolean", "optional": false, "description": "True for showing paint rectangles", "typeRef": null }], [], "Requests that backend shows paint rectangles");
    inspectorBackend.registerCommand("Overlay.setShowLayoutShiftRegions", [{ "name": "result", "type": "boolean", "optional": false, "description": "True for showing layout shift regions", "typeRef": null }], [], "Requests that backend shows layout shift regions");
    inspectorBackend.registerCommand("Overlay.setShowScrollBottleneckRects", [{ "name": "show", "type": "boolean", "optional": false, "description": "True for showing scroll bottleneck rects", "typeRef": null }], [], "Requests that backend shows scroll bottleneck rects");
    inspectorBackend.registerCommand("Overlay.setShowHitTestBorders", [{ "name": "show", "type": "boolean", "optional": false, "description": "True for showing hit-test borders", "typeRef": null }], [], "Deprecated, no longer has any effect.");
    inspectorBackend.registerCommand("Overlay.setShowWebVitals", [{ "name": "show", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "Deprecated, no longer has any effect.");
    inspectorBackend.registerCommand("Overlay.setShowViewportSizeOnResize", [{ "name": "show", "type": "boolean", "optional": false, "description": "Whether to paint size or not.", "typeRef": null }], [], "Paints viewport size upon main frame resize.");
    inspectorBackend.registerCommand("Overlay.setShowHinge", [{ "name": "hingeConfig", "type": "object", "optional": true, "description": "hinge data, null means hideHinge", "typeRef": "Overlay.HingeConfig" }], [], "Add a dual screen device hinge");
    inspectorBackend.registerCommand("Overlay.setShowIsolatedElements", [{ "name": "isolatedElementHighlightConfigs", "type": "array", "optional": false, "description": "An array of node identifiers and descriptors for the highlight appearance.", "typeRef": "Overlay.IsolatedElementHighlightConfig" }], [], "Show elements in isolation mode with overlays.");
    inspectorBackend.registerCommand("Overlay.setShowWindowControlsOverlay", [{ "name": "windowControlsOverlayConfig", "type": "object", "optional": true, "description": "Window Controls Overlay data, null means hide Window Controls Overlay", "typeRef": "Overlay.WindowControlsOverlayConfig" }], [], "Show Window Controls Overlay for PWA");
    inspectorBackend.registerType("Overlay.SourceOrderConfig", [{ "name": "parentOutlineColor", "type": "object", "optional": false, "description": "the color to outline the given element in.", "typeRef": "DOM.RGBA" }, { "name": "childOutlineColor", "type": "object", "optional": false, "description": "the color to outline the child elements in.", "typeRef": "DOM.RGBA" }]);
    inspectorBackend.registerType("Overlay.GridHighlightConfig", [{ "name": "showGridExtensionLines", "type": "boolean", "optional": true, "description": "Whether the extension lines from grid cells to the rulers should be shown (default: false).", "typeRef": null }, { "name": "showPositiveLineNumbers", "type": "boolean", "optional": true, "description": "Show Positive line number labels (default: false).", "typeRef": null }, { "name": "showNegativeLineNumbers", "type": "boolean", "optional": true, "description": "Show Negative line number labels (default: false).", "typeRef": null }, { "name": "showAreaNames", "type": "boolean", "optional": true, "description": "Show area name labels (default: false).", "typeRef": null }, { "name": "showLineNames", "type": "boolean", "optional": true, "description": "Show line name labels (default: false).", "typeRef": null }, { "name": "showTrackSizes", "type": "boolean", "optional": true, "description": "Show track size labels (default: false).", "typeRef": null }, { "name": "gridBorderColor", "type": "object", "optional": true, "description": "The grid container border highlight color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "cellBorderColor", "type": "object", "optional": true, "description": "The cell border color (default: transparent). Deprecated, please use rowLineColor and columnLineColor instead.", "typeRef": "DOM.RGBA" }, { "name": "rowLineColor", "type": "object", "optional": true, "description": "The row line color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "columnLineColor", "type": "object", "optional": true, "description": "The column line color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "gridBorderDash", "type": "boolean", "optional": true, "description": "Whether the grid border is dashed (default: false).", "typeRef": null }, { "name": "cellBorderDash", "type": "boolean", "optional": true, "description": "Whether the cell border is dashed (default: false). Deprecated, please us rowLineDash and columnLineDash instead.", "typeRef": null }, { "name": "rowLineDash", "type": "boolean", "optional": true, "description": "Whether row lines are dashed (default: false).", "typeRef": null }, { "name": "columnLineDash", "type": "boolean", "optional": true, "description": "Whether column lines are dashed (default: false).", "typeRef": null }, { "name": "rowGapColor", "type": "object", "optional": true, "description": "The row gap highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "rowHatchColor", "type": "object", "optional": true, "description": "The row gap hatching fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "columnGapColor", "type": "object", "optional": true, "description": "The column gap highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "columnHatchColor", "type": "object", "optional": true, "description": "The column gap hatching fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "areaBorderColor", "type": "object", "optional": true, "description": "The named grid areas border color (Default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "gridBackgroundColor", "type": "object", "optional": true, "description": "The grid container background color (Default: transparent).", "typeRef": "DOM.RGBA" }]);
    inspectorBackend.registerType("Overlay.FlexContainerHighlightConfig", [{ "name": "containerBorder", "type": "object", "optional": true, "description": "The style of the container border", "typeRef": "Overlay.LineStyle" }, { "name": "lineSeparator", "type": "object", "optional": true, "description": "The style of the separator between lines", "typeRef": "Overlay.LineStyle" }, { "name": "itemSeparator", "type": "object", "optional": true, "description": "The style of the separator between items", "typeRef": "Overlay.LineStyle" }, { "name": "mainDistributedSpace", "type": "object", "optional": true, "description": "Style of content-distribution space on the main axis (justify-content).", "typeRef": "Overlay.BoxStyle" }, { "name": "crossDistributedSpace", "type": "object", "optional": true, "description": "Style of content-distribution space on the cross axis (align-content).", "typeRef": "Overlay.BoxStyle" }, { "name": "rowGapSpace", "type": "object", "optional": true, "description": "Style of empty space caused by row gaps (gap/row-gap).", "typeRef": "Overlay.BoxStyle" }, { "name": "columnGapSpace", "type": "object", "optional": true, "description": "Style of empty space caused by columns gaps (gap/column-gap).", "typeRef": "Overlay.BoxStyle" }, { "name": "crossAlignment", "type": "object", "optional": true, "description": "Style of the self-alignment line (align-items).", "typeRef": "Overlay.LineStyle" }]);
    inspectorBackend.registerType("Overlay.FlexItemHighlightConfig", [{ "name": "baseSizeBox", "type": "object", "optional": true, "description": "Style of the box representing the item's base size", "typeRef": "Overlay.BoxStyle" }, { "name": "baseSizeBorder", "type": "object", "optional": true, "description": "Style of the border around the box representing the item's base size", "typeRef": "Overlay.LineStyle" }, { "name": "flexibilityArrow", "type": "object", "optional": true, "description": "Style of the arrow representing if the item grew or shrank", "typeRef": "Overlay.LineStyle" }]);
    inspectorBackend.registerType("Overlay.LineStyle", [{ "name": "color", "type": "object", "optional": true, "description": "The color of the line (default: transparent)", "typeRef": "DOM.RGBA" }, { "name": "pattern", "type": "string", "optional": true, "description": "The line pattern (default: solid)", "typeRef": null }]);
    inspectorBackend.registerType("Overlay.BoxStyle", [{ "name": "fillColor", "type": "object", "optional": true, "description": "The background color for the box (default: transparent)", "typeRef": "DOM.RGBA" }, { "name": "hatchColor", "type": "object", "optional": true, "description": "The hatching color for the box (default: transparent)", "typeRef": "DOM.RGBA" }]);
    inspectorBackend.registerType("Overlay.HighlightConfig", [{ "name": "showInfo", "type": "boolean", "optional": true, "description": "Whether the node info tooltip should be shown (default: false).", "typeRef": null }, { "name": "showStyles", "type": "boolean", "optional": true, "description": "Whether the node styles in the tooltip (default: false).", "typeRef": null }, { "name": "showRulers", "type": "boolean", "optional": true, "description": "Whether the rulers should be shown (default: false).", "typeRef": null }, { "name": "showAccessibilityInfo", "type": "boolean", "optional": true, "description": "Whether the a11y info should be shown (default: true).", "typeRef": null }, { "name": "showExtensionLines", "type": "boolean", "optional": true, "description": "Whether the extension lines from node to the rulers should be shown (default: false).", "typeRef": null }, { "name": "contentColor", "type": "object", "optional": true, "description": "The content box highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "paddingColor", "type": "object", "optional": true, "description": "The padding highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "borderColor", "type": "object", "optional": true, "description": "The border highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "marginColor", "type": "object", "optional": true, "description": "The margin highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "eventTargetColor", "type": "object", "optional": true, "description": "The event target element highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "shapeColor", "type": "object", "optional": true, "description": "The shape outside fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "shapeMarginColor", "type": "object", "optional": true, "description": "The shape margin fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "cssGridColor", "type": "object", "optional": true, "description": "The grid layout color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "colorFormat", "type": "string", "optional": true, "description": "The color format used to format color styles (default: hex).", "typeRef": "Overlay.ColorFormat" }, { "name": "gridHighlightConfig", "type": "object", "optional": true, "description": "The grid layout highlight configuration (default: all transparent).", "typeRef": "Overlay.GridHighlightConfig" }, { "name": "flexContainerHighlightConfig", "type": "object", "optional": true, "description": "The flex container highlight configuration (default: all transparent).", "typeRef": "Overlay.FlexContainerHighlightConfig" }, { "name": "flexItemHighlightConfig", "type": "object", "optional": true, "description": "The flex item highlight configuration (default: all transparent).", "typeRef": "Overlay.FlexItemHighlightConfig" }, { "name": "contrastAlgorithm", "type": "string", "optional": true, "description": "The contrast algorithm to use for the contrast ratio (default: aa).", "typeRef": "Overlay.ContrastAlgorithm" }, { "name": "containerQueryContainerHighlightConfig", "type": "object", "optional": true, "description": "The container query container highlight configuration (default: all transparent).", "typeRef": "Overlay.ContainerQueryContainerHighlightConfig" }]);
    inspectorBackend.registerType("Overlay.GridNodeHighlightConfig", [{ "name": "gridHighlightConfig", "type": "object", "optional": false, "description": "A descriptor for the highlight appearance.", "typeRef": "Overlay.GridHighlightConfig" }, { "name": "nodeId", "type": "number", "optional": false, "description": "Identifier of the node to highlight.", "typeRef": "DOM.NodeId" }]);
    inspectorBackend.registerType("Overlay.FlexNodeHighlightConfig", [{ "name": "flexContainerHighlightConfig", "type": "object", "optional": false, "description": "A descriptor for the highlight appearance of flex containers.", "typeRef": "Overlay.FlexContainerHighlightConfig" }, { "name": "nodeId", "type": "number", "optional": false, "description": "Identifier of the node to highlight.", "typeRef": "DOM.NodeId" }]);
    inspectorBackend.registerType("Overlay.ScrollSnapContainerHighlightConfig", [{ "name": "snapportBorder", "type": "object", "optional": true, "description": "The style of the snapport border (default: transparent)", "typeRef": "Overlay.LineStyle" }, { "name": "snapAreaBorder", "type": "object", "optional": true, "description": "The style of the snap area border (default: transparent)", "typeRef": "Overlay.LineStyle" }, { "name": "scrollMarginColor", "type": "object", "optional": true, "description": "The margin highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "scrollPaddingColor", "type": "object", "optional": true, "description": "The padding highlight fill color (default: transparent).", "typeRef": "DOM.RGBA" }]);
    inspectorBackend.registerType("Overlay.ScrollSnapHighlightConfig", [{ "name": "scrollSnapContainerHighlightConfig", "type": "object", "optional": false, "description": "A descriptor for the highlight appearance of scroll snap containers.", "typeRef": "Overlay.ScrollSnapContainerHighlightConfig" }, { "name": "nodeId", "type": "number", "optional": false, "description": "Identifier of the node to highlight.", "typeRef": "DOM.NodeId" }]);
    inspectorBackend.registerType("Overlay.HingeConfig", [{ "name": "rect", "type": "object", "optional": false, "description": "A rectangle represent hinge", "typeRef": "DOM.Rect" }, { "name": "contentColor", "type": "object", "optional": true, "description": "The content box highlight fill color (default: a dark color).", "typeRef": "DOM.RGBA" }, { "name": "outlineColor", "type": "object", "optional": true, "description": "The content box highlight outline color (default: transparent).", "typeRef": "DOM.RGBA" }]);
    inspectorBackend.registerType("Overlay.WindowControlsOverlayConfig", [{ "name": "showCSS", "type": "boolean", "optional": false, "description": "Whether the title bar CSS should be shown when emulating the Window Controls Overlay.", "typeRef": null }, { "name": "selectedPlatform", "type": "string", "optional": false, "description": "Selected platforms to show the overlay.", "typeRef": null }, { "name": "themeColor", "type": "string", "optional": false, "description": "The theme color defined in app manifest.", "typeRef": null }]);
    inspectorBackend.registerType("Overlay.ContainerQueryHighlightConfig", [{ "name": "containerQueryContainerHighlightConfig", "type": "object", "optional": false, "description": "A descriptor for the highlight appearance of container query containers.", "typeRef": "Overlay.ContainerQueryContainerHighlightConfig" }, { "name": "nodeId", "type": "number", "optional": false, "description": "Identifier of the container node to highlight.", "typeRef": "DOM.NodeId" }]);
    inspectorBackend.registerType("Overlay.ContainerQueryContainerHighlightConfig", [{ "name": "containerBorder", "type": "object", "optional": true, "description": "The style of the container border.", "typeRef": "Overlay.LineStyle" }, { "name": "descendantBorder", "type": "object", "optional": true, "description": "The style of the descendants' borders.", "typeRef": "Overlay.LineStyle" }]);
    inspectorBackend.registerType("Overlay.IsolatedElementHighlightConfig", [{ "name": "isolationModeHighlightConfig", "type": "object", "optional": false, "description": "A descriptor for the highlight appearance of an element in isolation mode.", "typeRef": "Overlay.IsolationModeHighlightConfig" }, { "name": "nodeId", "type": "number", "optional": false, "description": "Identifier of the isolated element to highlight.", "typeRef": "DOM.NodeId" }]);
    inspectorBackend.registerType("Overlay.IsolationModeHighlightConfig", [{ "name": "resizerColor", "type": "object", "optional": true, "description": "The fill color of the resizers (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "resizerHandleColor", "type": "object", "optional": true, "description": "The fill color for resizer handles (default: transparent).", "typeRef": "DOM.RGBA" }, { "name": "maskColor", "type": "object", "optional": true, "description": "The fill color for the mask covering non-isolated elements (default: transparent).", "typeRef": "DOM.RGBA" }]);
    inspectorBackend.registerType("Overlay.InspectedElementAnchorConfig", [{ "name": "nodeId", "type": "number", "optional": true, "description": "Identifier of the node to highlight.", "typeRef": "DOM.NodeId" }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "Identifier of the backend node to highlight.", "typeRef": "DOM.BackendNodeId" }]);
    inspectorBackend.registerEnum("PWA.DisplayMode", { Standalone: "standalone", Browser: "browser" });
    inspectorBackend.registerCommand("PWA.getOsAppState", [{ "name": "manifestId", "type": "string", "optional": false, "description": "The id from the webapp's manifest file, commonly it's the url of the site installing the webapp. See https://web.dev/learn/pwa/web-app-manifest.", "typeRef": null }], ["badgeCount", "fileHandlers"], "Returns the following OS state for the given manifest id.");
    inspectorBackend.registerCommand("PWA.install", [{ "name": "manifestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "installUrlOrBundleUrl", "type": "string", "optional": true, "description": "The location of the app or bundle overriding the one derived from the manifestId.", "typeRef": null }], [], "Installs the given manifest identity, optionally using the given installUrlOrBundleUrl  IWA-specific install description: manifestId corresponds to isolated-app:// + web_package::SignedWebBundleId  File installation mode: The installUrlOrBundleUrl can be either file:// or http(s):// pointing to a signed web bundle (.swbn). In this case SignedWebBundleId must correspond to The .swbn file's signing key.  Dev proxy installation mode: installUrlOrBundleUrl must be http(s):// that serves dev mode IWA. web_package::SignedWebBundleId must be of type dev proxy.  The advantage of dev proxy mode is that all changes to IWA automatically will be reflected in the running app without reinstallation.  To generate bundle id for proxy mode: 1. Generate 32 random bytes. 2. Add a specific suffix at the end following the documentation    https://github.com/WICG/isolated-web-apps/blob/main/Scheme.md#suffix 3. Encode the entire sequence using Base32 without padding.  If Chrome is not in IWA dev mode, the installation will fail, regardless of the state of the allowlist.");
    inspectorBackend.registerCommand("PWA.uninstall", [{ "name": "manifestId", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Uninstalls the given manifest_id and closes any opened app windows.");
    inspectorBackend.registerCommand("PWA.launch", [{ "name": "manifestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "url", "type": "string", "optional": true, "description": "", "typeRef": null }], ["targetId"], "Launches the installed web app, or an url in the same web app instead of the default start url if it is provided. Returns a page Target.TargetID which can be used to attach to via Target.attachToTarget or similar APIs.");
    inspectorBackend.registerCommand("PWA.launchFilesInApp", [{ "name": "manifestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "files", "type": "array", "optional": false, "description": "", "typeRef": "string" }], ["targetIds"], "Opens one or more local files from an installed web app identified by its manifestId. The web app needs to have file handlers registered to process the files. The API returns one or more page Target.TargetIDs which can be used to attach to via Target.attachToTarget or similar APIs. If some files in the parameters cannot be handled by the web app, they will be ignored. If none of the files can be handled, this API returns an error. If no files are provided as the parameter, this API also returns an error.  According to the definition of the file handlers in the manifest file, one Target.TargetID may represent a page handling one or more files. The order of the returned Target.TargetIDs is not guaranteed.  TODO(crbug.com/339454034): Check the existences of the input files.");
    inspectorBackend.registerCommand("PWA.openCurrentPageInApp", [{ "name": "manifestId", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Opens the current page in its web app identified by the manifest id, needs to be called on a page target. This function returns immediately without waiting for the app to finish loading.");
    inspectorBackend.registerCommand("PWA.changeAppUserSettings", [{ "name": "manifestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "linkCapturing", "type": "boolean", "optional": true, "description": "If user allows the links clicked on by the user in the app's scope, or extended scope if the manifest has scope extensions and the flags `DesktopPWAsLinkCapturingWithScopeExtensions` and `WebAppEnableScopeExtensions` are enabled.  Note, the API does not support resetting the linkCapturing to the initial value, uninstalling and installing the web app again will reset it.  TODO(crbug.com/339453269): Setting this value on ChromeOS is not supported yet.", "typeRef": null }, { "name": "displayMode", "type": "string", "optional": true, "description": "", "typeRef": "PWA.DisplayMode" }], [], "Changes user settings of the web app identified by its manifestId. If the app was not installed, this command returns an error. Unset parameters will be ignored; unrecognized values will cause an error.  Unlike the ones defined in the manifest files of the web apps, these settings are provided by the browser and controlled by the users, they impact the way the browser handling the web apps.  See the comment of each parameter.");
    inspectorBackend.registerType("PWA.FileHandlerAccept", [{ "name": "mediaType", "type": "string", "optional": false, "description": "New name of the mimetype according to https://www.iana.org/assignments/media-types/media-types.xhtml", "typeRef": null }, { "name": "fileExtensions", "type": "array", "optional": false, "description": "", "typeRef": "string" }]);
    inspectorBackend.registerType("PWA.FileHandler", [{ "name": "action", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "accepts", "type": "array", "optional": false, "description": "", "typeRef": "PWA.FileHandlerAccept" }, { "name": "displayName", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerEnum("Page.AdFrameType", { None: "none", Child: "child", Root: "root" });
    inspectorBackend.registerEnum("Page.AdFrameExplanation", { ParentIsAd: "ParentIsAd", CreatedByAdScript: "CreatedByAdScript", MatchedBlockingRule: "MatchedBlockingRule" });
    inspectorBackend.registerEnum("Page.SecureContextType", { Secure: "Secure", SecureLocalhost: "SecureLocalhost", InsecureScheme: "InsecureScheme", InsecureAncestor: "InsecureAncestor" });
    inspectorBackend.registerEnum("Page.CrossOriginIsolatedContextType", { Isolated: "Isolated", NotIsolated: "NotIsolated", NotIsolatedFeatureDisabled: "NotIsolatedFeatureDisabled" });
    inspectorBackend.registerEnum("Page.GatedAPIFeatures", { SharedArrayBuffers: "SharedArrayBuffers", SharedArrayBuffersTransferAllowed: "SharedArrayBuffersTransferAllowed", PerformanceMeasureMemory: "PerformanceMeasureMemory", PerformanceProfile: "PerformanceProfile" });
    inspectorBackend.registerEnum("Page.PermissionsPolicyFeature", { Accelerometer: "accelerometer", AllScreensCapture: "all-screens-capture", AmbientLightSensor: "ambient-light-sensor", AriaNotify: "aria-notify", AttributionReporting: "attribution-reporting", Autofill: "autofill", Autoplay: "autoplay", Bluetooth: "bluetooth", BrowsingTopics: "browsing-topics", Camera: "camera", CapturedSurfaceControl: "captured-surface-control", ChDpr: "ch-dpr", ChDeviceMemory: "ch-device-memory", ChDownlink: "ch-downlink", ChEct: "ch-ect", ChPrefersColorScheme: "ch-prefers-color-scheme", ChPrefersReducedMotion: "ch-prefers-reduced-motion", ChPrefersReducedTransparency: "ch-prefers-reduced-transparency", ChRtt: "ch-rtt", ChSaveData: "ch-save-data", ChUa: "ch-ua", ChUaArch: "ch-ua-arch", ChUaBitness: "ch-ua-bitness", ChUaHighEntropyValues: "ch-ua-high-entropy-values", ChUaPlatform: "ch-ua-platform", ChUaModel: "ch-ua-model", ChUaMobile: "ch-ua-mobile", ChUaFormFactors: "ch-ua-form-factors", ChUaFullVersion: "ch-ua-full-version", ChUaFullVersionList: "ch-ua-full-version-list", ChUaPlatformVersion: "ch-ua-platform-version", ChUaWow64: "ch-ua-wow64", ChViewportHeight: "ch-viewport-height", ChViewportWidth: "ch-viewport-width", ChWidth: "ch-width", ClipboardRead: "clipboard-read", ClipboardWrite: "clipboard-write", ComputePressure: "compute-pressure", ControlledFrame: "controlled-frame", CrossOriginIsolated: "cross-origin-isolated", DeferredFetch: "deferred-fetch", DeferredFetchMinimal: "deferred-fetch-minimal", DeviceAttributes: "device-attributes", DigitalCredentialsCreate: "digital-credentials-create", DigitalCredentialsGet: "digital-credentials-get", DirectSockets: "direct-sockets", DirectSocketsMulticast: "direct-sockets-multicast", DirectSocketsPrivate: "direct-sockets-private", DisplayCapture: "display-capture", DocumentDomain: "document-domain", EncryptedMedia: "encrypted-media", ExecutionWhileOutOfViewport: "execution-while-out-of-viewport", ExecutionWhileNotRendered: "execution-while-not-rendered", FencedUnpartitionedStorageRead: "fenced-unpartitioned-storage-read", FocusWithoutUserActivation: "focus-without-user-activation", Fullscreen: "fullscreen", Frobulate: "frobulate", Gamepad: "gamepad", Geolocation: "geolocation", Gyroscope: "gyroscope", Hid: "hid", IdentityCredentialsGet: "identity-credentials-get", IdleDetection: "idle-detection", InterestCohort: "interest-cohort", JoinAdInterestGroup: "join-ad-interest-group", KeyboardMap: "keyboard-map", LanguageDetector: "language-detector", LanguageModel: "language-model", LocalFonts: "local-fonts", LocalNetwork: "local-network", LocalNetworkAccess: "local-network-access", LoopbackNetwork: "loopback-network", Magnetometer: "magnetometer", ManualText: "manual-text", MediaPlaybackWhileNotVisible: "media-playback-while-not-visible", Microphone: "microphone", Midi: "midi", OnDeviceSpeechRecognition: "on-device-speech-recognition", OtpCredentials: "otp-credentials", Payment: "payment", PictureInPicture: "picture-in-picture", PrivateAggregation: "private-aggregation", PrivateStateTokenIssuance: "private-state-token-issuance", PrivateStateTokenRedemption: "private-state-token-redemption", PublickeyCredentialsCreate: "publickey-credentials-create", PublickeyCredentialsGet: "publickey-credentials-get", RecordAdAuctionEvents: "record-ad-auction-events", Rewriter: "rewriter", RunAdAuction: "run-ad-auction", ScreenWakeLock: "screen-wake-lock", Serial: "serial", SharedStorage: "shared-storage", SharedStorageSelectUrl: "shared-storage-select-url", SmartCard: "smart-card", SpeakerSelection: "speaker-selection", StorageAccess: "storage-access", SubApps: "sub-apps", Summarizer: "summarizer", SyncXhr: "sync-xhr", Translator: "translator", Unload: "unload", Usb: "usb", UsbUnrestricted: "usb-unrestricted", VerticalScroll: "vertical-scroll", WebAppInstallation: "web-app-installation", WebPrinting: "web-printing", WebShare: "web-share", WindowManagement: "window-management", Writer: "writer", XrSpatialTracking: "xr-spatial-tracking" });
    inspectorBackend.registerEnum("Page.PermissionsPolicyBlockReason", { Header: "Header", IframeAttribute: "IframeAttribute", InFencedFrameTree: "InFencedFrameTree", InIsolatedApp: "InIsolatedApp" });
    inspectorBackend.registerEnum("Page.OriginTrialTokenStatus", { Success: "Success", NotSupported: "NotSupported", Insecure: "Insecure", Expired: "Expired", WrongOrigin: "WrongOrigin", InvalidSignature: "InvalidSignature", Malformed: "Malformed", WrongVersion: "WrongVersion", FeatureDisabled: "FeatureDisabled", TokenDisabled: "TokenDisabled", FeatureDisabledForUser: "FeatureDisabledForUser", UnknownTrial: "UnknownTrial" });
    inspectorBackend.registerEnum("Page.OriginTrialStatus", { Enabled: "Enabled", ValidTokenNotProvided: "ValidTokenNotProvided", OSNotSupported: "OSNotSupported", TrialNotAllowed: "TrialNotAllowed" });
    inspectorBackend.registerEnum("Page.OriginTrialUsageRestriction", { None: "None", Subset: "Subset" });
    inspectorBackend.registerEnum("Page.TransitionType", { Link: "link", Typed: "typed", Address_bar: "address_bar", Auto_bookmark: "auto_bookmark", Auto_subframe: "auto_subframe", Manual_subframe: "manual_subframe", Generated: "generated", Auto_toplevel: "auto_toplevel", Form_submit: "form_submit", Reload: "reload", Keyword: "keyword", Keyword_generated: "keyword_generated", Other: "other" });
    inspectorBackend.registerEnum("Page.DialogType", { Alert: "alert", Confirm: "confirm", Prompt: "prompt", Beforeunload: "beforeunload" });
    inspectorBackend.registerEnum("Page.ClientNavigationReason", { AnchorClick: "anchorClick", FormSubmissionGet: "formSubmissionGet", FormSubmissionPost: "formSubmissionPost", HttpHeaderRefresh: "httpHeaderRefresh", InitialFrameNavigation: "initialFrameNavigation", MetaTagRefresh: "metaTagRefresh", Other: "other", PageBlockInterstitial: "pageBlockInterstitial", Reload: "reload", ScriptInitiated: "scriptInitiated" });
    inspectorBackend.registerEnum("Page.ClientNavigationDisposition", { CurrentTab: "currentTab", NewTab: "newTab", NewWindow: "newWindow", Download: "download" });
    inspectorBackend.registerEnum("Page.ReferrerPolicy", { NoReferrer: "noReferrer", NoReferrerWhenDowngrade: "noReferrerWhenDowngrade", Origin: "origin", OriginWhenCrossOrigin: "originWhenCrossOrigin", SameOrigin: "sameOrigin", StrictOrigin: "strictOrigin", StrictOriginWhenCrossOrigin: "strictOriginWhenCrossOrigin", UnsafeUrl: "unsafeUrl" });
    inspectorBackend.registerEnum("Page.NavigationType", { Navigation: "Navigation", BackForwardCacheRestore: "BackForwardCacheRestore" });
    inspectorBackend.registerEnum("Page.BackForwardCacheNotRestoredReason", { NotPrimaryMainFrame: "NotPrimaryMainFrame", BackForwardCacheDisabled: "BackForwardCacheDisabled", RelatedActiveContentsExist: "RelatedActiveContentsExist", HTTPStatusNotOK: "HTTPStatusNotOK", SchemeNotHTTPOrHTTPS: "SchemeNotHTTPOrHTTPS", Loading: "Loading", WasGrantedMediaAccess: "WasGrantedMediaAccess", DisableForRenderFrameHostCalled: "DisableForRenderFrameHostCalled", DomainNotAllowed: "DomainNotAllowed", HTTPMethodNotGET: "HTTPMethodNotGET", SubframeIsNavigating: "SubframeIsNavigating", Timeout: "Timeout", CacheLimit: "CacheLimit", JavaScriptExecution: "JavaScriptExecution", RendererProcessKilled: "RendererProcessKilled", RendererProcessCrashed: "RendererProcessCrashed", SchedulerTrackedFeatureUsed: "SchedulerTrackedFeatureUsed", ConflictingBrowsingInstance: "ConflictingBrowsingInstance", CacheFlushed: "CacheFlushed", ServiceWorkerVersionActivation: "ServiceWorkerVersionActivation", SessionRestored: "SessionRestored", ServiceWorkerPostMessage: "ServiceWorkerPostMessage", EnteredBackForwardCacheBeforeServiceWorkerHostAdded: "EnteredBackForwardCacheBeforeServiceWorkerHostAdded", RenderFrameHostReused_SameSite: "RenderFrameHostReused_SameSite", RenderFrameHostReused_CrossSite: "RenderFrameHostReused_CrossSite", ServiceWorkerClaim: "ServiceWorkerClaim", IgnoreEventAndEvict: "IgnoreEventAndEvict", HaveInnerContents: "HaveInnerContents", TimeoutPuttingInCache: "TimeoutPuttingInCache", BackForwardCacheDisabledByLowMemory: "BackForwardCacheDisabledByLowMemory", BackForwardCacheDisabledByCommandLine: "BackForwardCacheDisabledByCommandLine", NetworkRequestDatAPIpeDrainedAsBytesConsumer: "NetworkRequestDatapipeDrainedAsBytesConsumer", NetworkRequestRedirected: "NetworkRequestRedirected", NetworkRequestTimeout: "NetworkRequestTimeout", NetworkExceedsBufferLimit: "NetworkExceedsBufferLimit", NavigationCancelledWhileRestoring: "NavigationCancelledWhileRestoring", NotMostRecentNavigationEntry: "NotMostRecentNavigationEntry", BackForwardCacheDisabledForPrerender: "BackForwardCacheDisabledForPrerender", UserAgentOverrideDiffers: "UserAgentOverrideDiffers", ForegroundCacheLimit: "ForegroundCacheLimit", BrowsingInstanceNotSwapped: "BrowsingInstanceNotSwapped", BackForwardCacheDisabledForDelegate: "BackForwardCacheDisabledForDelegate", UnloadHandlerExistsInMainFrame: "UnloadHandlerExistsInMainFrame", UnloadHandlerExistsInSubFrame: "UnloadHandlerExistsInSubFrame", ServiceWorkerUnregistration: "ServiceWorkerUnregistration", CacheControlNoStore: "CacheControlNoStore", CacheControlNoStoreCookieModified: "CacheControlNoStoreCookieModified", CacheControlNoStoreHTTPOnlyCookieModified: "CacheControlNoStoreHTTPOnlyCookieModified", NoResponseHead: "NoResponseHead", Unknown: "Unknown", ActivationNavigationsDisallowedForBug1234857: "ActivationNavigationsDisallowedForBug1234857", ErrorDocument: "ErrorDocument", FencedFramesEmbedder: "FencedFramesEmbedder", CookieDisabled: "CookieDisabled", HTTPAuthRequired: "HTTPAuthRequired", CookieFlushed: "CookieFlushed", BroadcastChannelOnMessage: "BroadcastChannelOnMessage", WebViewSettingsChanged: "WebViewSettingsChanged", WebViewJavaScriptObjectChanged: "WebViewJavaScriptObjectChanged", WebViewMessageListenerInjected: "WebViewMessageListenerInjected", WebViewSafeBrowsingAllowlistChanged: "WebViewSafeBrowsingAllowlistChanged", WebViewDocumentStartJavascriptChanged: "WebViewDocumentStartJavascriptChanged", WebSocket: "WebSocket", WebTransport: "WebTransport", WebRTC: "WebRTC", MainResourceHasCacheControlNoStore: "MainResourceHasCacheControlNoStore", MainResourceHasCacheControlNoCache: "MainResourceHasCacheControlNoCache", SubresourceHasCacheControlNoStore: "SubresourceHasCacheControlNoStore", SubresourceHasCacheControlNoCache: "SubresourceHasCacheControlNoCache", ContainsPlugins: "ContainsPlugins", DocumentLoaded: "DocumentLoaded", OutstandingNetworkRequestOthers: "OutstandingNetworkRequestOthers", RequestedMIDIPermission: "RequestedMIDIPermission", RequestedAudioCapturePermission: "RequestedAudioCapturePermission", RequestedVideoCapturePermission: "RequestedVideoCapturePermission", RequestedBackForwardCacheBlockedSensors: "RequestedBackForwardCacheBlockedSensors", RequestedBackgroundWorkPermission: "RequestedBackgroundWorkPermission", BroadcastChannel: "BroadcastChannel", WebXR: "WebXR", SharedWorker: "SharedWorker", SharedWorkerMessage: "SharedWorkerMessage", SharedWorkerWithNoActiveClient: "SharedWorkerWithNoActiveClient", WebLocks: "WebLocks", WebLocksContention: "WebLocksContention", WebHID: "WebHID", WebBluetooth: "WebBluetooth", WebShare: "WebShare", RequestedStorageAccessGrant: "RequestedStorageAccessGrant", WebNfc: "WebNfc", OutstandingNetworkRequestFetch: "OutstandingNetworkRequestFetch", OutstandingNetworkRequestXHR: "OutstandingNetworkRequestXHR", AppBanner: "AppBanner", Printing: "Printing", WebDatabase: "WebDatabase", PictureInPicture: "PictureInPicture", SpeechRecognizer: "SpeechRecognizer", IdleManager: "IdleManager", PaymentManager: "PaymentManager", SpeechSynthesis: "SpeechSynthesis", KeyboardLock: "KeyboardLock", WebOTPService: "WebOTPService", OutstandingNetworkRequestDirectSocket: "OutstandingNetworkRequestDirectSocket", InjectedJavascript: "InjectedJavascript", InjectedStyleSheet: "InjectedStyleSheet", KeepaliveRequest: "KeepaliveRequest", IndexedDBEvent: "IndexedDBEvent", Dummy: "Dummy", JsNetworkRequestReceivedCacheControlNoStoreResource: "JsNetworkRequestReceivedCacheControlNoStoreResource", WebRTCUsedWithCCNS: "WebRTCUsedWithCCNS", WebTransportUsedWithCCNS: "WebTransportUsedWithCCNS", WebSocketUsedWithCCNS: "WebSocketUsedWithCCNS", SmartCard: "SmartCard", LiveMediaStreamTrack: "LiveMediaStreamTrack", UnloadHandler: "UnloadHandler", ParserAborted: "ParserAborted", ContentSecurityHandler: "ContentSecurityHandler", ContentWebAuthenticationAPI: "ContentWebAuthenticationAPI", ContentFileChooser: "ContentFileChooser", ContentSerial: "ContentSerial", ContentFileSystemAccess: "ContentFileSystemAccess", ContentMediaDevicesDispatcherHost: "ContentMediaDevicesDispatcherHost", ContentWebBluetooth: "ContentWebBluetooth", ContentWebUSB: "ContentWebUSB", ContentMediaSessionService: "ContentMediaSessionService", ContentScreenReader: "ContentScreenReader", ContentDiscarded: "ContentDiscarded", EmbedderPopupBlockerTabHelper: "EmbedderPopupBlockerTabHelper", EmbedderSafeBrowsingTriggeredPopupBlocker: "EmbedderSafeBrowsingTriggeredPopupBlocker", EmbedderSafeBrowsingThreatDetails: "EmbedderSafeBrowsingThreatDetails", EmbedderAppBannerManager: "EmbedderAppBannerManager", EmbedderDomDistillerViewerSource: "EmbedderDomDistillerViewerSource", EmbedderDomDistillerSelfDeletingRequestDelegate: "EmbedderDomDistillerSelfDeletingRequestDelegate", EmbedderOomInterventionTabHelper: "EmbedderOomInterventionTabHelper", EmbedderOfflinePage: "EmbedderOfflinePage", EmbedderChromePasswordManagerClientBindCredentialManager: "EmbedderChromePasswordManagerClientBindCredentialManager", EmbedderPermissionRequestManager: "EmbedderPermissionRequestManager", EmbedderModalDialog: "EmbedderModalDialog", EmbedderExtensions: "EmbedderExtensions", EmbedderExtensionMessaging: "EmbedderExtensionMessaging", EmbedderExtensionMessagingForOpenPort: "EmbedderExtensionMessagingForOpenPort", EmbedderExtensionSentMessageToCachedFrame: "EmbedderExtensionSentMessageToCachedFrame", RequestedByWebViewClient: "RequestedByWebViewClient", PostMessageByWebViewClient: "PostMessageByWebViewClient", CacheControlNoStoreDeviceBoundSessionTerminated: "CacheControlNoStoreDeviceBoundSessionTerminated", CacheLimitPrunedOnModerateMemoryPressure: "CacheLimitPrunedOnModerateMemoryPressure", CacheLimitPrunedOnCriticalMemoryPressure: "CacheLimitPrunedOnCriticalMemoryPressure" });
    inspectorBackend.registerEnum("Page.BackForwardCacheNotRestoredReasonType", { SupportPending: "SupportPending", PageSupportNeeded: "PageSupportNeeded", Circumstantial: "Circumstantial" });
    inspectorBackend.registerEvent("Page.domContentEventFired", ["timestamp"]);
    inspectorBackend.registerEnum("Page.FileChooserOpenedEventMode", { SelectSingle: "selectSingle", SelectMultiple: "selectMultiple" });
    inspectorBackend.registerEvent("Page.fileChooserOpened", ["frameId", "mode", "backendNodeId"]);
    inspectorBackend.registerEvent("Page.frameAttached", ["frameId", "parentFrameId", "stack"]);
    inspectorBackend.registerEvent("Page.frameClearedScheduledNavigation", ["frameId"]);
    inspectorBackend.registerEnum("Page.FrameDetachedEventReason", { Remove: "remove", Swap: "swap" });
    inspectorBackend.registerEvent("Page.frameDetached", ["frameId", "reason"]);
    inspectorBackend.registerEvent("Page.frameSubtreeWillBeDetached", ["frameId"]);
    inspectorBackend.registerEvent("Page.frameNavigated", ["frame", "type"]);
    inspectorBackend.registerEvent("Page.documentOpened", ["frame"]);
    inspectorBackend.registerEvent("Page.frameResized", []);
    inspectorBackend.registerEnum("Page.FrameStartedNavigatingEventNavigationType", { Reload: "reload", ReloadBypassingCache: "reloadBypassingCache", Restore: "restore", RestoreWithPost: "restoreWithPost", HistorySameDocument: "historySameDocument", HistoryDifferentDocument: "historyDifferentDocument", SameDocument: "sameDocument", DifferentDocument: "differentDocument" });
    inspectorBackend.registerEvent("Page.frameStartedNavigating", ["frameId", "url", "loaderId", "navigationType"]);
    inspectorBackend.registerEvent("Page.frameRequestedNavigation", ["frameId", "reason", "url", "disposition"]);
    inspectorBackend.registerEvent("Page.frameScheduledNavigation", ["frameId", "delay", "reason", "url"]);
    inspectorBackend.registerEvent("Page.frameStartedLoading", ["frameId"]);
    inspectorBackend.registerEvent("Page.frameStoppedLoading", ["frameId"]);
    inspectorBackend.registerEvent("Page.downloadWillBegin", ["frameId", "guid", "url", "suggestedFilename"]);
    inspectorBackend.registerEnum("Page.DownloadProgressEventState", { InProgress: "inProgress", Completed: "completed", Canceled: "canceled" });
    inspectorBackend.registerEvent("Page.downloadProgress", ["guid", "totalBytes", "receivedBytes", "state"]);
    inspectorBackend.registerEvent("Page.interstitialHidden", []);
    inspectorBackend.registerEvent("Page.interstitialShown", []);
    inspectorBackend.registerEvent("Page.javascriptDialogClosed", ["frameId", "result", "userInput"]);
    inspectorBackend.registerEvent("Page.javascriptDialogOpening", ["url", "frameId", "message", "type", "hasBrowserHandler", "defaultPrompt"]);
    inspectorBackend.registerEvent("Page.lifecycleEvent", ["frameId", "loaderId", "name", "timestamp"]);
    inspectorBackend.registerEvent("Page.backForwardCacheNotUsed", ["loaderId", "frameId", "notRestoredExplanations", "notRestoredExplanationsTree"]);
    inspectorBackend.registerEvent("Page.loadEventFired", ["timestamp"]);
    inspectorBackend.registerEnum("Page.NavigatedWithinDocumentEventNavigationType", { Fragment: "fragment", HistoryAPI: "historyApi", Other: "other" });
    inspectorBackend.registerEvent("Page.navigatedWithinDocument", ["frameId", "url", "navigationType"]);
    inspectorBackend.registerEvent("Page.screencastFrame", ["data", "metadata", "sessionId"]);
    inspectorBackend.registerEvent("Page.screencastVisibilityChanged", ["visible"]);
    inspectorBackend.registerEvent("Page.windowOpen", ["url", "windowName", "windowFeatures", "userGesture"]);
    inspectorBackend.registerEvent("Page.compilationCacheProduced", ["url", "data"]);
    inspectorBackend.registerCommand("Page.addScriptToEvaluateOnLoad", [{ "name": "scriptSource", "type": "string", "optional": false, "description": "", "typeRef": null }], ["identifier"], "Deprecated, please use addScriptToEvaluateOnNewDocument instead.");
    inspectorBackend.registerCommand("Page.addScriptToEvaluateOnNewDocument", [{ "name": "source", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "worldName", "type": "string", "optional": true, "description": "If specified, creates an isolated world with the given name and evaluates given script in it. This world name will be used as the ExecutionContextDescription::name when the corresponding event is emitted.", "typeRef": null }, { "name": "includeCommandLineAPI", "type": "boolean", "optional": true, "description": "Specifies whether command line API should be available to the script, defaults to false.", "typeRef": null }, { "name": "runImmediately", "type": "boolean", "optional": true, "description": "If true, runs the script immediately on existing execution contexts or worlds. Default: false.", "typeRef": null }], ["identifier"], "Evaluates given script in every frame upon creation (before loading frame's scripts).");
    inspectorBackend.registerCommand("Page.bringToFront", [], [], "Brings page to front (activates tab).");
    inspectorBackend.registerEnum("Page.CaptureScreenshotRequestFormat", { Jpeg: "jpeg", Png: "png", Webp: "webp" });
    inspectorBackend.registerCommand("Page.captureScreenshot", [{ "name": "format", "type": "string", "optional": true, "description": "Image compression format (defaults to png).", "typeRef": "Page.CaptureScreenshotRequestFormat" }, { "name": "quality", "type": "number", "optional": true, "description": "Compression quality from range [0..100] (jpeg only).", "typeRef": null }, { "name": "clip", "type": "object", "optional": true, "description": "Capture the screenshot of a given region only.", "typeRef": "Page.Viewport" }, { "name": "fromSurface", "type": "boolean", "optional": true, "description": "Capture the screenshot from the surface, rather than the view. Defaults to true.", "typeRef": null }, { "name": "captureBeyondViewport", "type": "boolean", "optional": true, "description": "Capture the screenshot beyond the viewport. Defaults to false.", "typeRef": null }, { "name": "optimizeForSpeed", "type": "boolean", "optional": true, "description": "Optimize image encoding for speed, not for resulting size (defaults to false)", "typeRef": null }], ["data"], "Capture page screenshot.");
    inspectorBackend.registerEnum("Page.CaptureSnapshotRequestFormat", { MHTML: "mhtml" });
    inspectorBackend.registerCommand("Page.captureSnapshot", [{ "name": "format", "type": "string", "optional": true, "description": "Format (defaults to mhtml).", "typeRef": "Page.CaptureSnapshotRequestFormat" }], ["data"], "Returns a snapshot of the page as a string. For MHTML format, the serialization includes iframes, shadow DOM, external resources, and element-inline styles.");
    inspectorBackend.registerCommand("Page.clearDeviceMetricsOverride", [], [], "Clears the overridden device metrics.");
    inspectorBackend.registerCommand("Page.clearDeviceOrientationOverride", [], [], "Clears the overridden Device Orientation.");
    inspectorBackend.registerCommand("Page.clearGeolocationOverride", [], [], "Clears the overridden Geolocation Position and Error.");
    inspectorBackend.registerCommand("Page.createIsolatedWorld", [{ "name": "frameId", "type": "string", "optional": false, "description": "Id of the frame in which the isolated world should be created.", "typeRef": "Page.FrameId" }, { "name": "worldName", "type": "string", "optional": true, "description": "An optional name which is reported in the Execution Context.", "typeRef": null }, { "name": "grantUniveralAccess", "type": "boolean", "optional": true, "description": "Whether or not universal access should be granted to the isolated world. This is a powerful option, use with caution.", "typeRef": null }], ["executionContextId"], "Creates an isolated world for the given frame.");
    inspectorBackend.registerCommand("Page.deleteCookie", [{ "name": "cookieName", "type": "string", "optional": false, "description": "Name of the cookie to remove.", "typeRef": null }, { "name": "url", "type": "string", "optional": false, "description": "URL to match cooke domain and path.", "typeRef": null }], [], "Deletes browser cookie with given name, domain and path.");
    inspectorBackend.registerCommand("Page.disable", [], [], "Disables page domain notifications.");
    inspectorBackend.registerCommand("Page.enable", [{ "name": "enableFileChooserOpenedEvent", "type": "boolean", "optional": true, "description": "If true, the `Page.fileChooserOpened` event will be emitted regardless of the state set by `Page.setInterceptFileChooserDialog` command (default: false).", "typeRef": null }], [], "Enables page domain notifications.");
    inspectorBackend.registerCommand("Page.getAppManifest", [{ "name": "manifestId", "type": "string", "optional": true, "description": "", "typeRef": null }], ["url", "errors", "data", "parsed", "manifest"], "Gets the processed manifest for this current document.   This API always waits for the manifest to be loaded.   If manifestId is provided, and it does not match the manifest of the     current document, this API errors out.   If there is not a loaded page, this API errors out immediately.");
    inspectorBackend.registerCommand("Page.getInstallabilityErrors", [], ["installabilityErrors"], "");
    inspectorBackend.registerCommand("Page.getManifestIcons", [], ["primaryIcon"], "Deprecated because it's not guaranteed that the returned icon is in fact the one used for PWA installation.");
    inspectorBackend.registerCommand("Page.getAppId", [], ["appId", "recommendedId"], "Returns the unique (PWA) app id. Only returns values if the feature flag 'WebAppEnableManifestId' is enabled");
    inspectorBackend.registerCommand("Page.getAdScriptAncestry", [{ "name": "frameId", "type": "string", "optional": false, "description": "", "typeRef": "Page.FrameId" }], ["adScriptAncestry"], "");
    inspectorBackend.registerCommand("Page.getFrameTree", [], ["frameTree"], "Returns present frame tree structure.");
    inspectorBackend.registerCommand("Page.getLayoutMetrics", [], ["layoutViewport", "visualViewport", "contentSize", "cssLayoutViewport", "cssVisualViewport", "cssContentSize"], "Returns metrics relating to the layouting of the page, such as viewport bounds/scale.");
    inspectorBackend.registerCommand("Page.getNavigationHistory", [], ["currentIndex", "entries"], "Returns navigation history for the current page.");
    inspectorBackend.registerCommand("Page.resetNavigationHistory", [], [], "Resets navigation history for the current page.");
    inspectorBackend.registerCommand("Page.getResourceContent", [{ "name": "frameId", "type": "string", "optional": false, "description": "Frame id to get resource for.", "typeRef": "Page.FrameId" }, { "name": "url", "type": "string", "optional": false, "description": "URL of the resource to get content for.", "typeRef": null }], ["content", "base64Encoded"], "Returns content of the given resource.");
    inspectorBackend.registerCommand("Page.getResourceTree", [], ["frameTree"], "Returns present frame / resource tree structure.");
    inspectorBackend.registerCommand("Page.handleJavaScriptDialog", [{ "name": "accept", "type": "boolean", "optional": false, "description": "Whether to accept or dismiss the dialog.", "typeRef": null }, { "name": "promptText", "type": "string", "optional": true, "description": "The text to enter into the dialog prompt before accepting. Used only if this is a prompt dialog.", "typeRef": null }], [], "Accepts or dismisses a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload).");
    inspectorBackend.registerCommand("Page.navigate", [{ "name": "url", "type": "string", "optional": false, "description": "URL to navigate the page to.", "typeRef": null }, { "name": "referrer", "type": "string", "optional": true, "description": "Referrer URL.", "typeRef": null }, { "name": "transitionType", "type": "string", "optional": true, "description": "Intended transition type.", "typeRef": "Page.TransitionType" }, { "name": "frameId", "type": "string", "optional": true, "description": "Frame id to navigate, if not specified navigates the top frame.", "typeRef": "Page.FrameId" }, { "name": "referrerPolicy", "type": "string", "optional": true, "description": "Referrer-policy used for the navigation.", "typeRef": "Page.ReferrerPolicy" }], ["frameId", "loaderId", "errorText", "isDownload"], "Navigates current page to the given URL.");
    inspectorBackend.registerCommand("Page.navigateToHistoryEntry", [{ "name": "entryId", "type": "number", "optional": false, "description": "Unique id of the entry to navigate to.", "typeRef": null }], [], "Navigates current page to the given history entry.");
    inspectorBackend.registerEnum("Page.PrintToPDFRequestTransferMode", { ReturnAsBase64: "ReturnAsBase64", ReturnAsStream: "ReturnAsStream" });
    inspectorBackend.registerCommand("Page.printToPDF", [{ "name": "landscape", "type": "boolean", "optional": true, "description": "Paper orientation. Defaults to false.", "typeRef": null }, { "name": "displayHeaderFooter", "type": "boolean", "optional": true, "description": "Display header and footer. Defaults to false.", "typeRef": null }, { "name": "printBackground", "type": "boolean", "optional": true, "description": "Print background graphics. Defaults to false.", "typeRef": null }, { "name": "scale", "type": "number", "optional": true, "description": "Scale of the webpage rendering. Defaults to 1.", "typeRef": null }, { "name": "paperWidth", "type": "number", "optional": true, "description": "Paper width in inches. Defaults to 8.5 inches.", "typeRef": null }, { "name": "paperHeight", "type": "number", "optional": true, "description": "Paper height in inches. Defaults to 11 inches.", "typeRef": null }, { "name": "marginTop", "type": "number", "optional": true, "description": "Top margin in inches. Defaults to 1cm (~0.4 inches).", "typeRef": null }, { "name": "marginBottom", "type": "number", "optional": true, "description": "Bottom margin in inches. Defaults to 1cm (~0.4 inches).", "typeRef": null }, { "name": "marginLeft", "type": "number", "optional": true, "description": "Left margin in inches. Defaults to 1cm (~0.4 inches).", "typeRef": null }, { "name": "marginRight", "type": "number", "optional": true, "description": "Right margin in inches. Defaults to 1cm (~0.4 inches).", "typeRef": null }, { "name": "pageRanges", "type": "string", "optional": true, "description": "Paper ranges to print, one based, e.g., '1-5, 8, 11-13'. Pages are printed in the document order, not in the order specified, and no more than once. Defaults to empty string, which implies the entire document is printed. The page numbers are quietly capped to actual page count of the document, and ranges beyond the end of the document are ignored. If this results in no pages to print, an error is reported. It is an error to specify a range with start greater than end.", "typeRef": null }, { "name": "headerTemplate", "type": "string", "optional": true, "description": "HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: - `date`: formatted print date - `title`: document title - `url`: document location - `pageNumber`: current page number - `totalPages`: total pages in the document  For example, `<span class=title></span>` would generate span containing the title.", "typeRef": null }, { "name": "footerTemplate", "type": "string", "optional": true, "description": "HTML template for the print footer. Should use the same format as the `headerTemplate`.", "typeRef": null }, { "name": "preferCSSPageSize", "type": "boolean", "optional": true, "description": "Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size.", "typeRef": null }, { "name": "transferMode", "type": "string", "optional": true, "description": "return as stream", "typeRef": "Page.PrintToPDFRequestTransferMode" }, { "name": "generateTaggedPDF", "type": "boolean", "optional": true, "description": "Whether or not to generate tagged (accessible) PDF. Defaults to embedder choice.", "typeRef": null }, { "name": "generateDocumentOutline", "type": "boolean", "optional": true, "description": "Whether or not to embed the document outline into the PDF.", "typeRef": null }], ["data", "stream"], "Print page as PDF.");
    inspectorBackend.registerCommand("Page.reload", [{ "name": "ignoreCache", "type": "boolean", "optional": true, "description": "If true, browser cache is ignored (as if the user pressed Shift+refresh).", "typeRef": null }, { "name": "scriptToEvaluateOnLoad", "type": "string", "optional": true, "description": "If set, the script will be injected into all frames of the inspected page after reload. Argument will be ignored if reloading dataURL origin.", "typeRef": null }, { "name": "loaderId", "type": "string", "optional": true, "description": "If set, an error will be thrown if the target page's main frame's loader id does not match the provided id. This prevents accidentally reloading an unintended target in case there's a racing navigation.", "typeRef": "Network.LoaderId" }], [], "Reloads given page optionally ignoring the cache.");
    inspectorBackend.registerCommand("Page.removeScriptToEvaluateOnLoad", [{ "name": "identifier", "type": "string", "optional": false, "description": "", "typeRef": "Page.ScriptIdentifier" }], [], "Deprecated, please use removeScriptToEvaluateOnNewDocument instead.");
    inspectorBackend.registerCommand("Page.removeScriptToEvaluateOnNewDocument", [{ "name": "identifier", "type": "string", "optional": false, "description": "", "typeRef": "Page.ScriptIdentifier" }], [], "Removes given script from the list.");
    inspectorBackend.registerCommand("Page.screencastFrameAck", [{ "name": "sessionId", "type": "number", "optional": false, "description": "Frame number.", "typeRef": null }], [], "Acknowledges that a screencast frame has been received by the frontend.");
    inspectorBackend.registerCommand("Page.searchInResource", [{ "name": "frameId", "type": "string", "optional": false, "description": "Frame id for resource to search in.", "typeRef": "Page.FrameId" }, { "name": "url", "type": "string", "optional": false, "description": "URL of the resource to search in.", "typeRef": null }, { "name": "query", "type": "string", "optional": false, "description": "String to search for.", "typeRef": null }, { "name": "caseSensitive", "type": "boolean", "optional": true, "description": "If true, search is case sensitive.", "typeRef": null }, { "name": "isRegex", "type": "boolean", "optional": true, "description": "If true, treats string parameter as regex.", "typeRef": null }], ["result"], "Searches for given string in resource content.");
    inspectorBackend.registerCommand("Page.setAdBlockingEnabled", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "Whether to block ads.", "typeRef": null }], [], "Enable Chrome's experimental ad filter on all sites.");
    inspectorBackend.registerCommand("Page.setBypassCSP", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "Whether to bypass page CSP.", "typeRef": null }], [], "Enable page Content Security Policy by-passing.");
    inspectorBackend.registerCommand("Page.getPermissionsPolicyState", [{ "name": "frameId", "type": "string", "optional": false, "description": "", "typeRef": "Page.FrameId" }], ["states"], "Get Permissions Policy state on given frame.");
    inspectorBackend.registerCommand("Page.getOriginTrials", [{ "name": "frameId", "type": "string", "optional": false, "description": "", "typeRef": "Page.FrameId" }], ["originTrials"], "Get Origin Trials on given frame.");
    inspectorBackend.registerCommand("Page.setDeviceMetricsOverride", [{ "name": "width", "type": "number", "optional": false, "description": "Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override.", "typeRef": null }, { "name": "height", "type": "number", "optional": false, "description": "Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override.", "typeRef": null }, { "name": "deviceScaleFactor", "type": "number", "optional": false, "description": "Overriding device scale factor value. 0 disables the override.", "typeRef": null }, { "name": "mobile", "type": "boolean", "optional": false, "description": "Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text autosizing and more.", "typeRef": null }, { "name": "scale", "type": "number", "optional": true, "description": "Scale to apply to resulting view image.", "typeRef": null }, { "name": "screenWidth", "type": "number", "optional": true, "description": "Overriding screen width value in pixels (minimum 0, maximum 10000000).", "typeRef": null }, { "name": "screenHeight", "type": "number", "optional": true, "description": "Overriding screen height value in pixels (minimum 0, maximum 10000000).", "typeRef": null }, { "name": "positionX", "type": "number", "optional": true, "description": "Overriding view X position on screen in pixels (minimum 0, maximum 10000000).", "typeRef": null }, { "name": "positionY", "type": "number", "optional": true, "description": "Overriding view Y position on screen in pixels (minimum 0, maximum 10000000).", "typeRef": null }, { "name": "dontSetVisibleSize", "type": "boolean", "optional": true, "description": "Do not set visible view size, rely upon explicit setVisibleSize call.", "typeRef": null }, { "name": "screenOrientation", "type": "object", "optional": true, "description": "Screen orientation override.", "typeRef": "Emulation.ScreenOrientation" }, { "name": "viewport", "type": "object", "optional": true, "description": "The viewport dimensions and scale. If not set, the override is cleared.", "typeRef": "Page.Viewport" }], [], "Overrides the values of device screen dimensions (window.screen.width, window.screen.height, window.innerWidth, window.innerHeight, and \"device-width\"/\"device-height\"-related CSS media query results).");
    inspectorBackend.registerCommand("Page.setDeviceOrientationOverride", [{ "name": "alpha", "type": "number", "optional": false, "description": "Mock alpha", "typeRef": null }, { "name": "beta", "type": "number", "optional": false, "description": "Mock beta", "typeRef": null }, { "name": "gamma", "type": "number", "optional": false, "description": "Mock gamma", "typeRef": null }], [], "Overrides the Device Orientation.");
    inspectorBackend.registerCommand("Page.setFontFamilies", [{ "name": "fontFamilies", "type": "object", "optional": false, "description": "Specifies font families to set. If a font family is not specified, it won't be changed.", "typeRef": "Page.FontFamilies" }, { "name": "forScripts", "type": "array", "optional": true, "description": "Specifies font families to set for individual scripts.", "typeRef": "Page.ScriptFontFamilies" }], [], "Set generic font families.");
    inspectorBackend.registerCommand("Page.setFontSizes", [{ "name": "fontSizes", "type": "object", "optional": false, "description": "Specifies font sizes to set. If a font size is not specified, it won't be changed.", "typeRef": "Page.FontSizes" }], [], "Set default font sizes.");
    inspectorBackend.registerCommand("Page.setDocumentContent", [{ "name": "frameId", "type": "string", "optional": false, "description": "Frame id to set HTML for.", "typeRef": "Page.FrameId" }, { "name": "html", "type": "string", "optional": false, "description": "HTML content to set.", "typeRef": null }], [], "Sets given markup as the document's HTML.");
    inspectorBackend.registerEnum("Page.SetDownloadBehaviorRequestBehavior", { Deny: "deny", Allow: "allow", Default: "default" });
    inspectorBackend.registerCommand("Page.setDownloadBehavior", [{ "name": "behavior", "type": "string", "optional": false, "description": "Whether to allow all or deny all download requests, or use default Chrome behavior if available (otherwise deny).", "typeRef": "Page.SetDownloadBehaviorRequestBehavior" }, { "name": "downloadPath", "type": "string", "optional": true, "description": "The default path to save downloaded files to. This is required if behavior is set to 'allow'", "typeRef": null }], [], "Set the behavior when downloading a file.");
    inspectorBackend.registerCommand("Page.setGeolocationOverride", [{ "name": "latitude", "type": "number", "optional": true, "description": "Mock latitude", "typeRef": null }, { "name": "longitude", "type": "number", "optional": true, "description": "Mock longitude", "typeRef": null }, { "name": "accuracy", "type": "number", "optional": true, "description": "Mock accuracy", "typeRef": null }], [], "Overrides the Geolocation Position or Error. Omitting any of the parameters emulates position unavailable.");
    inspectorBackend.registerCommand("Page.setLifecycleEventsEnabled", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "If true, starts emitting lifecycle events.", "typeRef": null }], [], "Controls whether page will emit lifecycle events.");
    inspectorBackend.registerEnum("Page.SetTouchEmulationEnabledRequestConfiguration", { Mobile: "mobile", Desktop: "desktop" });
    inspectorBackend.registerCommand("Page.setTouchEmulationEnabled", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "Whether the touch event emulation should be enabled.", "typeRef": null }, { "name": "configuration", "type": "string", "optional": true, "description": "Touch/gesture events configuration. Default: current platform.", "typeRef": "Page.SetTouchEmulationEnabledRequestConfiguration" }], [], "Toggles mouse event-based touch event emulation.");
    inspectorBackend.registerEnum("Page.StartScreencastRequestFormat", { Jpeg: "jpeg", Png: "png" });
    inspectorBackend.registerCommand("Page.startScreencast", [{ "name": "format", "type": "string", "optional": true, "description": "Image compression format.", "typeRef": "Page.StartScreencastRequestFormat" }, { "name": "quality", "type": "number", "optional": true, "description": "Compression quality from range [0..100].", "typeRef": null }, { "name": "maxWidth", "type": "number", "optional": true, "description": "Maximum screenshot width.", "typeRef": null }, { "name": "maxHeight", "type": "number", "optional": true, "description": "Maximum screenshot height.", "typeRef": null }, { "name": "everyNthFrame", "type": "number", "optional": true, "description": "Send every n-th frame.", "typeRef": null }], [], "Starts sending each frame using the `screencastFrame` event.");
    inspectorBackend.registerCommand("Page.stopLoading", [], [], "Force the page stop all navigations and pending resource fetches.");
    inspectorBackend.registerCommand("Page.crash", [], [], "Crashes renderer on the IO thread, generates minidumps.");
    inspectorBackend.registerCommand("Page.close", [], [], "Tries to close page, running its beforeunload hooks, if any.");
    inspectorBackend.registerEnum("Page.SetWebLifecycleStateRequestState", { Frozen: "frozen", Active: "active" });
    inspectorBackend.registerCommand("Page.setWebLifecycleState", [{ "name": "state", "type": "string", "optional": false, "description": "Target lifecycle state", "typeRef": "Page.SetWebLifecycleStateRequestState" }], [], "Tries to update the web lifecycle state of the page. It will transition the page to the given state according to: https://github.com/WICG/web-lifecycle/");
    inspectorBackend.registerCommand("Page.stopScreencast", [], [], "Stops sending each frame in the `screencastFrame`.");
    inspectorBackend.registerCommand("Page.produceCompilationCache", [{ "name": "scripts", "type": "array", "optional": false, "description": "", "typeRef": "Page.CompilationCacheParams" }], [], "Requests backend to produce compilation cache for the specified scripts. `scripts` are appended to the list of scripts for which the cache would be produced. The list may be reset during page navigation. When script with a matching URL is encountered, the cache is optionally produced upon backend discretion, based on internal heuristics. See also: `Page.compilationCacheProduced`.");
    inspectorBackend.registerCommand("Page.addCompilationCache", [{ "name": "url", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "data", "type": "string", "optional": false, "description": "Base64-encoded data", "typeRef": null }], [], "Seeds compilation cache for given url. Compilation cache does not survive cross-process navigation.");
    inspectorBackend.registerCommand("Page.clearCompilationCache", [], [], "Clears seeded compilation cache.");
    inspectorBackend.registerEnum("Page.SetSPCTransactionModeRequestMode", { None: "none", AutoAccept: "autoAccept", AutoChooseToAuthAnotherWay: "autoChooseToAuthAnotherWay", AutoReject: "autoReject", AutoOptOut: "autoOptOut" });
    inspectorBackend.registerCommand("Page.setSPCTransactionMode", [{ "name": "mode", "type": "string", "optional": false, "description": "", "typeRef": "Page.SetSPCTransactionModeRequestMode" }], [], "Sets the Secure Payment Confirmation transaction mode. https://w3c.github.io/secure-payment-confirmation/#sctn-automation-set-spc-transaction-mode");
    inspectorBackend.registerEnum("Page.SetRPHRegistrationModeRequestMode", { None: "none", AutoAccept: "autoAccept", AutoReject: "autoReject" });
    inspectorBackend.registerCommand("Page.setRPHRegistrationMode", [{ "name": "mode", "type": "string", "optional": false, "description": "", "typeRef": "Page.SetRPHRegistrationModeRequestMode" }], [], "Extensions for Custom Handlers API: https://html.spec.whatwg.org/multipage/system-state.html#rph-automation");
    inspectorBackend.registerCommand("Page.generateTestReport", [{ "name": "message", "type": "string", "optional": false, "description": "Message to be displayed in the report.", "typeRef": null }, { "name": "group", "type": "string", "optional": true, "description": "Specifies the endpoint group to deliver the report to.", "typeRef": null }], [], "Generates a report for testing.");
    inspectorBackend.registerCommand("Page.waitForDebugger", [], [], "Pauses page execution. Can be resumed using generic Runtime.runIfWaitingForDebugger.");
    inspectorBackend.registerCommand("Page.setInterceptFileChooserDialog", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "cancel", "type": "boolean", "optional": true, "description": "If true, cancels the dialog by emitting relevant events (if any) in addition to not showing it if the interception is enabled (default: false).", "typeRef": null }], [], "Intercept file chooser requests and transfer control to protocol clients. When file chooser interception is enabled, native file chooser dialog is not shown. Instead, a protocol event `Page.fileChooserOpened` is emitted.");
    inspectorBackend.registerCommand("Page.setPrerenderingAllowed", [{ "name": "isAllowed", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "Enable/disable prerendering manually.  This command is a short-term solution for https://crbug.com/1440085. See https://docs.google.com/document/d/12HVmFxYj5Jc-eJr5OmWsa2bqTJsbgGLKI6ZIyx0_wpA for more details.  TODO(https://crbug.com/1440085): Remove this once Puppeteer supports tab targets.");
    inspectorBackend.registerCommand("Page.getAnnotatedPageContent", [{ "name": "includeActionableInformation", "type": "boolean", "optional": true, "description": "Whether to include actionable information. Defaults to true.", "typeRef": null }], ["content"], "Get the annotated page content for the main frame. This is an experimental command that is subject to change.");
    inspectorBackend.registerType("Page.AdFrameStatus", [{ "name": "adFrameType", "type": "string", "optional": false, "description": "", "typeRef": "Page.AdFrameType" }, { "name": "explanations", "type": "array", "optional": true, "description": "", "typeRef": "Page.AdFrameExplanation" }]);
    inspectorBackend.registerType("Page.AdScriptId", [{ "name": "scriptId", "type": "string", "optional": false, "description": "Script Id of the script which caused a script or frame to be labelled as an ad.", "typeRef": "Runtime.ScriptId" }, { "name": "debuggerId", "type": "string", "optional": false, "description": "Id of scriptId's debugger.", "typeRef": "Runtime.UniqueDebuggerId" }]);
    inspectorBackend.registerType("Page.AdScriptAncestry", [{ "name": "ancestryChain", "type": "array", "optional": false, "description": "A chain of `AdScriptId`s representing the ancestry of an ad script that led to the creation of a frame. The chain is ordered from the script itself (lower level) up to its root ancestor that was flagged by filterlist.", "typeRef": "Page.AdScriptId" }, { "name": "rootScriptFilterlistRule", "type": "string", "optional": true, "description": "The filterlist rule that caused the root (last) script in `ancestryChain` to be ad-tagged. Only populated if the rule is available.", "typeRef": null }]);
    inspectorBackend.registerType("Page.PermissionsPolicyBlockLocator", [{ "name": "frameId", "type": "string", "optional": false, "description": "", "typeRef": "Page.FrameId" }, { "name": "blockReason", "type": "string", "optional": false, "description": "", "typeRef": "Page.PermissionsPolicyBlockReason" }]);
    inspectorBackend.registerType("Page.PermissionsPolicyFeatureState", [{ "name": "feature", "type": "string", "optional": false, "description": "", "typeRef": "Page.PermissionsPolicyFeature" }, { "name": "allowed", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "locator", "type": "object", "optional": true, "description": "", "typeRef": "Page.PermissionsPolicyBlockLocator" }]);
    inspectorBackend.registerType("Page.OriginTrialToken", [{ "name": "origin", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "matchSubDomains", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "trialName", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "expiryTime", "type": "number", "optional": false, "description": "", "typeRef": "Network.TimeSinceEpoch" }, { "name": "isThirdParty", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "usageRestriction", "type": "string", "optional": false, "description": "", "typeRef": "Page.OriginTrialUsageRestriction" }]);
    inspectorBackend.registerType("Page.OriginTrialTokenWithStatus", [{ "name": "rawTokenText", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "parsedToken", "type": "object", "optional": true, "description": "`parsedToken` is present only when the token is extractable and parsable.", "typeRef": "Page.OriginTrialToken" }, { "name": "status", "type": "string", "optional": false, "description": "", "typeRef": "Page.OriginTrialTokenStatus" }]);
    inspectorBackend.registerType("Page.OriginTrial", [{ "name": "trialName", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "status", "type": "string", "optional": false, "description": "", "typeRef": "Page.OriginTrialStatus" }, { "name": "tokensWithStatus", "type": "array", "optional": false, "description": "", "typeRef": "Page.OriginTrialTokenWithStatus" }]);
    inspectorBackend.registerType("Page.SecurityOriginDetails", [{ "name": "isLocalhost", "type": "boolean", "optional": false, "description": "Indicates whether the frame document's security origin is one of the local hostnames (e.g. \\\"localhost\\\") or IP addresses (IPv4 127.0.0.0/8 or IPv6 ::1).", "typeRef": null }]);
    inspectorBackend.registerType("Page.Frame", [{ "name": "id", "type": "string", "optional": false, "description": "Frame unique identifier.", "typeRef": "Page.FrameId" }, { "name": "parentId", "type": "string", "optional": true, "description": "Parent frame identifier.", "typeRef": "Page.FrameId" }, { "name": "loaderId", "type": "string", "optional": false, "description": "Identifier of the loader associated with this frame.", "typeRef": "Network.LoaderId" }, { "name": "name", "type": "string", "optional": true, "description": "Frame's name as specified in the tag.", "typeRef": null }, { "name": "url", "type": "string", "optional": false, "description": "Frame document's URL without fragment.", "typeRef": null }, { "name": "urlFragment", "type": "string", "optional": true, "description": "Frame document's URL fragment including the '#'.", "typeRef": null }, { "name": "domainAndRegistry", "type": "string", "optional": false, "description": "Frame document's registered domain, taking the public suffixes list into account. Extracted from the Frame's url. Example URLs: http://www.google.com/file.html -> \\\"google.com\\\"               http://a.b.co.uk/file.html      -> \\\"b.co.uk\\\"", "typeRef": null }, { "name": "securityOrigin", "type": "string", "optional": false, "description": "Frame document's security origin.", "typeRef": null }, { "name": "securityOriginDetails", "type": "object", "optional": true, "description": "Additional details about the frame document's security origin.", "typeRef": "Page.SecurityOriginDetails" }, { "name": "mimeType", "type": "string", "optional": false, "description": "Frame document's mimeType as determined by the browser.", "typeRef": null }, { "name": "unreachableUrl", "type": "string", "optional": true, "description": "If the frame failed to load, this contains the URL that could not be loaded. Note that unlike url above, this URL may contain a fragment.", "typeRef": null }, { "name": "adFrameStatus", "type": "object", "optional": true, "description": "Indicates whether this frame was tagged as an ad and why.", "typeRef": "Page.AdFrameStatus" }, { "name": "secureContextType", "type": "string", "optional": false, "description": "Indicates whether the main document is a secure context and explains why that is the case.", "typeRef": "Page.SecureContextType" }, { "name": "crossOriginIsolatedContextType", "type": "string", "optional": false, "description": "Indicates whether this is a cross origin isolated context.", "typeRef": "Page.CrossOriginIsolatedContextType" }, { "name": "gatedAPIFeatures", "type": "array", "optional": false, "description": "Indicated which gated APIs / features are available.", "typeRef": "Page.GatedAPIFeatures" }]);
    inspectorBackend.registerType("Page.FrameResource", [{ "name": "url", "type": "string", "optional": false, "description": "Resource URL.", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "Type of this resource.", "typeRef": "Network.ResourceType" }, { "name": "mimeType", "type": "string", "optional": false, "description": "Resource mimeType as determined by the browser.", "typeRef": null }, { "name": "lastModified", "type": "number", "optional": true, "description": "last-modified timestamp as reported by server.", "typeRef": "Network.TimeSinceEpoch" }, { "name": "contentSize", "type": "number", "optional": true, "description": "Resource content size.", "typeRef": null }, { "name": "failed", "type": "boolean", "optional": true, "description": "True if the resource failed to load.", "typeRef": null }, { "name": "canceled", "type": "boolean", "optional": true, "description": "True if the resource was canceled during loading.", "typeRef": null }]);
    inspectorBackend.registerType("Page.FrameResourceTree", [{ "name": "frame", "type": "object", "optional": false, "description": "Frame information for this tree item.", "typeRef": "Page.Frame" }, { "name": "childFrames", "type": "array", "optional": true, "description": "Child frames.", "typeRef": "Page.FrameResourceTree" }, { "name": "resources", "type": "array", "optional": false, "description": "Information about frame resources.", "typeRef": "Page.FrameResource" }]);
    inspectorBackend.registerType("Page.FrameTree", [{ "name": "frame", "type": "object", "optional": false, "description": "Frame information for this tree item.", "typeRef": "Page.Frame" }, { "name": "childFrames", "type": "array", "optional": true, "description": "Child frames.", "typeRef": "Page.FrameTree" }]);
    inspectorBackend.registerType("Page.NavigationEntry", [{ "name": "id", "type": "number", "optional": false, "description": "Unique id of the navigation history entry.", "typeRef": null }, { "name": "url", "type": "string", "optional": false, "description": "URL of the navigation history entry.", "typeRef": null }, { "name": "userTypedURL", "type": "string", "optional": false, "description": "URL that the user typed in the url bar.", "typeRef": null }, { "name": "title", "type": "string", "optional": false, "description": "Title of the navigation history entry.", "typeRef": null }, { "name": "transitionType", "type": "string", "optional": false, "description": "Transition type.", "typeRef": "Page.TransitionType" }]);
    inspectorBackend.registerType("Page.ScreencastFrameMetadata", [{ "name": "offsetTop", "type": "number", "optional": false, "description": "Top offset in DIP.", "typeRef": null }, { "name": "pageScaleFactor", "type": "number", "optional": false, "description": "Page scale factor.", "typeRef": null }, { "name": "deviceWidth", "type": "number", "optional": false, "description": "Device screen width in DIP.", "typeRef": null }, { "name": "deviceHeight", "type": "number", "optional": false, "description": "Device screen height in DIP.", "typeRef": null }, { "name": "scrollOffsetX", "type": "number", "optional": false, "description": "Position of horizontal scroll in CSS pixels.", "typeRef": null }, { "name": "scrollOffsetY", "type": "number", "optional": false, "description": "Position of vertical scroll in CSS pixels.", "typeRef": null }, { "name": "timestamp", "type": "number", "optional": true, "description": "Frame swap timestamp.", "typeRef": "Network.TimeSinceEpoch" }]);
    inspectorBackend.registerType("Page.AppManifestError", [{ "name": "message", "type": "string", "optional": false, "description": "Error message.", "typeRef": null }, { "name": "critical", "type": "number", "optional": false, "description": "If critical, this is a non-recoverable parse error.", "typeRef": null }, { "name": "line", "type": "number", "optional": false, "description": "Error line.", "typeRef": null }, { "name": "column", "type": "number", "optional": false, "description": "Error column.", "typeRef": null }]);
    inspectorBackend.registerType("Page.AppManifestParsedProperties", [{ "name": "scope", "type": "string", "optional": false, "description": "Computed scope value", "typeRef": null }]);
    inspectorBackend.registerType("Page.LayoutViewport", [{ "name": "pageX", "type": "number", "optional": false, "description": "Horizontal offset relative to the document (CSS pixels).", "typeRef": null }, { "name": "pageY", "type": "number", "optional": false, "description": "Vertical offset relative to the document (CSS pixels).", "typeRef": null }, { "name": "clientWidth", "type": "number", "optional": false, "description": "Width (CSS pixels), excludes scrollbar if present.", "typeRef": null }, { "name": "clientHeight", "type": "number", "optional": false, "description": "Height (CSS pixels), excludes scrollbar if present.", "typeRef": null }]);
    inspectorBackend.registerType("Page.VisualViewport", [{ "name": "offsetX", "type": "number", "optional": false, "description": "Horizontal offset relative to the layout viewport (CSS pixels).", "typeRef": null }, { "name": "offsetY", "type": "number", "optional": false, "description": "Vertical offset relative to the layout viewport (CSS pixels).", "typeRef": null }, { "name": "pageX", "type": "number", "optional": false, "description": "Horizontal offset relative to the document (CSS pixels).", "typeRef": null }, { "name": "pageY", "type": "number", "optional": false, "description": "Vertical offset relative to the document (CSS pixels).", "typeRef": null }, { "name": "clientWidth", "type": "number", "optional": false, "description": "Width (CSS pixels), excludes scrollbar if present.", "typeRef": null }, { "name": "clientHeight", "type": "number", "optional": false, "description": "Height (CSS pixels), excludes scrollbar if present.", "typeRef": null }, { "name": "scale", "type": "number", "optional": false, "description": "Scale relative to the ideal viewport (size at width=device-width).", "typeRef": null }, { "name": "zoom", "type": "number", "optional": true, "description": "Page zoom factor (CSS to device independent pixels ratio).", "typeRef": null }]);
    inspectorBackend.registerType("Page.Viewport", [{ "name": "x", "type": "number", "optional": false, "description": "X offset in device independent pixels (dip).", "typeRef": null }, { "name": "y", "type": "number", "optional": false, "description": "Y offset in device independent pixels (dip).", "typeRef": null }, { "name": "width", "type": "number", "optional": false, "description": "Rectangle width in device independent pixels (dip).", "typeRef": null }, { "name": "height", "type": "number", "optional": false, "description": "Rectangle height in device independent pixels (dip).", "typeRef": null }, { "name": "scale", "type": "number", "optional": false, "description": "Page scale factor.", "typeRef": null }]);
    inspectorBackend.registerType("Page.FontFamilies", [{ "name": "standard", "type": "string", "optional": true, "description": "The standard font-family.", "typeRef": null }, { "name": "fixed", "type": "string", "optional": true, "description": "The fixed font-family.", "typeRef": null }, { "name": "serif", "type": "string", "optional": true, "description": "The serif font-family.", "typeRef": null }, { "name": "sansSerif", "type": "string", "optional": true, "description": "The sansSerif font-family.", "typeRef": null }, { "name": "cursive", "type": "string", "optional": true, "description": "The cursive font-family.", "typeRef": null }, { "name": "fantasy", "type": "string", "optional": true, "description": "The fantasy font-family.", "typeRef": null }, { "name": "math", "type": "string", "optional": true, "description": "The math font-family.", "typeRef": null }]);
    inspectorBackend.registerType("Page.ScriptFontFamilies", [{ "name": "script", "type": "string", "optional": false, "description": "Name of the script which these font families are defined for.", "typeRef": null }, { "name": "fontFamilies", "type": "object", "optional": false, "description": "Generic font families collection for the script.", "typeRef": "Page.FontFamilies" }]);
    inspectorBackend.registerType("Page.FontSizes", [{ "name": "standard", "type": "number", "optional": true, "description": "Default standard font size.", "typeRef": null }, { "name": "fixed", "type": "number", "optional": true, "description": "Default fixed font size.", "typeRef": null }]);
    inspectorBackend.registerType("Page.InstallabilityErrorArgument", [{ "name": "name", "type": "string", "optional": false, "description": "Argument name (e.g. name:'minimum-icon-size-in-pixels').", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "Argument value (e.g. value:'64').", "typeRef": null }]);
    inspectorBackend.registerType("Page.InstallabilityError", [{ "name": "errorId", "type": "string", "optional": false, "description": "The error id (e.g. 'manifest-missing-suitable-icon').", "typeRef": null }, { "name": "errorArguments", "type": "array", "optional": false, "description": "The list of error arguments (e.g. {name:'minimum-icon-size-in-pixels', value:'64'}).", "typeRef": "Page.InstallabilityErrorArgument" }]);
    inspectorBackend.registerType("Page.CompilationCacheParams", [{ "name": "url", "type": "string", "optional": false, "description": "The URL of the script to produce a compilation cache entry for.", "typeRef": null }, { "name": "eager", "type": "boolean", "optional": true, "description": "A hint to the backend whether eager compilation is recommended. (the actual compilation mode used is upon backend discretion).", "typeRef": null }]);
    inspectorBackend.registerType("Page.FileFilter", [{ "name": "name", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "accepts", "type": "array", "optional": true, "description": "", "typeRef": "string" }]);
    inspectorBackend.registerType("Page.FileHandler", [{ "name": "action", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "icons", "type": "array", "optional": true, "description": "", "typeRef": "Page.ImageResource" }, { "name": "accepts", "type": "array", "optional": true, "description": "Mimic a map, name is the key, accepts is the value.", "typeRef": "Page.FileFilter" }, { "name": "launchType", "type": "string", "optional": false, "description": "Won't repeat the enums, using string for easy comparison. Same as the other enums below.", "typeRef": null }]);
    inspectorBackend.registerType("Page.ImageResource", [{ "name": "url", "type": "string", "optional": false, "description": "The src field in the definition, but changing to url in favor of consistency.", "typeRef": null }, { "name": "sizes", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "type", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Page.LaunchHandler", [{ "name": "clientMode", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Page.ProtocolHandler", [{ "name": "protocol", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "url", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Page.RelatedApplication", [{ "name": "id", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "url", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Page.ScopeExtension", [{ "name": "origin", "type": "string", "optional": false, "description": "Instead of using tuple, this field always returns the serialized string for easy understanding and comparison.", "typeRef": null }, { "name": "hasOriginWildcard", "type": "boolean", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Page.Screenshot", [{ "name": "image", "type": "object", "optional": false, "description": "", "typeRef": "Page.ImageResource" }, { "name": "formFactor", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "label", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Page.ShareTarget", [{ "name": "action", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "method", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "enctype", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "title", "type": "string", "optional": true, "description": "Embed the ShareTargetParams", "typeRef": null }, { "name": "text", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "url", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "files", "type": "array", "optional": true, "description": "", "typeRef": "Page.FileFilter" }]);
    inspectorBackend.registerType("Page.Shortcut", [{ "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "url", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Page.WebAppManifest", [{ "name": "backgroundColor", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "description", "type": "string", "optional": true, "description": "The extra description provided by the manifest.", "typeRef": null }, { "name": "dir", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "display", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "displayOverrides", "type": "array", "optional": true, "description": "The overrided display mode controlled by the user.", "typeRef": "string" }, { "name": "fileHandlers", "type": "array", "optional": true, "description": "The handlers to open files.", "typeRef": "Page.FileHandler" }, { "name": "icons", "type": "array", "optional": true, "description": "", "typeRef": "Page.ImageResource" }, { "name": "id", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "lang", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "launchHandler", "type": "object", "optional": true, "description": "TODO(crbug.com/1231886): This field is non-standard and part of a Chrome experiment. See: https://github.com/WICG/web-app-launch/blob/main/launch_handler.md", "typeRef": "Page.LaunchHandler" }, { "name": "name", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "orientation", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "preferRelatedApplications", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "protocolHandlers", "type": "array", "optional": true, "description": "The handlers to open protocols.", "typeRef": "Page.ProtocolHandler" }, { "name": "relatedApplications", "type": "array", "optional": true, "description": "", "typeRef": "Page.RelatedApplication" }, { "name": "scope", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "scopeExtensions", "type": "array", "optional": true, "description": "Non-standard, see https://github.com/WICG/manifest-incubations/blob/gh-pages/scope_extensions-explainer.md", "typeRef": "Page.ScopeExtension" }, { "name": "screenshots", "type": "array", "optional": true, "description": "The screenshots used by chromium.", "typeRef": "Page.Screenshot" }, { "name": "shareTarget", "type": "object", "optional": true, "description": "", "typeRef": "Page.ShareTarget" }, { "name": "shortName", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "shortcuts", "type": "array", "optional": true, "description": "", "typeRef": "Page.Shortcut" }, { "name": "startUrl", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "themeColor", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Page.BackForwardCacheBlockingDetails", [{ "name": "url", "type": "string", "optional": true, "description": "Url of the file where blockage happened. Optional because of tests.", "typeRef": null }, { "name": "function", "type": "string", "optional": true, "description": "Function name where blockage happened. Optional because of anonymous functions and tests.", "typeRef": null }, { "name": "lineNumber", "type": "number", "optional": false, "description": "Line number in the script (0-based).", "typeRef": null }, { "name": "columnNumber", "type": "number", "optional": false, "description": "Column number in the script (0-based).", "typeRef": null }]);
    inspectorBackend.registerType("Page.BackForwardCacheNotRestoredExplanation", [{ "name": "type", "type": "string", "optional": false, "description": "Type of the reason", "typeRef": "Page.BackForwardCacheNotRestoredReasonType" }, { "name": "reason", "type": "string", "optional": false, "description": "Not restored reason", "typeRef": "Page.BackForwardCacheNotRestoredReason" }, { "name": "context", "type": "string", "optional": true, "description": "Context associated with the reason. The meaning of this context is dependent on the reason: - EmbedderExtensionSentMessageToCachedFrame: the extension ID.", "typeRef": null }, { "name": "details", "type": "array", "optional": true, "description": "", "typeRef": "Page.BackForwardCacheBlockingDetails" }]);
    inspectorBackend.registerType("Page.BackForwardCacheNotRestoredExplanationTree", [{ "name": "url", "type": "string", "optional": false, "description": "URL of each frame", "typeRef": null }, { "name": "explanations", "type": "array", "optional": false, "description": "Not restored reasons of each frame", "typeRef": "Page.BackForwardCacheNotRestoredExplanation" }, { "name": "children", "type": "array", "optional": false, "description": "Array of children frame", "typeRef": "Page.BackForwardCacheNotRestoredExplanationTree" }]);
    inspectorBackend.registerEvent("Performance.metrics", ["metrics", "title"]);
    inspectorBackend.registerCommand("Performance.disable", [], [], "Disable collecting and reporting metrics.");
    inspectorBackend.registerEnum("Performance.EnableRequestTimeDomain", { TimeTicks: "timeTicks", ThreadTicks: "threadTicks" });
    inspectorBackend.registerCommand("Performance.enable", [{ "name": "timeDomain", "type": "string", "optional": true, "description": "Time domain to use for collecting and reporting duration metrics.", "typeRef": "Performance.EnableRequestTimeDomain" }], [], "Enable collecting and reporting metrics.");
    inspectorBackend.registerEnum("Performance.SetTimeDomainRequestTimeDomain", { TimeTicks: "timeTicks", ThreadTicks: "threadTicks" });
    inspectorBackend.registerCommand("Performance.setTimeDomain", [{ "name": "timeDomain", "type": "string", "optional": false, "description": "Time domain", "typeRef": "Performance.SetTimeDomainRequestTimeDomain" }], [], "Sets time domain to use for collecting and reporting duration metrics. Note that this must be called before enabling metrics collection. Calling this method while metrics collection is enabled returns an error.");
    inspectorBackend.registerCommand("Performance.getMetrics", [], ["metrics"], "Retrieve current values of run-time metrics.");
    inspectorBackend.registerType("Performance.Metric", [{ "name": "name", "type": "string", "optional": false, "description": "Metric name.", "typeRef": null }, { "name": "value", "type": "number", "optional": false, "description": "Metric value.", "typeRef": null }]);
    inspectorBackend.registerEvent("PerformanceTimeline.timelineEventAdded", ["event"]);
    inspectorBackend.registerCommand("PerformanceTimeline.enable", [{ "name": "eventTypes", "type": "array", "optional": false, "description": "The types of event to report, as specified in https://w3c.github.io/performance-timeline/#dom-performanceentry-entrytype The specified filter overrides any previous filters, passing empty filter disables recording. Note that not all types exposed to the web platform are currently supported.", "typeRef": "string" }], [], "Previously buffered events would be reported before method returns. See also: timelineEventAdded");
    inspectorBackend.registerType("PerformanceTimeline.LargestContentfulPaint", [{ "name": "renderTime", "type": "number", "optional": false, "description": "", "typeRef": "Network.TimeSinceEpoch" }, { "name": "loadTime", "type": "number", "optional": false, "description": "", "typeRef": "Network.TimeSinceEpoch" }, { "name": "size", "type": "number", "optional": false, "description": "The number of pixels being painted.", "typeRef": null }, { "name": "elementId", "type": "string", "optional": true, "description": "The id attribute of the element, if available.", "typeRef": null }, { "name": "url", "type": "string", "optional": true, "description": "The URL of the image (may be trimmed).", "typeRef": null }, { "name": "nodeId", "type": "number", "optional": true, "description": "", "typeRef": "DOM.BackendNodeId" }]);
    inspectorBackend.registerType("PerformanceTimeline.LayoutShiftAttribution", [{ "name": "previousRect", "type": "object", "optional": false, "description": "", "typeRef": "DOM.Rect" }, { "name": "currentRect", "type": "object", "optional": false, "description": "", "typeRef": "DOM.Rect" }, { "name": "nodeId", "type": "number", "optional": true, "description": "", "typeRef": "DOM.BackendNodeId" }]);
    inspectorBackend.registerType("PerformanceTimeline.LayoutShift", [{ "name": "value", "type": "number", "optional": false, "description": "Score increment produced by this event.", "typeRef": null }, { "name": "hadRecentInput", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "lastInputTime", "type": "number", "optional": false, "description": "", "typeRef": "Network.TimeSinceEpoch" }, { "name": "sources", "type": "array", "optional": false, "description": "", "typeRef": "PerformanceTimeline.LayoutShiftAttribution" }]);
    inspectorBackend.registerType("PerformanceTimeline.TimelineEvent", [{ "name": "frameId", "type": "string", "optional": false, "description": "Identifies the frame that this event is related to. Empty for non-frame targets.", "typeRef": "Page.FrameId" }, { "name": "type", "type": "string", "optional": false, "description": "The event type, as specified in https://w3c.github.io/performance-timeline/#dom-performanceentry-entrytype This determines which of the optional \\\"details\\\" fields is present.", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "Name may be empty depending on the type.", "typeRef": null }, { "name": "time", "type": "number", "optional": false, "description": "Time in seconds since Epoch, monotonically increasing within document lifetime.", "typeRef": "Network.TimeSinceEpoch" }, { "name": "duration", "type": "number", "optional": true, "description": "Event duration, if applicable.", "typeRef": null }, { "name": "lcpDetails", "type": "object", "optional": true, "description": "", "typeRef": "PerformanceTimeline.LargestContentfulPaint" }, { "name": "layoutShiftDetails", "type": "object", "optional": true, "description": "", "typeRef": "PerformanceTimeline.LayoutShift" }]);
    inspectorBackend.registerEnum("Preload.RuleSetErrorType", { SourceIsNotJsonObject: "SourceIsNotJsonObject", InvalidRulesSkipped: "InvalidRulesSkipped", InvalidRulesetLevelTag: "InvalidRulesetLevelTag" });
    inspectorBackend.registerEnum("Preload.SpeculationAction", { Prefetch: "Prefetch", Prerender: "Prerender", PrerenderUntilScript: "PrerenderUntilScript" });
    inspectorBackend.registerEnum("Preload.SpeculationTargetHint", { Blank: "Blank", Self: "Self" });
    inspectorBackend.registerEnum("Preload.PrerenderFinalStatus", { Activated: "Activated", Destroyed: "Destroyed", LowEndDevice: "LowEndDevice", InvalidSchemeRedirect: "InvalidSchemeRedirect", InvalidSchemeNavigation: "InvalidSchemeNavigation", NavigationRequestBlockedByCsp: "NavigationRequestBlockedByCsp", MojoBinderPolicy: "MojoBinderPolicy", RendererProcessCrashed: "RendererProcessCrashed", RendererProcessKilled: "RendererProcessKilled", Download: "Download", TriggerDestroyed: "TriggerDestroyed", NavigationNotCommitted: "NavigationNotCommitted", NavigationBadHttpStatus: "NavigationBadHttpStatus", ClientCertRequested: "ClientCertRequested", NavigationRequestNetworkError: "NavigationRequestNetworkError", CancelAllHostsForTesting: "CancelAllHostsForTesting", DidFailLoad: "DidFailLoad", Stop: "Stop", SslCertificateError: "SslCertificateError", LoginAuthRequested: "LoginAuthRequested", UaChangeRequiresReload: "UaChangeRequiresReload", BlockedByClient: "BlockedByClient", AudioOutputDeviceRequested: "AudioOutputDeviceRequested", MixedContent: "MixedContent", TriggerBackgrounded: "TriggerBackgrounded", MemoryLimitExceeded: "MemoryLimitExceeded", DataSaverEnabled: "DataSaverEnabled", TriggerUrlHasEffectiveUrl: "TriggerUrlHasEffectiveUrl", ActivatedBeforeStarted: "ActivatedBeforeStarted", InactivePageRestriction: "InactivePageRestriction", StartFailed: "StartFailed", TimeoutBackgrounded: "TimeoutBackgrounded", CrossSiteRedirectInInitialNavigation: "CrossSiteRedirectInInitialNavigation", CrossSiteNavigationInInitialNavigation: "CrossSiteNavigationInInitialNavigation", SameSiteCrossOriginRedirectNotOptInInInitialNavigation: "SameSiteCrossOriginRedirectNotOptInInInitialNavigation", SameSiteCrossOriginNavigationNotOptInInInitialNavigation: "SameSiteCrossOriginNavigationNotOptInInInitialNavigation", ActivationNavigationParameterMismatch: "ActivationNavigationParameterMismatch", ActivatedInBackground: "ActivatedInBackground", EmbedderHostDisallowed: "EmbedderHostDisallowed", ActivationNavigationDestroyedBeforeSuccess: "ActivationNavigationDestroyedBeforeSuccess", TabClosedByUserGesture: "TabClosedByUserGesture", TabClosedWithoutUserGesture: "TabClosedWithoutUserGesture", PrimaryMainFrameRendererProcessCrashed: "PrimaryMainFrameRendererProcessCrashed", PrimaryMainFrameRendererProcessKilled: "PrimaryMainFrameRendererProcessKilled", ActivationFramePolicyNotCompatible: "ActivationFramePolicyNotCompatible", PreloadingDisabled: "PreloadingDisabled", BatterySaverEnabled: "BatterySaverEnabled", ActivatedDuringMainFrameNavigation: "ActivatedDuringMainFrameNavigation", PreloadingUnsupportedByWebContents: "PreloadingUnsupportedByWebContents", CrossSiteRedirectInMainFrameNavigation: "CrossSiteRedirectInMainFrameNavigation", CrossSiteNavigationInMainFrameNavigation: "CrossSiteNavigationInMainFrameNavigation", SameSiteCrossOriginRedirectNotOptInInMainFrameNavigation: "SameSiteCrossOriginRedirectNotOptInInMainFrameNavigation", SameSiteCrossOriginNavigationNotOptInInMainFrameNavigation: "SameSiteCrossOriginNavigationNotOptInInMainFrameNavigation", MemoryPressureOnTrigger: "MemoryPressureOnTrigger", MemoryPressureAfterTriggered: "MemoryPressureAfterTriggered", PrerenderingDisabledByDevTools: "PrerenderingDisabledByDevTools", SpeculationRuleRemoved: "SpeculationRuleRemoved", ActivatedWithAuxiliaryBrowsingContexts: "ActivatedWithAuxiliaryBrowsingContexts", MaxNumOfRunningEagerPrerendersExceeded: "MaxNumOfRunningEagerPrerendersExceeded", MaxNumOfRunningNonEagerPrerendersExceeded: "MaxNumOfRunningNonEagerPrerendersExceeded", MaxNumOfRunningEmbedderPrerendersExceeded: "MaxNumOfRunningEmbedderPrerendersExceeded", PrerenderingUrlHasEffectiveUrl: "PrerenderingUrlHasEffectiveUrl", RedirectedPrerenderingUrlHasEffectiveUrl: "RedirectedPrerenderingUrlHasEffectiveUrl", ActivationUrlHasEffectiveUrl: "ActivationUrlHasEffectiveUrl", JavaScriptInterfaceAdded: "JavaScriptInterfaceAdded", JavaScriptInterfaceRemoved: "JavaScriptInterfaceRemoved", AllPrerenderingCanceled: "AllPrerenderingCanceled", WindowClosed: "WindowClosed", SlowNetwork: "SlowNetwork", OtherPrerenderedPageActivated: "OtherPrerenderedPageActivated", V8OptimizerDisabled: "V8OptimizerDisabled", PrerenderFailedDuringPrefetch: "PrerenderFailedDuringPrefetch", BrowsingDataRemoved: "BrowsingDataRemoved", PrerenderHostReused: "PrerenderHostReused" });
    inspectorBackend.registerEnum("Preload.PreloadingStatus", { Pending: "Pending", Running: "Running", Ready: "Ready", Success: "Success", Failure: "Failure", NotSupported: "NotSupported" });
    inspectorBackend.registerEnum("Preload.PrefetchStatus", { PrefetchAllowed: "PrefetchAllowed", PrefetchFailedIneligibleRedirect: "PrefetchFailedIneligibleRedirect", PrefetchFailedInvalidRedirect: "PrefetchFailedInvalidRedirect", PrefetchFailedMIMENotSupported: "PrefetchFailedMIMENotSupported", PrefetchFailedNetError: "PrefetchFailedNetError", PrefetchFailedNon2XX: "PrefetchFailedNon2XX", PrefetchEvictedAfterBrowsingDataRemoved: "PrefetchEvictedAfterBrowsingDataRemoved", PrefetchEvictedAfterCandidateRemoved: "PrefetchEvictedAfterCandidateRemoved", PrefetchEvictedForNewerPrefetch: "PrefetchEvictedForNewerPrefetch", PrefetchHeldback: "PrefetchHeldback", PrefetchIneligibleRetryAfter: "PrefetchIneligibleRetryAfter", PrefetchIsPrivacyDecoy: "PrefetchIsPrivacyDecoy", PrefetchIsStale: "PrefetchIsStale", PrefetchNotEligibleBrowserContextOffTheRecord: "PrefetchNotEligibleBrowserContextOffTheRecord", PrefetchNotEligibleDataSaverEnabled: "PrefetchNotEligibleDataSaverEnabled", PrefetchNotEligibleExistingProxy: "PrefetchNotEligibleExistingProxy", PrefetchNotEligibleHostIsNonUnique: "PrefetchNotEligibleHostIsNonUnique", PrefetchNotEligibleNonDefaultStoragePartition: "PrefetchNotEligibleNonDefaultStoragePartition", PrefetchNotEligibleSameSiteCrossOriginPrefetchRequiredProxy: "PrefetchNotEligibleSameSiteCrossOriginPrefetchRequiredProxy", PrefetchNotEligibleSchemeIsNotHttps: "PrefetchNotEligibleSchemeIsNotHttps", PrefetchNotEligibleUserHasCookies: "PrefetchNotEligibleUserHasCookies", PrefetchNotEligibleUserHasServiceWorker: "PrefetchNotEligibleUserHasServiceWorker", PrefetchNotEligibleUserHasServiceWorkerNoFetchHandler: "PrefetchNotEligibleUserHasServiceWorkerNoFetchHandler", PrefetchNotEligibleRedirectFromServiceWorker: "PrefetchNotEligibleRedirectFromServiceWorker", PrefetchNotEligibleRedirectToServiceWorker: "PrefetchNotEligibleRedirectToServiceWorker", PrefetchNotEligibleBatterySaverEnabled: "PrefetchNotEligibleBatterySaverEnabled", PrefetchNotEligiblePreloadingDisabled: "PrefetchNotEligiblePreloadingDisabled", PrefetchNotFinishedInTime: "PrefetchNotFinishedInTime", PrefetchNotStarted: "PrefetchNotStarted", PrefetchNotUsedCookiesChanged: "PrefetchNotUsedCookiesChanged", PrefetchProxyNotAvailable: "PrefetchProxyNotAvailable", PrefetchResponseUsed: "PrefetchResponseUsed", PrefetchSuccessfulButNotUsed: "PrefetchSuccessfulButNotUsed", PrefetchNotUsedProbeFailed: "PrefetchNotUsedProbeFailed" });
    inspectorBackend.registerEvent("Preload.ruleSetUpdated", ["ruleSet"]);
    inspectorBackend.registerEvent("Preload.ruleSetRemoved", ["id"]);
    inspectorBackend.registerEvent("Preload.preloadEnabledStateUpdated", ["disabledByPreference", "disabledByDataSaver", "disabledByBatterySaver", "disabledByHoldbackPrefetchSpeculationRules", "disabledByHoldbackPrerenderSpeculationRules"]);
    inspectorBackend.registerEvent("Preload.prefetchStatusUpdated", ["key", "pipelineId", "initiatingFrameId", "prefetchUrl", "status", "prefetchStatus", "requestId"]);
    inspectorBackend.registerEvent("Preload.prerenderStatusUpdated", ["key", "pipelineId", "status", "prerenderStatus", "disallowedMojoInterface", "mismatchedHeaders"]);
    inspectorBackend.registerEvent("Preload.preloadingAttemptSourcesUpdated", ["loaderId", "preloadingAttemptSources"]);
    inspectorBackend.registerCommand("Preload.enable", [], [], "");
    inspectorBackend.registerCommand("Preload.disable", [], [], "");
    inspectorBackend.registerType("Preload.RuleSet", [{ "name": "id", "type": "string", "optional": false, "description": "", "typeRef": "Preload.RuleSetId" }, { "name": "loaderId", "type": "string", "optional": false, "description": "Identifies a document which the rule set is associated with.", "typeRef": "Network.LoaderId" }, { "name": "sourceText", "type": "string", "optional": false, "description": "Source text of JSON representing the rule set. If it comes from `<script>` tag, it is the textContent of the node. Note that it is a JSON for valid case.  See also: - https://wicg.github.io/nav-speculation/speculation-rules.html - https://github.com/WICG/nav-speculation/blob/main/triggers.md", "typeRef": null }, { "name": "backendNodeId", "type": "number", "optional": true, "description": "A speculation rule set is either added through an inline `<script>` tag or through an external resource via the 'Speculation-Rules' HTTP header. For the first case, we include the BackendNodeId of the relevant `<script>` tag. For the second case, we include the external URL where the rule set was loaded from, and also RequestId if Network domain is enabled.  See also: - https://wicg.github.io/nav-speculation/speculation-rules.html#speculation-rules-script - https://wicg.github.io/nav-speculation/speculation-rules.html#speculation-rules-header", "typeRef": "DOM.BackendNodeId" }, { "name": "url", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "requestId", "type": "string", "optional": true, "description": "", "typeRef": "Network.RequestId" }, { "name": "errorType", "type": "string", "optional": true, "description": "Error information `errorMessage` is null iff `errorType` is null.", "typeRef": "Preload.RuleSetErrorType" }, { "name": "errorMessage", "type": "string", "optional": true, "description": "TODO(https://crbug.com/1425354): Replace this property with structured error.", "typeRef": null }, { "name": "tag", "type": "string", "optional": true, "description": "For more details, see: https://github.com/WICG/nav-speculation/blob/main/speculation-rules-tags.md", "typeRef": null }]);
    inspectorBackend.registerType("Preload.PreloadingAttemptKey", [{ "name": "loaderId", "type": "string", "optional": false, "description": "", "typeRef": "Network.LoaderId" }, { "name": "action", "type": "string", "optional": false, "description": "", "typeRef": "Preload.SpeculationAction" }, { "name": "url", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "targetHint", "type": "string", "optional": true, "description": "", "typeRef": "Preload.SpeculationTargetHint" }]);
    inspectorBackend.registerType("Preload.PreloadingAttemptSource", [{ "name": "key", "type": "object", "optional": false, "description": "", "typeRef": "Preload.PreloadingAttemptKey" }, { "name": "ruleSetIds", "type": "array", "optional": false, "description": "", "typeRef": "Preload.RuleSetId" }, { "name": "nodeIds", "type": "array", "optional": false, "description": "", "typeRef": "DOM.BackendNodeId" }]);
    inspectorBackend.registerType("Preload.PrerenderMismatchedHeaders", [{ "name": "headerName", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "initialValue", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "activationValue", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerEnum("Security.MixedContentType", { Blockable: "blockable", OptionallyBlockable: "optionally-blockable", None: "none" });
    inspectorBackend.registerEnum("Security.SecurityState", { Unknown: "unknown", Neutral: "neutral", Insecure: "insecure", Secure: "secure", Info: "info", InsecureBroken: "insecure-broken" });
    inspectorBackend.registerEnum("Security.SafetyTipStatus", { BadReputation: "badReputation", Lookalike: "lookalike" });
    inspectorBackend.registerEnum("Security.CertificateErrorAction", { Continue: "continue", Cancel: "cancel" });
    inspectorBackend.registerEvent("Security.certificateError", ["eventId", "errorType", "requestURL"]);
    inspectorBackend.registerEvent("Security.visibleSecurityStateChanged", ["visibleSecurityState"]);
    inspectorBackend.registerEvent("Security.securityStateChanged", ["securityState", "schemeIsCryptographic", "explanations", "insecureContentStatus", "summary"]);
    inspectorBackend.registerCommand("Security.disable", [], [], "Disables tracking security state changes.");
    inspectorBackend.registerCommand("Security.enable", [], [], "Enables tracking security state changes.");
    inspectorBackend.registerCommand("Security.setIgnoreCertificateErrors", [{ "name": "ignore", "type": "boolean", "optional": false, "description": "If true, all certificate errors will be ignored.", "typeRef": null }], [], "Enable/disable whether all certificate errors should be ignored.");
    inspectorBackend.registerCommand("Security.handleCertificateError", [{ "name": "eventId", "type": "number", "optional": false, "description": "The ID of the event.", "typeRef": null }, { "name": "action", "type": "string", "optional": false, "description": "The action to take on the certificate error.", "typeRef": "Security.CertificateErrorAction" }], [], "Handles a certificate error that fired a certificateError event.");
    inspectorBackend.registerCommand("Security.setOverrideCertificateErrors", [{ "name": "override", "type": "boolean", "optional": false, "description": "If true, certificate errors will be overridden.", "typeRef": null }], [], "Enable/disable overriding certificate errors. If enabled, all certificate error events need to be handled by the DevTools client and should be answered with `handleCertificateError` commands.");
    inspectorBackend.registerType("Security.CertificateSecurityState", [{ "name": "protocol", "type": "string", "optional": false, "description": "Protocol name (e.g. \\\"TLS 1.2\\\" or \\\"QUIC\\\").", "typeRef": null }, { "name": "keyExchange", "type": "string", "optional": false, "description": "Key Exchange used by the connection, or the empty string if not applicable.", "typeRef": null }, { "name": "keyExchangeGroup", "type": "string", "optional": true, "description": "(EC)DH group used by the connection, if applicable.", "typeRef": null }, { "name": "cipher", "type": "string", "optional": false, "description": "Cipher name.", "typeRef": null }, { "name": "mac", "type": "string", "optional": true, "description": "TLS MAC. Note that AEAD ciphers do not have separate MACs.", "typeRef": null }, { "name": "certificate", "type": "array", "optional": false, "description": "Page certificate.", "typeRef": "string" }, { "name": "subjectName", "type": "string", "optional": false, "description": "Certificate subject name.", "typeRef": null }, { "name": "issuer", "type": "string", "optional": false, "description": "Name of the issuing CA.", "typeRef": null }, { "name": "validFrom", "type": "number", "optional": false, "description": "Certificate valid from date.", "typeRef": "Network.TimeSinceEpoch" }, { "name": "validTo", "type": "number", "optional": false, "description": "Certificate valid to (expiration) date", "typeRef": "Network.TimeSinceEpoch" }, { "name": "certificateNetworkError", "type": "string", "optional": true, "description": "The highest priority network error code, if the certificate has an error.", "typeRef": null }, { "name": "certificateHasWeakSignature", "type": "boolean", "optional": false, "description": "True if the certificate uses a weak signature algorithm.", "typeRef": null }, { "name": "certificateHasSha1Signature", "type": "boolean", "optional": false, "description": "True if the certificate has a SHA1 signature in the chain.", "typeRef": null }, { "name": "modernSSL", "type": "boolean", "optional": false, "description": "True if modern SSL", "typeRef": null }, { "name": "obsoleteSslProtocol", "type": "boolean", "optional": false, "description": "True if the connection is using an obsolete SSL protocol.", "typeRef": null }, { "name": "obsoleteSslKeyExchange", "type": "boolean", "optional": false, "description": "True if the connection is using an obsolete SSL key exchange.", "typeRef": null }, { "name": "obsoleteSslCipher", "type": "boolean", "optional": false, "description": "True if the connection is using an obsolete SSL cipher.", "typeRef": null }, { "name": "obsoleteSslSignature", "type": "boolean", "optional": false, "description": "True if the connection is using an obsolete SSL signature.", "typeRef": null }]);
    inspectorBackend.registerType("Security.SafetyTipInfo", [{ "name": "safetyTipStatus", "type": "string", "optional": false, "description": "Describes whether the page triggers any safety tips or reputation warnings. Default is unknown.", "typeRef": "Security.SafetyTipStatus" }, { "name": "safeUrl", "type": "string", "optional": true, "description": "The URL the safety tip suggested (\\\"Did you mean?\\\"). Only filled in for lookalike matches.", "typeRef": null }]);
    inspectorBackend.registerType("Security.VisibleSecurityState", [{ "name": "securityState", "type": "string", "optional": false, "description": "The security level of the page.", "typeRef": "Security.SecurityState" }, { "name": "certificateSecurityState", "type": "object", "optional": true, "description": "Security state details about the page certificate.", "typeRef": "Security.CertificateSecurityState" }, { "name": "safetyTipInfo", "type": "object", "optional": true, "description": "The type of Safety Tip triggered on the page. Note that this field will be set even if the Safety Tip UI was not actually shown.", "typeRef": "Security.SafetyTipInfo" }, { "name": "securityStateIssueIds", "type": "array", "optional": false, "description": "Array of security state issues ids.", "typeRef": "string" }]);
    inspectorBackend.registerType("Security.SecurityStateExplanation", [{ "name": "securityState", "type": "string", "optional": false, "description": "Security state representing the severity of the factor being explained.", "typeRef": "Security.SecurityState" }, { "name": "title", "type": "string", "optional": false, "description": "Title describing the type of factor.", "typeRef": null }, { "name": "summary", "type": "string", "optional": false, "description": "Short phrase describing the type of factor.", "typeRef": null }, { "name": "description", "type": "string", "optional": false, "description": "Full text explanation of the factor.", "typeRef": null }, { "name": "mixedContentType", "type": "string", "optional": false, "description": "The type of mixed content described by the explanation.", "typeRef": "Security.MixedContentType" }, { "name": "certificate", "type": "array", "optional": false, "description": "Page certificate.", "typeRef": "string" }, { "name": "recommendations", "type": "array", "optional": true, "description": "Recommendations to fix any issues.", "typeRef": "string" }]);
    inspectorBackend.registerType("Security.InsecureContentStatus", [{ "name": "ranMixedContent", "type": "boolean", "optional": false, "description": "Always false.", "typeRef": null }, { "name": "displayedMixedContent", "type": "boolean", "optional": false, "description": "Always false.", "typeRef": null }, { "name": "containedMixedForm", "type": "boolean", "optional": false, "description": "Always false.", "typeRef": null }, { "name": "ranContentWithCertErrors", "type": "boolean", "optional": false, "description": "Always false.", "typeRef": null }, { "name": "displayedContentWithCertErrors", "type": "boolean", "optional": false, "description": "Always false.", "typeRef": null }, { "name": "ranInsecureContentStyle", "type": "string", "optional": false, "description": "Always set to unknown.", "typeRef": "Security.SecurityState" }, { "name": "displayedInsecureContentStyle", "type": "string", "optional": false, "description": "Always set to unknown.", "typeRef": "Security.SecurityState" }]);
    inspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionRunningStatus", { Stopped: "stopped", Starting: "starting", Running: "running", Stopping: "stopping" });
    inspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionStatus", { New: "new", Installing: "installing", Installed: "installed", Activating: "activating", Activated: "activated", Redundant: "redundant" });
    inspectorBackend.registerEvent("ServiceWorker.workerErrorReported", ["errorMessage"]);
    inspectorBackend.registerEvent("ServiceWorker.workerRegistrationUpdated", ["registrations"]);
    inspectorBackend.registerEvent("ServiceWorker.workerVersionUpdated", ["versions"]);
    inspectorBackend.registerCommand("ServiceWorker.deliverPushMessage", [{ "name": "origin", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "registrationId", "type": "string", "optional": false, "description": "", "typeRef": "ServiceWorker.RegistrationID" }, { "name": "data", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("ServiceWorker.disable", [], [], "");
    inspectorBackend.registerCommand("ServiceWorker.dispatchSyncEvent", [{ "name": "origin", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "registrationId", "type": "string", "optional": false, "description": "", "typeRef": "ServiceWorker.RegistrationID" }, { "name": "tag", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "lastChance", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("ServiceWorker.dispatchPeriodicSyncEvent", [{ "name": "origin", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "registrationId", "type": "string", "optional": false, "description": "", "typeRef": "ServiceWorker.RegistrationID" }, { "name": "tag", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("ServiceWorker.enable", [], [], "");
    inspectorBackend.registerCommand("ServiceWorker.setForceUpdateOnPageLoad", [{ "name": "forceUpdateOnPageLoad", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("ServiceWorker.skipWaiting", [{ "name": "scopeURL", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("ServiceWorker.startWorker", [{ "name": "scopeURL", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("ServiceWorker.stopAllWorkers", [], [], "");
    inspectorBackend.registerCommand("ServiceWorker.stopWorker", [{ "name": "versionId", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("ServiceWorker.unregister", [{ "name": "scopeURL", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("ServiceWorker.updateRegistration", [{ "name": "scopeURL", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerType("ServiceWorker.ServiceWorkerRegistration", [{ "name": "registrationId", "type": "string", "optional": false, "description": "", "typeRef": "ServiceWorker.RegistrationID" }, { "name": "scopeURL", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "isDeleted", "type": "boolean", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("ServiceWorker.ServiceWorkerVersion", [{ "name": "versionId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "registrationId", "type": "string", "optional": false, "description": "", "typeRef": "ServiceWorker.RegistrationID" }, { "name": "scriptURL", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "runningStatus", "type": "string", "optional": false, "description": "", "typeRef": "ServiceWorker.ServiceWorkerVersionRunningStatus" }, { "name": "status", "type": "string", "optional": false, "description": "", "typeRef": "ServiceWorker.ServiceWorkerVersionStatus" }, { "name": "scriptLastModified", "type": "number", "optional": true, "description": "The Last-Modified header value of the main script.", "typeRef": null }, { "name": "scriptResponseTime", "type": "number", "optional": true, "description": "The time at which the response headers of the main script were received from the server. For cached script it is the last time the cache entry was validated.", "typeRef": null }, { "name": "controlledClients", "type": "array", "optional": true, "description": "", "typeRef": "Target.TargetID" }, { "name": "targetId", "type": "string", "optional": true, "description": "", "typeRef": "Target.TargetID" }, { "name": "routerRules", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("ServiceWorker.ServiceWorkerErrorMessage", [{ "name": "errorMessage", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "registrationId", "type": "string", "optional": false, "description": "", "typeRef": "ServiceWorker.RegistrationID" }, { "name": "versionId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "sourceURL", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "lineNumber", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "columnNumber", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerEnum("SmartCardEmulation.ResultCode", { Success: "success", RemovedCard: "removed-card", ResetCard: "reset-card", UnpoweredCard: "unpowered-card", UnresponsiveCard: "unresponsive-card", UnsupportedCard: "unsupported-card", ReaderUnavailable: "reader-unavailable", SharingViolation: "sharing-violation", NotTransacted: "not-transacted", NoSmartcard: "no-smartcard", ProtoMismatch: "proto-mismatch", SystemCancelled: "system-cancelled", NotReady: "not-ready", Cancelled: "cancelled", InsufficientBuffer: "insufficient-buffer", InvalidHandle: "invalid-handle", InvalidParameter: "invalid-parameter", InvalidValue: "invalid-value", NoMemory: "no-memory", Timeout: "timeout", UnknownReader: "unknown-reader", UnsupportedFeature: "unsupported-feature", NoReadersAvailable: "no-readers-available", ServiceStopped: "service-stopped", NoService: "no-service", CommError: "comm-error", InternalError: "internal-error", ServerTooBusy: "server-too-busy", Unexpected: "unexpected", Shutdown: "shutdown", UnknownCard: "unknown-card", Unknown: "unknown" });
    inspectorBackend.registerEnum("SmartCardEmulation.ShareMode", { Shared: "shared", Exclusive: "exclusive", Direct: "direct" });
    inspectorBackend.registerEnum("SmartCardEmulation.Disposition", { LeaveCard: "leave-card", ResetCard: "reset-card", UnpowerCard: "unpower-card", EjectCard: "eject-card" });
    inspectorBackend.registerEnum("SmartCardEmulation.ConnectionState", { Absent: "absent", Present: "present", Swallowed: "swallowed", Powered: "powered", Negotiable: "negotiable", Specific: "specific" });
    inspectorBackend.registerEnum("SmartCardEmulation.Protocol", { T0: "t0", T1: "t1", Raw: "raw" });
    inspectorBackend.registerEvent("SmartCardEmulation.establishContextRequested", ["requestId"]);
    inspectorBackend.registerEvent("SmartCardEmulation.releaseContextRequested", ["requestId", "contextId"]);
    inspectorBackend.registerEvent("SmartCardEmulation.listReadersRequested", ["requestId", "contextId"]);
    inspectorBackend.registerEvent("SmartCardEmulation.getStatusChangeRequested", ["requestId", "contextId", "readerStates", "timeout"]);
    inspectorBackend.registerEvent("SmartCardEmulation.cancelRequested", ["requestId", "contextId"]);
    inspectorBackend.registerEvent("SmartCardEmulation.connectRequested", ["requestId", "contextId", "reader", "shareMode", "preferredProtocols"]);
    inspectorBackend.registerEvent("SmartCardEmulation.disconnectRequested", ["requestId", "handle", "disposition"]);
    inspectorBackend.registerEvent("SmartCardEmulation.transmitRequested", ["requestId", "handle", "data", "protocol"]);
    inspectorBackend.registerEvent("SmartCardEmulation.controlRequested", ["requestId", "handle", "controlCode", "data"]);
    inspectorBackend.registerEvent("SmartCardEmulation.getAttribRequested", ["requestId", "handle", "attribId"]);
    inspectorBackend.registerEvent("SmartCardEmulation.setAttribRequested", ["requestId", "handle", "attribId", "data"]);
    inspectorBackend.registerEvent("SmartCardEmulation.statusRequested", ["requestId", "handle"]);
    inspectorBackend.registerEvent("SmartCardEmulation.beginTransactionRequested", ["requestId", "handle"]);
    inspectorBackend.registerEvent("SmartCardEmulation.endTransactionRequested", ["requestId", "handle", "disposition"]);
    inspectorBackend.registerCommand("SmartCardEmulation.enable", [], [], "Enables the |SmartCardEmulation| domain.");
    inspectorBackend.registerCommand("SmartCardEmulation.disable", [], [], "Disables the |SmartCardEmulation| domain.");
    inspectorBackend.registerCommand("SmartCardEmulation.reportEstablishContextResult", [{ "name": "requestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "contextId", "type": "number", "optional": false, "description": "", "typeRef": null }], [], "Reports the successful result of a |SCardEstablishContext| call.  This maps to: PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#gaa1b8970169fd4883a6dc4a8f43f19b67 Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardestablishcontext");
    inspectorBackend.registerCommand("SmartCardEmulation.reportReleaseContextResult", [{ "name": "requestId", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Reports the successful result of a |SCardReleaseContext| call.  This maps to: PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#ga6aabcba7744c5c9419fdd6404f73a934 Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardreleasecontext");
    inspectorBackend.registerCommand("SmartCardEmulation.reportListReadersResult", [{ "name": "requestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "readers", "type": "array", "optional": false, "description": "", "typeRef": "string" }], [], "Reports the successful result of a |SCardListReaders| call.  This maps to: PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#ga93b07815789b3cf2629d439ecf20f0d9 Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardlistreadersa");
    inspectorBackend.registerCommand("SmartCardEmulation.reportGetStatusChangeResult", [{ "name": "requestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "readerStates", "type": "array", "optional": false, "description": "", "typeRef": "SmartCardEmulation.ReaderStateOut" }], [], "Reports the successful result of a |SCardGetStatusChange| call.  This maps to: PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#ga33247d5d1257d59e55647c3bb717db24 Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardgetstatuschangea");
    inspectorBackend.registerCommand("SmartCardEmulation.reportBeginTransactionResult", [{ "name": "requestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "handle", "type": "number", "optional": false, "description": "", "typeRef": null }], [], "Reports the result of a |SCardBeginTransaction| call. On success, this creates a new transaction object.  This maps to: PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#gaddb835dce01a0da1d6ca02d33ee7d861 Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardbegintransaction");
    inspectorBackend.registerCommand("SmartCardEmulation.reportPlainResult", [{ "name": "requestId", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Reports the successful result of a call that returns only a result code. Used for: |SCardCancel|, |SCardDisconnect|, |SCardSetAttrib|, |SCardEndTransaction|.  This maps to: 1. SCardCancel    PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#gaacbbc0c6d6c0cbbeb4f4debf6fbeeee6    Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardcancel  2. SCardDisconnect    PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#ga4be198045c73ec0deb79e66c0ca1738a    Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scarddisconnect  3. SCardSetAttrib    PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#ga060f0038a4ddfd5dd2b8fadf3c3a2e4f    Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardsetattrib  4. SCardEndTransaction    PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#gae8742473b404363e5c587f570d7e2f3b    Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardendtransaction");
    inspectorBackend.registerCommand("SmartCardEmulation.reportConnectResult", [{ "name": "requestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "handle", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "activeProtocol", "type": "string", "optional": true, "description": "", "typeRef": "SmartCardEmulation.Protocol" }], [], "Reports the successful result of a |SCardConnect| call.  This maps to: PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#ga4e515829752e0a8dbc4d630696a8d6a5 Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardconnecta");
    inspectorBackend.registerCommand("SmartCardEmulation.reportDataResult", [{ "name": "requestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "data", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Reports the successful result of a call that sends back data on success. Used for |SCardTransmit|, |SCardControl|, and |SCardGetAttrib|.  This maps to: 1. SCardTransmit    PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#ga9a2d77242a271310269065e64633ab99    Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardtransmit  2. SCardControl    PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#gac3454d4657110fd7f753b2d3d8f4e32f    Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardcontrol  3. SCardGetAttrib    PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#gaacfec51917255b7a25b94c5104961602    Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardgetattrib");
    inspectorBackend.registerCommand("SmartCardEmulation.reportStatusResult", [{ "name": "requestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "readerName", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "state", "type": "string", "optional": false, "description": "", "typeRef": "SmartCardEmulation.ConnectionState" }, { "name": "atr", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "protocol", "type": "string", "optional": true, "description": "", "typeRef": "SmartCardEmulation.Protocol" }], [], "Reports the successful result of a |SCardStatus| call.  This maps to: PC/SC Lite: https://pcsclite.apdu.fr/api/group__API.html#gae49c3c894ad7ac12a5b896bde70d0382 Microsoft: https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardstatusa");
    inspectorBackend.registerCommand("SmartCardEmulation.reportError", [{ "name": "requestId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "resultCode", "type": "string", "optional": false, "description": "", "typeRef": "SmartCardEmulation.ResultCode" }], [], "Reports an error result for the given request.");
    inspectorBackend.registerType("SmartCardEmulation.ReaderStateFlags", [{ "name": "unaware", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "ignore", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "changed", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "unknown", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "unavailable", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "empty", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "present", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "exclusive", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "inuse", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "mute", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "unpowered", "type": "boolean", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("SmartCardEmulation.ProtocolSet", [{ "name": "t0", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "t1", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "raw", "type": "boolean", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("SmartCardEmulation.ReaderStateIn", [{ "name": "reader", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "currentState", "type": "object", "optional": false, "description": "", "typeRef": "SmartCardEmulation.ReaderStateFlags" }, { "name": "currentInsertionCount", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("SmartCardEmulation.ReaderStateOut", [{ "name": "reader", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "eventState", "type": "object", "optional": false, "description": "", "typeRef": "SmartCardEmulation.ReaderStateFlags" }, { "name": "eventCount", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "atr", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerEnum("Storage.StorageType", { Cookies: "cookies", File_systems: "file_systems", Indexeddb: "indexeddb", Local_storage: "local_storage", Shader_cache: "shader_cache", Websql: "websql", Service_workers: "service_workers", Cache_storage: "cache_storage", Interest_groups: "interest_groups", Shared_storage: "shared_storage", Storage_buckets: "storage_buckets", All: "all", Other: "other" });
    inspectorBackend.registerEnum("Storage.InterestGroupAccessType", { Join: "join", Leave: "leave", Update: "update", Loaded: "loaded", Bid: "bid", Win: "win", AdditionalBid: "additionalBid", AdditionalBidWin: "additionalBidWin", TopLevelBid: "topLevelBid", TopLevelAdditionalBid: "topLevelAdditionalBid", Clear: "clear" });
    inspectorBackend.registerEnum("Storage.InterestGroupAuctionEventType", { Started: "started", ConfigResolved: "configResolved" });
    inspectorBackend.registerEnum("Storage.InterestGroupAuctionFetchType", { BidderJs: "bidderJs", BidderWasm: "bidderWasm", SellerJs: "sellerJs", BidderTrustedSignals: "bidderTrustedSignals", SellerTrustedSignals: "sellerTrustedSignals" });
    inspectorBackend.registerEnum("Storage.SharedStorageAccessScope", { Window: "window", SharedStorageWorklet: "sharedStorageWorklet", ProtectedAudienceWorklet: "protectedAudienceWorklet", Header: "header" });
    inspectorBackend.registerEnum("Storage.SharedStorageAccessMethod", { AddModule: "addModule", CreateWorklet: "createWorklet", SelectURL: "selectURL", Run: "run", BatchUpdate: "batchUpdate", Set: "set", Append: "append", Delete: "delete", Clear: "clear", Get: "get", Keys: "keys", Values: "values", Entries: "entries", Length: "length", RemainingBudget: "remainingBudget" });
    inspectorBackend.registerEnum("Storage.StorageBucketsDurability", { Relaxed: "relaxed", Strict: "strict" });
    inspectorBackend.registerEnum("Storage.AttributionReportingSourceType", { Navigation: "navigation", Event: "event" });
    inspectorBackend.registerEnum("Storage.AttributionReportingTriggerDataMatching", { Exact: "exact", Modulus: "modulus" });
    inspectorBackend.registerEnum("Storage.AttributionReportingSourceRegistrationResult", { Success: "success", InternalError: "internalError", InsufficientSourceCapacity: "insufficientSourceCapacity", InsufficientUniqueDestinationCapacity: "insufficientUniqueDestinationCapacity", ExcessiveReportingOrigins: "excessiveReportingOrigins", ProhibitedByBrowserPolicy: "prohibitedByBrowserPolicy", SuccessNoised: "successNoised", DestinationReportingLimitReached: "destinationReportingLimitReached", DestinationGlobalLimitReached: "destinationGlobalLimitReached", DestinationBothLimitsReached: "destinationBothLimitsReached", ReportingOriginsPerSiteLimitReached: "reportingOriginsPerSiteLimitReached", ExceedsMaxChannelCapacity: "exceedsMaxChannelCapacity", ExceedsMaxScopesChannelCapacity: "exceedsMaxScopesChannelCapacity", ExceedsMaxTriggerStateCardinality: "exceedsMaxTriggerStateCardinality", ExceedsMaxEventStatesLimit: "exceedsMaxEventStatesLimit", DestinationPerDayReportingLimitReached: "destinationPerDayReportingLimitReached" });
    inspectorBackend.registerEnum("Storage.AttributionReportingSourceRegistrationTimeConfig", { Include: "include", Exclude: "exclude" });
    inspectorBackend.registerEnum("Storage.AttributionReportingEventLevelResult", { Success: "success", SuccessDroppedLowerPriority: "successDroppedLowerPriority", InternalError: "internalError", NoCapacityForAttributionDestination: "noCapacityForAttributionDestination", NoMatchingSources: "noMatchingSources", Deduplicated: "deduplicated", ExcessiveAttributions: "excessiveAttributions", PriorityTooLow: "priorityTooLow", NeverAttributedSource: "neverAttributedSource", ExcessiveReportingOrigins: "excessiveReportingOrigins", NoMatchingSourceFilterData: "noMatchingSourceFilterData", ProhibitedByBrowserPolicy: "prohibitedByBrowserPolicy", NoMatchingConfigurations: "noMatchingConfigurations", ExcessiveReports: "excessiveReports", FalselyAttributedSource: "falselyAttributedSource", ReportWindowPassed: "reportWindowPassed", NotRegistered: "notRegistered", ReportWindowNotStarted: "reportWindowNotStarted", NoMatchingTriggerData: "noMatchingTriggerData" });
    inspectorBackend.registerEnum("Storage.AttributionReportingAggregatableResult", { Success: "success", InternalError: "internalError", NoCapacityForAttributionDestination: "noCapacityForAttributionDestination", NoMatchingSources: "noMatchingSources", ExcessiveAttributions: "excessiveAttributions", ExcessiveReportingOrigins: "excessiveReportingOrigins", NoHistograms: "noHistograms", InsufficientBudget: "insufficientBudget", InsufficientNamedBudget: "insufficientNamedBudget", NoMatchingSourceFilterData: "noMatchingSourceFilterData", NotRegistered: "notRegistered", ProhibitedByBrowserPolicy: "prohibitedByBrowserPolicy", Deduplicated: "deduplicated", ReportWindowPassed: "reportWindowPassed", ExcessiveReports: "excessiveReports" });
    inspectorBackend.registerEnum("Storage.AttributionReportingReportResult", { Sent: "sent", Prohibited: "prohibited", FailedToAssemble: "failedToAssemble", Expired: "expired" });
    inspectorBackend.registerEvent("Storage.cacheStorageContentUpdated", ["origin", "storageKey", "bucketId", "cacheName"]);
    inspectorBackend.registerEvent("Storage.cacheStorageListUpdated", ["origin", "storageKey", "bucketId"]);
    inspectorBackend.registerEvent("Storage.indexedDBContentUpdated", ["origin", "storageKey", "bucketId", "databaseName", "objectStoreName"]);
    inspectorBackend.registerEvent("Storage.indexedDBListUpdated", ["origin", "storageKey", "bucketId"]);
    inspectorBackend.registerEvent("Storage.interestGroupAccessed", ["accessTime", "type", "ownerOrigin", "name", "componentSellerOrigin", "bid", "bidCurrency", "uniqueAuctionId"]);
    inspectorBackend.registerEvent("Storage.interestGroupAuctionEventOccurred", ["eventTime", "type", "uniqueAuctionId", "parentAuctionId", "auctionConfig"]);
    inspectorBackend.registerEvent("Storage.interestGroupAuctionNetworkRequestCreated", ["type", "requestId", "auctions"]);
    inspectorBackend.registerEvent("Storage.sharedStorageAccessed", ["accessTime", "scope", "method", "mainFrameId", "ownerOrigin", "ownerSite", "params"]);
    inspectorBackend.registerEvent("Storage.sharedStorageWorkletOperationExecutionFinished", ["finishedTime", "executionTime", "method", "operationId", "workletTargetId", "mainFrameId", "ownerOrigin"]);
    inspectorBackend.registerEvent("Storage.storageBucketCreatedOrUpdated", ["bucketInfo"]);
    inspectorBackend.registerEvent("Storage.storageBucketDeleted", ["bucketId"]);
    inspectorBackend.registerEvent("Storage.attributionReportingSourceRegistered", ["registration", "result"]);
    inspectorBackend.registerEvent("Storage.attributionReportingTriggerRegistered", ["registration", "eventLevel", "aggregatable"]);
    inspectorBackend.registerEvent("Storage.attributionReportingReportSent", ["url", "body", "result", "netError", "netErrorName", "httpStatusCode"]);
    inspectorBackend.registerEvent("Storage.attributionReportingVerboseDebugReportSent", ["url", "body", "netError", "netErrorName", "httpStatusCode"]);
    inspectorBackend.registerCommand("Storage.getStorageKeyForFrame", [{ "name": "frameId", "type": "string", "optional": false, "description": "", "typeRef": "Page.FrameId" }], ["storageKey"], "Returns a storage key given a frame id. Deprecated. Please use Storage.getStorageKey instead.");
    inspectorBackend.registerCommand("Storage.getStorageKey", [{ "name": "frameId", "type": "string", "optional": true, "description": "", "typeRef": "Page.FrameId" }], ["storageKey"], "Returns storage key for the given frame. If no frame ID is provided, the storage key of the target executing this command is returned.");
    inspectorBackend.registerCommand("Storage.clearDataForOrigin", [{ "name": "origin", "type": "string", "optional": false, "description": "Security origin.", "typeRef": null }, { "name": "storageTypes", "type": "string", "optional": false, "description": "Comma separated list of StorageType to clear.", "typeRef": null }], [], "Clears storage for origin.");
    inspectorBackend.registerCommand("Storage.clearDataForStorageKey", [{ "name": "storageKey", "type": "string", "optional": false, "description": "Storage key.", "typeRef": null }, { "name": "storageTypes", "type": "string", "optional": false, "description": "Comma separated list of StorageType to clear.", "typeRef": null }], [], "Clears storage for storage key.");
    inspectorBackend.registerCommand("Storage.getCookies", [{ "name": "browserContextId", "type": "string", "optional": true, "description": "Browser context to use when called on the browser endpoint.", "typeRef": "Browser.BrowserContextID" }], ["cookies"], "Returns all browser cookies.");
    inspectorBackend.registerCommand("Storage.setCookies", [{ "name": "cookies", "type": "array", "optional": false, "description": "Cookies to be set.", "typeRef": "Network.CookieParam" }, { "name": "browserContextId", "type": "string", "optional": true, "description": "Browser context to use when called on the browser endpoint.", "typeRef": "Browser.BrowserContextID" }], [], "Sets given cookies.");
    inspectorBackend.registerCommand("Storage.clearCookies", [{ "name": "browserContextId", "type": "string", "optional": true, "description": "Browser context to use when called on the browser endpoint.", "typeRef": "Browser.BrowserContextID" }], [], "Clears cookies.");
    inspectorBackend.registerCommand("Storage.getUsageAndQuota", [{ "name": "origin", "type": "string", "optional": false, "description": "Security origin.", "typeRef": null }], ["usage", "quota", "overrideActive", "usageBreakdown"], "Returns usage and quota in bytes.");
    inspectorBackend.registerCommand("Storage.overrideQuotaForOrigin", [{ "name": "origin", "type": "string", "optional": false, "description": "Security origin.", "typeRef": null }, { "name": "quotaSize", "type": "number", "optional": true, "description": "The quota size (in bytes) to override the original quota with. If this is called multiple times, the overridden quota will be equal to the quotaSize provided in the final call. If this is called without specifying a quotaSize, the quota will be reset to the default value for the specified origin. If this is called multiple times with different origins, the override will be maintained for each origin until it is disabled (called without a quotaSize).", "typeRef": null }], [], "Override quota for the specified origin");
    inspectorBackend.registerCommand("Storage.trackCacheStorageForOrigin", [{ "name": "origin", "type": "string", "optional": false, "description": "Security origin.", "typeRef": null }], [], "Registers origin to be notified when an update occurs to its cache storage list.");
    inspectorBackend.registerCommand("Storage.trackCacheStorageForStorageKey", [{ "name": "storageKey", "type": "string", "optional": false, "description": "Storage key.", "typeRef": null }], [], "Registers storage key to be notified when an update occurs to its cache storage list.");
    inspectorBackend.registerCommand("Storage.trackIndexedDBForOrigin", [{ "name": "origin", "type": "string", "optional": false, "description": "Security origin.", "typeRef": null }], [], "Registers origin to be notified when an update occurs to its IndexedDB.");
    inspectorBackend.registerCommand("Storage.trackIndexedDBForStorageKey", [{ "name": "storageKey", "type": "string", "optional": false, "description": "Storage key.", "typeRef": null }], [], "Registers storage key to be notified when an update occurs to its IndexedDB.");
    inspectorBackend.registerCommand("Storage.untrackCacheStorageForOrigin", [{ "name": "origin", "type": "string", "optional": false, "description": "Security origin.", "typeRef": null }], [], "Unregisters origin from receiving notifications for cache storage.");
    inspectorBackend.registerCommand("Storage.untrackCacheStorageForStorageKey", [{ "name": "storageKey", "type": "string", "optional": false, "description": "Storage key.", "typeRef": null }], [], "Unregisters storage key from receiving notifications for cache storage.");
    inspectorBackend.registerCommand("Storage.untrackIndexedDBForOrigin", [{ "name": "origin", "type": "string", "optional": false, "description": "Security origin.", "typeRef": null }], [], "Unregisters origin from receiving notifications for IndexedDB.");
    inspectorBackend.registerCommand("Storage.untrackIndexedDBForStorageKey", [{ "name": "storageKey", "type": "string", "optional": false, "description": "Storage key.", "typeRef": null }], [], "Unregisters storage key from receiving notifications for IndexedDB.");
    inspectorBackend.registerCommand("Storage.getTrustTokens", [], ["tokens"], "Returns the number of stored Trust Tokens per issuer for the current browsing context.");
    inspectorBackend.registerCommand("Storage.clearTrustTokens", [{ "name": "issuerOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }], ["didDeleteTokens"], "Removes all Trust Tokens issued by the provided issuerOrigin. Leaves other stored data, including the issuer's Redemption Records, intact.");
    inspectorBackend.registerCommand("Storage.getInterestGroupDetails", [{ "name": "ownerOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }], ["details"], "Gets details for a named interest group.");
    inspectorBackend.registerCommand("Storage.setInterestGroupTracking", [{ "name": "enable", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "Enables/Disables issuing of interestGroupAccessed events.");
    inspectorBackend.registerCommand("Storage.setInterestGroupAuctionTracking", [{ "name": "enable", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "Enables/Disables issuing of interestGroupAuctionEventOccurred and interestGroupAuctionNetworkRequestCreated.");
    inspectorBackend.registerCommand("Storage.getSharedStorageMetadata", [{ "name": "ownerOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }], ["metadata"], "Gets metadata for an origin's shared storage.");
    inspectorBackend.registerCommand("Storage.getSharedStorageEntries", [{ "name": "ownerOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }], ["entries"], "Gets the entries in an given origin's shared storage.");
    inspectorBackend.registerCommand("Storage.setSharedStorageEntry", [{ "name": "ownerOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "key", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "ignoreIfPresent", "type": "boolean", "optional": true, "description": "If `ignoreIfPresent` is included and true, then only sets the entry if `key` doesn't already exist.", "typeRef": null }], [], "Sets entry with `key` and `value` for a given origin's shared storage.");
    inspectorBackend.registerCommand("Storage.deleteSharedStorageEntry", [{ "name": "ownerOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "key", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Deletes entry for `key` (if it exists) for a given origin's shared storage.");
    inspectorBackend.registerCommand("Storage.clearSharedStorageEntries", [{ "name": "ownerOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Clears all entries for a given origin's shared storage.");
    inspectorBackend.registerCommand("Storage.resetSharedStorageBudget", [{ "name": "ownerOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Resets the budget for `ownerOrigin` by clearing all budget withdrawals.");
    inspectorBackend.registerCommand("Storage.setSharedStorageTracking", [{ "name": "enable", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "Enables/disables issuing of sharedStorageAccessed events.");
    inspectorBackend.registerCommand("Storage.setStorageBucketTracking", [{ "name": "storageKey", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "enable", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "Set tracking for a storage key's buckets.");
    inspectorBackend.registerCommand("Storage.deleteStorageBucket", [{ "name": "bucket", "type": "object", "optional": false, "description": "", "typeRef": "Storage.StorageBucket" }], [], "Deletes the Storage Bucket with the given storage key and bucket name.");
    inspectorBackend.registerCommand("Storage.runBounceTrackingMitigations", [], ["deletedSites"], "Deletes state for sites identified as potential bounce trackers, immediately.");
    inspectorBackend.registerCommand("Storage.setAttributionReportingLocalTestingMode", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "If enabled, noise is suppressed and reports are sent immediately.", "typeRef": null }], [], "https://wicg.github.io/attribution-reporting-api/");
    inspectorBackend.registerCommand("Storage.setAttributionReportingTracking", [{ "name": "enable", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "Enables/disables issuing of Attribution Reporting events.");
    inspectorBackend.registerCommand("Storage.sendPendingAttributionReports", [], ["numSent"], "Sends all pending Attribution Reports immediately, regardless of their scheduled report time.");
    inspectorBackend.registerCommand("Storage.getRelatedWebsiteSets", [], ["sets"], "Returns the effective Related Website Sets in use by this profile for the browser session. The effective Related Website Sets will not change during a browser session.");
    inspectorBackend.registerCommand("Storage.getAffectedUrlsForThirdPartyCookieMetadata", [{ "name": "firstPartyUrl", "type": "string", "optional": false, "description": "The URL of the page currently being visited.", "typeRef": null }, { "name": "thirdPartyUrls", "type": "array", "optional": false, "description": "The list of embedded resource URLs from the page.", "typeRef": "string" }], ["matchedUrls"], "Returns the list of URLs from a page and its embedded resources that match existing grace period URL pattern rules. https://developers.google.com/privacy-sandbox/cookies/temporary-exceptions/grace-period");
    inspectorBackend.registerCommand("Storage.setProtectedAudienceKAnonymity", [{ "name": "owner", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "hashes", "type": "array", "optional": false, "description": "", "typeRef": "binary" }], [], "");
    inspectorBackend.registerType("Storage.UsageForType", [{ "name": "storageType", "type": "string", "optional": false, "description": "Name of storage type.", "typeRef": "Storage.StorageType" }, { "name": "usage", "type": "number", "optional": false, "description": "Storage usage (bytes).", "typeRef": null }]);
    inspectorBackend.registerType("Storage.TrustTokens", [{ "name": "issuerOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "count", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Storage.SharedStorageEntry", [{ "name": "key", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Storage.SharedStorageMetadata", [{ "name": "creationTime", "type": "number", "optional": false, "description": "Time when the origin's shared storage was last created.", "typeRef": "Network.TimeSinceEpoch" }, { "name": "length", "type": "number", "optional": false, "description": "Number of key-value pairs stored in origin's shared storage.", "typeRef": null }, { "name": "remainingBudget", "type": "number", "optional": false, "description": "Current amount of bits of entropy remaining in the navigation budget.", "typeRef": null }, { "name": "bytesUsed", "type": "number", "optional": false, "description": "Total number of bytes stored as key-value pairs in origin's shared storage.", "typeRef": null }]);
    inspectorBackend.registerType("Storage.SharedStoragePrivateAggregationConfig", [{ "name": "aggregationCoordinatorOrigin", "type": "string", "optional": true, "description": "The chosen aggregation service deployment.", "typeRef": null }, { "name": "contextId", "type": "string", "optional": true, "description": "The context ID provided.", "typeRef": null }, { "name": "filteringIdMaxBytes", "type": "number", "optional": false, "description": "Configures the maximum size allowed for filtering IDs.", "typeRef": null }, { "name": "maxContributions", "type": "number", "optional": true, "description": "The limit on the number of contributions in the final report.", "typeRef": null }]);
    inspectorBackend.registerType("Storage.SharedStorageReportingMetadata", [{ "name": "eventType", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "reportingUrl", "type": "string", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Storage.SharedStorageUrlWithMetadata", [{ "name": "url", "type": "string", "optional": false, "description": "Spec of candidate URL.", "typeRef": null }, { "name": "reportingMetadata", "type": "array", "optional": false, "description": "Any associated reporting metadata.", "typeRef": "Storage.SharedStorageReportingMetadata" }]);
    inspectorBackend.registerType("Storage.SharedStorageAccessParams", [{ "name": "scriptSourceUrl", "type": "string", "optional": true, "description": "Spec of the module script URL. Present only for SharedStorageAccessMethods: addModule and createWorklet.", "typeRef": null }, { "name": "dataOrigin", "type": "string", "optional": true, "description": "String denoting \\\"context-origin\\\", \\\"script-origin\\\", or a custom origin to be used as the worklet's data origin. Present only for SharedStorageAccessMethod: createWorklet.", "typeRef": null }, { "name": "operationName", "type": "string", "optional": true, "description": "Name of the registered operation to be run. Present only for SharedStorageAccessMethods: run and selectURL.", "typeRef": null }, { "name": "operationId", "type": "string", "optional": true, "description": "ID of the operation call. Present only for SharedStorageAccessMethods: run and selectURL.", "typeRef": null }, { "name": "keepAlive", "type": "boolean", "optional": true, "description": "Whether or not to keep the worket alive for future run or selectURL calls. Present only for SharedStorageAccessMethods: run and selectURL.", "typeRef": null }, { "name": "privateAggregationConfig", "type": "object", "optional": true, "description": "Configures the private aggregation options. Present only for SharedStorageAccessMethods: run and selectURL.", "typeRef": "Storage.SharedStoragePrivateAggregationConfig" }, { "name": "serializedData", "type": "string", "optional": true, "description": "The operation's serialized data in bytes (converted to a string). Present only for SharedStorageAccessMethods: run and selectURL. TODO(crbug.com/401011862): Consider updating this parameter to binary.", "typeRef": null }, { "name": "urlsWithMetadata", "type": "array", "optional": true, "description": "Array of candidate URLs' specs, along with any associated metadata. Present only for SharedStorageAccessMethod: selectURL.", "typeRef": "Storage.SharedStorageUrlWithMetadata" }, { "name": "urnUuid", "type": "string", "optional": true, "description": "Spec of the URN:UUID generated for a selectURL call. Present only for SharedStorageAccessMethod: selectURL.", "typeRef": null }, { "name": "key", "type": "string", "optional": true, "description": "Key for a specific entry in an origin's shared storage. Present only for SharedStorageAccessMethods: set, append, delete, and get.", "typeRef": null }, { "name": "value", "type": "string", "optional": true, "description": "Value for a specific entry in an origin's shared storage. Present only for SharedStorageAccessMethods: set and append.", "typeRef": null }, { "name": "ignoreIfPresent", "type": "boolean", "optional": true, "description": "Whether or not to set an entry for a key if that key is already present. Present only for SharedStorageAccessMethod: set.", "typeRef": null }, { "name": "workletOrdinal", "type": "number", "optional": true, "description": "A number denoting the (0-based) order of the worklet's creation relative to all other shared storage worklets created by documents using the current storage partition. Present only for SharedStorageAccessMethods: addModule, createWorklet.", "typeRef": null }, { "name": "workletTargetId", "type": "string", "optional": true, "description": "Hex representation of the DevTools token used as the TargetID for the associated shared storage worklet. Present only for SharedStorageAccessMethods: addModule, createWorklet, run, selectURL, and any other SharedStorageAccessMethod when the SharedStorageAccessScope is sharedStorageWorklet.", "typeRef": "Target.TargetID" }, { "name": "withLock", "type": "string", "optional": true, "description": "Name of the lock to be acquired, if present. Optionally present only for SharedStorageAccessMethods: batchUpdate, set, append, delete, and clear.", "typeRef": null }, { "name": "batchUpdateId", "type": "string", "optional": true, "description": "If the method has been called as part of a batchUpdate, then this number identifies the batch to which it belongs. Optionally present only for SharedStorageAccessMethods: batchUpdate (required), set, append, delete, and clear.", "typeRef": null }, { "name": "batchSize", "type": "number", "optional": true, "description": "Number of modifier methods sent in batch. Present only for SharedStorageAccessMethod: batchUpdate.", "typeRef": null }]);
    inspectorBackend.registerType("Storage.StorageBucket", [{ "name": "storageKey", "type": "string", "optional": false, "description": "", "typeRef": "Storage.SerializedStorageKey" }, { "name": "name", "type": "string", "optional": true, "description": "If not specified, it is the default bucket of the storageKey.", "typeRef": null }]);
    inspectorBackend.registerType("Storage.StorageBucketInfo", [{ "name": "bucket", "type": "object", "optional": false, "description": "", "typeRef": "Storage.StorageBucket" }, { "name": "id", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "expiration", "type": "number", "optional": false, "description": "", "typeRef": "Network.TimeSinceEpoch" }, { "name": "quota", "type": "number", "optional": false, "description": "Storage quota (bytes).", "typeRef": null }, { "name": "persistent", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "durability", "type": "string", "optional": false, "description": "", "typeRef": "Storage.StorageBucketsDurability" }]);
    inspectorBackend.registerType("Storage.AttributionReportingFilterDataEntry", [{ "name": "key", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "values", "type": "array", "optional": false, "description": "", "typeRef": "string" }]);
    inspectorBackend.registerType("Storage.AttributionReportingFilterConfig", [{ "name": "filterValues", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingFilterDataEntry" }, { "name": "lookbackWindow", "type": "number", "optional": true, "description": "duration in seconds", "typeRef": null }]);
    inspectorBackend.registerType("Storage.AttributionReportingFilterPair", [{ "name": "filters", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingFilterConfig" }, { "name": "notFilters", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingFilterConfig" }]);
    inspectorBackend.registerType("Storage.AttributionReportingAggregationKeysEntry", [{ "name": "key", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "string", "optional": false, "description": "", "typeRef": "Storage.UnsignedInt128AsBase16" }]);
    inspectorBackend.registerType("Storage.AttributionReportingEventReportWindows", [{ "name": "start", "type": "number", "optional": false, "description": "duration in seconds", "typeRef": null }, { "name": "ends", "type": "array", "optional": false, "description": "duration in seconds", "typeRef": "integer" }]);
    inspectorBackend.registerType("Storage.AttributionReportingAggregatableDebugReportingData", [{ "name": "keyPiece", "type": "string", "optional": false, "description": "", "typeRef": "Storage.UnsignedInt128AsBase16" }, { "name": "value", "type": "number", "optional": false, "description": "number instead of integer because not all uint32 can be represented by int", "typeRef": null }, { "name": "types", "type": "array", "optional": false, "description": "", "typeRef": "string" }]);
    inspectorBackend.registerType("Storage.AttributionReportingAggregatableDebugReportingConfig", [{ "name": "budget", "type": "number", "optional": true, "description": "number instead of integer because not all uint32 can be represented by int, only present for source registrations", "typeRef": null }, { "name": "keyPiece", "type": "string", "optional": false, "description": "", "typeRef": "Storage.UnsignedInt128AsBase16" }, { "name": "debugData", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingAggregatableDebugReportingData" }, { "name": "aggregationCoordinatorOrigin", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Storage.AttributionScopesData", [{ "name": "values", "type": "array", "optional": false, "description": "", "typeRef": "string" }, { "name": "limit", "type": "number", "optional": false, "description": "number instead of integer because not all uint32 can be represented by int", "typeRef": null }, { "name": "maxEventStates", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Storage.AttributionReportingNamedBudgetDef", [{ "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "budget", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Storage.AttributionReportingSourceRegistration", [{ "name": "time", "type": "number", "optional": false, "description": "", "typeRef": "Network.TimeSinceEpoch" }, { "name": "expiry", "type": "number", "optional": false, "description": "duration in seconds", "typeRef": null }, { "name": "triggerData", "type": "array", "optional": false, "description": "number instead of integer because not all uint32 can be represented by int", "typeRef": "number" }, { "name": "eventReportWindows", "type": "object", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingEventReportWindows" }, { "name": "aggregatableReportWindow", "type": "number", "optional": false, "description": "duration in seconds", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingSourceType" }, { "name": "sourceOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "reportingOrigin", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "destinationSites", "type": "array", "optional": false, "description": "", "typeRef": "string" }, { "name": "eventId", "type": "string", "optional": false, "description": "", "typeRef": "Storage.UnsignedInt64AsBase10" }, { "name": "priority", "type": "string", "optional": false, "description": "", "typeRef": "Storage.SignedInt64AsBase10" }, { "name": "filterData", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingFilterDataEntry" }, { "name": "aggregationKeys", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingAggregationKeysEntry" }, { "name": "debugKey", "type": "string", "optional": true, "description": "", "typeRef": "Storage.UnsignedInt64AsBase10" }, { "name": "triggerDataMatching", "type": "string", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingTriggerDataMatching" }, { "name": "destinationLimitPriority", "type": "string", "optional": false, "description": "", "typeRef": "Storage.SignedInt64AsBase10" }, { "name": "aggregatableDebugReportingConfig", "type": "object", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingAggregatableDebugReportingConfig" }, { "name": "scopesData", "type": "object", "optional": true, "description": "", "typeRef": "Storage.AttributionScopesData" }, { "name": "maxEventLevelReports", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "namedBudgets", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingNamedBudgetDef" }, { "name": "debugReporting", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "eventLevelEpsilon", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Storage.AttributionReportingAggregatableValueDictEntry", [{ "name": "key", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "number", "optional": false, "description": "number instead of integer because not all uint32 can be represented by int", "typeRef": null }, { "name": "filteringId", "type": "string", "optional": false, "description": "", "typeRef": "Storage.UnsignedInt64AsBase10" }]);
    inspectorBackend.registerType("Storage.AttributionReportingAggregatableValueEntry", [{ "name": "values", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingAggregatableValueDictEntry" }, { "name": "filters", "type": "object", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingFilterPair" }]);
    inspectorBackend.registerType("Storage.AttributionReportingEventTriggerData", [{ "name": "data", "type": "string", "optional": false, "description": "", "typeRef": "Storage.UnsignedInt64AsBase10" }, { "name": "priority", "type": "string", "optional": false, "description": "", "typeRef": "Storage.SignedInt64AsBase10" }, { "name": "dedupKey", "type": "string", "optional": true, "description": "", "typeRef": "Storage.UnsignedInt64AsBase10" }, { "name": "filters", "type": "object", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingFilterPair" }]);
    inspectorBackend.registerType("Storage.AttributionReportingAggregatableTriggerData", [{ "name": "keyPiece", "type": "string", "optional": false, "description": "", "typeRef": "Storage.UnsignedInt128AsBase16" }, { "name": "sourceKeys", "type": "array", "optional": false, "description": "", "typeRef": "string" }, { "name": "filters", "type": "object", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingFilterPair" }]);
    inspectorBackend.registerType("Storage.AttributionReportingAggregatableDedupKey", [{ "name": "dedupKey", "type": "string", "optional": true, "description": "", "typeRef": "Storage.UnsignedInt64AsBase10" }, { "name": "filters", "type": "object", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingFilterPair" }]);
    inspectorBackend.registerType("Storage.AttributionReportingNamedBudgetCandidate", [{ "name": "name", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "filters", "type": "object", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingFilterPair" }]);
    inspectorBackend.registerType("Storage.AttributionReportingTriggerRegistration", [{ "name": "filters", "type": "object", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingFilterPair" }, { "name": "debugKey", "type": "string", "optional": true, "description": "", "typeRef": "Storage.UnsignedInt64AsBase10" }, { "name": "aggregatableDedupKeys", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingAggregatableDedupKey" }, { "name": "eventTriggerData", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingEventTriggerData" }, { "name": "aggregatableTriggerData", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingAggregatableTriggerData" }, { "name": "aggregatableValues", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingAggregatableValueEntry" }, { "name": "aggregatableFilteringIdMaxBytes", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "debugReporting", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "aggregationCoordinatorOrigin", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "sourceRegistrationTimeConfig", "type": "string", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingSourceRegistrationTimeConfig" }, { "name": "triggerContextId", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "aggregatableDebugReportingConfig", "type": "object", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingAggregatableDebugReportingConfig" }, { "name": "scopes", "type": "array", "optional": false, "description": "", "typeRef": "string" }, { "name": "namedBudgets", "type": "array", "optional": false, "description": "", "typeRef": "Storage.AttributionReportingNamedBudgetCandidate" }]);
    inspectorBackend.registerType("Storage.RelatedWebsiteSet", [{ "name": "primarySites", "type": "array", "optional": false, "description": "The primary site of this set, along with the ccTLDs if there is any.", "typeRef": "string" }, { "name": "associatedSites", "type": "array", "optional": false, "description": "The associated sites of this set, along with the ccTLDs if there is any.", "typeRef": "string" }, { "name": "serviceSites", "type": "array", "optional": false, "description": "The service sites of this set, along with the ccTLDs if there is any.", "typeRef": "string" }]);
    inspectorBackend.registerEnum("SystemInfo.SubsamplingFormat", { Yuv420: "yuv420", Yuv422: "yuv422", Yuv444: "yuv444" });
    inspectorBackend.registerEnum("SystemInfo.ImageType", { Jpeg: "jpeg", Webp: "webp", Unknown: "unknown" });
    inspectorBackend.registerCommand("SystemInfo.getInfo", [], ["gpu", "modelName", "modelVersion", "commandLine"], "Returns information about the system.");
    inspectorBackend.registerCommand("SystemInfo.getFeatureState", [{ "name": "featureState", "type": "string", "optional": false, "description": "", "typeRef": null }], ["featureEnabled"], "Returns information about the feature state.");
    inspectorBackend.registerCommand("SystemInfo.getProcessInfo", [], ["processInfo"], "Returns information about all running processes.");
    inspectorBackend.registerType("SystemInfo.GPUDevice", [{ "name": "vendorId", "type": "number", "optional": false, "description": "PCI ID of the GPU vendor, if available; 0 otherwise.", "typeRef": null }, { "name": "deviceId", "type": "number", "optional": false, "description": "PCI ID of the GPU device, if available; 0 otherwise.", "typeRef": null }, { "name": "subSysId", "type": "number", "optional": true, "description": "Sub sys ID of the GPU, only available on Windows.", "typeRef": null }, { "name": "revision", "type": "number", "optional": true, "description": "Revision of the GPU, only available on Windows.", "typeRef": null }, { "name": "vendorString", "type": "string", "optional": false, "description": "String description of the GPU vendor, if the PCI ID is not available.", "typeRef": null }, { "name": "deviceString", "type": "string", "optional": false, "description": "String description of the GPU device, if the PCI ID is not available.", "typeRef": null }, { "name": "driverVendor", "type": "string", "optional": false, "description": "String description of the GPU driver vendor.", "typeRef": null }, { "name": "driverVersion", "type": "string", "optional": false, "description": "String description of the GPU driver version.", "typeRef": null }]);
    inspectorBackend.registerType("SystemInfo.Size", [{ "name": "width", "type": "number", "optional": false, "description": "Width in pixels.", "typeRef": null }, { "name": "height", "type": "number", "optional": false, "description": "Height in pixels.", "typeRef": null }]);
    inspectorBackend.registerType("SystemInfo.VideoDecodeAcceleratorCapability", [{ "name": "profile", "type": "string", "optional": false, "description": "Video codec profile that is supported, e.g. VP9 Profile 2.", "typeRef": null }, { "name": "maxResolution", "type": "object", "optional": false, "description": "Maximum video dimensions in pixels supported for this |profile|.", "typeRef": "SystemInfo.Size" }, { "name": "minResolution", "type": "object", "optional": false, "description": "Minimum video dimensions in pixels supported for this |profile|.", "typeRef": "SystemInfo.Size" }]);
    inspectorBackend.registerType("SystemInfo.VideoEncodeAcceleratorCapability", [{ "name": "profile", "type": "string", "optional": false, "description": "Video codec profile that is supported, e.g H264 Main.", "typeRef": null }, { "name": "maxResolution", "type": "object", "optional": false, "description": "Maximum video dimensions in pixels supported for this |profile|.", "typeRef": "SystemInfo.Size" }, { "name": "maxFramerateNumerator", "type": "number", "optional": false, "description": "Maximum encoding framerate in frames per second supported for this |profile|, as fraction's numerator and denominator, e.g. 24/1 fps, 24000/1001 fps, etc.", "typeRef": null }, { "name": "maxFramerateDenominator", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("SystemInfo.GPUInfo", [{ "name": "devices", "type": "array", "optional": false, "description": "The graphics devices on the system. Element 0 is the primary GPU.", "typeRef": "SystemInfo.GPUDevice" }, { "name": "auxAttributes", "type": "object", "optional": true, "description": "An optional dictionary of additional GPU related attributes.", "typeRef": null }, { "name": "featureStatus", "type": "object", "optional": true, "description": "An optional dictionary of graphics features and their status.", "typeRef": null }, { "name": "driverBugWorkarounds", "type": "array", "optional": false, "description": "An optional array of GPU driver bug workarounds.", "typeRef": "string" }, { "name": "videoDecoding", "type": "array", "optional": false, "description": "Supported accelerated video decoding capabilities.", "typeRef": "SystemInfo.VideoDecodeAcceleratorCapability" }, { "name": "videoEncoding", "type": "array", "optional": false, "description": "Supported accelerated video encoding capabilities.", "typeRef": "SystemInfo.VideoEncodeAcceleratorCapability" }]);
    inspectorBackend.registerType("SystemInfo.ProcessInfo", [{ "name": "type", "type": "string", "optional": false, "description": "Specifies process type.", "typeRef": null }, { "name": "id", "type": "number", "optional": false, "description": "Specifies process id.", "typeRef": null }, { "name": "cpuTime", "type": "number", "optional": false, "description": "Specifies cumulative CPU usage in seconds across all threads of the process since the process start.", "typeRef": null }]);
    inspectorBackend.registerEnum("Target.WindowState", { Normal: "normal", Minimized: "minimized", Maximized: "maximized", Fullscreen: "fullscreen" });
    inspectorBackend.registerEvent("Target.attachedToTarget", ["sessionId", "targetInfo", "waitingForDebugger"]);
    inspectorBackend.registerEvent("Target.detachedFromTarget", ["sessionId", "targetId"]);
    inspectorBackend.registerEvent("Target.receivedMessageFromTarget", ["sessionId", "message", "targetId"]);
    inspectorBackend.registerEvent("Target.targetCreated", ["targetInfo"]);
    inspectorBackend.registerEvent("Target.targetDestroyed", ["targetId"]);
    inspectorBackend.registerEvent("Target.targetCrashed", ["targetId", "status", "errorCode"]);
    inspectorBackend.registerEvent("Target.targetInfoChanged", ["targetInfo"]);
    inspectorBackend.registerCommand("Target.activateTarget", [{ "name": "targetId", "type": "string", "optional": false, "description": "", "typeRef": "Target.TargetID" }], [], "Activates (focuses) the target.");
    inspectorBackend.registerCommand("Target.attachToTarget", [{ "name": "targetId", "type": "string", "optional": false, "description": "", "typeRef": "Target.TargetID" }, { "name": "flatten", "type": "boolean", "optional": true, "description": "Enables \\\"flat\\\" access to the session via specifying sessionId attribute in the commands. We plan to make this the default, deprecate non-flattened mode, and eventually retire it. See crbug.com/991325.", "typeRef": null }], ["sessionId"], "Attaches to the target with given id.");
    inspectorBackend.registerCommand("Target.attachToBrowserTarget", [], ["sessionId"], "Attaches to the browser target, only uses flat sessionId mode.");
    inspectorBackend.registerCommand("Target.closeTarget", [{ "name": "targetId", "type": "string", "optional": false, "description": "", "typeRef": "Target.TargetID" }], ["success"], "Closes the target. If the target is a page that gets closed too.");
    inspectorBackend.registerCommand("Target.exposeDevToolsProtocol", [{ "name": "targetId", "type": "string", "optional": false, "description": "", "typeRef": "Target.TargetID" }, { "name": "bindingName", "type": "string", "optional": true, "description": "Binding name, 'cdp' if not specified.", "typeRef": null }, { "name": "inheritPermissions", "type": "boolean", "optional": true, "description": "If true, inherits the current root session's permissions (default: false).", "typeRef": null }], [], "Inject object to the target's main frame that provides a communication channel with browser target.  Injected object will be available as `window[bindingName]`.  The object has the following API: - `binding.send(json)` - a method to send messages over the remote debugging protocol - `binding.onmessage = json => handleMessage(json)` - a callback that will be called for the protocol notifications and command responses.");
    inspectorBackend.registerCommand("Target.createBrowserContext", [{ "name": "disposeOnDetach", "type": "boolean", "optional": true, "description": "If specified, disposes this context when debugging session disconnects.", "typeRef": null }, { "name": "proxyServer", "type": "string", "optional": true, "description": "Proxy server, similar to the one passed to --proxy-server", "typeRef": null }, { "name": "proxyBypassList", "type": "string", "optional": true, "description": "Proxy bypass list, similar to the one passed to --proxy-bypass-list", "typeRef": null }, { "name": "originsWithUniversalNetworkAccess", "type": "array", "optional": true, "description": "An optional list of origins to grant unlimited cross-origin access to. Parts of the URL other than those constituting origin are ignored.", "typeRef": "string" }], ["browserContextId"], "Creates a new empty BrowserContext. Similar to an incognito profile but you can have more than one.");
    inspectorBackend.registerCommand("Target.getBrowserContexts", [], ["browserContextIds", "defaultBrowserContextId"], "Returns all browser contexts created with `Target.createBrowserContext` method.");
    inspectorBackend.registerCommand("Target.createTarget", [{ "name": "url", "type": "string", "optional": false, "description": "The initial URL the page will be navigated to. An empty string indicates about:blank.", "typeRef": null }, { "name": "left", "type": "number", "optional": true, "description": "Frame left origin in DIP (requires newWindow to be true or headless shell).", "typeRef": null }, { "name": "top", "type": "number", "optional": true, "description": "Frame top origin in DIP (requires newWindow to be true or headless shell).", "typeRef": null }, { "name": "width", "type": "number", "optional": true, "description": "Frame width in DIP (requires newWindow to be true or headless shell).", "typeRef": null }, { "name": "height", "type": "number", "optional": true, "description": "Frame height in DIP (requires newWindow to be true or headless shell).", "typeRef": null }, { "name": "windowState", "type": "string", "optional": true, "description": "Frame window state (requires newWindow to be true or headless shell). Default is normal.", "typeRef": "Target.WindowState" }, { "name": "browserContextId", "type": "string", "optional": true, "description": "The browser context to create the page in.", "typeRef": "Browser.BrowserContextID" }, { "name": "enableBeginFrameControl", "type": "boolean", "optional": true, "description": "Whether BeginFrames for this target will be controlled via DevTools (headless shell only, not supported on MacOS yet, false by default).", "typeRef": null }, { "name": "newWindow", "type": "boolean", "optional": true, "description": "Whether to create a new Window or Tab (false by default, not supported by headless shell).", "typeRef": null }, { "name": "background", "type": "boolean", "optional": true, "description": "Whether to create the target in background or foreground (false by default, not supported by headless shell).", "typeRef": null }, { "name": "forTab", "type": "boolean", "optional": true, "description": "Whether to create the target of type \\\"tab\\\".", "typeRef": null }, { "name": "hidden", "type": "boolean", "optional": true, "description": "Whether to create a hidden target. The hidden target is observable via protocol, but not present in the tab UI strip. Cannot be created with `forTab: true`, `newWindow: true` or `background: false`. The life-time of the tab is limited to the life-time of the session.", "typeRef": null }, { "name": "focus", "type": "boolean", "optional": true, "description": "If specified, the option is used to determine if the new target should be focused or not. By default, the focus behavior depends on the value of the background field. For example, background=false and focus=false will result in the target tab being opened but the browser window remain unchanged (if it was in the background, it will remain in the background) and background=false with focus=undefined will result in the window being focused. Using background: true and focus: true is not supported and will result in an error.", "typeRef": null }], ["targetId"], "Creates a new page.");
    inspectorBackend.registerCommand("Target.detachFromTarget", [{ "name": "sessionId", "type": "string", "optional": true, "description": "Session to detach.", "typeRef": "Target.SessionID" }, { "name": "targetId", "type": "string", "optional": true, "description": "Deprecated.", "typeRef": "Target.TargetID" }], [], "Detaches session with given id.");
    inspectorBackend.registerCommand("Target.disposeBrowserContext", [{ "name": "browserContextId", "type": "string", "optional": false, "description": "", "typeRef": "Browser.BrowserContextID" }], [], "Deletes a BrowserContext. All the belonging pages will be closed without calling their beforeunload hooks.");
    inspectorBackend.registerCommand("Target.getTargetInfo", [{ "name": "targetId", "type": "string", "optional": true, "description": "", "typeRef": "Target.TargetID" }], ["targetInfo"], "Returns information about a target.");
    inspectorBackend.registerCommand("Target.getTargets", [{ "name": "filter", "type": "array", "optional": true, "description": "Only targets matching filter will be reported. If filter is not specified and target discovery is currently enabled, a filter used for target discovery is used for consistency.", "typeRef": "Target.TargetFilter" }], ["targetInfos"], "Retrieves a list of available targets.");
    inspectorBackend.registerCommand("Target.sendMessageToTarget", [{ "name": "message", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "sessionId", "type": "string", "optional": true, "description": "Identifier of the session.", "typeRef": "Target.SessionID" }, { "name": "targetId", "type": "string", "optional": true, "description": "Deprecated.", "typeRef": "Target.TargetID" }], [], "Sends protocol message over session with given id. Consider using flat mode instead; see commands attachToTarget, setAutoAttach, and crbug.com/991325.");
    inspectorBackend.registerCommand("Target.setAutoAttach", [{ "name": "autoAttach", "type": "boolean", "optional": false, "description": "Whether to auto-attach to related targets.", "typeRef": null }, { "name": "waitForDebuggerOnStart", "type": "boolean", "optional": false, "description": "Whether to pause new targets when attaching to them. Use `Runtime.runIfWaitingForDebugger` to run paused targets.", "typeRef": null }, { "name": "flatten", "type": "boolean", "optional": true, "description": "Enables \\\"flat\\\" access to the session via specifying sessionId attribute in the commands. We plan to make this the default, deprecate non-flattened mode, and eventually retire it. See crbug.com/991325.", "typeRef": null }, { "name": "filter", "type": "array", "optional": true, "description": "Only targets matching filter will be attached.", "typeRef": "Target.TargetFilter" }], [], "Controls whether to automatically attach to new targets which are considered to be directly related to this one (for example, iframes or workers). When turned on, attaches to all existing related targets as well. When turned off, automatically detaches from all currently attached targets. This also clears all targets added by `autoAttachRelated` from the list of targets to watch for creation of related targets. You might want to call this recursively for auto-attached targets to attach to all available targets.");
    inspectorBackend.registerCommand("Target.autoAttachRelated", [{ "name": "targetId", "type": "string", "optional": false, "description": "", "typeRef": "Target.TargetID" }, { "name": "waitForDebuggerOnStart", "type": "boolean", "optional": false, "description": "Whether to pause new targets when attaching to them. Use `Runtime.runIfWaitingForDebugger` to run paused targets.", "typeRef": null }, { "name": "filter", "type": "array", "optional": true, "description": "Only targets matching filter will be attached.", "typeRef": "Target.TargetFilter" }], [], "Adds the specified target to the list of targets that will be monitored for any related target creation (such as child frames, child workers and new versions of service worker) and reported through `attachedToTarget`. The specified target is also auto-attached. This cancels the effect of any previous `setAutoAttach` and is also cancelled by subsequent `setAutoAttach`. Only available at the Browser target.");
    inspectorBackend.registerCommand("Target.setDiscoverTargets", [{ "name": "discover", "type": "boolean", "optional": false, "description": "Whether to discover available targets.", "typeRef": null }, { "name": "filter", "type": "array", "optional": true, "description": "Only targets matching filter will be attached. If `discover` is false, `filter` must be omitted or empty.", "typeRef": "Target.TargetFilter" }], [], "Controls whether to discover available targets and notify via `targetCreated/targetInfoChanged/targetDestroyed` events.");
    inspectorBackend.registerCommand("Target.setRemoteLocations", [{ "name": "locations", "type": "array", "optional": false, "description": "List of remote locations.", "typeRef": "Target.RemoteLocation" }], [], "Enables target discovery for the specified locations, when `setDiscoverTargets` was set to `true`.");
    inspectorBackend.registerCommand("Target.getDevToolsTarget", [{ "name": "targetId", "type": "string", "optional": false, "description": "Page or tab target ID.", "typeRef": "Target.TargetID" }], ["targetId"], "Gets the targetId of the DevTools page target opened for the given target (if any).");
    inspectorBackend.registerCommand("Target.openDevTools", [{ "name": "targetId", "type": "string", "optional": false, "description": "This can be the page or tab target ID.", "typeRef": "Target.TargetID" }, { "name": "panelId", "type": "string", "optional": true, "description": "The id of the panel we want DevTools to open initially. Currently supported panels are elements, console, network, sources, resources and performance.", "typeRef": null }], ["targetId"], "Opens a DevTools window for the target.");
    inspectorBackend.registerType("Target.TargetInfo", [{ "name": "targetId", "type": "string", "optional": false, "description": "", "typeRef": "Target.TargetID" }, { "name": "type", "type": "string", "optional": false, "description": "List of types: https://source.chromium.org/chromium/chromium/src/+/main:content/browser/devtools/devtools_agent_host_impl.cc?ss=chromium&q=f:devtools%20-f:out%20%22::kTypeTab%5B%5D%22", "typeRef": null }, { "name": "title", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "url", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "attached", "type": "boolean", "optional": false, "description": "Whether the target has an attached client.", "typeRef": null }, { "name": "openerId", "type": "string", "optional": true, "description": "Opener target Id", "typeRef": "Target.TargetID" }, { "name": "canAccessOpener", "type": "boolean", "optional": false, "description": "Whether the target has access to the originating window.", "typeRef": null }, { "name": "openerFrameId", "type": "string", "optional": true, "description": "Frame id of originating window (is only set if target has an opener).", "typeRef": "Page.FrameId" }, { "name": "parentFrameId", "type": "string", "optional": true, "description": "Id of the parent frame, only present for the \\\"iframe\\\" targets.", "typeRef": "Page.FrameId" }, { "name": "browserContextId", "type": "string", "optional": true, "description": "", "typeRef": "Browser.BrowserContextID" }, { "name": "subtype", "type": "string", "optional": true, "description": "Provides additional details for specific target types. For example, for the type of \\\"page\\\", this may be set to \\\"prerender\\\".", "typeRef": null }]);
    inspectorBackend.registerType("Target.FilterEntry", [{ "name": "exclude", "type": "boolean", "optional": true, "description": "If set, causes exclusion of matching targets from the list.", "typeRef": null }, { "name": "type", "type": "string", "optional": true, "description": "If not present, matches any type.", "typeRef": null }]);
    inspectorBackend.registerType("Target.TargetFilter", [{ "name": "TargetFilter", "type": "array", "optional": false, "description": "The entries in TargetFilter are matched sequentially against targets and the first entry that matches determines if the target is included or not, depending on the value of `exclude` field in the entry. If filter is not specified, the one assumed is [{type: \\\"browser\\\", exclude: true}, {type: \\\"tab\\\", exclude: true}, {}] (i.e. include everything but `browser` and `tab`).", "typeRef": "Target.FilterEntry" }]);
    inspectorBackend.registerType("Target.RemoteLocation", [{ "name": "host", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "port", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerEvent("Tethering.accepted", ["port", "connectionId"]);
    inspectorBackend.registerCommand("Tethering.bind", [{ "name": "port", "type": "number", "optional": false, "description": "Port number to bind.", "typeRef": null }], [], "Request browser port binding.");
    inspectorBackend.registerCommand("Tethering.unbind", [{ "name": "port", "type": "number", "optional": false, "description": "Port number to unbind.", "typeRef": null }], [], "Request browser port unbinding.");
    inspectorBackend.registerEnum("Tracing.TraceConfigRecordMode", { RecordUntilFull: "recordUntilFull", RecordContinuously: "recordContinuously", RecordAsMuchAsPossible: "recordAsMuchAsPossible", EchoToConsole: "echoToConsole" });
    inspectorBackend.registerEnum("Tracing.StreamFormat", { Json: "json", Proto: "proto" });
    inspectorBackend.registerEnum("Tracing.StreamCompression", { None: "none", Gzip: "gzip" });
    inspectorBackend.registerEnum("Tracing.MemoryDumpLevelOfDetail", { Background: "background", Light: "light", Detailed: "detailed" });
    inspectorBackend.registerEnum("Tracing.TracingBackend", { Auto: "auto", Chrome: "chrome", System: "system" });
    inspectorBackend.registerEvent("Tracing.bufferUsage", ["percentFull", "eventCount", "value"]);
    inspectorBackend.registerEvent("Tracing.dataCollected", ["value"]);
    inspectorBackend.registerEvent("Tracing.tracingComplete", ["dataLossOccurred", "stream", "traceFormat", "streamCompression"]);
    inspectorBackend.registerCommand("Tracing.end", [], [], "Stop trace events collection.");
    inspectorBackend.registerCommand("Tracing.getCategories", [], ["categories"], "Gets supported tracing categories.");
    inspectorBackend.registerCommand("Tracing.getTrackEventDescriptor", [], ["descriptor"], "Return a descriptor for all available tracing categories.");
    inspectorBackend.registerCommand("Tracing.recordClockSyncMarker", [{ "name": "syncId", "type": "string", "optional": false, "description": "The ID of this clock sync marker", "typeRef": null }], [], "Record a clock sync marker in the trace.");
    inspectorBackend.registerCommand("Tracing.requestMemoryDump", [{ "name": "deterministic", "type": "boolean", "optional": true, "description": "Enables more deterministic results by forcing garbage collection", "typeRef": null }, { "name": "levelOfDetail", "type": "string", "optional": true, "description": "Specifies level of details in memory dump. Defaults to \\\"detailed\\\".", "typeRef": "Tracing.MemoryDumpLevelOfDetail" }], ["dumpGuid", "success"], "Request a global memory dump.");
    inspectorBackend.registerEnum("Tracing.StartRequestTransferMode", { ReportEvents: "ReportEvents", ReturnAsStream: "ReturnAsStream" });
    inspectorBackend.registerCommand("Tracing.start", [{ "name": "categories", "type": "string", "optional": true, "description": "Category/tag filter", "typeRef": null }, { "name": "options", "type": "string", "optional": true, "description": "Tracing options", "typeRef": null }, { "name": "bufferUsageReportingInterval", "type": "number", "optional": true, "description": "If set, the agent will issue bufferUsage events at this interval, specified in milliseconds", "typeRef": null }, { "name": "transferMode", "type": "string", "optional": true, "description": "Whether to report trace events as series of dataCollected events or to save trace to a stream (defaults to `ReportEvents`).", "typeRef": "Tracing.StartRequestTransferMode" }, { "name": "streamFormat", "type": "string", "optional": true, "description": "Trace data format to use. This only applies when using `ReturnAsStream` transfer mode (defaults to `json`).", "typeRef": "Tracing.StreamFormat" }, { "name": "streamCompression", "type": "string", "optional": true, "description": "Compression format to use. This only applies when using `ReturnAsStream` transfer mode (defaults to `none`)", "typeRef": "Tracing.StreamCompression" }, { "name": "traceConfig", "type": "object", "optional": true, "description": "", "typeRef": "Tracing.TraceConfig" }, { "name": "perfettoConfig", "type": "string", "optional": true, "description": "Base64-encoded serialized perfetto.protos.TraceConfig protobuf message When specified, the parameters `categories`, `options`, `traceConfig` are ignored.", "typeRef": null }, { "name": "tracingBackend", "type": "string", "optional": true, "description": "Backend type (defaults to `auto`)", "typeRef": "Tracing.TracingBackend" }], [], "Start trace events collection.");
    inspectorBackend.registerType("Tracing.TraceConfig", [{ "name": "recordMode", "type": "string", "optional": true, "description": "Controls how the trace buffer stores data. The default is `recordUntilFull`.", "typeRef": null }, { "name": "traceBufferSizeInKb", "type": "number", "optional": true, "description": "Size of the trace buffer in kilobytes. If not specified or zero is passed, a default value of 200 MB would be used.", "typeRef": null }, { "name": "enableSampling", "type": "boolean", "optional": true, "description": "Turns on JavaScript stack sampling.", "typeRef": null }, { "name": "enableSystrace", "type": "boolean", "optional": true, "description": "Turns on system tracing.", "typeRef": null }, { "name": "enableArgumentFilter", "type": "boolean", "optional": true, "description": "Turns on argument filter.", "typeRef": null }, { "name": "includedCategories", "type": "array", "optional": true, "description": "Included category filters.", "typeRef": "string" }, { "name": "excludedCategories", "type": "array", "optional": true, "description": "Excluded category filters.", "typeRef": "string" }, { "name": "syntheticDelays", "type": "array", "optional": true, "description": "Configuration to synthesize the delays in tracing.", "typeRef": "string" }, { "name": "memoryDumpConfig", "type": "object", "optional": true, "description": "Configuration for memory dump triggers. Used only when \\\"memory-infra\\\" category is enabled.", "typeRef": "Tracing.MemoryDumpConfig" }]);
    inspectorBackend.registerEnum("WebAudio.ContextType", { Realtime: "realtime", Offline: "offline" });
    inspectorBackend.registerEnum("WebAudio.ContextState", { Suspended: "suspended", Running: "running", Closed: "closed", Interrupted: "interrupted" });
    inspectorBackend.registerEnum("WebAudio.ChannelCountMode", { ClampedMax: "clamped-max", Explicit: "explicit", Max: "max" });
    inspectorBackend.registerEnum("WebAudio.ChannelInterpretation", { Discrete: "discrete", Speakers: "speakers" });
    inspectorBackend.registerEnum("WebAudio.AutomationRate", { ARate: "a-rate", KRate: "k-rate" });
    inspectorBackend.registerEvent("WebAudio.contextCreated", ["context"]);
    inspectorBackend.registerEvent("WebAudio.contextWillBeDestroyed", ["contextId"]);
    inspectorBackend.registerEvent("WebAudio.contextChanged", ["context"]);
    inspectorBackend.registerEvent("WebAudio.audioListenerCreated", ["listener"]);
    inspectorBackend.registerEvent("WebAudio.audioListenerWillBeDestroyed", ["contextId", "listenerId"]);
    inspectorBackend.registerEvent("WebAudio.audioNodeCreated", ["node"]);
    inspectorBackend.registerEvent("WebAudio.audioNodeWillBeDestroyed", ["contextId", "nodeId"]);
    inspectorBackend.registerEvent("WebAudio.audioParamCreated", ["param"]);
    inspectorBackend.registerEvent("WebAudio.audioParamWillBeDestroyed", ["contextId", "nodeId", "paramId"]);
    inspectorBackend.registerEvent("WebAudio.nodesConnected", ["contextId", "sourceId", "destinationId", "sourceOutputIndex", "destinationInputIndex"]);
    inspectorBackend.registerEvent("WebAudio.nodesDisconnected", ["contextId", "sourceId", "destinationId", "sourceOutputIndex", "destinationInputIndex"]);
    inspectorBackend.registerEvent("WebAudio.nodeParamConnected", ["contextId", "sourceId", "destinationId", "sourceOutputIndex"]);
    inspectorBackend.registerEvent("WebAudio.nodeParamDisconnected", ["contextId", "sourceId", "destinationId", "sourceOutputIndex"]);
    inspectorBackend.registerCommand("WebAudio.enable", [], [], "Enables the WebAudio domain and starts sending context lifetime events.");
    inspectorBackend.registerCommand("WebAudio.disable", [], [], "Disables the WebAudio domain.");
    inspectorBackend.registerCommand("WebAudio.getRealtimeData", [{ "name": "contextId", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.GraphObjectId" }], ["realtimeData"], "Fetch the realtime data from the registered contexts.");
    inspectorBackend.registerType("WebAudio.ContextRealtimeData", [{ "name": "currentTime", "type": "number", "optional": false, "description": "The current context time in second in BaseAudioContext.", "typeRef": null }, { "name": "renderCapacity", "type": "number", "optional": false, "description": "The time spent on rendering graph divided by render quantum duration, and multiplied by 100. 100 means the audio renderer reached the full capacity and glitch may occur.", "typeRef": null }, { "name": "callbackIntervalMean", "type": "number", "optional": false, "description": "A running mean of callback interval.", "typeRef": null }, { "name": "callbackIntervalVariance", "type": "number", "optional": false, "description": "A running variance of callback interval.", "typeRef": null }]);
    inspectorBackend.registerType("WebAudio.BaseAudioContext", [{ "name": "contextId", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.GraphObjectId" }, { "name": "contextType", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.ContextType" }, { "name": "contextState", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.ContextState" }, { "name": "realtimeData", "type": "object", "optional": true, "description": "", "typeRef": "WebAudio.ContextRealtimeData" }, { "name": "callbackBufferSize", "type": "number", "optional": false, "description": "Platform-dependent callback buffer size.", "typeRef": null }, { "name": "maxOutputChannelCount", "type": "number", "optional": false, "description": "Number of output channels supported by audio hardware in use.", "typeRef": null }, { "name": "sampleRate", "type": "number", "optional": false, "description": "Context sample rate.", "typeRef": null }]);
    inspectorBackend.registerType("WebAudio.AudioListener", [{ "name": "listenerId", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.GraphObjectId" }, { "name": "contextId", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.GraphObjectId" }]);
    inspectorBackend.registerType("WebAudio.AudioNode", [{ "name": "nodeId", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.GraphObjectId" }, { "name": "contextId", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.GraphObjectId" }, { "name": "nodeType", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.NodeType" }, { "name": "numberOfInputs", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "numberOfOutputs", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "channelCount", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "channelCountMode", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.ChannelCountMode" }, { "name": "channelInterpretation", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.ChannelInterpretation" }]);
    inspectorBackend.registerType("WebAudio.AudioParam", [{ "name": "paramId", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.GraphObjectId" }, { "name": "nodeId", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.GraphObjectId" }, { "name": "contextId", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.GraphObjectId" }, { "name": "paramType", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.ParamType" }, { "name": "rate", "type": "string", "optional": false, "description": "", "typeRef": "WebAudio.AutomationRate" }, { "name": "defaultValue", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "minValue", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "maxValue", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerEnum("WebAuthn.AuthenticatorProtocol", { U2f: "u2f", Ctap2: "ctap2" });
    inspectorBackend.registerEnum("WebAuthn.Ctap2Version", { Ctap2_0: "ctap2_0", Ctap2_1: "ctap2_1" });
    inspectorBackend.registerEnum("WebAuthn.AuthenticatorTransport", { Usb: "usb", Nfc: "nfc", Ble: "ble", Cable: "cable", Internal: "internal" });
    inspectorBackend.registerEvent("WebAuthn.credentialAdded", ["authenticatorId", "credential"]);
    inspectorBackend.registerEvent("WebAuthn.credentialDeleted", ["authenticatorId", "credentialId"]);
    inspectorBackend.registerEvent("WebAuthn.credentialUpdated", ["authenticatorId", "credential"]);
    inspectorBackend.registerEvent("WebAuthn.credentialAsserted", ["authenticatorId", "credential"]);
    inspectorBackend.registerCommand("WebAuthn.enable", [{ "name": "enableUI", "type": "boolean", "optional": true, "description": "Whether to enable the WebAuthn user interface. Enabling the UI is recommended for debugging and demo purposes, as it is closer to the real experience. Disabling the UI is recommended for automated testing. Supported at the embedder's discretion if UI is available. Defaults to false.", "typeRef": null }], [], "Enable the WebAuthn domain and start intercepting credential storage and retrieval with a virtual authenticator.");
    inspectorBackend.registerCommand("WebAuthn.disable", [], [], "Disable the WebAuthn domain.");
    inspectorBackend.registerCommand("WebAuthn.addVirtualAuthenticator", [{ "name": "options", "type": "object", "optional": false, "description": "", "typeRef": "WebAuthn.VirtualAuthenticatorOptions" }], ["authenticatorId"], "Creates and adds a virtual authenticator.");
    inspectorBackend.registerCommand("WebAuthn.setResponseOverrideBits", [{ "name": "authenticatorId", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorId" }, { "name": "isBogusSignature", "type": "boolean", "optional": true, "description": "If isBogusSignature is set, overrides the signature in the authenticator response to be zero. Defaults to false.", "typeRef": null }, { "name": "isBadUV", "type": "boolean", "optional": true, "description": "If isBadUV is set, overrides the UV bit in the flags in the authenticator response to be zero. Defaults to false.", "typeRef": null }, { "name": "isBadUP", "type": "boolean", "optional": true, "description": "If isBadUP is set, overrides the UP bit in the flags in the authenticator response to be zero. Defaults to false.", "typeRef": null }], [], "Resets parameters isBogusSignature, isBadUV, isBadUP to false if they are not present.");
    inspectorBackend.registerCommand("WebAuthn.removeVirtualAuthenticator", [{ "name": "authenticatorId", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorId" }], [], "Removes the given authenticator.");
    inspectorBackend.registerCommand("WebAuthn.addCredential", [{ "name": "authenticatorId", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorId" }, { "name": "credential", "type": "object", "optional": false, "description": "", "typeRef": "WebAuthn.Credential" }], [], "Adds the credential to the specified authenticator.");
    inspectorBackend.registerCommand("WebAuthn.getCredential", [{ "name": "authenticatorId", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorId" }, { "name": "credentialId", "type": "string", "optional": false, "description": "", "typeRef": null }], ["credential"], "Returns a single credential stored in the given virtual authenticator that matches the credential ID.");
    inspectorBackend.registerCommand("WebAuthn.getCredentials", [{ "name": "authenticatorId", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorId" }], ["credentials"], "Returns all the credentials stored in the given virtual authenticator.");
    inspectorBackend.registerCommand("WebAuthn.removeCredential", [{ "name": "authenticatorId", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorId" }, { "name": "credentialId", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "Removes a credential from the authenticator.");
    inspectorBackend.registerCommand("WebAuthn.clearCredentials", [{ "name": "authenticatorId", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorId" }], [], "Clears all the credentials from the specified device.");
    inspectorBackend.registerCommand("WebAuthn.setUserVerified", [{ "name": "authenticatorId", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorId" }, { "name": "isUserVerified", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "Sets whether User Verification succeeds or fails for an authenticator. The default is true.");
    inspectorBackend.registerCommand("WebAuthn.setAutomaticPresenceSimulation", [{ "name": "authenticatorId", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorId" }, { "name": "enabled", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "Sets whether tests of user presence will succeed immediately (if true) or fail to resolve (if false) for an authenticator. The default is true.");
    inspectorBackend.registerCommand("WebAuthn.setCredentialProperties", [{ "name": "authenticatorId", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorId" }, { "name": "credentialId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "backupEligibility", "type": "boolean", "optional": true, "description": "", "typeRef": null }, { "name": "backupState", "type": "boolean", "optional": true, "description": "", "typeRef": null }], [], "Allows setting credential properties. https://w3c.github.io/webauthn/#sctn-automation-set-credential-properties");
    inspectorBackend.registerType("WebAuthn.VirtualAuthenticatorOptions", [{ "name": "protocol", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorProtocol" }, { "name": "ctap2Version", "type": "string", "optional": true, "description": "Defaults to ctap2_0. Ignored if |protocol| == u2f.", "typeRef": "WebAuthn.Ctap2Version" }, { "name": "transport", "type": "string", "optional": false, "description": "", "typeRef": "WebAuthn.AuthenticatorTransport" }, { "name": "hasResidentKey", "type": "boolean", "optional": true, "description": "Defaults to false.", "typeRef": null }, { "name": "hasUserVerification", "type": "boolean", "optional": true, "description": "Defaults to false.", "typeRef": null }, { "name": "hasLargeBlob", "type": "boolean", "optional": true, "description": "If set to true, the authenticator will support the largeBlob extension. https://w3c.github.io/webauthn#largeBlob Defaults to false.", "typeRef": null }, { "name": "hasCredBlob", "type": "boolean", "optional": true, "description": "If set to true, the authenticator will support the credBlob extension. https://fidoalliance.org/specs/fido-v2.1-rd-20201208/fido-client-to-authenticator-protocol-v2.1-rd-20201208.html#sctn-credBlob-extension Defaults to false.", "typeRef": null }, { "name": "hasMinPinLength", "type": "boolean", "optional": true, "description": "If set to true, the authenticator will support the minPinLength extension. https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-20210615.html#sctn-minpinlength-extension Defaults to false.", "typeRef": null }, { "name": "hasPrf", "type": "boolean", "optional": true, "description": "If set to true, the authenticator will support the prf extension. https://w3c.github.io/webauthn/#prf-extension Defaults to false.", "typeRef": null }, { "name": "automaticPresenceSimulation", "type": "boolean", "optional": true, "description": "If set to true, tests of user presence will succeed immediately. Otherwise, they will not be resolved. Defaults to true.", "typeRef": null }, { "name": "isUserVerified", "type": "boolean", "optional": true, "description": "Sets whether User Verification succeeds or fails for an authenticator. Defaults to false.", "typeRef": null }, { "name": "defaultBackupEligibility", "type": "boolean", "optional": true, "description": "Credentials created by this authenticator will have the backup eligibility (BE) flag set to this value. Defaults to false. https://w3c.github.io/webauthn/#sctn-credential-backup", "typeRef": null }, { "name": "defaultBackupState", "type": "boolean", "optional": true, "description": "Credentials created by this authenticator will have the backup state (BS) flag set to this value. Defaults to false. https://w3c.github.io/webauthn/#sctn-credential-backup", "typeRef": null }]);
    inspectorBackend.registerType("WebAuthn.Credential", [{ "name": "credentialId", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "isResidentCredential", "type": "boolean", "optional": false, "description": "", "typeRef": null }, { "name": "rpId", "type": "string", "optional": true, "description": "Relying Party ID the credential is scoped to. Must be set when adding a credential.", "typeRef": null }, { "name": "privateKey", "type": "string", "optional": false, "description": "The ECDSA P-256 private key in PKCS#8 format.", "typeRef": null }, { "name": "userHandle", "type": "string", "optional": true, "description": "An opaque byte sequence with a maximum size of 64 bytes mapping the credential to a specific user.", "typeRef": null }, { "name": "signCount", "type": "number", "optional": false, "description": "Signature counter. This is incremented by one for each successful assertion. See https://w3c.github.io/webauthn/#signature-counter", "typeRef": null }, { "name": "largeBlob", "type": "string", "optional": true, "description": "The large blob associated with the credential. See https://w3c.github.io/webauthn/#sctn-large-blob-extension", "typeRef": null }, { "name": "backupEligibility", "type": "boolean", "optional": true, "description": "Assertions returned by this credential will have the backup eligibility (BE) flag set to this value. Defaults to the authenticator's defaultBackupEligibility value.", "typeRef": null }, { "name": "backupState", "type": "boolean", "optional": true, "description": "Assertions returned by this credential will have the backup state (BS) flag set to this value. Defaults to the authenticator's defaultBackupState value.", "typeRef": null }, { "name": "userName", "type": "string", "optional": true, "description": "The credential's user.name property. Equivalent to empty if not set. https://w3c.github.io/webauthn/#dom-publickeycredentialentity-name", "typeRef": null }, { "name": "userDisplayName", "type": "string", "optional": true, "description": "The credential's user.displayName property. Equivalent to empty if not set. https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-displayname", "typeRef": null }]);
    inspectorBackend.registerEnum("Debugger.ScopeType", { Global: "global", Local: "local", With: "with", Closure: "closure", Catch: "catch", Block: "block", Script: "script", Eval: "eval", Module: "module", WasmExpressionStack: "wasm-expression-stack" });
    inspectorBackend.registerEnum("Debugger.BreakLocationType", { DebuggerStatement: "debuggerStatement", Call: "call", Return: "return" });
    inspectorBackend.registerEnum("Debugger.ScriptLanguage", { JavaScript: "JavaScript", WebAssembly: "WebAssembly" });
    inspectorBackend.registerEnum("Debugger.DebugSymbolsType", { SourceMap: "SourceMap", EmbeddedDWARF: "EmbeddedDWARF", ExternalDWARF: "ExternalDWARF" });
    inspectorBackend.registerEvent("Debugger.breakpointResolved", ["breakpointId", "location"]);
    inspectorBackend.registerEnum("Debugger.PausedEventReason", { Ambiguous: "ambiguous", Assert: "assert", CSPViolation: "CSPViolation", DebugCommand: "debugCommand", DOM: "DOM", EventListener: "EventListener", Exception: "exception", Instrumentation: "instrumentation", OOM: "OOM", Other: "other", PromiseRejection: "promiseRejection", XHR: "XHR", Step: "step" });
    inspectorBackend.registerEvent("Debugger.paused", ["callFrames", "reason", "data", "hitBreakpoints", "asyncStackTrace", "asyncStackTraceId", "asyncCallStackTraceId"]);
    inspectorBackend.registerEvent("Debugger.resumed", []);
    inspectorBackend.registerEvent("Debugger.scriptFailedToParse", ["scriptId", "url", "startLine", "startColumn", "endLine", "endColumn", "executionContextId", "hash", "buildId", "executionContextAuxData", "sourceMapURL", "hasSourceURL", "isModule", "length", "stackTrace", "codeOffset", "scriptLanguage", "embedderName"]);
    inspectorBackend.registerEvent("Debugger.scriptParsed", ["scriptId", "url", "startLine", "startColumn", "endLine", "endColumn", "executionContextId", "hash", "buildId", "executionContextAuxData", "isLiveEdit", "sourceMapURL", "hasSourceURL", "isModule", "length", "stackTrace", "codeOffset", "scriptLanguage", "debugSymbols", "embedderName", "resolvedBreakpoints"]);
    inspectorBackend.registerEnum("Debugger.ContinueToLocationRequestTargetCallFrames", { Any: "any", Current: "current" });
    inspectorBackend.registerCommand("Debugger.continueToLocation", [{ "name": "location", "type": "object", "optional": false, "description": "Location to continue to.", "typeRef": "Debugger.Location" }, { "name": "targetCallFrames", "type": "string", "optional": true, "description": "", "typeRef": "Debugger.ContinueToLocationRequestTargetCallFrames" }], [], "Continues execution until specific location is reached.");
    inspectorBackend.registerCommand("Debugger.disable", [], [], "Disables debugger for given page.");
    inspectorBackend.registerCommand("Debugger.enable", [{ "name": "maxScriptsCacheSize", "type": "number", "optional": true, "description": "The maximum size in bytes of collected scripts (not referenced by other heap objects) the debugger can hold. Puts no limit if parameter is omitted.", "typeRef": null }], ["debuggerId"], "Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received.");
    inspectorBackend.registerCommand("Debugger.evaluateOnCallFrame", [{ "name": "callFrameId", "type": "string", "optional": false, "description": "Call frame identifier to evaluate on.", "typeRef": "Debugger.CallFrameId" }, { "name": "expression", "type": "string", "optional": false, "description": "Expression to evaluate.", "typeRef": null }, { "name": "objectGroup", "type": "string", "optional": true, "description": "String object group name to put result into (allows rapid releasing resulting object handles using `releaseObjectGroup`).", "typeRef": null }, { "name": "includeCommandLineAPI", "type": "boolean", "optional": true, "description": "Specifies whether command line API should be available to the evaluated expression, defaults to false.", "typeRef": null }, { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides `setPauseOnException` state.", "typeRef": null }, { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object that should be sent by value.", "typeRef": null }, { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result.", "typeRef": null }, { "name": "throwOnSideEffect", "type": "boolean", "optional": true, "description": "Whether to throw an exception if side effect cannot be ruled out during evaluation.", "typeRef": null }, { "name": "timeout", "type": "number", "optional": true, "description": "Terminate execution after timing out (number of milliseconds).", "typeRef": "Runtime.TimeDelta" }], ["result", "exceptionDetails"], "Evaluates expression on a given call frame.");
    inspectorBackend.registerCommand("Debugger.getPossibleBreakpoints", [{ "name": "start", "type": "object", "optional": false, "description": "Start of range to search possible breakpoint locations in.", "typeRef": "Debugger.Location" }, { "name": "end", "type": "object", "optional": true, "description": "End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range.", "typeRef": "Debugger.Location" }, { "name": "restrictToFunction", "type": "boolean", "optional": true, "description": "Only consider locations which are in the same (non-nested) function as start.", "typeRef": null }], ["locations"], "Returns possible locations for breakpoint. scriptId in start and end range locations should be the same.");
    inspectorBackend.registerCommand("Debugger.getScriptSource", [{ "name": "scriptId", "type": "string", "optional": false, "description": "Id of the script to get source for.", "typeRef": "Runtime.ScriptId" }], ["scriptSource", "bytecode"], "Returns source for the script with given id.");
    inspectorBackend.registerCommand("Debugger.disassembleWasmModule", [{ "name": "scriptId", "type": "string", "optional": false, "description": "Id of the script to disassemble", "typeRef": "Runtime.ScriptId" }], ["streamId", "totalNumberOfLines", "functionBodyOffsets", "chunk"], "");
    inspectorBackend.registerCommand("Debugger.nextWasmDisassemblyChunk", [{ "name": "streamId", "type": "string", "optional": false, "description": "", "typeRef": null }], ["chunk"], "Disassemble the next chunk of lines for the module corresponding to the stream. If disassembly is complete, this API will invalidate the streamId and return an empty chunk. Any subsequent calls for the now invalid stream will return errors.");
    inspectorBackend.registerCommand("Debugger.getWasmBytecode", [{ "name": "scriptId", "type": "string", "optional": false, "description": "Id of the Wasm script to get source for.", "typeRef": "Runtime.ScriptId" }], ["bytecode"], "This command is deprecated. Use getScriptSource instead.");
    inspectorBackend.registerCommand("Debugger.getStackTrace", [{ "name": "stackTraceId", "type": "object", "optional": false, "description": "", "typeRef": "Runtime.StackTraceId" }], ["stackTrace"], "Returns stack trace with given `stackTraceId`.");
    inspectorBackend.registerCommand("Debugger.pause", [], [], "Stops on the next JavaScript statement.");
    inspectorBackend.registerCommand("Debugger.pauseOnAsyncCall", [{ "name": "parentStackTraceId", "type": "object", "optional": false, "description": "Debugger will pause when async call with given stack trace is started.", "typeRef": "Runtime.StackTraceId" }], [], "");
    inspectorBackend.registerCommand("Debugger.removeBreakpoint", [{ "name": "breakpointId", "type": "string", "optional": false, "description": "", "typeRef": "Debugger.BreakpointId" }], [], "Removes JavaScript breakpoint.");
    inspectorBackend.registerEnum("Debugger.RestartFrameRequestMode", { StepInto: "StepInto" });
    inspectorBackend.registerCommand("Debugger.restartFrame", [{ "name": "callFrameId", "type": "string", "optional": false, "description": "Call frame identifier to evaluate on.", "typeRef": "Debugger.CallFrameId" }, { "name": "mode", "type": "string", "optional": true, "description": "The `mode` parameter must be present and set to 'StepInto', otherwise `restartFrame` will error out.", "typeRef": "Debugger.RestartFrameRequestMode" }], ["callFrames", "asyncStackTrace", "asyncStackTraceId"], "Restarts particular call frame from the beginning. The old, deprecated behavior of `restartFrame` is to stay paused and allow further CDP commands after a restart was scheduled. This can cause problems with restarting, so we now continue execution immediatly after it has been scheduled until we reach the beginning of the restarted frame.  To stay back-wards compatible, `restartFrame` now expects a `mode` parameter to be present. If the `mode` parameter is missing, `restartFrame` errors out.  The various return values are deprecated and `callFrames` is always empty. Use the call frames from the `Debugger#paused` events instead, that fires once V8 pauses at the beginning of the restarted function.");
    inspectorBackend.registerCommand("Debugger.resume", [{ "name": "terminateOnResume", "type": "boolean", "optional": true, "description": "Set to true to terminate execution upon resuming execution. In contrast to Runtime.terminateExecution, this will allows to execute further JavaScript (i.e. via evaluation) until execution of the paused code is actually resumed, at which point termination is triggered. If execution is currently not paused, this parameter has no effect.", "typeRef": null }], [], "Resumes JavaScript execution.");
    inspectorBackend.registerCommand("Debugger.searchInContent", [{ "name": "scriptId", "type": "string", "optional": false, "description": "Id of the script to search in.", "typeRef": "Runtime.ScriptId" }, { "name": "query", "type": "string", "optional": false, "description": "String to search for.", "typeRef": null }, { "name": "caseSensitive", "type": "boolean", "optional": true, "description": "If true, search is case sensitive.", "typeRef": null }, { "name": "isRegex", "type": "boolean", "optional": true, "description": "If true, treats string parameter as regex.", "typeRef": null }], ["result"], "Searches for given string in script content.");
    inspectorBackend.registerCommand("Debugger.setAsyncCallStackDepth", [{ "name": "maxDepth", "type": "number", "optional": false, "description": "Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async call stacks (default).", "typeRef": null }], [], "Enables or disables async call stacks tracking.");
    inspectorBackend.registerCommand("Debugger.setBlackboxExecutionContexts", [{ "name": "uniqueIds", "type": "array", "optional": false, "description": "Array of execution context unique ids for the debugger to ignore.", "typeRef": "string" }], [], "Replace previous blackbox execution contexts with passed ones. Forces backend to skip stepping/pausing in scripts in these execution contexts. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful.");
    inspectorBackend.registerCommand("Debugger.setBlackboxPatterns", [{ "name": "patterns", "type": "array", "optional": false, "description": "Array of regexps that will be used to check script url for blackbox state.", "typeRef": "string" }, { "name": "skipAnonymous", "type": "boolean", "optional": true, "description": "If true, also ignore scripts with no source url.", "typeRef": null }], [], "Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful.");
    inspectorBackend.registerCommand("Debugger.setBlackboxedRanges", [{ "name": "scriptId", "type": "string", "optional": false, "description": "Id of the script.", "typeRef": "Runtime.ScriptId" }, { "name": "positions", "type": "array", "optional": false, "description": "", "typeRef": "Debugger.ScriptPosition" }], [], "Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted.");
    inspectorBackend.registerCommand("Debugger.setBreakpoint", [{ "name": "location", "type": "object", "optional": false, "description": "Location to set breakpoint in.", "typeRef": "Debugger.Location" }, { "name": "condition", "type": "string", "optional": true, "description": "Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true.", "typeRef": null }], ["breakpointId", "actualLocation"], "Sets JavaScript breakpoint at a given location.");
    inspectorBackend.registerEnum("Debugger.SetInstrumentationBreakpointRequestInstrumentation", { BeforeScriptExecution: "beforeScriptExecution", BeforeScriptWithSourceMapExecution: "beforeScriptWithSourceMapExecution" });
    inspectorBackend.registerCommand("Debugger.setInstrumentationBreakpoint", [{ "name": "instrumentation", "type": "string", "optional": false, "description": "Instrumentation name.", "typeRef": "Debugger.SetInstrumentationBreakpointRequestInstrumentation" }], ["breakpointId"], "Sets instrumentation breakpoint.");
    inspectorBackend.registerCommand("Debugger.setBreakpointByUrl", [{ "name": "lineNumber", "type": "number", "optional": false, "description": "Line number to set breakpoint at.", "typeRef": null }, { "name": "url", "type": "string", "optional": true, "description": "URL of the resources to set breakpoint on.", "typeRef": null }, { "name": "urlRegex", "type": "string", "optional": true, "description": "Regex pattern for the URLs of the resources to set breakpoints on. Either `url` or `urlRegex` must be specified.", "typeRef": null }, { "name": "scriptHash", "type": "string", "optional": true, "description": "Script hash of the resources to set breakpoint on.", "typeRef": null }, { "name": "columnNumber", "type": "number", "optional": true, "description": "Offset in the line to set breakpoint at.", "typeRef": null }, { "name": "condition", "type": "string", "optional": true, "description": "Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true.", "typeRef": null }], ["breakpointId", "locations"], "Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in `locations` property. Further matching script parsing will result in subsequent `breakpointResolved` events issued. This logical breakpoint will survive page reloads.");
    inspectorBackend.registerCommand("Debugger.setBreakpointOnFunctionCall", [{ "name": "objectId", "type": "string", "optional": false, "description": "Function object id.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "condition", "type": "string", "optional": true, "description": "Expression to use as a breakpoint condition. When specified, debugger will stop on the breakpoint if this expression evaluates to true.", "typeRef": null }], ["breakpointId"], "Sets JavaScript breakpoint before each call to the given function. If another function was created from the same source as a given one, calling it will also trigger the breakpoint.");
    inspectorBackend.registerCommand("Debugger.setBreakpointsActive", [{ "name": "active", "type": "boolean", "optional": false, "description": "New value for breakpoints active state.", "typeRef": null }], [], "Activates / deactivates all breakpoints on the page.");
    inspectorBackend.registerEnum("Debugger.SetPauseOnExceptionsRequestState", { None: "none", Caught: "caught", Uncaught: "uncaught", All: "all" });
    inspectorBackend.registerCommand("Debugger.setPauseOnExceptions", [{ "name": "state", "type": "string", "optional": false, "description": "Pause on exceptions mode.", "typeRef": "Debugger.SetPauseOnExceptionsRequestState" }], [], "Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions, or caught exceptions, no exceptions. Initial pause on exceptions state is `none`.");
    inspectorBackend.registerCommand("Debugger.setReturnValue", [{ "name": "newValue", "type": "object", "optional": false, "description": "New return value.", "typeRef": "Runtime.CallArgument" }], [], "Changes return value in top frame. Available only at return break position.");
    inspectorBackend.registerCommand("Debugger.setScriptSource", [{ "name": "scriptId", "type": "string", "optional": false, "description": "Id of the script to edit.", "typeRef": "Runtime.ScriptId" }, { "name": "scriptSource", "type": "string", "optional": false, "description": "New content of the script.", "typeRef": null }, { "name": "dryRun", "type": "boolean", "optional": true, "description": "If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code.", "typeRef": null }, { "name": "allowTopFrameEditing", "type": "boolean", "optional": true, "description": "If true, then `scriptSource` is allowed to change the function on top of the stack as long as the top-most stack frame is the only activation of that function.", "typeRef": null }], ["callFrames", "stackChanged", "asyncStackTrace", "asyncStackTraceId", "status", "exceptionDetails"], "Edits JavaScript source live.  In general, functions that are currently on the stack can not be edited with a single exception: If the edited function is the top-most stack frame and that is the only activation of that function on the stack. In this case the live edit will be successful and a `Debugger.restartFrame` for the top-most function is automatically triggered.");
    inspectorBackend.registerCommand("Debugger.setSkipAllPauses", [{ "name": "skip", "type": "boolean", "optional": false, "description": "New value for skip pauses state.", "typeRef": null }], [], "Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc).");
    inspectorBackend.registerCommand("Debugger.setVariableValue", [{ "name": "scopeNumber", "type": "number", "optional": false, "description": "0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually.", "typeRef": null }, { "name": "variableName", "type": "string", "optional": false, "description": "Variable name.", "typeRef": null }, { "name": "newValue", "type": "object", "optional": false, "description": "New variable value.", "typeRef": "Runtime.CallArgument" }, { "name": "callFrameId", "type": "string", "optional": false, "description": "Id of callframe that holds variable.", "typeRef": "Debugger.CallFrameId" }], [], "Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually.");
    inspectorBackend.registerCommand("Debugger.stepInto", [{ "name": "breakOnAsyncCall", "type": "boolean", "optional": true, "description": "Debugger will pause on the execution of the first async task which was scheduled before next pause.", "typeRef": null }, { "name": "skipList", "type": "array", "optional": true, "description": "The skipList specifies location ranges that should be skipped on step into.", "typeRef": "Debugger.LocationRange" }], [], "Steps into the function call.");
    inspectorBackend.registerCommand("Debugger.stepOut", [], [], "Steps out of the function call.");
    inspectorBackend.registerCommand("Debugger.stepOver", [{ "name": "skipList", "type": "array", "optional": true, "description": "The skipList specifies location ranges that should be skipped on step over.", "typeRef": "Debugger.LocationRange" }], [], "Steps over the statement.");
    inspectorBackend.registerType("Debugger.Location", [{ "name": "scriptId", "type": "string", "optional": false, "description": "Script identifier as reported in the `Debugger.scriptParsed`.", "typeRef": "Runtime.ScriptId" }, { "name": "lineNumber", "type": "number", "optional": false, "description": "Line number in the script (0-based).", "typeRef": null }, { "name": "columnNumber", "type": "number", "optional": true, "description": "Column number in the script (0-based).", "typeRef": null }]);
    inspectorBackend.registerType("Debugger.ScriptPosition", [{ "name": "lineNumber", "type": "number", "optional": false, "description": "", "typeRef": null }, { "name": "columnNumber", "type": "number", "optional": false, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Debugger.LocationRange", [{ "name": "scriptId", "type": "string", "optional": false, "description": "", "typeRef": "Runtime.ScriptId" }, { "name": "start", "type": "object", "optional": false, "description": "", "typeRef": "Debugger.ScriptPosition" }, { "name": "end", "type": "object", "optional": false, "description": "", "typeRef": "Debugger.ScriptPosition" }]);
    inspectorBackend.registerType("Debugger.CallFrame", [{ "name": "callFrameId", "type": "string", "optional": false, "description": "Call frame identifier. This identifier is only valid while the virtual machine is paused.", "typeRef": "Debugger.CallFrameId" }, { "name": "functionName", "type": "string", "optional": false, "description": "Name of the JavaScript function called on this call frame.", "typeRef": null }, { "name": "functionLocation", "type": "object", "optional": true, "description": "Location in the source code.", "typeRef": "Debugger.Location" }, { "name": "location", "type": "object", "optional": false, "description": "Location in the source code.", "typeRef": "Debugger.Location" }, { "name": "url", "type": "string", "optional": false, "description": "JavaScript script name or url. Deprecated in favor of using the `location.scriptId` to resolve the URL via a previously sent `Debugger.scriptParsed` event.", "typeRef": null }, { "name": "scopeChain", "type": "array", "optional": false, "description": "Scope chain for this call frame.", "typeRef": "Debugger.Scope" }, { "name": "this", "type": "object", "optional": false, "description": "`this` object for this call frame.", "typeRef": "Runtime.RemoteObject" }, { "name": "returnValue", "type": "object", "optional": true, "description": "The value being returned, if the function is at return point.", "typeRef": "Runtime.RemoteObject" }, { "name": "canBeRestarted", "type": "boolean", "optional": true, "description": "Valid only while the VM is paused and indicates whether this frame can be restarted or not. Note that a `true` value here does not guarantee that Debugger#restartFrame with this CallFrameId will be successful, but it is very likely.", "typeRef": null }]);
    inspectorBackend.registerType("Debugger.Scope", [{ "name": "type", "type": "string", "optional": false, "description": "Scope type.", "typeRef": null }, { "name": "object", "type": "object", "optional": false, "description": "Object representing the scope. For `global` and `with` scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties.", "typeRef": "Runtime.RemoteObject" }, { "name": "name", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "startLocation", "type": "object", "optional": true, "description": "Location in the source code where scope starts", "typeRef": "Debugger.Location" }, { "name": "endLocation", "type": "object", "optional": true, "description": "Location in the source code where scope ends", "typeRef": "Debugger.Location" }]);
    inspectorBackend.registerType("Debugger.SearchMatch", [{ "name": "lineNumber", "type": "number", "optional": false, "description": "Line number in resource content.", "typeRef": null }, { "name": "lineContent", "type": "string", "optional": false, "description": "Line with match content.", "typeRef": null }]);
    inspectorBackend.registerType("Debugger.BreakLocation", [{ "name": "scriptId", "type": "string", "optional": false, "description": "Script identifier as reported in the `Debugger.scriptParsed`.", "typeRef": "Runtime.ScriptId" }, { "name": "lineNumber", "type": "number", "optional": false, "description": "Line number in the script (0-based).", "typeRef": null }, { "name": "columnNumber", "type": "number", "optional": true, "description": "Column number in the script (0-based).", "typeRef": null }, { "name": "type", "type": "string", "optional": true, "description": "", "typeRef": null }]);
    inspectorBackend.registerType("Debugger.WasmDisassemblyChunk", [{ "name": "lines", "type": "array", "optional": false, "description": "The next chunk of disassembled lines.", "typeRef": "string" }, { "name": "bytecodeOffsets", "type": "array", "optional": false, "description": "The bytecode offsets describing the start of each line.", "typeRef": "integer" }]);
    inspectorBackend.registerType("Debugger.DebugSymbols", [{ "name": "type", "type": "string", "optional": false, "description": "Type of the debug symbols.", "typeRef": null }, { "name": "externalURL", "type": "string", "optional": true, "description": "URL of the external symbol source.", "typeRef": null }]);
    inspectorBackend.registerType("Debugger.ResolvedBreakpoint", [{ "name": "breakpointId", "type": "string", "optional": false, "description": "Breakpoint unique identifier.", "typeRef": "Debugger.BreakpointId" }, { "name": "location", "type": "object", "optional": false, "description": "Actual breakpoint location.", "typeRef": "Debugger.Location" }]);
    inspectorBackend.registerEvent("HeapProfiler.addHeapSnapshotChunk", ["chunk"]);
    inspectorBackend.registerEvent("HeapProfiler.heapStatsUpdate", ["statsUpdate"]);
    inspectorBackend.registerEvent("HeapProfiler.lastSeenObjectId", ["lastSeenObjectId", "timestamp"]);
    inspectorBackend.registerEvent("HeapProfiler.reportHeapSnapshotProgress", ["done", "total", "finished"]);
    inspectorBackend.registerEvent("HeapProfiler.resetProfiles", []);
    inspectorBackend.registerCommand("HeapProfiler.addInspectedHeapObject", [{ "name": "heapObjectId", "type": "string", "optional": false, "description": "Heap snapshot object id to be accessible by means of $x command line API.", "typeRef": "HeapProfiler.HeapSnapshotObjectId" }], [], "Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions).");
    inspectorBackend.registerCommand("HeapProfiler.collectGarbage", [], [], "");
    inspectorBackend.registerCommand("HeapProfiler.disable", [], [], "");
    inspectorBackend.registerCommand("HeapProfiler.enable", [], [], "");
    inspectorBackend.registerCommand("HeapProfiler.getHeapObjectId", [{ "name": "objectId", "type": "string", "optional": false, "description": "Identifier of the object to get heap object id for.", "typeRef": "Runtime.RemoteObjectId" }], ["heapSnapshotObjectId"], "");
    inspectorBackend.registerCommand("HeapProfiler.getObjectByHeapObjectId", [{ "name": "objectId", "type": "string", "optional": false, "description": "", "typeRef": "HeapProfiler.HeapSnapshotObjectId" }, { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects.", "typeRef": null }], ["result"], "");
    inspectorBackend.registerCommand("HeapProfiler.getSamplingProfile", [], ["profile"], "");
    inspectorBackend.registerCommand("HeapProfiler.startSampling", [{ "name": "samplingInterval", "type": "number", "optional": true, "description": "Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes.", "typeRef": null }, { "name": "stackDepth", "type": "number", "optional": true, "description": "Maximum stack depth. The default value is 128.", "typeRef": null }, { "name": "includeObjectsCollectedByMajorGC", "type": "boolean", "optional": true, "description": "By default, the sampling heap profiler reports only objects which are still alive when the profile is returned via getSamplingProfile or stopSampling, which is useful for determining what functions contribute the most to steady-state memory usage. This flag instructs the sampling heap profiler to also include information about objects discarded by major GC, which will show which functions cause large temporary memory usage or long GC pauses.", "typeRef": null }, { "name": "includeObjectsCollectedByMinorGC", "type": "boolean", "optional": true, "description": "By default, the sampling heap profiler reports only objects which are still alive when the profile is returned via getSamplingProfile or stopSampling, which is useful for determining what functions contribute the most to steady-state memory usage. This flag instructs the sampling heap profiler to also include information about objects discarded by minor GC, which is useful when tuning a latency-sensitive application for minimal GC activity.", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("HeapProfiler.startTrackingHeapObjects", [{ "name": "trackAllocations", "type": "boolean", "optional": true, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("HeapProfiler.stopSampling", [], ["profile"], "");
    inspectorBackend.registerCommand("HeapProfiler.stopTrackingHeapObjects", [{ "name": "reportProgress", "type": "boolean", "optional": true, "description": "If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped.", "typeRef": null }, { "name": "treatGlobalObjectsAsRoots", "type": "boolean", "optional": true, "description": "Deprecated in favor of `exposeInternals`.", "typeRef": null }, { "name": "captureNumericValue", "type": "boolean", "optional": true, "description": "If true, numerical values are included in the snapshot", "typeRef": null }, { "name": "exposeInternals", "type": "boolean", "optional": true, "description": "If true, exposes internals of the snapshot.", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("HeapProfiler.takeHeapSnapshot", [{ "name": "reportProgress", "type": "boolean", "optional": true, "description": "If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken.", "typeRef": null }, { "name": "treatGlobalObjectsAsRoots", "type": "boolean", "optional": true, "description": "If true, a raw snapshot without artificial roots will be generated. Deprecated in favor of `exposeInternals`.", "typeRef": null }, { "name": "captureNumericValue", "type": "boolean", "optional": true, "description": "If true, numerical values are included in the snapshot", "typeRef": null }, { "name": "exposeInternals", "type": "boolean", "optional": true, "description": "If true, exposes internals of the snapshot.", "typeRef": null }], [], "");
    inspectorBackend.registerType("HeapProfiler.SamplingHeapProfileNode", [{ "name": "callFrame", "type": "object", "optional": false, "description": "Function location.", "typeRef": "Runtime.CallFrame" }, { "name": "selfSize", "type": "number", "optional": false, "description": "Allocations size in bytes for the node excluding children.", "typeRef": null }, { "name": "id", "type": "number", "optional": false, "description": "Node id. Ids are unique across all profiles collected between startSampling and stopSampling.", "typeRef": null }, { "name": "children", "type": "array", "optional": false, "description": "Child nodes.", "typeRef": "HeapProfiler.SamplingHeapProfileNode" }]);
    inspectorBackend.registerType("HeapProfiler.SamplingHeapProfileSample", [{ "name": "size", "type": "number", "optional": false, "description": "Allocation size in bytes attributed to the sample.", "typeRef": null }, { "name": "nodeId", "type": "number", "optional": false, "description": "Id of the corresponding profile tree node.", "typeRef": null }, { "name": "ordinal", "type": "number", "optional": false, "description": "Time-ordered sample ordinal number. It is unique across all profiles retrieved between startSampling and stopSampling.", "typeRef": null }]);
    inspectorBackend.registerType("HeapProfiler.SamplingHeapProfile", [{ "name": "head", "type": "object", "optional": false, "description": "", "typeRef": "HeapProfiler.SamplingHeapProfileNode" }, { "name": "samples", "type": "array", "optional": false, "description": "", "typeRef": "HeapProfiler.SamplingHeapProfileSample" }]);
    inspectorBackend.registerEvent("Profiler.consoleProfileFinished", ["id", "location", "profile", "title"]);
    inspectorBackend.registerEvent("Profiler.consoleProfileStarted", ["id", "location", "title"]);
    inspectorBackend.registerEvent("Profiler.preciseCoverageDeltaUpdate", ["timestamp", "occasion", "result"]);
    inspectorBackend.registerCommand("Profiler.disable", [], [], "");
    inspectorBackend.registerCommand("Profiler.enable", [], [], "");
    inspectorBackend.registerCommand("Profiler.getBestEffortCoverage", [], ["result"], "Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection.");
    inspectorBackend.registerCommand("Profiler.setSamplingInterval", [{ "name": "interval", "type": "number", "optional": false, "description": "New sampling interval in microseconds.", "typeRef": null }], [], "Changes CPU profiler sampling interval. Must be called before CPU profiles recording started.");
    inspectorBackend.registerCommand("Profiler.start", [], [], "");
    inspectorBackend.registerCommand("Profiler.startPreciseCoverage", [{ "name": "callCount", "type": "boolean", "optional": true, "description": "Collect accurate call counts beyond simple 'covered' or 'not covered'.", "typeRef": null }, { "name": "detailed", "type": "boolean", "optional": true, "description": "Collect block-based coverage.", "typeRef": null }, { "name": "allowTriggeredUpdates", "type": "boolean", "optional": true, "description": "Allow the backend to send updates on its own initiative", "typeRef": null }], ["timestamp"], "Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters.");
    inspectorBackend.registerCommand("Profiler.stop", [], ["profile"], "");
    inspectorBackend.registerCommand("Profiler.stopPreciseCoverage", [], [], "Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code.");
    inspectorBackend.registerCommand("Profiler.takePreciseCoverage", [], ["result", "timestamp"], "Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started.");
    inspectorBackend.registerType("Profiler.ProfileNode", [{ "name": "id", "type": "number", "optional": false, "description": "Unique id of the node.", "typeRef": null }, { "name": "callFrame", "type": "object", "optional": false, "description": "Function location.", "typeRef": "Runtime.CallFrame" }, { "name": "hitCount", "type": "number", "optional": true, "description": "Number of samples where this node was on top of the call stack.", "typeRef": null }, { "name": "children", "type": "array", "optional": true, "description": "Child node ids.", "typeRef": "integer" }, { "name": "deoptReason", "type": "string", "optional": true, "description": "The reason of being not optimized. The function may be deoptimized or marked as don't optimize.", "typeRef": null }, { "name": "positionTicks", "type": "array", "optional": true, "description": "An array of source position ticks.", "typeRef": "Profiler.PositionTickInfo" }]);
    inspectorBackend.registerType("Profiler.Profile", [{ "name": "nodes", "type": "array", "optional": false, "description": "The list of profile nodes. First item is the root node.", "typeRef": "Profiler.ProfileNode" }, { "name": "startTime", "type": "number", "optional": false, "description": "Profiling start timestamp in microseconds.", "typeRef": null }, { "name": "endTime", "type": "number", "optional": false, "description": "Profiling end timestamp in microseconds.", "typeRef": null }, { "name": "samples", "type": "array", "optional": true, "description": "Ids of samples top nodes.", "typeRef": "integer" }, { "name": "timeDeltas", "type": "array", "optional": true, "description": "Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime.", "typeRef": "integer" }]);
    inspectorBackend.registerType("Profiler.PositionTickInfo", [{ "name": "line", "type": "number", "optional": false, "description": "Source line number (1-based).", "typeRef": null }, { "name": "ticks", "type": "number", "optional": false, "description": "Number of samples attributed to the source line.", "typeRef": null }]);
    inspectorBackend.registerType("Profiler.CoverageRange", [{ "name": "startOffset", "type": "number", "optional": false, "description": "JavaScript script source offset for the range start.", "typeRef": null }, { "name": "endOffset", "type": "number", "optional": false, "description": "JavaScript script source offset for the range end.", "typeRef": null }, { "name": "count", "type": "number", "optional": false, "description": "Collected execution count of the source range.", "typeRef": null }]);
    inspectorBackend.registerType("Profiler.FunctionCoverage", [{ "name": "functionName", "type": "string", "optional": false, "description": "JavaScript function name.", "typeRef": null }, { "name": "ranges", "type": "array", "optional": false, "description": "Source ranges inside the function with coverage data.", "typeRef": "Profiler.CoverageRange" }, { "name": "isBlockCoverage", "type": "boolean", "optional": false, "description": "Whether coverage data for this function has block granularity.", "typeRef": null }]);
    inspectorBackend.registerType("Profiler.ScriptCoverage", [{ "name": "scriptId", "type": "string", "optional": false, "description": "JavaScript script id.", "typeRef": "Runtime.ScriptId" }, { "name": "url", "type": "string", "optional": false, "description": "JavaScript script name or url.", "typeRef": null }, { "name": "functions", "type": "array", "optional": false, "description": "Functions contained in the script that has coverage data.", "typeRef": "Profiler.FunctionCoverage" }]);
    inspectorBackend.registerEnum("Runtime.SerializationOptionsSerialization", { Deep: "deep", Json: "json", IdOnly: "idOnly" });
    inspectorBackend.registerEnum("Runtime.DeepSerializedValueType", { Undefined: "undefined", Null: "null", String: "string", Number: "number", Boolean: "boolean", Bigint: "bigint", Regexp: "regexp", Date: "date", Symbol: "symbol", Array: "array", Object: "object", Function: "function", Map: "map", Set: "set", Weakmap: "weakmap", Weakset: "weakset", Error: "error", Proxy: "proxy", Promise: "promise", Typedarray: "typedarray", Arraybuffer: "arraybuffer", Node: "node", Window: "window", Generator: "generator" });
    inspectorBackend.registerEnum("Runtime.RemoteObjectType", { Object: "object", Function: "function", Undefined: "undefined", String: "string", Number: "number", Boolean: "boolean", Symbol: "symbol", Bigint: "bigint" });
    inspectorBackend.registerEnum("Runtime.RemoteObjectSubtype", { Array: "array", Null: "null", Node: "node", Regexp: "regexp", Date: "date", Map: "map", Set: "set", Weakmap: "weakmap", Weakset: "weakset", Iterator: "iterator", Generator: "generator", Error: "error", Proxy: "proxy", Promise: "promise", Typedarray: "typedarray", Arraybuffer: "arraybuffer", Dataview: "dataview", Webassemblymemory: "webassemblymemory", Wasmvalue: "wasmvalue", Trustedtype: "trustedtype" });
    inspectorBackend.registerEnum("Runtime.ObjectPreviewType", { Object: "object", Function: "function", Undefined: "undefined", String: "string", Number: "number", Boolean: "boolean", Symbol: "symbol", Bigint: "bigint" });
    inspectorBackend.registerEnum("Runtime.ObjectPreviewSubtype", { Array: "array", Null: "null", Node: "node", Regexp: "regexp", Date: "date", Map: "map", Set: "set", Weakmap: "weakmap", Weakset: "weakset", Iterator: "iterator", Generator: "generator", Error: "error", Proxy: "proxy", Promise: "promise", Typedarray: "typedarray", Arraybuffer: "arraybuffer", Dataview: "dataview", Webassemblymemory: "webassemblymemory", Wasmvalue: "wasmvalue", Trustedtype: "trustedtype" });
    inspectorBackend.registerEnum("Runtime.PropertyPreviewType", { Object: "object", Function: "function", Undefined: "undefined", String: "string", Number: "number", Boolean: "boolean", Symbol: "symbol", Accessor: "accessor", Bigint: "bigint" });
    inspectorBackend.registerEnum("Runtime.PropertyPreviewSubtype", { Array: "array", Null: "null", Node: "node", Regexp: "regexp", Date: "date", Map: "map", Set: "set", Weakmap: "weakmap", Weakset: "weakset", Iterator: "iterator", Generator: "generator", Error: "error", Proxy: "proxy", Promise: "promise", Typedarray: "typedarray", Arraybuffer: "arraybuffer", Dataview: "dataview", Webassemblymemory: "webassemblymemory", Wasmvalue: "wasmvalue", Trustedtype: "trustedtype" });
    inspectorBackend.registerEvent("Runtime.bindingCalled", ["name", "payload", "executionContextId"]);
    inspectorBackend.registerEnum("Runtime.ConsoleAPICalledEventType", { Log: "log", Debug: "debug", Info: "info", Error: "error", Warning: "warning", Dir: "dir", DirXML: "dirxml", Table: "table", Trace: "trace", Clear: "clear", StartGroup: "startGroup", StartGroupCollapsed: "startGroupCollapsed", EndGroup: "endGroup", Assert: "assert", Profile: "profile", ProfileEnd: "profileEnd", Count: "count", TimeEnd: "timeEnd" });
    inspectorBackend.registerEvent("Runtime.consoleAPICalled", ["type", "args", "executionContextId", "timestamp", "stackTrace", "context"]);
    inspectorBackend.registerEvent("Runtime.exceptionRevoked", ["reason", "exceptionId"]);
    inspectorBackend.registerEvent("Runtime.exceptionThrown", ["timestamp", "exceptionDetails"]);
    inspectorBackend.registerEvent("Runtime.executionContextCreated", ["context"]);
    inspectorBackend.registerEvent("Runtime.executionContextDestroyed", ["executionContextId", "executionContextUniqueId"]);
    inspectorBackend.registerEvent("Runtime.executionContextsCleared", []);
    inspectorBackend.registerEvent("Runtime.inspectRequested", ["object", "hints", "executionContextId"]);
    inspectorBackend.registerCommand("Runtime.awaitPromise", [{ "name": "promiseObjectId", "type": "string", "optional": false, "description": "Identifier of the promise.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object that should be sent by value.", "typeRef": null }, { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result.", "typeRef": null }], ["result", "exceptionDetails"], "Add handler to promise with given promise object id.");
    inspectorBackend.registerCommand("Runtime.callFunctionOn", [{ "name": "functionDeclaration", "type": "string", "optional": false, "description": "Declaration of the function to call.", "typeRef": null }, { "name": "objectId", "type": "string", "optional": true, "description": "Identifier of the object to call function on. Either objectId or executionContextId should be specified.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "arguments", "type": "array", "optional": true, "description": "Call arguments. All call arguments must belong to the same JavaScript world as the target object.", "typeRef": "Runtime.CallArgument" }, { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides `setPauseOnException` state.", "typeRef": null }, { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object which should be sent by value. Can be overriden by `serializationOptions`.", "typeRef": null }, { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result.", "typeRef": null }, { "name": "userGesture", "type": "boolean", "optional": true, "description": "Whether execution should be treated as initiated by user in the UI.", "typeRef": null }, { "name": "awaitPromise", "type": "boolean", "optional": true, "description": "Whether execution should `await` for resulting value and return once awaited promise is resolved.", "typeRef": null }, { "name": "executionContextId", "type": "number", "optional": true, "description": "Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified.", "typeRef": "Runtime.ExecutionContextId" }, { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object.", "typeRef": null }, { "name": "throwOnSideEffect", "type": "boolean", "optional": true, "description": "Whether to throw an exception if side effect cannot be ruled out during evaluation.", "typeRef": null }, { "name": "uniqueContextId", "type": "string", "optional": true, "description": "An alternative way to specify the execution context to call function on. Compared to contextId that may be reused across processes, this is guaranteed to be system-unique, so it can be used to prevent accidental function call in context different than intended (e.g. as a result of navigation across process boundaries). This is mutually exclusive with `executionContextId`.", "typeRef": null }, { "name": "serializationOptions", "type": "object", "optional": true, "description": "Specifies the result serialization. If provided, overrides `generatePreview` and `returnByValue`.", "typeRef": "Runtime.SerializationOptions" }], ["result", "exceptionDetails"], "Calls function with given declaration on the given object. Object group of the result is inherited from the target object.");
    inspectorBackend.registerCommand("Runtime.compileScript", [{ "name": "expression", "type": "string", "optional": false, "description": "Expression to compile.", "typeRef": null }, { "name": "sourceURL", "type": "string", "optional": false, "description": "Source url to be set for the script.", "typeRef": null }, { "name": "persistScript", "type": "boolean", "optional": false, "description": "Specifies whether the compiled script should be persisted.", "typeRef": null }, { "name": "executionContextId", "type": "number", "optional": true, "description": "Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page.", "typeRef": "Runtime.ExecutionContextId" }], ["scriptId", "exceptionDetails"], "Compiles expression.");
    inspectorBackend.registerCommand("Runtime.disable", [], [], "Disables reporting of execution contexts creation.");
    inspectorBackend.registerCommand("Runtime.discardConsoleEntries", [], [], "Discards collected exceptions and console API calls.");
    inspectorBackend.registerCommand("Runtime.enable", [], [], "Enables reporting of execution contexts creation by means of `executionContextCreated` event. When the reporting gets enabled the event will be sent immediately for each existing execution context.");
    inspectorBackend.registerCommand("Runtime.evaluate", [{ "name": "expression", "type": "string", "optional": false, "description": "Expression to evaluate.", "typeRef": null }, { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects.", "typeRef": null }, { "name": "includeCommandLineAPI", "type": "boolean", "optional": true, "description": "Determines whether Command Line API should be available during the evaluation.", "typeRef": null }, { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides `setPauseOnException` state.", "typeRef": null }, { "name": "contextId", "type": "number", "optional": true, "description": "Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. This is mutually exclusive with `uniqueContextId`, which offers an alternative way to identify the execution context that is more reliable in a multi-process environment.", "typeRef": "Runtime.ExecutionContextId" }, { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object that should be sent by value.", "typeRef": null }, { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result.", "typeRef": null }, { "name": "userGesture", "type": "boolean", "optional": true, "description": "Whether execution should be treated as initiated by user in the UI.", "typeRef": null }, { "name": "awaitPromise", "type": "boolean", "optional": true, "description": "Whether execution should `await` for resulting value and return once awaited promise is resolved.", "typeRef": null }, { "name": "throwOnSideEffect", "type": "boolean", "optional": true, "description": "Whether to throw an exception if side effect cannot be ruled out during evaluation. This implies `disableBreaks` below.", "typeRef": null }, { "name": "timeout", "type": "number", "optional": true, "description": "Terminate execution after timing out (number of milliseconds).", "typeRef": "Runtime.TimeDelta" }, { "name": "disableBreaks", "type": "boolean", "optional": true, "description": "Disable breakpoints during execution.", "typeRef": null }, { "name": "replMode", "type": "boolean", "optional": true, "description": "Setting this flag to true enables `let` re-declaration and top-level `await`. Note that `let` variables can only be re-declared if they originate from `replMode` themselves.", "typeRef": null }, { "name": "allowUnsafeEvalBlockedByCSP", "type": "boolean", "optional": true, "description": "The Content Security Policy (CSP) for the target might block 'unsafe-eval' which includes eval(), Function(), setTimeout() and setInterval() when called with non-callable arguments. This flag bypasses CSP for this evaluation and allows unsafe-eval. Defaults to true.", "typeRef": null }, { "name": "uniqueContextId", "type": "string", "optional": true, "description": "An alternative way to specify the execution context to evaluate in. Compared to contextId that may be reused across processes, this is guaranteed to be system-unique, so it can be used to prevent accidental evaluation of the expression in context different than intended (e.g. as a result of navigation across process boundaries). This is mutually exclusive with `contextId`.", "typeRef": null }, { "name": "serializationOptions", "type": "object", "optional": true, "description": "Specifies the result serialization. If provided, overrides `generatePreview` and `returnByValue`.", "typeRef": "Runtime.SerializationOptions" }], ["result", "exceptionDetails"], "Evaluates expression on global object.");
    inspectorBackend.registerCommand("Runtime.getIsolateId", [], ["id"], "Returns the isolate id.");
    inspectorBackend.registerCommand("Runtime.getHeapUsage", [], ["usedSize", "totalSize", "embedderHeapUsedSize", "backingStorageSize"], "Returns the JavaScript heap usage. It is the total usage of the corresponding isolate not scoped to a particular Runtime.");
    inspectorBackend.registerCommand("Runtime.getProperties", [{ "name": "objectId", "type": "string", "optional": false, "description": "Identifier of the object to return properties for.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "ownProperties", "type": "boolean", "optional": true, "description": "If true, returns properties belonging only to the element itself, not to its prototype chain.", "typeRef": null }, { "name": "accessorPropertiesOnly", "type": "boolean", "optional": true, "description": "If true, returns accessor properties (with getter/setter) only; internal properties are not returned either.", "typeRef": null }, { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the results.", "typeRef": null }, { "name": "nonIndexedPropertiesOnly", "type": "boolean", "optional": true, "description": "If true, returns non-indexed properties only.", "typeRef": null }], ["result", "internalProperties", "privateProperties", "exceptionDetails"], "Returns properties of a given object. Object group of the result is inherited from the target object.");
    inspectorBackend.registerCommand("Runtime.globalLexicalScopeNames", [{ "name": "executionContextId", "type": "number", "optional": true, "description": "Specifies in which execution context to lookup global scope variables.", "typeRef": "Runtime.ExecutionContextId" }], ["names"], "Returns all let, const and class variables from global scope.");
    inspectorBackend.registerCommand("Runtime.queryObjects", [{ "name": "prototypeObjectId", "type": "string", "optional": false, "description": "Identifier of the prototype to return objects for.", "typeRef": "Runtime.RemoteObjectId" }, { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release the results.", "typeRef": null }], ["objects"], "");
    inspectorBackend.registerCommand("Runtime.releaseObject", [{ "name": "objectId", "type": "string", "optional": false, "description": "Identifier of the object to release.", "typeRef": "Runtime.RemoteObjectId" }], [], "Releases remote object with given id.");
    inspectorBackend.registerCommand("Runtime.releaseObjectGroup", [{ "name": "objectGroup", "type": "string", "optional": false, "description": "Symbolic object group name.", "typeRef": null }], [], "Releases all remote objects that belong to a given group.");
    inspectorBackend.registerCommand("Runtime.runIfWaitingForDebugger", [], [], "Tells inspected instance to run if it was waiting for debugger to attach.");
    inspectorBackend.registerCommand("Runtime.runScript", [{ "name": "scriptId", "type": "string", "optional": false, "description": "Id of the script to run.", "typeRef": "Runtime.ScriptId" }, { "name": "executionContextId", "type": "number", "optional": true, "description": "Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page.", "typeRef": "Runtime.ExecutionContextId" }, { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects.", "typeRef": null }, { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides `setPauseOnException` state.", "typeRef": null }, { "name": "includeCommandLineAPI", "type": "boolean", "optional": true, "description": "Determines whether Command Line API should be available during the evaluation.", "typeRef": null }, { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object which should be sent by value.", "typeRef": null }, { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result.", "typeRef": null }, { "name": "awaitPromise", "type": "boolean", "optional": true, "description": "Whether execution should `await` for resulting value and return once awaited promise is resolved.", "typeRef": null }], ["result", "exceptionDetails"], "Runs script with given id in a given context.");
    inspectorBackend.registerCommand("Runtime.setAsyncCallStackDepth", [{ "name": "maxDepth", "type": "number", "optional": false, "description": "Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async call stacks (default).", "typeRef": null }], [], "Enables or disables async call stacks tracking.");
    inspectorBackend.registerCommand("Runtime.setCustomObjectFormatterEnabled", [{ "name": "enabled", "type": "boolean", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("Runtime.setMaxCallStackSizeToCapture", [{ "name": "size", "type": "number", "optional": false, "description": "", "typeRef": null }], [], "");
    inspectorBackend.registerCommand("Runtime.terminateExecution", [], [], "Terminate current or next JavaScript execution. Will cancel the termination when the outer-most script execution ends.");
    inspectorBackend.registerCommand("Runtime.addBinding", [{ "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "executionContextId", "type": "number", "optional": true, "description": "If specified, the binding would only be exposed to the specified execution context. If omitted and `executionContextName` is not set, the binding is exposed to all execution contexts of the target. This parameter is mutually exclusive with `executionContextName`. Deprecated in favor of `executionContextName` due to an unclear use case and bugs in implementation (crbug.com/1169639). `executionContextId` will be removed in the future.", "typeRef": "Runtime.ExecutionContextId" }, { "name": "executionContextName", "type": "string", "optional": true, "description": "If specified, the binding is exposed to the executionContext with matching name, even for contexts created after the binding is added. See also `ExecutionContext.name` and `worldName` parameter to `Page.addScriptToEvaluateOnNewDocument`. This parameter is mutually exclusive with `executionContextId`.", "typeRef": null }], [], "If executionContextId is empty, adds binding with the given name on the global objects of all inspected contexts, including those created later, bindings survive reloads. Binding function takes exactly one argument, this argument should be string, in case of any other input, function throws an exception. Each binding function call produces Runtime.bindingCalled notification.");
    inspectorBackend.registerCommand("Runtime.removeBinding", [{ "name": "name", "type": "string", "optional": false, "description": "", "typeRef": null }], [], "This method does not remove binding function from global object but unsubscribes current runtime agent from Runtime.bindingCalled notifications.");
    inspectorBackend.registerCommand("Runtime.getExceptionDetails", [{ "name": "errorObjectId", "type": "string", "optional": false, "description": "The error object for which to resolve the exception details.", "typeRef": "Runtime.RemoteObjectId" }], ["exceptionDetails"], "This method tries to lookup and populate exception details for a JavaScript Error object. Note that the stackTrace portion of the resulting exceptionDetails will only be populated if the Runtime domain was enabled at the time when the Error was thrown.");
    inspectorBackend.registerType("Runtime.SerializationOptions", [{ "name": "serialization", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "maxDepth", "type": "number", "optional": true, "description": "Deep serialization depth. Default is full depth. Respected only in `deep` serialization mode.", "typeRef": null }, { "name": "additionalParameters", "type": "object", "optional": true, "description": "Embedder-specific parameters. For example if connected to V8 in Chrome these control DOM serialization via `maxNodeDepth: integer` and `includeShadowTree: \\\"none\\\" | \\\"open\\\" | \\\"all\\\"`. Values can be only of type string or integer.", "typeRef": null }]);
    inspectorBackend.registerType("Runtime.DeepSerializedValue", [{ "name": "type", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "value", "type": "any", "optional": true, "description": "", "typeRef": null }, { "name": "objectId", "type": "string", "optional": true, "description": "", "typeRef": null }, { "name": "weakLocalObjectReference", "type": "number", "optional": true, "description": "Set if value reference met more then once during serialization. In such case, value is provided only to one of the serialized values. Unique per value in the scope of one CDP call.", "typeRef": null }]);
    inspectorBackend.registerType("Runtime.RemoteObject", [{ "name": "type", "type": "string", "optional": false, "description": "Object type.", "typeRef": null }, { "name": "subtype", "type": "string", "optional": true, "description": "Object subtype hint. Specified for `object` type values only. NOTE: If you change anything here, make sure to also update `subtype` in `ObjectPreview` and `PropertyPreview` below.", "typeRef": null }, { "name": "className", "type": "string", "optional": true, "description": "Object class (constructor) name. Specified for `object` type values only.", "typeRef": null }, { "name": "value", "type": "any", "optional": true, "description": "Remote object value in case of primitive values or JSON values (if it was requested).", "typeRef": null }, { "name": "unserializableValue", "type": "string", "optional": true, "description": "Primitive value which can not be JSON-stringified does not have `value`, but gets this property.", "typeRef": "Runtime.UnserializableValue" }, { "name": "description", "type": "string", "optional": true, "description": "String representation of the object.", "typeRef": null }, { "name": "deepSerializedValue", "type": "object", "optional": true, "description": "Deep serialized value.", "typeRef": "Runtime.DeepSerializedValue" }, { "name": "objectId", "type": "string", "optional": true, "description": "Unique object identifier (for non-primitive values).", "typeRef": "Runtime.RemoteObjectId" }, { "name": "preview", "type": "object", "optional": true, "description": "Preview containing abbreviated property values. Specified for `object` type values only.", "typeRef": "Runtime.ObjectPreview" }, { "name": "customPreview", "type": "object", "optional": true, "description": "", "typeRef": "Runtime.CustomPreview" }]);
    inspectorBackend.registerType("Runtime.CustomPreview", [{ "name": "header", "type": "string", "optional": false, "description": "The JSON-stringified result of formatter.header(object, config) call. It contains json ML array that represents RemoteObject.", "typeRef": null }, { "name": "bodyGetterId", "type": "string", "optional": true, "description": "If formatter returns true as a result of formatter.hasBody call then bodyGetterId will contain RemoteObjectId for the function that returns result of formatter.body(object, config) call. The result value is json ML array.", "typeRef": "Runtime.RemoteObjectId" }]);
    inspectorBackend.registerType("Runtime.ObjectPreview", [{ "name": "type", "type": "string", "optional": false, "description": "Object type.", "typeRef": null }, { "name": "subtype", "type": "string", "optional": true, "description": "Object subtype hint. Specified for `object` type values only.", "typeRef": null }, { "name": "description", "type": "string", "optional": true, "description": "String representation of the object.", "typeRef": null }, { "name": "overflow", "type": "boolean", "optional": false, "description": "True iff some of the properties or entries of the original object did not fit.", "typeRef": null }, { "name": "properties", "type": "array", "optional": false, "description": "List of the properties.", "typeRef": "Runtime.PropertyPreview" }, { "name": "entries", "type": "array", "optional": true, "description": "List of the entries. Specified for `map` and `set` subtype values only.", "typeRef": "Runtime.EntryPreview" }]);
    inspectorBackend.registerType("Runtime.PropertyPreview", [{ "name": "name", "type": "string", "optional": false, "description": "Property name.", "typeRef": null }, { "name": "type", "type": "string", "optional": false, "description": "Object type. Accessor means that the property itself is an accessor property.", "typeRef": null }, { "name": "value", "type": "string", "optional": true, "description": "User-friendly property value string.", "typeRef": null }, { "name": "valuePreview", "type": "object", "optional": true, "description": "Nested value preview.", "typeRef": "Runtime.ObjectPreview" }, { "name": "subtype", "type": "string", "optional": true, "description": "Object subtype hint. Specified for `object` type values only.", "typeRef": null }]);
    inspectorBackend.registerType("Runtime.EntryPreview", [{ "name": "key", "type": "object", "optional": true, "description": "Preview of the key. Specified for map-like collection entries.", "typeRef": "Runtime.ObjectPreview" }, { "name": "value", "type": "object", "optional": false, "description": "Preview of the value.", "typeRef": "Runtime.ObjectPreview" }]);
    inspectorBackend.registerType("Runtime.PropertyDescriptor", [{ "name": "name", "type": "string", "optional": false, "description": "Property name or symbol description.", "typeRef": null }, { "name": "value", "type": "object", "optional": true, "description": "The value associated with the property.", "typeRef": "Runtime.RemoteObject" }, { "name": "writable", "type": "boolean", "optional": true, "description": "True if the value associated with the property may be changed (data descriptors only).", "typeRef": null }, { "name": "get", "type": "object", "optional": true, "description": "A function which serves as a getter for the property, or `undefined` if there is no getter (accessor descriptors only).", "typeRef": "Runtime.RemoteObject" }, { "name": "set", "type": "object", "optional": true, "description": "A function which serves as a setter for the property, or `undefined` if there is no setter (accessor descriptors only).", "typeRef": "Runtime.RemoteObject" }, { "name": "configurable", "type": "boolean", "optional": false, "description": "True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.", "typeRef": null }, { "name": "enumerable", "type": "boolean", "optional": false, "description": "True if this property shows up during enumeration of the properties on the corresponding object.", "typeRef": null }, { "name": "wasThrown", "type": "boolean", "optional": true, "description": "True if the result was thrown during the evaluation.", "typeRef": null }, { "name": "isOwn", "type": "boolean", "optional": true, "description": "True if the property is owned for the object.", "typeRef": null }, { "name": "symbol", "type": "object", "optional": true, "description": "Property symbol object, if the property is of the `symbol` type.", "typeRef": "Runtime.RemoteObject" }]);
    inspectorBackend.registerType("Runtime.InternalPropertyDescriptor", [{ "name": "name", "type": "string", "optional": false, "description": "Conventional property name.", "typeRef": null }, { "name": "value", "type": "object", "optional": true, "description": "The value associated with the property.", "typeRef": "Runtime.RemoteObject" }]);
    inspectorBackend.registerType("Runtime.PrivatePropertyDescriptor", [{ "name": "name", "type": "string", "optional": false, "description": "Private property name.", "typeRef": null }, { "name": "value", "type": "object", "optional": true, "description": "The value associated with the private property.", "typeRef": "Runtime.RemoteObject" }, { "name": "get", "type": "object", "optional": true, "description": "A function which serves as a getter for the private property, or `undefined` if there is no getter (accessor descriptors only).", "typeRef": "Runtime.RemoteObject" }, { "name": "set", "type": "object", "optional": true, "description": "A function which serves as a setter for the private property, or `undefined` if there is no setter (accessor descriptors only).", "typeRef": "Runtime.RemoteObject" }]);
    inspectorBackend.registerType("Runtime.CallArgument", [{ "name": "value", "type": "any", "optional": true, "description": "Primitive value or serializable javascript object.", "typeRef": null }, { "name": "unserializableValue", "type": "string", "optional": true, "description": "Primitive value which can not be JSON-stringified.", "typeRef": "Runtime.UnserializableValue" }, { "name": "objectId", "type": "string", "optional": true, "description": "Remote object handle.", "typeRef": "Runtime.RemoteObjectId" }]);
    inspectorBackend.registerType("Runtime.ExecutionContextDescription", [{ "name": "id", "type": "number", "optional": false, "description": "Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed.", "typeRef": "Runtime.ExecutionContextId" }, { "name": "origin", "type": "string", "optional": false, "description": "Execution context origin.", "typeRef": null }, { "name": "name", "type": "string", "optional": false, "description": "Human readable name describing given context.", "typeRef": null }, { "name": "uniqueId", "type": "string", "optional": false, "description": "A system-unique execution context identifier. Unlike the id, this is unique across multiple processes, so can be reliably used to identify specific context while backend performs a cross-process navigation.", "typeRef": null }, { "name": "auxData", "type": "object", "optional": true, "description": "Embedder-specific auxiliary data likely matching {isDefault: boolean, type: 'default'|'isolated'|'worker', frameId: string}", "typeRef": null }]);
    inspectorBackend.registerType("Runtime.ExceptionDetails", [{ "name": "exceptionId", "type": "number", "optional": false, "description": "Exception id.", "typeRef": null }, { "name": "text", "type": "string", "optional": false, "description": "Exception text, which should be used together with exception object when available.", "typeRef": null }, { "name": "lineNumber", "type": "number", "optional": false, "description": "Line number of the exception location (0-based).", "typeRef": null }, { "name": "columnNumber", "type": "number", "optional": false, "description": "Column number of the exception location (0-based).", "typeRef": null }, { "name": "scriptId", "type": "string", "optional": true, "description": "Script ID of the exception location.", "typeRef": "Runtime.ScriptId" }, { "name": "url", "type": "string", "optional": true, "description": "URL of the exception location, to be used when the script was not reported.", "typeRef": null }, { "name": "stackTrace", "type": "object", "optional": true, "description": "JavaScript stack trace if available.", "typeRef": "Runtime.StackTrace" }, { "name": "exception", "type": "object", "optional": true, "description": "Exception object if available.", "typeRef": "Runtime.RemoteObject" }, { "name": "executionContextId", "type": "number", "optional": true, "description": "Identifier of the context where exception happened.", "typeRef": "Runtime.ExecutionContextId" }, { "name": "exceptionMetaData", "type": "object", "optional": true, "description": "Dictionary with entries of meta data that the client associated with this exception, such as information about associated network requests, etc.", "typeRef": null }]);
    inspectorBackend.registerType("Runtime.CallFrame", [{ "name": "functionName", "type": "string", "optional": false, "description": "JavaScript function name.", "typeRef": null }, { "name": "scriptId", "type": "string", "optional": false, "description": "JavaScript script id.", "typeRef": "Runtime.ScriptId" }, { "name": "url", "type": "string", "optional": false, "description": "JavaScript script name or url.", "typeRef": null }, { "name": "lineNumber", "type": "number", "optional": false, "description": "JavaScript script line number (0-based).", "typeRef": null }, { "name": "columnNumber", "type": "number", "optional": false, "description": "JavaScript script column number (0-based).", "typeRef": null }]);
    inspectorBackend.registerType("Runtime.StackTrace", [{ "name": "description", "type": "string", "optional": true, "description": "String label of this stack trace. For async traces this may be a name of the function that initiated the async call.", "typeRef": null }, { "name": "callFrames", "type": "array", "optional": false, "description": "JavaScript function name.", "typeRef": "Runtime.CallFrame" }, { "name": "parent", "type": "object", "optional": true, "description": "Asynchronous JavaScript stack trace that preceded this stack, if available.", "typeRef": "Runtime.StackTrace" }, { "name": "parentId", "type": "object", "optional": true, "description": "Asynchronous JavaScript stack trace that preceded this stack, if available.", "typeRef": "Runtime.StackTraceId" }]);
    inspectorBackend.registerType("Runtime.StackTraceId", [{ "name": "id", "type": "string", "optional": false, "description": "", "typeRef": null }, { "name": "debuggerId", "type": "string", "optional": true, "description": "", "typeRef": "Runtime.UniqueDebuggerId" }]);
    inspectorBackend.registerCommand("Schema.getDomains", [], ["domains"], "Returns supported domains.");
    inspectorBackend.registerType("Schema.Domain", [{ "name": "name", "type": "string", "optional": false, "description": "Domain name.", "typeRef": null }, { "name": "version", "type": "string", "optional": false, "description": "Domain version.", "typeRef": null }]);
}

// Copyright 2011 The Chromium Authors
const splitQualifiedName = (string) => {
    const [domain, eventName] = string.split('.');
    return [domain, eventName];
};
const qualifyName = (domain, name) => {
    return `${domain}.${name}`;
};
class InspectorBackend {
    agentPrototypes = new Map();
    #eventParameterNamesForDomain = new Map();
    typeMap = new Map();
    enumMap = new Map();
    constructor() {
        globalThis.Protocol ||= {};
        registerCommands(this);
    }
    getOrCreateEventParameterNamesForDomain(domain) {
        let map = this.#eventParameterNamesForDomain.get(domain);
        if (!map) {
            map = new Map();
            this.#eventParameterNamesForDomain.set(domain, map);
        }
        return map;
    }
    getOrCreateEventParameterNamesForDomainForTesting(domain) {
        return this.getOrCreateEventParameterNamesForDomain(domain);
    }
    getEventParameterNames() {
        return this.#eventParameterNamesForDomain;
    }
    static reportProtocolError(error, messageObject) {
        console.error(error + ': ' + JSON.stringify(messageObject));
    }
    static reportProtocolWarning(error, messageObject) {
        console.warn(error + ': ' + JSON.stringify(messageObject));
    }
    agentPrototype(domain) {
        let prototype = this.agentPrototypes.get(domain);
        if (!prototype) {
            prototype = new AgentPrototype(domain);
            this.agentPrototypes.set(domain, prototype);
        }
        return prototype;
    }
    registerCommand(method, parameters, replyArgs, description) {
        const [domain, command] = splitQualifiedName(method);
        this.agentPrototype(domain).registerCommand(command, parameters, replyArgs, description);
    }
    registerEnum(type, values) {
        const [domain, name] = splitQualifiedName(type);
        if (!globalThis.Protocol[domain]) {
            globalThis.Protocol[domain] = {};
        }
        globalThis.Protocol[domain][name] = values;
        this.enumMap.set(type, values);
    }
    registerType(method, parameters) {
        this.typeMap.set(method, parameters);
    }
    registerEvent(eventName, params) {
        const domain = eventName.split('.')[0];
        const eventParameterNames = this.getOrCreateEventParameterNamesForDomain(domain);
        eventParameterNames.set(eventName, params);
    }
}
const test = {
    dumpProtocol: null,
    deprecatedRunAfterPendingDispatches: null,
    sendRawMessage: null,
    suppressRequestErrors: false,
    onMessageSent: null,
    onMessageReceived: null,
};
class SessionRouter {
    #connection;
    #sessions = new Map();
    constructor(connection) {
        this.#connection = connection;
        this.#connection.observe(this);
    }
    registerSession(target, sessionId) {
        this.#sessions.set(sessionId, { target });
    }
    unregisterSession(sessionId) {
        const session = this.#sessions.get(sessionId);
        if (!session) {
            return;
        }
        if (this.#connection instanceof DevToolsCDPConnection) {
            this.#connection.resolvePendingCalls(sessionId);
        }
        this.#sessions.delete(sessionId);
    }
    onDisconnect(reason) {
        const session = this.#sessions.get('');
        if (session) {
            session.target.dispose(reason);
        }
    }
    onEvent(event) {
        const sessionId = event.sessionId || '';
        const session = this.#sessions.get(sessionId);
        session?.target.dispatch(event);
    }
    get connection() {
        return this.#connection;
    }
}
class TargetBase {
    sessionId;
    #router;
    #agents = new Map();
    #dispatchers = new Map();
    constructor(parentTarget, sessionId, connection) {
        this.sessionId = sessionId;
        if (parentTarget && !sessionId) {
            throw new Error('Specifying a parent target requires a session ID');
        }
        let router;
        if (parentTarget && parentTarget.#router) {
            router = parentTarget.#router;
        }
        else if (connection) {
            router = new SessionRouter(connection);
        }
        else {
            router = new SessionRouter(new DevToolsCDPConnection(ConnectionTransport.getFactory()()));
        }
        this.#router = router;
        router.registerSession(this, this.sessionId);
        for (const [domain, agentPrototype] of inspectorBackend.agentPrototypes) {
            const agent = Object.create((agentPrototype));
            agent.target = this;
            this.#agents.set(domain, agent);
        }
        for (const [domain, eventParameterNames] of inspectorBackend.getEventParameterNames().entries()) {
            this.#dispatchers.set(domain, new DispatcherManager(eventParameterNames));
        }
    }
    dispatch(eventMessage) {
        const [domainName, method] = splitQualifiedName(eventMessage.method);
        const dispatcher = this.#dispatchers.get(domainName);
        if (!dispatcher) {
            InspectorBackend.reportProtocolError(`Protocol Error: the message ${eventMessage.method} is for non-existing domain '${domainName}'`, eventMessage);
            return;
        }
        dispatcher.dispatch(method, eventMessage);
    }
    dispose(_reason) {
        if (!this.#router) {
            return;
        }
        this.#router.unregisterSession(this.sessionId);
        this.#router = null;
    }
    isDisposed() {
        return !this.#router;
    }
    router() {
        return this.#router;
    }
    getAgent(domain) {
        const agent = this.#agents.get(domain);
        if (!agent) {
            throw new Error('Accessing undefined agent');
        }
        return agent;
    }
    accessibilityAgent() {
        return this.getAgent('Accessibility');
    }
    animationAgent() {
        return this.getAgent('Animation');
    }
    auditsAgent() {
        return this.getAgent('Audits');
    }
    autofillAgent() {
        return this.getAgent('Autofill');
    }
    browserAgent() {
        return this.getAgent('Browser');
    }
    backgroundServiceAgent() {
        return this.getAgent('BackgroundService');
    }
    cacheStorageAgent() {
        return this.getAgent('CacheStorage');
    }
    cssAgent() {
        return this.getAgent('CSS');
    }
    debuggerAgent() {
        return this.getAgent('Debugger');
    }
    deviceOrientationAgent() {
        return this.getAgent('DeviceOrientation');
    }
    domAgent() {
        return this.getAgent('DOM');
    }
    domdebuggerAgent() {
        return this.getAgent('DOMDebugger');
    }
    domsnapshotAgent() {
        return this.getAgent('DOMSnapshot');
    }
    domstorageAgent() {
        return this.getAgent('DOMStorage');
    }
    emulationAgent() {
        return this.getAgent('Emulation');
    }
    eventBreakpointsAgent() {
        return this.getAgent('EventBreakpoints');
    }
    extensionsAgent() {
        return this.getAgent('Extensions');
    }
    fetchAgent() {
        return this.getAgent('Fetch');
    }
    heapProfilerAgent() {
        return this.getAgent('HeapProfiler');
    }
    indexedDBAgent() {
        return this.getAgent('IndexedDB');
    }
    inputAgent() {
        return this.getAgent('Input');
    }
    ioAgent() {
        return this.getAgent('IO');
    }
    inspectorAgent() {
        return this.getAgent('Inspector');
    }
    layerTreeAgent() {
        return this.getAgent('LayerTree');
    }
    logAgent() {
        return this.getAgent('Log');
    }
    mediaAgent() {
        return this.getAgent('Media');
    }
    memoryAgent() {
        return this.getAgent('Memory');
    }
    networkAgent() {
        return this.getAgent('Network');
    }
    overlayAgent() {
        return this.getAgent('Overlay');
    }
    pageAgent() {
        return this.getAgent('Page');
    }
    preloadAgent() {
        return this.getAgent('Preload');
    }
    profilerAgent() {
        return this.getAgent('Profiler');
    }
    performanceAgent() {
        return this.getAgent('Performance');
    }
    runtimeAgent() {
        return this.getAgent('Runtime');
    }
    securityAgent() {
        return this.getAgent('Security');
    }
    serviceWorkerAgent() {
        return this.getAgent('ServiceWorker');
    }
    storageAgent() {
        return this.getAgent('Storage');
    }
    systemInfo() {
        return this.getAgent('SystemInfo');
    }
    targetAgent() {
        return this.getAgent('Target');
    }
    tracingAgent() {
        return this.getAgent('Tracing');
    }
    webAudioAgent() {
        return this.getAgent('WebAudio');
    }
    webAuthnAgent() {
        return this.getAgent('WebAuthn');
    }
    registerDispatcher(domain, dispatcher) {
        const manager = this.#dispatchers.get(domain);
        if (!manager) {
            return;
        }
        manager.addDomainDispatcher(dispatcher);
    }
    unregisterDispatcher(domain, dispatcher) {
        const manager = this.#dispatchers.get(domain);
        if (!manager) {
            return;
        }
        manager.removeDomainDispatcher(dispatcher);
    }
    registerAccessibilityDispatcher(dispatcher) {
        this.registerDispatcher('Accessibility', dispatcher);
    }
    registerAutofillDispatcher(dispatcher) {
        this.registerDispatcher('Autofill', dispatcher);
    }
    registerAnimationDispatcher(dispatcher) {
        this.registerDispatcher('Animation', dispatcher);
    }
    registerAuditsDispatcher(dispatcher) {
        this.registerDispatcher('Audits', dispatcher);
    }
    registerCSSDispatcher(dispatcher) {
        this.registerDispatcher('CSS', dispatcher);
    }
    registerBackgroundServiceDispatcher(dispatcher) {
        this.registerDispatcher('BackgroundService', dispatcher);
    }
    registerDebuggerDispatcher(dispatcher) {
        this.registerDispatcher('Debugger', dispatcher);
    }
    unregisterDebuggerDispatcher(dispatcher) {
        this.unregisterDispatcher('Debugger', dispatcher);
    }
    registerDOMDispatcher(dispatcher) {
        this.registerDispatcher('DOM', dispatcher);
    }
    registerDOMStorageDispatcher(dispatcher) {
        this.registerDispatcher('DOMStorage', dispatcher);
    }
    registerEmulationDispatcher(dispatcher) {
        this.registerDispatcher('Emulation', dispatcher);
    }
    registerFetchDispatcher(dispatcher) {
        this.registerDispatcher('Fetch', dispatcher);
    }
    registerHeapProfilerDispatcher(dispatcher) {
        this.registerDispatcher('HeapProfiler', dispatcher);
    }
    registerInspectorDispatcher(dispatcher) {
        this.registerDispatcher('Inspector', dispatcher);
    }
    registerLayerTreeDispatcher(dispatcher) {
        this.registerDispatcher('LayerTree', dispatcher);
    }
    registerLogDispatcher(dispatcher) {
        this.registerDispatcher('Log', dispatcher);
    }
    registerMediaDispatcher(dispatcher) {
        this.registerDispatcher('Media', dispatcher);
    }
    registerNetworkDispatcher(dispatcher) {
        this.registerDispatcher('Network', dispatcher);
    }
    registerOverlayDispatcher(dispatcher) {
        this.registerDispatcher('Overlay', dispatcher);
    }
    registerPageDispatcher(dispatcher) {
        this.registerDispatcher('Page', dispatcher);
    }
    registerPreloadDispatcher(dispatcher) {
        this.registerDispatcher('Preload', dispatcher);
    }
    registerProfilerDispatcher(dispatcher) {
        this.registerDispatcher('Profiler', dispatcher);
    }
    registerRuntimeDispatcher(dispatcher) {
        this.registerDispatcher('Runtime', dispatcher);
    }
    registerSecurityDispatcher(dispatcher) {
        this.registerDispatcher('Security', dispatcher);
    }
    registerServiceWorkerDispatcher(dispatcher) {
        this.registerDispatcher('ServiceWorker', dispatcher);
    }
    registerStorageDispatcher(dispatcher) {
        this.registerDispatcher('Storage', dispatcher);
    }
    registerTargetDispatcher(dispatcher) {
        this.registerDispatcher('Target', dispatcher);
    }
    registerTracingDispatcher(dispatcher) {
        this.registerDispatcher('Tracing', dispatcher);
    }
    registerWebAudioDispatcher(dispatcher) {
        this.registerDispatcher('WebAudio', dispatcher);
    }
    registerWebAuthnDispatcher(dispatcher) {
        this.registerDispatcher('WebAuthn', dispatcher);
    }
}
const IGNORED_ERRORS = new Set([
    CDPErrorStatus.DEVTOOLS_REHYDRATION_ERROR,
    CDPErrorStatus.DEVTOOLS_STUB_ERROR,
    CDPErrorStatus.SERVER_ERROR,
    CDPErrorStatus.SESSION_NOT_FOUND,
]);
class AgentPrototype {
    description = '';
    metadata;
    domain;
    target;
    constructor(domain) {
        this.domain = domain;
        this.metadata = {};
    }
    registerCommand(methodName, parameters, replyArgs, description) {
        const domainAndMethod = qualifyName(this.domain, methodName);
        this.metadata[domainAndMethod] = { parameters, description, replyArgs };
        function invoke(request = {}) {
            return this.invoke(domainAndMethod, request);
        }
        this['invoke_' + methodName] = invoke;
    }
    invoke(method, request) {
        const connection = this.target.router()?.connection;
        if (!connection) {
            return Promise.resolve({ result: null, getError: () => `Connection is closed, can\'t dispatch pending call to ${method}` });
        }
        return connection.send(method, request, this.target.sessionId)
            .then(response => {
            if ('error' in response && response.error) {
                if (!test.suppressRequestErrors && !IGNORED_ERRORS.has(response.error.code)) {
                    console.error('Request ' + method + ' failed. ' + JSON.stringify(response.error));
                }
                return { getError: () => response.error.message };
            }
            if ('result' in response) {
                return { ...response.result, getError: () => undefined };
            }
            return {
                getError: () => `Command ${method} returned neither result nor an error, params: ${JSON.stringify(request, undefined, 2)}`,
            };
        });
    }
}
class DispatcherManager {
    #eventArgs;
    #dispatchers = [];
    constructor(eventArgs) {
        this.#eventArgs = eventArgs;
    }
    addDomainDispatcher(dispatcher) {
        this.#dispatchers.push(dispatcher);
    }
    removeDomainDispatcher(dispatcher) {
        const index = this.#dispatchers.indexOf(dispatcher);
        if (index === -1) {
            return;
        }
        this.#dispatchers.splice(index, 1);
    }
    dispatch(event, messageObject) {
        if (!this.#dispatchers.length) {
            return;
        }
        if (!this.#eventArgs.has(messageObject.method)) {
            InspectorBackend.reportProtocolWarning(`Protocol Warning: Attempted to dispatch an unspecified event '${messageObject.method}'`, messageObject);
            return;
        }
        for (let index = 0; index < this.#dispatchers.length; ++index) {
            const dispatcher = this.#dispatchers[index];
            if (event in dispatcher) {
                const f = dispatcher[event];
                f.call(dispatcher, messageObject.params);
            }
        }
    }
}
const inspectorBackend = new InspectorBackend();

var InspectorBackend$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	InspectorBackend: InspectorBackend,
	SessionRouter: SessionRouter,
	TargetBase: TargetBase,
	inspectorBackend: inspectorBackend,
	qualifyName: qualifyName,
	splitQualifiedName: splitQualifiedName,
	test: test
});

// Copyright 2025 The Chromium Authors
const LongPollingMethods = new Set(['CSS.takeComputedStyleUpdates']);
class DevToolsCDPConnection {
    #transport;
    #lastMessageId = 1;
    #pendingResponsesCount = 0;
    #pendingLongPollingMessageIds = new Set();
    #pendingScripts = [];
    #callbacks = new Map();
    #observers = new Set();
    constructor(transport) {
        this.#transport = transport;
        test.deprecatedRunAfterPendingDispatches = this.deprecatedRunAfterPendingDispatches.bind(this);
        test.sendRawMessage = this.sendRawMessageForTesting.bind(this);
        this.#transport.setOnMessage(this.onMessage.bind(this));
        this.#transport.setOnDisconnect(reason => {
            this.#observers.forEach(observer => observer.onDisconnect(reason));
        });
    }
    observe(observer) {
        this.#observers.add(observer);
    }
    unobserve(observer) {
        this.#observers.delete(observer);
    }
    send(method, params, sessionId) {
        const messageId = ++this.#lastMessageId;
        const messageObject = {
            id: messageId,
            method,
        };
        if (params) {
            messageObject.params = params;
        }
        if (sessionId) {
            messageObject.sessionId = sessionId;
        }
        if (test.dumpProtocol) {
            test.dumpProtocol('frontend: ' + JSON.stringify(messageObject));
        }
        if (test.onMessageSent) {
            const domain = method.split('.')[0];
            const paramsObject = JSON.parse(JSON.stringify(params || {}));
            test.onMessageSent({ domain, method, params: paramsObject, id: messageId, sessionId });
        }
        ++this.#pendingResponsesCount;
        if (LongPollingMethods.has(method)) {
            this.#pendingLongPollingMessageIds.add(messageId);
        }
        return new Promise(resolve => {
            this.#callbacks.set(messageId, { resolve, method, sessionId });
            this.#transport.sendRawMessage(JSON.stringify(messageObject));
        });
    }
    resolvePendingCalls(sessionId) {
        for (const { resolve, method, sessionId: callbackSessionId } of this.#callbacks.values()) {
            if (sessionId !== callbackSessionId) {
                continue;
            }
            resolve({
                error: {
                    message: `Session is unregistering, can\'t dispatch pending call to ${method}`,
                    code: CDPErrorStatus.SESSION_NOT_FOUND,
                }
            });
        }
    }
    sendRawMessageForTesting(method, params, callback, sessionId = '') {
        void this.send(method, params, sessionId).then(response => {
            if ('error' in response && response.error) {
                callback?.(response.error, null);
            }
            else if ('result' in response) {
                callback?.(null, response.result);
            }
        });
    }
    onMessage(message) {
        if (test.dumpProtocol) {
            test.dumpProtocol('backend: ' + ((typeof message === 'string') ? message : JSON.stringify(message)));
        }
        if (test.onMessageReceived) {
            const messageObjectCopy = JSON.parse((typeof message === 'string') ? message : JSON.stringify(message));
            test.onMessageReceived(messageObjectCopy);
        }
        const messageObject = ((typeof message === 'string') ? JSON.parse(message) : message);
        if ('id' in messageObject && messageObject.id !== undefined) {
            const callback = this.#callbacks.get(messageObject.id);
            this.#callbacks.delete(messageObject.id);
            if (!callback) {
                return;
            }
            callback.resolve(messageObject);
            --this.#pendingResponsesCount;
            this.#pendingLongPollingMessageIds.delete(messageObject.id);
            if (this.#pendingScripts.length && !this.hasOutstandingNonLongPollingRequests()) {
                this.deprecatedRunAfterPendingDispatches();
            }
        }
        else if ('method' in messageObject) {
            this.#observers.forEach(observer => observer.onEvent(messageObject));
        }
        else {
            InspectorBackend.reportProtocolError('Protocol Error: the message without method', messageObject);
        }
    }
    hasOutstandingNonLongPollingRequests() {
        return this.#pendingResponsesCount - this.#pendingLongPollingMessageIds.size > 0;
    }
    deprecatedRunAfterPendingDispatches(script) {
        if (script) {
            this.#pendingScripts.push(script);
        }
        setTimeout(() => {
            if (!this.hasOutstandingNonLongPollingRequests()) {
                this.executeAfterPendingDispatches();
            }
            else {
                this.deprecatedRunAfterPendingDispatches();
            }
        }, 0);
    }
    executeAfterPendingDispatches() {
        if (!this.hasOutstandingNonLongPollingRequests()) {
            const scripts = this.#pendingScripts;
            this.#pendingScripts = [];
            for (let id = 0; id < scripts.length; ++id) {
                scripts[id]();
            }
        }
    }
}

var DevToolsCDPConnection$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	DevToolsCDPConnection: DevToolsCDPConnection
});

// Copyright 2019 The Chromium Authors

var protocol_client = /*#__PURE__*/Object.freeze({
	__proto__: null,
	CDPConnection: CDPConnection,
	ConnectionTransport: ConnectionTransport$1,
	DevToolsCDPConnection: DevToolsCDPConnection$1,
	InspectorBackend: InspectorBackend$1
});

// Copyright 2009 The Chromium Authors
let RemoteObject$1 = class RemoteObject {
    static fromLocalObject(value) {
        return new LocalJSONObject(value);
    }
    static type(remoteObject) {
        if (remoteObject === null) {
            return 'null';
        }
        const type = typeof remoteObject;
        if (type !== 'object' && type !== 'function') {
            return type;
        }
        return remoteObject.type;
    }
    static isNullOrUndefined(remoteObject) {
        if (remoteObject === undefined) {
            return true;
        }
        switch (remoteObject.type) {
            case "object" :
                return remoteObject.subtype === "null" ;
            case "undefined" :
                return true;
            default:
                return false;
        }
    }
    static arrayNameFromDescription(description) {
        return description.replace(descriptionLengthParenRegex, '').replace(descriptionLengthSquareRegex, '');
    }
    static arrayLength(object) {
        if (object.subtype !== 'array' && object.subtype !== 'typedarray') {
            return 0;
        }
        const parenMatches = object.description?.match(descriptionLengthParenRegex);
        const squareMatches = object.description?.match(descriptionLengthSquareRegex);
        return parenMatches ? parseInt(parenMatches[1], 10) : (squareMatches ? parseInt(squareMatches[1], 10) : 0);
    }
    static arrayBufferByteLength(object) {
        if (object.subtype !== 'arraybuffer') {
            return 0;
        }
        const matches = object.description?.match(descriptionLengthParenRegex);
        return matches ? parseInt(matches[1], 10) : 0;
    }
    static isEmptyArray(object) {
        const matches = object.description?.match(descriptionLengthParenRegex);
        return Boolean(matches?.[1] === '0');
    }
    static unserializableDescription(object) {
        if (typeof object === 'number') {
            const description = String(object);
            if (object === 0 && 1 / object < 0) {
                return "-0" ;
            }
            if (description === "NaN"  || description === "Infinity"  ||
                description === "-Infinity" ) {
                return description;
            }
        }
        if (typeof object === 'bigint') {
            return object + 'n';
        }
        return null;
    }
    static toCallArgument(object) {
        const type = typeof object;
        if (type === 'undefined') {
            return {};
        }
        const unserializableDescription = RemoteObject.unserializableDescription(object);
        if (type === 'number') {
            if (unserializableDescription !== null) {
                return { unserializableValue: unserializableDescription };
            }
            return { value: object };
        }
        if (type === 'bigint') {
            return { unserializableValue: unserializableDescription ?? undefined };
        }
        if (type === 'string' || type === 'boolean') {
            return { value: object };
        }
        if (!object) {
            return { value: null };
        }
        const objectAsProtocolRemoteObject = object;
        if (object instanceof RemoteObject) {
            const unserializableValue = object.unserializableValue();
            if (unserializableValue !== undefined) {
                return { unserializableValue };
            }
        }
        else if (objectAsProtocolRemoteObject.unserializableValue !== undefined) {
            return { unserializableValue: objectAsProtocolRemoteObject.unserializableValue };
        }
        if (typeof objectAsProtocolRemoteObject.objectId !== 'undefined') {
            return { objectId: objectAsProtocolRemoteObject.objectId };
        }
        return { value: objectAsProtocolRemoteObject.value };
    }
    static async loadFromObjectPerProto(object, generatePreview, nonIndexedPropertiesOnly = false) {
        const result = await Promise.all([
            object.getAllProperties(true , generatePreview, nonIndexedPropertiesOnly),
            object.getOwnProperties(generatePreview, nonIndexedPropertiesOnly),
        ]);
        const accessorProperties = result[0].properties;
        const ownProperties = result[1].properties;
        const internalProperties = result[1].internalProperties;
        if (!ownProperties || !accessorProperties) {
            return { properties: null, internalProperties: null };
        }
        const propertiesMap = new Map();
        const propertySymbols = [];
        for (let i = 0; i < accessorProperties.length; i++) {
            const property = accessorProperties[i];
            if (property.symbol) {
                propertySymbols.push(property);
            }
            else if (property.isOwn || property.name !== '__proto__') {
                propertiesMap.set(property.name, property);
            }
        }
        for (let i = 0; i < ownProperties.length; i++) {
            const property = ownProperties[i];
            if (property.isAccessorProperty()) {
                continue;
            }
            if (property.private || property.symbol) {
                propertySymbols.push(property);
            }
            else {
                propertiesMap.set(property.name, property);
            }
        }
        return {
            properties: [...propertiesMap.values()].concat(propertySymbols),
            internalProperties: internalProperties ? internalProperties : null,
        };
    }
    customPreview() {
        return null;
    }
    unserializableValue() {
        throw new Error('Not implemented');
    }
    get preview() {
        return undefined;
    }
    get className() {
        return null;
    }
    callFunction(_functionDeclaration, _args) {
        throw new Error('Not implemented');
    }
    callFunctionJSON(_functionDeclaration, _args) {
        throw new Error('Not implemented');
    }
    arrayBufferByteLength() {
        throw new Error('Not implemented');
    }
    deleteProperty(_name) {
        throw new Error('Not implemented');
    }
    setPropertyValue(_name, _value) {
        throw new Error('Not implemented');
    }
    release() {
    }
    debuggerModel() {
        throw new Error('DebuggerModel-less object');
    }
    runtimeModel() {
        throw new Error('RuntimeModel-less object');
    }
    isNode() {
        return false;
    }
    isLinearMemoryInspectable() {
        return false;
    }
    webIdl;
};
class RemoteObjectImpl extends RemoteObject$1 {
    #runtimeModel;
    #runtimeAgent;
    #type;
    #subtype;
    #objectId;
    #description;
    #hasChildren;
    #preview;
    #unserializableValue;
    #value;
    #customPreview;
    #className;
    constructor(runtimeModel, objectId, type, subtype, value, unserializableValue, description, preview, customPreview, className) {
        super();
        this.#runtimeModel = runtimeModel;
        this.#runtimeAgent = runtimeModel.target().runtimeAgent();
        this.#type = type;
        this.#subtype = subtype;
        if (objectId) {
            this.#objectId = objectId;
            this.#description = description;
            this.#hasChildren = (type !== 'symbol');
            this.#preview = preview;
        }
        else {
            this.#description = description;
            if (!this.description && unserializableValue) {
                this.#description = unserializableValue;
            }
            if (!this.#description && (typeof value !== 'object' || value === null)) {
                this.#description = String(value);
            }
            this.#hasChildren = false;
            if (typeof unserializableValue === 'string') {
                this.#unserializableValue = unserializableValue;
                if (unserializableValue === "Infinity"  ||
                    unserializableValue === "-Infinity"  ||
                    unserializableValue === "-0"  ||
                    unserializableValue === "NaN" ) {
                    this.#value = Number(unserializableValue);
                }
                else if (type === 'bigint' && unserializableValue.endsWith('n')) {
                    this.#value = BigInt(unserializableValue.substring(0, unserializableValue.length - 1));
                }
                else {
                    this.#value = unserializableValue;
                }
            }
            else {
                this.#value = value;
            }
        }
        this.#customPreview = customPreview || null;
        this.#className = typeof className === 'string' ? className : null;
    }
    customPreview() {
        return this.#customPreview;
    }
    get objectId() {
        return this.#objectId;
    }
    get type() {
        return this.#type;
    }
    get subtype() {
        return this.#subtype;
    }
    get value() {
        return this.#value;
    }
    unserializableValue() {
        return this.#unserializableValue;
    }
    get description() {
        return this.#description;
    }
    set description(description) {
        this.#description = description;
    }
    get hasChildren() {
        return this.#hasChildren;
    }
    get preview() {
        return this.#preview;
    }
    get className() {
        return this.#className;
    }
    getOwnProperties(generatePreview, nonIndexedPropertiesOnly = false) {
        return this.doGetProperties(true, false, nonIndexedPropertiesOnly, generatePreview);
    }
    getAllProperties(accessorPropertiesOnly, generatePreview, nonIndexedPropertiesOnly = false) {
        return this.doGetProperties(false, accessorPropertiesOnly, nonIndexedPropertiesOnly, generatePreview);
    }
    async createRemoteObject(object) {
        return this.#runtimeModel.createRemoteObject(object);
    }
    async doGetProperties(ownProperties, accessorPropertiesOnly, nonIndexedPropertiesOnly, generatePreview) {
        if (!this.#objectId) {
            return { properties: null, internalProperties: null };
        }
        const response = await this.#runtimeAgent.invoke_getProperties({
            objectId: this.#objectId,
            ownProperties,
            accessorPropertiesOnly,
            nonIndexedPropertiesOnly,
            generatePreview,
        });
        if (response.getError()) {
            return { properties: null, internalProperties: null };
        }
        if (response.exceptionDetails) {
            this.#runtimeModel.exceptionThrown(Date.now(), response.exceptionDetails);
            return { properties: null, internalProperties: null };
        }
        const { result: properties = [], internalProperties = [], privateProperties = [] } = response;
        const result = [];
        for (const property of properties) {
            const propertyValue = property.value ? await this.createRemoteObject(property.value) : null;
            const propertySymbol = property.symbol ? this.#runtimeModel.createRemoteObject(property.symbol) : null;
            const remoteProperty = new RemoteObjectProperty(property.name, propertyValue, Boolean(property.enumerable), Boolean(property.writable), Boolean(property.isOwn), Boolean(property.wasThrown), propertySymbol);
            if (typeof property.value === 'undefined') {
                if (property.get && property.get.type !== 'undefined') {
                    remoteProperty.getter = this.#runtimeModel.createRemoteObject(property.get);
                }
                if (property.set && property.set.type !== 'undefined') {
                    remoteProperty.setter = this.#runtimeModel.createRemoteObject(property.set);
                }
            }
            result.push(remoteProperty);
        }
        for (const property of privateProperties) {
            const propertyValue = property.value ? this.#runtimeModel.createRemoteObject(property.value) : null;
            const remoteProperty = new RemoteObjectProperty(property.name, propertyValue, true, true, true, false, undefined, false, undefined, true);
            if (typeof property.value === 'undefined') {
                if (property.get && property.get.type !== 'undefined') {
                    remoteProperty.getter = this.#runtimeModel.createRemoteObject(property.get);
                }
                if (property.set && property.set.type !== 'undefined') {
                    remoteProperty.setter = this.#runtimeModel.createRemoteObject(property.set);
                }
            }
            result.push(remoteProperty);
        }
        const internalPropertiesResult = [];
        for (const property of internalProperties) {
            if (!property.value) {
                continue;
            }
            const propertyValue = this.#runtimeModel.createRemoteObject(property.value);
            internalPropertiesResult.push(new RemoteObjectProperty(property.name, propertyValue, true, false, undefined, undefined, undefined, true));
        }
        return { properties: result, internalProperties: internalPropertiesResult };
    }
    async setPropertyValue(name, value) {
        if (!this.#objectId) {
            return 'Can’t set a property of non-object.';
        }
        const response = await this.#runtimeAgent.invoke_evaluate({ expression: value, silent: true });
        if (response.getError() || response.exceptionDetails) {
            return response.getError() ||
                (response.result.type !== 'string' ? response.result.description : response.result.value);
        }
        if (typeof name === 'string') {
            name = RemoteObject$1.toCallArgument(name);
        }
        const resultPromise = this.doSetObjectPropertyValue(response.result, name);
        if (response.result.objectId) {
            void this.#runtimeAgent.invoke_releaseObject({ objectId: response.result.objectId });
        }
        return await resultPromise;
    }
    async doSetObjectPropertyValue(result, name) {
        const setPropertyValueFunction = 'function(a, b) { this[a] = b; }';
        const argv = [name, RemoteObject$1.toCallArgument(result)];
        const response = await this.#runtimeAgent.invoke_callFunctionOn({
            objectId: this.#objectId,
            functionDeclaration: setPropertyValueFunction,
            arguments: argv,
            silent: true,
        });
        const error = response.getError();
        return error || response.exceptionDetails ? error || response.result.description : undefined;
    }
    async deleteProperty(name) {
        if (!this.#objectId) {
            return 'Can’t delete a property of non-object.';
        }
        const deletePropertyFunction = 'function(a) { delete this[a]; return !(a in this); }';
        const response = await this.#runtimeAgent.invoke_callFunctionOn({
            objectId: this.#objectId,
            functionDeclaration: deletePropertyFunction,
            arguments: [name],
            silent: true,
        });
        if (response.getError() || response.exceptionDetails) {
            return response.getError() || response.result.description;
        }
        if (!response.result.value) {
            return 'Failed to delete property.';
        }
        return undefined;
    }
    async callFunction(functionDeclaration, args) {
        const response = await this.#runtimeAgent.invoke_callFunctionOn({
            objectId: this.#objectId,
            functionDeclaration: functionDeclaration.toString(),
            arguments: args,
            silent: true,
        });
        if (response.getError()) {
            return { object: null, wasThrown: false };
        }
        return {
            object: this.#runtimeModel.createRemoteObject(response.result),
            wasThrown: Boolean(response.exceptionDetails),
        };
    }
    async callFunctionJSON(functionDeclaration, args) {
        const response = await this.#runtimeAgent.invoke_callFunctionOn({
            objectId: this.#objectId,
            functionDeclaration: functionDeclaration.toString(),
            arguments: args,
            silent: true,
            returnByValue: true,
        });
        if (response.getError() || response.exceptionDetails) {
            return null;
        }
        return response.result.value;
    }
    release() {
        if (!this.#objectId) {
            return;
        }
        void this.#runtimeAgent.invoke_releaseObject({ objectId: this.#objectId });
    }
    arrayLength() {
        return RemoteObject$1.arrayLength(this);
    }
    arrayBufferByteLength() {
        return RemoteObject$1.arrayBufferByteLength(this);
    }
    debuggerModel() {
        return this.#runtimeModel.debuggerModel();
    }
    runtimeModel() {
        return this.#runtimeModel;
    }
    isNode() {
        return Boolean(this.#objectId) && this.type === 'object' && this.subtype === 'node';
    }
    isLinearMemoryInspectable() {
        return this.type === 'object' && this.subtype !== undefined &&
            ['webassemblymemory', 'typedarray', 'dataview', 'arraybuffer'].includes(this.subtype) &&
            !RemoteObject$1.isEmptyArray(this);
    }
}
class ScopeRemoteObject extends RemoteObjectImpl {
    #scopeRef;
    #savedScopeProperties;
    constructor(runtimeModel, objectId, scopeRef, type, subtype, value, unserializableValue, description, preview) {
        super(runtimeModel, objectId, type, subtype, value, unserializableValue, description, preview);
        this.#scopeRef = scopeRef;
        this.#savedScopeProperties = undefined;
    }
    async doGetProperties(ownProperties, accessorPropertiesOnly, _generatePreview) {
        if (accessorPropertiesOnly) {
            return { properties: [], internalProperties: [] };
        }
        if (this.#savedScopeProperties) {
            return { properties: this.#savedScopeProperties.slice(), internalProperties: null };
        }
        const allProperties = await super.doGetProperties(ownProperties, accessorPropertiesOnly, false , true );
        if (Array.isArray(allProperties.properties)) {
            this.#savedScopeProperties = allProperties.properties.slice();
        }
        return allProperties;
    }
    async doSetObjectPropertyValue(result, argumentName) {
        const name = argumentName.value;
        const error = await this.debuggerModel().setVariableValue(this.#scopeRef.number, name, RemoteObject$1.toCallArgument(result), this.#scopeRef.callFrameId);
        if (error) {
            return error;
        }
        if (this.#savedScopeProperties) {
            for (const property of this.#savedScopeProperties) {
                if (property.name === name) {
                    property.value = this.runtimeModel().createRemoteObject(result);
                }
            }
        }
        return;
    }
}
class ScopeRef {
    number;
    callFrameId;
    constructor(number, callFrameId) {
        this.number = number;
        this.callFrameId = callFrameId;
    }
}
class RemoteObjectProperty {
    name;
    value;
    enumerable;
    writable;
    isOwn;
    wasThrown;
    symbol;
    synthetic;
    syntheticSetter;
    private;
    getter;
    setter;
    webIdl;
    constructor(name, value, enumerable, writable, isOwn, wasThrown, symbol, synthetic, syntheticSetter, isPrivate) {
        this.name = name;
        this.value = value !== null ? value : undefined;
        this.enumerable = typeof enumerable !== 'undefined' ? enumerable : true;
        const isNonSyntheticOrSyntheticWritable = !synthetic || Boolean(syntheticSetter);
        this.writable = typeof writable !== 'undefined' ? writable : isNonSyntheticOrSyntheticWritable;
        this.isOwn = Boolean(isOwn);
        this.wasThrown = Boolean(wasThrown);
        if (symbol) {
            this.symbol = symbol;
        }
        this.synthetic = Boolean(synthetic);
        if (syntheticSetter) {
            this.syntheticSetter = syntheticSetter;
        }
        this.private = Boolean(isPrivate);
    }
    async setSyntheticValue(expression) {
        if (!this.syntheticSetter) {
            return false;
        }
        const result = await this.syntheticSetter(expression);
        if (result) {
            this.value = result;
        }
        return Boolean(result);
    }
    isAccessorProperty() {
        return Boolean(this.getter || this.setter);
    }
    match({ includeNullOrUndefinedValues, regex }) {
        if (regex !== null) {
            if (!regex.test(this.name) && !regex.test(this.value?.description ?? '')) {
                return false;
            }
        }
        if (!includeNullOrUndefinedValues) {
            if (!this.isAccessorProperty() && RemoteObject$1.isNullOrUndefined(this.value)) {
                return false;
            }
        }
        return true;
    }
    cloneWithNewName(newName) {
        const property = new RemoteObjectProperty(newName, this.value ?? null, this.enumerable, this.writable, this.isOwn, this.wasThrown, this.symbol, this.synthetic, this.syntheticSetter, this.private);
        property.getter = this.getter;
        property.setter = this.setter;
        return property;
    }
}
class LocalJSONObject extends RemoteObject$1 {
    #value;
    #cachedDescription;
    #cachedChildren;
    constructor(value) {
        super();
        this.#value = value;
    }
    get objectId() {
        return undefined;
    }
    get value() {
        return this.#value;
    }
    unserializableValue() {
        const unserializableDescription = RemoteObject$1.unserializableDescription(this.#value);
        return unserializableDescription || undefined;
    }
    get description() {
        if (this.#cachedDescription) {
            return this.#cachedDescription;
        }
        function formatArrayItem(property) {
            return this.formatValue(property.value || null);
        }
        function formatObjectItem(property) {
            let name = property.name;
            if (/^\s|\s$|^$|\n/.test(name)) {
                name = '"' + name.replace(/\n/g, '\u21B5') + '"';
            }
            return name + ': ' + this.formatValue(property.value || null);
        }
        if (this.type === 'object') {
            switch (this.subtype) {
                case 'array':
                    this.#cachedDescription = this.concatenate('[', ']', formatArrayItem.bind(this));
                    break;
                case 'date':
                    this.#cachedDescription = String(this.#value);
                    break;
                case 'null':
                    this.#cachedDescription = 'null';
                    break;
                default:
                    this.#cachedDescription = this.concatenate('{', '}', formatObjectItem.bind(this));
            }
        }
        else {
            this.#cachedDescription = String(this.#value);
        }
        return this.#cachedDescription;
    }
    formatValue(value) {
        if (!value) {
            return 'undefined';
        }
        const description = value.description || '';
        if (value.type === 'string') {
            return '"' + description.replace(/\n/g, '\u21B5') + '"';
        }
        return description;
    }
    concatenate(prefix, suffix, formatProperty) {
        const previewChars = 100;
        let buffer = prefix;
        const children = this.children();
        for (let i = 0; i < children.length; ++i) {
            const itemDescription = formatProperty(children[i]);
            if (buffer.length + itemDescription.length > previewChars) {
                buffer += ',…';
                break;
            }
            if (i) {
                buffer += ', ';
            }
            buffer += itemDescription;
        }
        buffer += suffix;
        return buffer;
    }
    get type() {
        return typeof this.#value;
    }
    get subtype() {
        if (this.#value === null) {
            return 'null';
        }
        if (Array.isArray(this.#value)) {
            return 'array';
        }
        if (this.#value instanceof Date) {
            return 'date';
        }
        if (this.#value instanceof Error) {
            return 'error';
        }
        return undefined;
    }
    get hasChildren() {
        if ((typeof this.#value !== 'object') || (this.#value === null)) {
            return false;
        }
        return Boolean(Object.keys(this.#value).length);
    }
    async getOwnProperties(_generatePreview, nonIndexedPropertiesOnly = false) {
        function isArrayIndex(name) {
            const index = Number(name) >>> 0;
            return String(index) === name;
        }
        let properties = this.children();
        if (nonIndexedPropertiesOnly) {
            properties = properties.filter(property => !isArrayIndex(property.name));
        }
        return { properties, internalProperties: null };
    }
    async getAllProperties(accessorPropertiesOnly, generatePreview, nonIndexedPropertiesOnly = false) {
        if (accessorPropertiesOnly) {
            return { properties: [], internalProperties: null };
        }
        return await this.getOwnProperties(generatePreview, nonIndexedPropertiesOnly);
    }
    children() {
        if (!this.hasChildren) {
            return [];
        }
        if (!this.#cachedChildren) {
            this.#cachedChildren = Object.entries(this.#value).map(([name, value]) => {
                return new RemoteObjectProperty(name, value instanceof RemoteObject$1 ? value : RemoteObject$1.fromLocalObject(value));
            });
        }
        return this.#cachedChildren;
    }
    arrayLength() {
        return Array.isArray(this.#value) ? this.#value.length : 0;
    }
    async callFunction(functionDeclaration, args) {
        const target = this.#value;
        const rawArgs = args ? args.map(arg => arg.value) : [];
        let result;
        let wasThrown = false;
        try {
            result = functionDeclaration.apply(target, rawArgs);
        }
        catch {
            wasThrown = true;
        }
        const object = RemoteObject$1.fromLocalObject(result);
        return { object, wasThrown };
    }
    async callFunctionJSON(functionDeclaration, args) {
        const target = this.#value;
        const rawArgs = args ? args.map(arg => arg.value) : [];
        let result;
        try {
            result = functionDeclaration.apply(target, rawArgs);
        }
        catch {
            result = null;
        }
        return result;
    }
}
class RemoteFunction {
    #object;
    constructor(object) {
        this.#object = object;
    }
    static objectAsFunction(object) {
        if (object.type !== 'function') {
            throw new Error('Object is empty or not a function');
        }
        return new RemoteFunction(object);
    }
    async targetFunction() {
        const ownProperties = await this.#object.getOwnProperties(false );
        const targetFunction = ownProperties.internalProperties?.find(({ name }) => name === '[[TargetFunction]]');
        return targetFunction?.value ?? this.#object;
    }
    async targetFunctionDetails() {
        const targetFunction = await this.targetFunction();
        const functionDetails = await targetFunction.debuggerModel().functionDetailsPromise(targetFunction);
        if (this.#object !== targetFunction) {
            targetFunction.release();
        }
        return functionDetails;
    }
}
const descriptionLengthParenRegex = /\(([0-9]+)\)/;
const descriptionLengthSquareRegex = /\[([0-9]+)\]/;

// Copyright 2022 The Chromium Authors
function createCssTokenizer() {
    async function tokenize(line, callback) {
        const streamParser = await undefined();
        const stream = new undefined(line, 4, 2);
        const state = streamParser.startState(2);
        let lastPos = stream.pos;
        while (!stream.eol()) {
            stream.start = lastPos;
            let tokenType = streamParser.token(stream, state);
            if (tokenType === 'error' && state.state === 'maybeprop') {
                tokenType = 'property';
            }
            const segment = stream.current();
            callback(segment, tokenType);
            lastPos = stream.pos;
        }
    }
    return tokenize;
}

// Copyright 2012 The Chromium Authors
class SearchMatch {
    lineNumber;
    lineContent;
    columnNumber;
    matchLength;
    constructor(lineNumber, lineContent, columnNumber, matchLength) {
        this.lineNumber = lineNumber;
        this.lineContent = lineContent;
        this.columnNumber = columnNumber;
        this.matchLength = matchLength;
    }
    static comparator(a, b) {
        return a.lineNumber - b.lineNumber || a.columnNumber - b.columnNumber;
    }
}
const contentAsDataURL = function (content, mimeType, contentEncoded, charset, limitSize = true) {
    const maxDataUrlSize = 1024 * 1024;
    if (content === undefined || content === null || (limitSize && content.length > maxDataUrlSize)) {
        return null;
    }
    content = contentEncoded ? content : encodeURIComponent(content);
    return 'data:' + mimeType + (charset ? ';charset=' + charset : '') + (contentEncoded ? ';base64' : '') + ',' +
        content;
};

// Copyright 2020 The Chromium Authors
class TextCursor {
    #lineEndings;
    #offset = 0;
    #lineNumber = 0;
    #columnNumber = 0;
    constructor(lineEndings) {
        this.#lineEndings = lineEndings;
    }
    advance(offset) {
        this.#offset = offset;
        while (this.#lineNumber < this.#lineEndings.length && this.#lineEndings[this.#lineNumber] < this.#offset) {
            ++this.#lineNumber;
        }
        this.#columnNumber = this.#lineNumber ? this.#offset - this.#lineEndings[this.#lineNumber - 1] - 1 : this.#offset;
    }
    offset() {
        return this.#offset;
    }
    resetTo(offset) {
        this.#offset = offset;
        this.#lineNumber =
            lowerBound(this.#lineEndings, offset, DEFAULT_COMPARATOR);
        this.#columnNumber = this.#lineNumber ? this.#offset - this.#lineEndings[this.#lineNumber - 1] - 1 : this.#offset;
    }
    lineNumber() {
        return this.#lineNumber;
    }
    columnNumber() {
        return this.#columnNumber;
    }
}

// Copyright 2013 The Chromium Authors
const MAX_SAFE_INT32 = 2 ** 31 - 1;
class TextRange {
    startLine;
    startColumn;
    endLine;
    endColumn;
    constructor(startLine, startColumn, endLine, endColumn) {
        this.startLine = startLine;
        this.startColumn = startColumn;
        this.endLine = endLine;
        this.endColumn = endColumn;
    }
    static createFromLocation(line, column) {
        return new TextRange(line, column, line, column);
    }
    static createUnboundedFromLocation(line, column) {
        return new TextRange(line, column, MAX_SAFE_INT32, MAX_SAFE_INT32);
    }
    static fromObject(serializedTextRange) {
        return new TextRange(serializedTextRange.startLine, serializedTextRange.startColumn, serializedTextRange.endLine, serializedTextRange.endColumn);
    }
    static comparator(range1, range2) {
        return range1.compareTo(range2);
    }
    static fromEdit(oldRange, newText) {
        let endLine = oldRange.startLine;
        let endColumn = oldRange.startColumn + newText.length;
        const lineEndings = findLineEndingIndexes(newText);
        if (lineEndings.length > 1) {
            endLine = oldRange.startLine + lineEndings.length - 1;
            const len = lineEndings.length;
            endColumn = lineEndings[len - 1] - lineEndings[len - 2] - 1;
        }
        return new TextRange(oldRange.startLine, oldRange.startColumn, endLine, endColumn);
    }
    isEmpty() {
        return this.startLine === this.endLine && this.startColumn === this.endColumn;
    }
    immediatelyPrecedes(range) {
        if (!range) {
            return false;
        }
        return this.endLine === range.startLine && this.endColumn === range.startColumn;
    }
    immediatelyFollows(range) {
        if (!range) {
            return false;
        }
        return range.immediatelyPrecedes(this);
    }
    follows(range) {
        return (range.endLine === this.startLine && range.endColumn <= this.startColumn) || range.endLine < this.startLine;
    }
    get linesCount() {
        return this.endLine - this.startLine;
    }
    collapseToEnd() {
        return new TextRange(this.endLine, this.endColumn, this.endLine, this.endColumn);
    }
    collapseToStart() {
        return new TextRange(this.startLine, this.startColumn, this.startLine, this.startColumn);
    }
    normalize() {
        if (this.startLine > this.endLine || (this.startLine === this.endLine && this.startColumn > this.endColumn)) {
            return new TextRange(this.endLine, this.endColumn, this.startLine, this.startColumn);
        }
        return this.clone();
    }
    clone() {
        return new TextRange(this.startLine, this.startColumn, this.endLine, this.endColumn);
    }
    serializeToObject() {
        return {
            startLine: this.startLine,
            startColumn: this.startColumn,
            endLine: this.endLine,
            endColumn: this.endColumn,
        };
    }
    compareTo(other) {
        if (this.startLine > other.startLine) {
            return 1;
        }
        if (this.startLine < other.startLine) {
            return -1;
        }
        if (this.startColumn > other.startColumn) {
            return 1;
        }
        if (this.startColumn < other.startColumn) {
            return -1;
        }
        return 0;
    }
    compareToPosition(lineNumber, columnNumber) {
        if (lineNumber < this.startLine || (lineNumber === this.startLine && columnNumber < this.startColumn)) {
            return -1;
        }
        if (lineNumber > this.endLine || (lineNumber === this.endLine && columnNumber > this.endColumn)) {
            return 1;
        }
        return 0;
    }
    equal(other) {
        return this.startLine === other.startLine && this.endLine === other.endLine &&
            this.startColumn === other.startColumn && this.endColumn === other.endColumn;
    }
    relativeTo(line, column) {
        const relative = this.clone();
        if (this.startLine === line) {
            relative.startColumn -= column;
        }
        if (this.endLine === line) {
            relative.endColumn -= column;
        }
        relative.startLine -= line;
        relative.endLine -= line;
        return relative;
    }
    relativeFrom(line, column) {
        const relative = this.clone();
        if (this.startLine === 0) {
            relative.startColumn += column;
        }
        if (this.endLine === 0) {
            relative.endColumn += column;
        }
        relative.startLine += line;
        relative.endLine += line;
        return relative;
    }
    rebaseAfterTextEdit(originalRange, editedRange) {
        console.assert(originalRange.startLine === editedRange.startLine);
        console.assert(originalRange.startColumn === editedRange.startColumn);
        const rebase = this.clone();
        if (!this.follows(originalRange)) {
            return rebase;
        }
        const lineDelta = editedRange.endLine - originalRange.endLine;
        const columnDelta = editedRange.endColumn - originalRange.endColumn;
        rebase.startLine += lineDelta;
        rebase.endLine += lineDelta;
        if (rebase.startLine === editedRange.endLine) {
            rebase.startColumn += columnDelta;
        }
        if (rebase.endLine === editedRange.endLine) {
            rebase.endColumn += columnDelta;
        }
        return rebase;
    }
    toString() {
        return JSON.stringify(this);
    }
    containsLocation(lineNumber, columnNumber) {
        if (this.startLine === this.endLine) {
            return this.startLine === lineNumber && this.startColumn <= columnNumber && columnNumber < this.endColumn;
        }
        if (this.startLine === lineNumber) {
            return this.startColumn <= columnNumber;
        }
        if (this.endLine === lineNumber) {
            return columnNumber < this.endColumn;
        }
        return this.startLine < lineNumber && lineNumber < this.endLine;
    }
    get start() {
        return { lineNumber: this.startLine, columnNumber: this.startColumn };
    }
    get end() {
        return { lineNumber: this.endLine, columnNumber: this.endColumn };
    }
    intersection(that) {
        let { startLine, startColumn } = this;
        if (startLine < that.startLine) {
            startLine = that.startLine;
            startColumn = that.startColumn;
        }
        else if (startLine === that.startLine) {
            startColumn = Math.max(startColumn, that.startColumn);
        }
        let { endLine, endColumn } = this;
        if (endLine > that.endLine) {
            endLine = that.endLine;
            endColumn = that.endColumn;
        }
        else if (endLine === that.endLine) {
            endColumn = Math.min(endColumn, that.endColumn);
        }
        if (startLine > endLine || (startLine === endLine && startColumn >= endColumn)) {
            return new TextRange(0, 0, 0, 0);
        }
        return new TextRange(startLine, startColumn, endLine, endColumn);
    }
}
class SourceRange {
    offset;
    length;
    constructor(offset, length) {
        this.offset = offset;
        this.length = length;
    }
}

// Copyright 2016 The Chromium Authors
class Text {
    #value;
    #lineEndings;
    constructor(value) {
        this.#value = value;
    }
    lineEndings() {
        if (!this.#lineEndings) {
            this.#lineEndings = findLineEndingIndexes(this.#value);
        }
        return this.#lineEndings;
    }
    value() {
        return this.#value;
    }
    lineCount() {
        const lineEndings = this.lineEndings();
        return lineEndings.length;
    }
    offsetFromPosition(lineNumber, columnNumber) {
        return (lineNumber ? this.lineEndings()[lineNumber - 1] + 1 : 0) + columnNumber;
    }
    positionFromOffset(offset) {
        const lineEndings = this.lineEndings();
        const lineNumber = lowerBound(lineEndings, offset, DEFAULT_COMPARATOR);
        return { lineNumber, columnNumber: offset - (lineNumber && (lineEndings[lineNumber - 1] + 1)) };
    }
    lineAt(lineNumber) {
        const lineEndings = this.lineEndings();
        const lineStart = lineNumber > 0 ? lineEndings[lineNumber - 1] + 1 : 0;
        const lineEnd = lineEndings[lineNumber];
        let lineContent = this.#value.substring(lineStart, lineEnd);
        if (lineContent.length > 0 && lineContent.charAt(lineContent.length - 1) === '\r') {
            lineContent = lineContent.substring(0, lineContent.length - 1);
        }
        return lineContent;
    }
    toSourceRange(range) {
        const start = this.offsetFromPosition(range.startLine, range.startColumn);
        const end = this.offsetFromPosition(range.endLine, range.endColumn);
        return new SourceRange(start, end - start);
    }
    toTextRange(sourceRange) {
        const cursor = new TextCursor(this.lineEndings());
        const result = TextRange.createFromLocation(0, 0);
        cursor.resetTo(sourceRange.offset);
        result.startLine = cursor.lineNumber();
        result.startColumn = cursor.columnNumber();
        cursor.advance(sourceRange.offset + sourceRange.length);
        result.endLine = cursor.lineNumber();
        result.endColumn = cursor.columnNumber();
        return result;
    }
    replaceRange(range, replacement) {
        const sourceRange = this.toSourceRange(range);
        return this.#value.substring(0, sourceRange.offset) + replacement +
            this.#value.substring(sourceRange.offset + sourceRange.length);
    }
    extract(range) {
        const sourceRange = this.toSourceRange(range);
        return this.#value.substr(sourceRange.offset, sourceRange.length);
    }
}

// Copyright 2023 The Chromium Authors
class ContentData {
    mimeType;
    charset;
    #contentAsBase64;
    #contentAsText;
    #contentAsTextObj;
    constructor(data, isBase64, mimeType, charset) {
        this.charset = charset || 'utf-8';
        if (isBase64) {
            this.#contentAsBase64 = data;
        }
        else {
            this.#contentAsText = data;
        }
        this.mimeType = mimeType;
        if (!this.mimeType) {
            this.mimeType = isBase64 ? 'application/octet-stream' : 'text/plain';
        }
    }
    get base64() {
        if (this.#contentAsBase64 === undefined) {
            throw new Error('Encoding text content as base64 is not supported');
        }
        return this.#contentAsBase64;
    }
    get text() {
        if (this.#contentAsText !== undefined) {
            return this.#contentAsText;
        }
        if (!this.isTextContent) {
            throw new Error('Cannot interpret binary data as text');
        }
        const binaryString = window.atob(this.#contentAsBase64);
        const len = binaryString.length;
        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; i++) {
            bytes[i] = binaryString.charCodeAt(i);
        }
        this.#contentAsText = new TextDecoder(this.charset).decode(bytes);
        return this.#contentAsText;
    }
    get isTextContent() {
        return this.#createdFromText || isTextType(this.mimeType);
    }
    get isEmpty() {
        return !Boolean(this.#contentAsBase64) && !Boolean(this.#contentAsText);
    }
    get createdFromBase64() {
        return this.#contentAsBase64 !== undefined;
    }
    get #createdFromText() {
        return this.#contentAsBase64 === undefined;
    }
    get textObj() {
        if (this.#contentAsTextObj === undefined) {
            this.#contentAsTextObj = new Text(this.text);
        }
        return this.#contentAsTextObj;
    }
    contentEqualTo(other) {
        if (this.#contentAsBase64 !== undefined && other.#contentAsBase64 !== undefined) {
            return this.#contentAsBase64 === other.#contentAsBase64;
        }
        if (this.#contentAsText !== undefined && other.#contentAsText !== undefined) {
            return this.#contentAsText === other.#contentAsText;
        }
        if (this.isTextContent && other.isTextContent) {
            return this.text === other.text;
        }
        return false;
    }
    asDataUrl() {
        if (this.#contentAsBase64 !== undefined) {
            const charset = this.isTextContent ? this.charset : null;
            return contentAsDataURL(this.#contentAsBase64, this.mimeType ?? '', true, charset);
        }
        return contentAsDataURL(this.text, this.mimeType ?? '', false, 'utf-8');
    }
    asDeferedContent() {
        if (this.isTextContent) {
            return { content: this.text, isEncoded: false };
        }
        if (this.#contentAsText !== undefined) {
            return { content: this.#contentAsText, isEncoded: false };
        }
        if (this.#contentAsBase64 !== undefined) {
            return { content: this.#contentAsBase64, isEncoded: true };
        }
        throw new Error('Unreachable');
    }
    static isError(contentDataOrError) {
        return 'error' in contentDataOrError;
    }
    static textOr(contentDataOrError, value) {
        if (ContentData.isError(contentDataOrError)) {
            return value;
        }
        return contentDataOrError.text;
    }
    static contentDataOrEmpty(contentDataOrError) {
        if (ContentData.isError(contentDataOrError)) {
            return EMPTY_TEXT_CONTENT_DATA;
        }
        return contentDataOrError;
    }
    static asDeferredContent(contentDataOrError) {
        if (ContentData.isError(contentDataOrError)) {
            return { error: contentDataOrError.error, content: null, isEncoded: false };
        }
        return contentDataOrError.asDeferedContent();
    }
}
const EMPTY_TEXT_CONTENT_DATA = new ContentData('',  false, 'text/plain');

// Copyright 2013 The Chromium Authors
const SPACE_CHAR_REGEXP = /\s/;
const Utils = {
    isSpaceChar: function (char) {
        return SPACE_CHAR_REGEXP.test(char);
    },
    lineIndent: function (line) {
        let indentation = 0;
        while (indentation < line.length && Utils.isSpaceChar(line.charAt(indentation))) {
            ++indentation;
        }
        return line.substr(0, indentation);
    },
    splitStringByRegexes(text, regexes) {
        const matches = [];
        const globalRegexes = [];
        for (let i = 0; i < regexes.length; i++) {
            const regex = regexes[i];
            if (!regex.global) {
                globalRegexes.push(new RegExp(regex.source, regex.flags ? regex.flags + 'g' : 'g'));
            }
            else {
                globalRegexes.push(regex);
            }
        }
        doSplit(text, 0, 0);
        return matches;
        function doSplit(text, regexIndex, startIndex) {
            if (regexIndex >= globalRegexes.length) {
                matches.push({ value: text, position: startIndex, regexIndex: -1, captureGroups: [] });
                return;
            }
            const regex = globalRegexes[regexIndex];
            let currentIndex = 0;
            let result;
            regex.lastIndex = 0;
            while ((result = regex.exec(text)) !== null) {
                const stringBeforeMatch = text.substring(currentIndex, result.index);
                if (stringBeforeMatch) {
                    doSplit(stringBeforeMatch, regexIndex + 1, startIndex + currentIndex);
                }
                const match = result[0];
                matches.push({
                    value: match,
                    position: startIndex + result.index,
                    regexIndex,
                    captureGroups: result.slice(1),
                });
                currentIndex = result.index + match.length;
            }
            const stringAfterMatches = text.substring(currentIndex);
            if (stringAfterMatches) {
                doSplit(stringAfterMatches, regexIndex + 1, startIndex + currentIndex);
            }
        }
    },
};
const performSearchInContentData = function (contentData, query, caseSensitive, isRegex) {
    if (ContentData.isError(contentData) || !contentData.isTextContent) {
        return [];
    }
    return performSearchInContent(contentData.textObj, query, caseSensitive, isRegex);
};
const performSearchInContent = function (text, query, caseSensitive, isRegex) {
    const regex = createSearchRegex(query, caseSensitive, isRegex);
    const result = [];
    for (let i = 0; i < text.lineCount(); ++i) {
        const lineContent = text.lineAt(i);
        const matches = lineContent.matchAll(regex);
        for (const match of matches) {
            result.push(new SearchMatch(i, lineContent, match.index, match[0].length));
        }
    }
    return result;
};
const performSearchInSearchMatches = function (matches, query, caseSensitive, isRegex) {
    const regex = createSearchRegex(query, caseSensitive, isRegex);
    const result = [];
    for (const { lineNumber, lineContent } of matches) {
        const matches = lineContent.matchAll(regex);
        for (const match of matches) {
            result.push(new SearchMatch(lineNumber, lineContent, match.index, match[0].length));
        }
    }
    return result;
};

// Copyright 2014 The Chromium Authors
class StaticContentProvider {
    #contentURL;
    #contentType;
    #lazyContent;
    constructor(contentURL, contentType, lazyContent) {
        this.#contentURL = contentURL;
        this.#contentType = contentType;
        this.#lazyContent = lazyContent;
    }
    static fromString(contentURL, contentType, content) {
        const lazyContent = () => Promise.resolve(new ContentData(content,  false, contentType.canonicalMimeType()));
        return new StaticContentProvider(contentURL, contentType, lazyContent);
    }
    contentURL() {
        return this.#contentURL;
    }
    contentType() {
        return this.#contentType;
    }
    requestContentData() {
        return this.#lazyContent();
    }
    async searchInContent(query, caseSensitive, isRegex) {
        const contentData = await this.requestContentData();
        return performSearchInContentData(contentData, query, caseSensitive, isRegex);
    }
}

// Copyright 2024 The Chromium Authors
class StreamingContentData extends ObjectWrapper {
    mimeType;
    #charset;
    #disallowStreaming;
    #chunks = [];
    #contentData;
    constructor(mimeType, charset, initialContent) {
        super();
        this.mimeType = mimeType;
        this.#charset = charset;
        this.#disallowStreaming = Boolean(initialContent && !initialContent.createdFromBase64);
        this.#contentData = initialContent;
    }
    static create(mimeType, charset) {
        return new StreamingContentData(mimeType, charset);
    }
    static from(content) {
        return new StreamingContentData(content.mimeType, content.charset, content);
    }
    get isTextContent() {
        if (this.#contentData) {
            return this.#contentData.isTextContent;
        }
        return isTextType(this.mimeType);
    }
    addChunk(chunk) {
        if (this.#disallowStreaming) {
            throw new Error('Cannot add base64 data to a text-only ContentData.');
        }
        this.#chunks.push(chunk);
        this.dispatchEventToListeners("ChunkAdded" , { content: this, chunk });
    }
    content() {
        if (this.#contentData && this.#chunks.length === 0) {
            return this.#contentData;
        }
        const initialBase64 = this.#contentData?.base64 ?? '';
        const base64Content = this.#chunks.reduce((acc, chunk) => concatBase64(acc, chunk), initialBase64);
        this.#contentData = new ContentData(base64Content,  true, this.mimeType, this.#charset);
        this.#chunks = [];
        return this.#contentData;
    }
}
const isError = function (contentDataOrError) {
    return 'error' in contentDataOrError;
};

// Copyright 2024 The Chromium Authors
class WasmDisassembly extends ContentData {
    lines;
    #offsets;
    #functionBodyOffsets;
    #cachedText;
    constructor(lines, offsets, functionBodyOffsets) {
        super('',  false, 'text/x-wast', 'utf-8');
        if (lines.length !== offsets.length) {
            throw new Error('Lines and offsets don\'t match');
        }
        this.lines = lines;
        this.#offsets = offsets;
        this.#functionBodyOffsets = functionBodyOffsets;
    }
    get text() {
        if (typeof this.#cachedText === 'undefined') {
            this.#cachedText = this.lines.join('\n');
        }
        return this.#cachedText;
    }
    get isEmpty() {
        return this.lines.length === 0 || (this.lines.length === 1 && this.lines[0].length === 0);
    }
    get lineNumbers() {
        return this.#offsets.length;
    }
    bytecodeOffsetToLineNumber(bytecodeOffset) {
        return upperBound(this.#offsets, bytecodeOffset, DEFAULT_COMPARATOR) -
            1;
    }
    lineNumberToBytecodeOffset(lineNumber) {
        return this.#offsets[lineNumber];
    }
    *nonBreakableLineNumbers() {
        let lineNumber = 0;
        let functionIndex = 0;
        while (lineNumber < this.lineNumbers) {
            if (functionIndex < this.#functionBodyOffsets.length) {
                const offset = this.lineNumberToBytecodeOffset(lineNumber);
                if (offset >= this.#functionBodyOffsets[functionIndex].start) {
                    lineNumber = this.bytecodeOffsetToLineNumber(this.#functionBodyOffsets[functionIndex++].end) + 1;
                    continue;
                }
            }
            yield lineNumber++;
        }
    }
    asDeferedContent() {
        return { content: '', isEncoded: false, wasmDisassemblyInfo: this };
    }
}

// Copyright 2025 The Chromium Authors
var ErrorType;
(function (ErrorType) {
    ErrorType["HTTP_RESPONSE_UNAVAILABLE"] = "HTTP_RESPONSE_UNAVAILABLE";
    ErrorType["NOT_FOUND"] = "NOT_FOUND";
    ErrorType["ABORT"] = "ABORT";
})(ErrorType || (ErrorType = {}));
function setDebugDispatchHttpRequestEnabled(enabled) {
    if (enabled) {
        localStorage.setItem('debugDispatchHttpRequestEnabled', 'true');
    }
    else {
        localStorage.removeItem('debugDispatchHttpRequestEnabled');
    }
}
globalThis.setDebugDispatchHttpRequestEnabled = setDebugDispatchHttpRequestEnabled;

// Copyright 2023 The Chromium Authors
var Role;
(function (Role) {
    Role[Role["ROLE_UNSPECIFIED"] = 0] = "ROLE_UNSPECIFIED";
    Role[Role["USER"] = 1] = "USER";
    Role[Role["MODEL"] = 2] = "MODEL";
})(Role || (Role = {}));
var FunctionalityType;
(function (FunctionalityType) {
    FunctionalityType[FunctionalityType["FUNCTIONALITY_TYPE_UNSPECIFIED"] = 0] = "FUNCTIONALITY_TYPE_UNSPECIFIED";
    FunctionalityType[FunctionalityType["CHAT"] = 1] = "CHAT";
    FunctionalityType[FunctionalityType["EXPLAIN_ERROR"] = 2] = "EXPLAIN_ERROR";
    FunctionalityType[FunctionalityType["AGENTIC_CHAT"] = 5] = "AGENTIC_CHAT";
})(FunctionalityType || (FunctionalityType = {}));
var ClientFeature;
(function (ClientFeature) {
    ClientFeature[ClientFeature["CLIENT_FEATURE_UNSPECIFIED"] = 0] = "CLIENT_FEATURE_UNSPECIFIED";
    ClientFeature[ClientFeature["CHROME_CONSOLE_INSIGHTS"] = 1] = "CHROME_CONSOLE_INSIGHTS";
    ClientFeature[ClientFeature["CHROME_STYLING_AGENT"] = 2] = "CHROME_STYLING_AGENT";
    ClientFeature[ClientFeature["CHROME_NETWORK_AGENT"] = 7] = "CHROME_NETWORK_AGENT";
    ClientFeature[ClientFeature["CHROME_PERFORMANCE_ANNOTATIONS_AGENT"] = 20] = "CHROME_PERFORMANCE_ANNOTATIONS_AGENT";
    ClientFeature[ClientFeature["CHROME_FILE_AGENT"] = 9] = "CHROME_FILE_AGENT";
    ClientFeature[ClientFeature["CHROME_PATCH_AGENT"] = 12] = "CHROME_PATCH_AGENT";
    ClientFeature[ClientFeature["CHROME_PERFORMANCE_FULL_AGENT"] = 24] = "CHROME_PERFORMANCE_FULL_AGENT";
})(ClientFeature || (ClientFeature = {}));
var UserTier;
(function (UserTier) {
    UserTier[UserTier["USER_TIER_UNSPECIFIED"] = 0] = "USER_TIER_UNSPECIFIED";
    UserTier[UserTier["TESTERS"] = 1] = "TESTERS";
    UserTier[UserTier["BETA"] = 2] = "BETA";
    UserTier[UserTier["PUBLIC"] = 3] = "PUBLIC";
})(UserTier || (UserTier = {}));
var EditType;
(function (EditType) {
    EditType[EditType["EDIT_TYPE_UNSPECIFIED"] = 0] = "EDIT_TYPE_UNSPECIFIED";
    EditType[EditType["ADD"] = 1] = "ADD";
    EditType[EditType["DELETE"] = 2] = "DELETE";
    EditType[EditType["PASTE"] = 3] = "PASTE";
    EditType[EditType["UNDO"] = 4] = "UNDO";
    EditType[EditType["REDO"] = 5] = "REDO";
    EditType[EditType["ACCEPT_COMPLETION"] = 6] = "ACCEPT_COMPLETION";
})(EditType || (EditType = {}));
var Reason;
(function (Reason) {
    Reason[Reason["UNKNOWN"] = 0] = "UNKNOWN";
    Reason[Reason["CURRENTLY_OPEN"] = 1] = "CURRENTLY_OPEN";
    Reason[Reason["RECENTLY_OPENED"] = 2] = "RECENTLY_OPENED";
    Reason[Reason["RECENTLY_EDITED"] = 3] = "RECENTLY_EDITED";
    Reason[Reason["COLOCATED"] = 4] = "COLOCATED";
    Reason[Reason["RELATED_FILE"] = 5] = "RELATED_FILE";
})(Reason || (Reason = {}));
var UseCase;
(function (UseCase) {
    UseCase[UseCase["USE_CASE_UNSPECIFIED"] = 0] = "USE_CASE_UNSPECIFIED";
    UseCase[UseCase["CODE_GENERATION"] = 1] = "CODE_GENERATION";
})(UseCase || (UseCase = {}));
var RecitationAction;
(function (RecitationAction) {
    RecitationAction["ACTION_UNSPECIFIED"] = "ACTION_UNSPECIFIED";
    RecitationAction["CITE"] = "CITE";
    RecitationAction["BLOCK"] = "BLOCK";
    RecitationAction["NO_ACTION"] = "NO_ACTION";
    RecitationAction["EXEMPT_FOUND_IN_PROMPT"] = "EXEMPT_FOUND_IN_PROMPT";
})(RecitationAction || (RecitationAction = {}));
var CitationSourceType;
(function (CitationSourceType) {
    CitationSourceType["CITATION_SOURCE_TYPE_UNSPECIFIED"] = "CITATION_SOURCE_TYPE_UNSPECIFIED";
    CitationSourceType["TRAINING_DATA"] = "TRAINING_DATA";
    CitationSourceType["WORLD_FACTS"] = "WORLD_FACTS";
    CitationSourceType["LOCAL_FACTS"] = "LOCAL_FACTS";
    CitationSourceType["INDIRECT"] = "INDIRECT";
})(CitationSourceType || (CitationSourceType = {}));

// Copyright 2025 The Chromium Authors
var SubscriptionStatus;
(function (SubscriptionStatus) {
    SubscriptionStatus["ENABLED"] = "SUBSCRIPTION_STATE_ENABLED";
    SubscriptionStatus["PENDING"] = "SUBSCRIPTION_STATE_PENDING";
    SubscriptionStatus["CANCELED"] = "SUBSCRIPTION_STATE_CANCELED";
    SubscriptionStatus["REFUNDED"] = "SUBSCRIPTION_STATE_REFUNDED";
    SubscriptionStatus["AWAITING_FIX"] = "SUBSCRIPTION_STATE_AWAITING_FIX";
    SubscriptionStatus["ON_HOLD"] = "SUBSCRIPTION_STATE_ACCOUNT_ON_HOLD";
})(SubscriptionStatus || (SubscriptionStatus = {}));
var SubscriptionTier;
(function (SubscriptionTier) {
    SubscriptionTier["PREMIUM_ANNUAL"] = "SUBSCRIPTION_TIER_PREMIUM_ANNUAL";
    SubscriptionTier["PREMIUM_MONTHLY"] = "SUBSCRIPTION_TIER_PREMIUM_MONTHLY";
    SubscriptionTier["PRO_ANNUAL"] = "SUBSCRIPTION_TIER_PRO_ANNUAL";
    SubscriptionTier["PRO_MONTHLY"] = "SUBSCRIPTION_TIER_PRO_MONTHLY";
})(SubscriptionTier || (SubscriptionTier = {}));
var EligibilityStatus;
(function (EligibilityStatus) {
    EligibilityStatus["ELIGIBLE"] = "ELIGIBLE";
    EligibilityStatus["NOT_ELIGIBLE"] = "NOT_ELIGIBLE";
})(EligibilityStatus || (EligibilityStatus = {}));
var EmailPreference;
(function (EmailPreference) {
    EmailPreference["ENABLED"] = "ENABLED";
    EmailPreference["DISABLED"] = "DISABLED";
})(EmailPreference || (EmailPreference = {}));

// Copyright 2011 The Chromium Authors
class UserMetrics {
    #panelChangedSinceLaunch;
    #firedLaunchHistogram;
    #launchPanelName;
    constructor() {
        this.#panelChangedSinceLaunch = false;
        this.#firedLaunchHistogram = false;
        this.#launchPanelName = '';
    }
    panelShown(panelName, isLaunching) {
        const code = PanelCodes[panelName] || 0;
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.PanelShown" , code, PanelCodes.MAX_VALUE);
        InspectorFrontendHostInstance.recordUserMetricsAction('DevTools_PanelShown_' + panelName);
        if (!isLaunching) {
            this.#panelChangedSinceLaunch = true;
        }
    }
    settingsPanelShown(settingsViewId) {
        this.panelShown('settings-' + settingsViewId);
    }
    sourcesPanelFileDebugged(mediaType) {
        const code = (mediaType && MediaTypes[mediaType]) || MediaTypes.Unknown;
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.SourcesPanelFileDebugged" , code, MediaTypes.MAX_VALUE);
    }
    sourcesPanelFileOpened(mediaType) {
        const code = (mediaType && MediaTypes[mediaType]) || MediaTypes.Unknown;
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.SourcesPanelFileOpened" , code, MediaTypes.MAX_VALUE);
    }
    networkPanelResponsePreviewOpened(mediaType) {
        const code = (mediaType && MediaTypes[mediaType]) || MediaTypes.Unknown;
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.NetworkPanelResponsePreviewOpened" , code, MediaTypes.MAX_VALUE);
    }
    actionTaken(action) {
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.ActionTaken" , action, Action.MAX_VALUE);
    }
    panelLoaded(panelName, histogramName) {
        if (this.#firedLaunchHistogram || panelName !== this.#launchPanelName) {
            return;
        }
        this.#firedLaunchHistogram = true;
        requestAnimationFrame(() => {
            window.setTimeout(() => {
                performance.mark(histogramName);
                if (this.#panelChangedSinceLaunch) {
                    return;
                }
                InspectorFrontendHostInstance.recordPerformanceHistogram(histogramName, performance.now());
            }, 0);
        });
    }
    setLaunchPanel(panelName) {
        this.#launchPanelName = panelName;
    }
    performanceTraceLoad(measure) {
        InspectorFrontendHostInstance.recordPerformanceHistogram('DevTools.TraceLoad', measure.duration);
    }
    keybindSetSettingChanged(keybindSet) {
        const value = KeybindSetSettings[keybindSet] || 0;
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.KeybindSetSettingChanged" , value, KeybindSetSettings.MAX_VALUE);
    }
    keyboardShortcutFired(actionId) {
        const action = KeyboardShortcutAction[actionId] || KeyboardShortcutAction.OtherShortcut;
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.KeyboardShortcutFired" , action, KeyboardShortcutAction.MAX_VALUE);
    }
    issuesPanelOpenedFrom(issueOpener) {
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.IssuesPanelOpenedFrom" , issueOpener, 6 );
    }
    issuesPanelIssueExpanded(issueExpandedCategory) {
        if (issueExpandedCategory === undefined) {
            return;
        }
        const issueExpanded = IssueExpanded[issueExpandedCategory];
        if (issueExpanded === undefined) {
            return;
        }
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.IssuesPanelIssueExpanded" , issueExpanded, IssueExpanded.MAX_VALUE);
    }
    issuesPanelResourceOpened(issueCategory, type) {
        const key = issueCategory + type;
        const value = IssueResourceOpened[key];
        if (value === undefined) {
            return;
        }
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.IssuesPanelResourceOpened" , value, IssueResourceOpened.MAX_VALUE);
    }
    issueCreated(code) {
        const issueCreated = IssueCreated[code];
        if (issueCreated === undefined) {
            return;
        }
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.IssueCreated" , issueCreated, IssueCreated.MAX_VALUE);
    }
    experimentEnabledAtLaunch(experimentId) {
        const experiment = DevtoolsExperiments[experimentId];
        if (experiment === undefined) {
            return;
        }
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.ExperimentEnabledAtLaunch" , experiment, DevtoolsExperiments.MAX_VALUE);
    }
    navigationSettingAtFirstTimelineLoad(state) {
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.TimelineNavigationSettingState" , state, 4 );
    }
    experimentDisabledAtLaunch(experimentId) {
        const experiment = DevtoolsExperiments[experimentId];
        if (experiment === undefined) {
            return;
        }
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.ExperimentDisabledAtLaunch" , experiment, DevtoolsExperiments.MAX_VALUE);
    }
    experimentChanged(experimentId, isEnabled) {
        const experiment = DevtoolsExperiments[experimentId];
        if (experiment === undefined) {
            return;
        }
        const actionName = isEnabled ? "DevTools.ExperimentEnabled"  : "DevTools.ExperimentDisabled" ;
        InspectorFrontendHostInstance.recordEnumeratedHistogram(actionName, experiment, DevtoolsExperiments.MAX_VALUE);
    }
    developerResourceLoaded(developerResourceLoaded) {
        if (developerResourceLoaded >= 8 ) {
            return;
        }
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.DeveloperResourceLoaded" , developerResourceLoaded, 8 );
    }
    developerResourceScheme(developerResourceScheme) {
        if (developerResourceScheme >= 9 ) {
            return;
        }
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.DeveloperResourceScheme" , developerResourceScheme, 9 );
    }
    language(language) {
        const languageCode = Language[language];
        if (languageCode === undefined) {
            return;
        }
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.Language" , languageCode, Language.MAX_VALUE);
    }
    syncSetting(devtoolsSyncSettingEnabled) {
        InspectorFrontendHostInstance.getSyncInformation(syncInfo => {
            let settingValue = 1 ;
            if (syncInfo.isSyncActive && !syncInfo.arePreferencesSynced) {
                settingValue = 2 ;
            }
            else if (syncInfo.isSyncActive && syncInfo.arePreferencesSynced) {
                settingValue = devtoolsSyncSettingEnabled ? 4  :
                    3 ;
            }
            InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.SyncSetting" , settingValue, 5 );
        });
    }
    recordingToggled(value) {
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.RecordingToggled" , value, 3 );
    }
    recordingReplayFinished(value) {
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.RecordingReplayFinished" , value, 5 );
    }
    recordingReplayStarted(value) {
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.RecordingReplayStarted" , value, 4 );
    }
    lighthouseModeRun(type) {
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.LighthouseModeRun" , type, 4 );
    }
    lighthouseCategoryUsed(type) {
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.LighthouseCategoryUsed" , type, 6 );
    }
    swatchActivated(swatch) {
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.SwatchActivated" , swatch, 13 );
    }
    workspacesPopulated(wallClockTimeInMilliseconds) {
        InspectorFrontendHostInstance.recordPerformanceHistogram('DevTools.Workspaces.PopulateWallClocktime', wallClockTimeInMilliseconds);
    }
    visualLoggingProcessingDone(timeInMilliseconds) {
        InspectorFrontendHostInstance.recordPerformanceHistogram('DevTools.VisualLogging.ProcessingTime', timeInMilliseconds);
    }
    freestylerQueryLength(numberOfCharacters) {
        InspectorFrontendHostInstance.recordCountHistogram('DevTools.Freestyler.QueryLength', numberOfCharacters, 0, 100_000, 100);
    }
    freestylerEvalResponseSize(bytes) {
        InspectorFrontendHostInstance.recordCountHistogram('DevTools.Freestyler.EvalResponseSize', bytes, 0, 100_000, 100);
    }
    performanceAINetworkSummaryResponseSize(bytes) {
        InspectorFrontendHostInstance.recordCountHistogram('DevTools.PerformanceAI.NetworkSummaryResponseSize', bytes, 0, 100_000, 100);
    }
    performanceAINetworkRequestDetailResponseSize(bytes) {
        InspectorFrontendHostInstance.recordCountHistogram('DevTools.PerformanceAI.NetworkRequestDetailResponseSize', bytes, 0, 100_000, 100);
    }
    performanceAIMainThreadActivityResponseSize(bytes) {
        InspectorFrontendHostInstance.recordCountHistogram('DevTools.PerformanceAI.MainThreadActivityResponseSize', bytes, 0, 100_000, 100);
    }
    builtInAiAvailability(availability) {
        InspectorFrontendHostInstance.recordEnumeratedHistogram("DevTools.BuiltInAiAvailability" , availability, 10 );
    }
    consoleInsightTeaserGenerated(timeInMilliseconds) {
        InspectorFrontendHostInstance.recordPerformanceHistogram('DevTools.Insights.TeaserGenerationTime', timeInMilliseconds);
    }
    consoleInsightTeaserGeneratedMedium(timeInMilliseconds) {
        InspectorFrontendHostInstance.recordPerformanceHistogramMedium('DevTools.Insights.TeaserGenerationTimeMedium', timeInMilliseconds);
    }
    consoleInsightTeaserFirstChunkGenerated(timeInMilliseconds) {
        InspectorFrontendHostInstance.recordPerformanceHistogram('DevTools.Insights.TeaserFirstChunkGenerationTime', timeInMilliseconds);
    }
    consoleInsightTeaserFirstChunkGeneratedMedium(timeInMilliseconds) {
        InspectorFrontendHostInstance.recordPerformanceHistogramMedium('DevTools.Insights.TeaserFirstChunkGenerationTimeMedium', timeInMilliseconds);
    }
    consoleInsightTeaserChunkToEndMedium(timeInMilliseconds) {
        InspectorFrontendHostInstance.recordPerformanceHistogramMedium('DevTools.Insights.TeaserChunkToEndMedium', timeInMilliseconds);
    }
    consoleInsightTeaserAbortedAfterFirstCharacter(timeInMilliseconds) {
        InspectorFrontendHostInstance.recordPerformanceHistogram('DevTools.Insights.TeaserAfterFirstCharacterAbortionTime', timeInMilliseconds);
    }
    consoleInsightTeaserAbortedBeforeFirstCharacter(timeInMilliseconds) {
        InspectorFrontendHostInstance.recordPerformanceHistogram('DevTools.Insights.TeaserBeforeFirstCharacterAbortionTime', timeInMilliseconds);
    }
    consoleInsightLongTeaserGenerated(timeInMilliseconds) {
        InspectorFrontendHostInstance.recordPerformanceHistogram('DevTools.Insights.LongTeaserGenerationTime', timeInMilliseconds);
    }
    consoleInsightShortTeaserGenerated(timeInMilliseconds) {
        InspectorFrontendHostInstance.recordPerformanceHistogram('DevTools.Insights.ShortTeaserGenerationTime', timeInMilliseconds);
    }
}
var Action;
(function (Action) {
    Action[Action["WindowDocked"] = 1] = "WindowDocked";
    Action[Action["WindowUndocked"] = 2] = "WindowUndocked";
    Action[Action["ScriptsBreakpointSet"] = 3] = "ScriptsBreakpointSet";
    Action[Action["TimelineStarted"] = 4] = "TimelineStarted";
    Action[Action["ProfilesCPUProfileTaken"] = 5] = "ProfilesCPUProfileTaken";
    Action[Action["ProfilesHeapProfileTaken"] = 6] = "ProfilesHeapProfileTaken";
    Action[Action["ConsoleEvaluated"] = 8] = "ConsoleEvaluated";
    Action[Action["FileSavedInWorkspace"] = 9] = "FileSavedInWorkspace";
    Action[Action["DeviceModeEnabled"] = 10] = "DeviceModeEnabled";
    Action[Action["AnimationsPlaybackRateChanged"] = 11] = "AnimationsPlaybackRateChanged";
    Action[Action["RevisionApplied"] = 12] = "RevisionApplied";
    Action[Action["FileSystemDirectoryContentReceived"] = 13] = "FileSystemDirectoryContentReceived";
    Action[Action["StyleRuleEdited"] = 14] = "StyleRuleEdited";
    Action[Action["CommandEvaluatedInConsolePanel"] = 15] = "CommandEvaluatedInConsolePanel";
    Action[Action["DOMPropertiesExpanded"] = 16] = "DOMPropertiesExpanded";
    Action[Action["ResizedViewInResponsiveMode"] = 17] = "ResizedViewInResponsiveMode";
    Action[Action["TimelinePageReloadStarted"] = 18] = "TimelinePageReloadStarted";
    Action[Action["ConnectToNodeJSFromFrontend"] = 19] = "ConnectToNodeJSFromFrontend";
    Action[Action["ConnectToNodeJSDirectly"] = 20] = "ConnectToNodeJSDirectly";
    Action[Action["CpuThrottlingEnabled"] = 21] = "CpuThrottlingEnabled";
    Action[Action["CpuProfileNodeFocused"] = 22] = "CpuProfileNodeFocused";
    Action[Action["CpuProfileNodeExcluded"] = 23] = "CpuProfileNodeExcluded";
    Action[Action["SelectFileFromFilePicker"] = 24] = "SelectFileFromFilePicker";
    Action[Action["SelectCommandFromCommandMenu"] = 25] = "SelectCommandFromCommandMenu";
    Action[Action["ChangeInspectedNodeInElementsPanel"] = 26] = "ChangeInspectedNodeInElementsPanel";
    Action[Action["StyleRuleCopied"] = 27] = "StyleRuleCopied";
    Action[Action["CoverageStarted"] = 28] = "CoverageStarted";
    Action[Action["LighthouseStarted"] = 29] = "LighthouseStarted";
    Action[Action["LighthouseFinished"] = 30] = "LighthouseFinished";
    Action[Action["ShowedThirdPartyBadges"] = 31] = "ShowedThirdPartyBadges";
    Action[Action["LighthouseViewTrace"] = 32] = "LighthouseViewTrace";
    Action[Action["FilmStripStartedRecording"] = 33] = "FilmStripStartedRecording";
    Action[Action["CoverageReportFiltered"] = 34] = "CoverageReportFiltered";
    Action[Action["CoverageStartedPerBlock"] = 35] = "CoverageStartedPerBlock";
    Action[Action["SettingsOpenedFromGear-deprecated"] = 36] = "SettingsOpenedFromGear-deprecated";
    Action[Action["SettingsOpenedFromMenu-deprecated"] = 37] = "SettingsOpenedFromMenu-deprecated";
    Action[Action["SettingsOpenedFromCommandMenu-deprecated"] = 38] = "SettingsOpenedFromCommandMenu-deprecated";
    Action[Action["TabMovedToDrawer"] = 39] = "TabMovedToDrawer";
    Action[Action["TabMovedToMainPanel"] = 40] = "TabMovedToMainPanel";
    Action[Action["CaptureCssOverviewClicked"] = 41] = "CaptureCssOverviewClicked";
    Action[Action["VirtualAuthenticatorEnvironmentEnabled"] = 42] = "VirtualAuthenticatorEnvironmentEnabled";
    Action[Action["SourceOrderViewActivated"] = 43] = "SourceOrderViewActivated";
    Action[Action["UserShortcutAdded"] = 44] = "UserShortcutAdded";
    Action[Action["ShortcutRemoved"] = 45] = "ShortcutRemoved";
    Action[Action["ShortcutModified"] = 46] = "ShortcutModified";
    Action[Action["CustomPropertyLinkClicked"] = 47] = "CustomPropertyLinkClicked";
    Action[Action["CustomPropertyEdited"] = 48] = "CustomPropertyEdited";
    Action[Action["ServiceWorkerNetworkRequestClicked"] = 49] = "ServiceWorkerNetworkRequestClicked";
    Action[Action["ServiceWorkerNetworkRequestClosedQuickly"] = 50] = "ServiceWorkerNetworkRequestClosedQuickly";
    Action[Action["NetworkPanelServiceWorkerRespondWith"] = 51] = "NetworkPanelServiceWorkerRespondWith";
    Action[Action["NetworkPanelCopyValue"] = 52] = "NetworkPanelCopyValue";
    Action[Action["ConsoleSidebarOpened"] = 53] = "ConsoleSidebarOpened";
    Action[Action["PerfPanelTraceImported"] = 54] = "PerfPanelTraceImported";
    Action[Action["PerfPanelTraceExported"] = 55] = "PerfPanelTraceExported";
    Action[Action["StackFrameRestarted"] = 56] = "StackFrameRestarted";
    Action[Action["CaptureTestProtocolClicked"] = 57] = "CaptureTestProtocolClicked";
    Action[Action["BreakpointRemovedFromRemoveButton"] = 58] = "BreakpointRemovedFromRemoveButton";
    Action[Action["BreakpointGroupExpandedStateChanged"] = 59] = "BreakpointGroupExpandedStateChanged";
    Action[Action["HeaderOverrideFileCreated"] = 60] = "HeaderOverrideFileCreated";
    Action[Action["HeaderOverrideEnableEditingClicked"] = 61] = "HeaderOverrideEnableEditingClicked";
    Action[Action["HeaderOverrideHeaderAdded"] = 62] = "HeaderOverrideHeaderAdded";
    Action[Action["HeaderOverrideHeaderEdited"] = 63] = "HeaderOverrideHeaderEdited";
    Action[Action["HeaderOverrideHeaderRemoved"] = 64] = "HeaderOverrideHeaderRemoved";
    Action[Action["HeaderOverrideHeadersFileEdited"] = 65] = "HeaderOverrideHeadersFileEdited";
    Action[Action["PersistenceNetworkOverridesEnabled"] = 66] = "PersistenceNetworkOverridesEnabled";
    Action[Action["PersistenceNetworkOverridesDisabled"] = 67] = "PersistenceNetworkOverridesDisabled";
    Action[Action["BreakpointRemovedFromContextMenu"] = 68] = "BreakpointRemovedFromContextMenu";
    Action[Action["BreakpointsInFileRemovedFromRemoveButton"] = 69] = "BreakpointsInFileRemovedFromRemoveButton";
    Action[Action["BreakpointsInFileRemovedFromContextMenu"] = 70] = "BreakpointsInFileRemovedFromContextMenu";
    Action[Action["BreakpointsInFileCheckboxToggled"] = 71] = "BreakpointsInFileCheckboxToggled";
    Action[Action["BreakpointsInFileEnabledDisabledFromContextMenu"] = 72] = "BreakpointsInFileEnabledDisabledFromContextMenu";
    Action[Action["BreakpointConditionEditedFromSidebar"] = 73] = "BreakpointConditionEditedFromSidebar";
    Action[Action["WorkspaceTabAddFolder"] = 74] = "WorkspaceTabAddFolder";
    Action[Action["WorkspaceTabRemoveFolder"] = 75] = "WorkspaceTabRemoveFolder";
    Action[Action["OverrideTabAddFolder"] = 76] = "OverrideTabAddFolder";
    Action[Action["OverrideTabRemoveFolder"] = 77] = "OverrideTabRemoveFolder";
    Action[Action["WorkspaceSourceSelected"] = 78] = "WorkspaceSourceSelected";
    Action[Action["OverridesSourceSelected"] = 79] = "OverridesSourceSelected";
    Action[Action["StyleSheetInitiatorLinkClicked"] = 80] = "StyleSheetInitiatorLinkClicked";
    Action[Action["BreakpointRemovedFromGutterContextMenu"] = 81] = "BreakpointRemovedFromGutterContextMenu";
    Action[Action["BreakpointRemovedFromGutterToggle"] = 82] = "BreakpointRemovedFromGutterToggle";
    Action[Action["StylePropertyInsideKeyframeEdited"] = 83] = "StylePropertyInsideKeyframeEdited";
    Action[Action["OverrideContentFromSourcesContextMenu"] = 84] = "OverrideContentFromSourcesContextMenu";
    Action[Action["OverrideContentFromNetworkContextMenu"] = 85] = "OverrideContentFromNetworkContextMenu";
    Action[Action["OverrideScript"] = 86] = "OverrideScript";
    Action[Action["OverrideStyleSheet"] = 87] = "OverrideStyleSheet";
    Action[Action["OverrideDocument"] = 88] = "OverrideDocument";
    Action[Action["OverrideFetchXHR"] = 89] = "OverrideFetchXHR";
    Action[Action["OverrideImage"] = 90] = "OverrideImage";
    Action[Action["OverrideFont"] = 91] = "OverrideFont";
    Action[Action["OverrideContentContextMenuSetup"] = 92] = "OverrideContentContextMenuSetup";
    Action[Action["OverrideContentContextMenuAbandonSetup"] = 93] = "OverrideContentContextMenuAbandonSetup";
    Action[Action["OverrideContentContextMenuActivateDisabled"] = 94] = "OverrideContentContextMenuActivateDisabled";
    Action[Action["OverrideContentContextMenuOpenExistingFile"] = 95] = "OverrideContentContextMenuOpenExistingFile";
    Action[Action["OverrideContentContextMenuSaveNewFile"] = 96] = "OverrideContentContextMenuSaveNewFile";
    Action[Action["ShowAllOverridesFromSourcesContextMenu"] = 97] = "ShowAllOverridesFromSourcesContextMenu";
    Action[Action["ShowAllOverridesFromNetworkContextMenu"] = 98] = "ShowAllOverridesFromNetworkContextMenu";
    Action[Action["AnimationGroupsCleared"] = 99] = "AnimationGroupsCleared";
    Action[Action["AnimationsPaused"] = 100] = "AnimationsPaused";
    Action[Action["AnimationsResumed"] = 101] = "AnimationsResumed";
    Action[Action["AnimatedNodeDescriptionClicked"] = 102] = "AnimatedNodeDescriptionClicked";
    Action[Action["AnimationGroupScrubbed"] = 103] = "AnimationGroupScrubbed";
    Action[Action["AnimationGroupReplayed"] = 104] = "AnimationGroupReplayed";
    Action[Action["OverrideTabDeleteFolderContextMenu"] = 105] = "OverrideTabDeleteFolderContextMenu";
    Action[Action["WorkspaceDropFolder"] = 107] = "WorkspaceDropFolder";
    Action[Action["WorkspaceSelectFolder"] = 108] = "WorkspaceSelectFolder";
    Action[Action["OverrideContentContextMenuSourceMappedWarning"] = 109] = "OverrideContentContextMenuSourceMappedWarning";
    Action[Action["OverrideContentContextMenuRedirectToDeployed"] = 110] = "OverrideContentContextMenuRedirectToDeployed";
    Action[Action["NewStyleRuleAdded"] = 111] = "NewStyleRuleAdded";
    Action[Action["TraceExpanded"] = 112] = "TraceExpanded";
    Action[Action["InsightConsoleMessageShown"] = 113] = "InsightConsoleMessageShown";
    Action[Action["InsightRequestedViaContextMenu"] = 114] = "InsightRequestedViaContextMenu";
    Action[Action["InsightRequestedViaHoverButton"] = 115] = "InsightRequestedViaHoverButton";
    Action[Action["InsightRatedPositive"] = 117] = "InsightRatedPositive";
    Action[Action["InsightRatedNegative"] = 118] = "InsightRatedNegative";
    Action[Action["InsightClosed"] = 119] = "InsightClosed";
    Action[Action["InsightErrored"] = 120] = "InsightErrored";
    Action[Action["InsightHoverButtonShown"] = 121] = "InsightHoverButtonShown";
    Action[Action["SelfXssWarningConsoleMessageShown"] = 122] = "SelfXssWarningConsoleMessageShown";
    Action[Action["SelfXssWarningDialogShown"] = 123] = "SelfXssWarningDialogShown";
    Action[Action["SelfXssAllowPastingInConsole"] = 124] = "SelfXssAllowPastingInConsole";
    Action[Action["SelfXssAllowPastingInDialog"] = 125] = "SelfXssAllowPastingInDialog";
    Action[Action["ToggleEmulateFocusedPageFromStylesPaneOn"] = 126] = "ToggleEmulateFocusedPageFromStylesPaneOn";
    Action[Action["ToggleEmulateFocusedPageFromStylesPaneOff"] = 127] = "ToggleEmulateFocusedPageFromStylesPaneOff";
    Action[Action["ToggleEmulateFocusedPageFromRenderingTab"] = 128] = "ToggleEmulateFocusedPageFromRenderingTab";
    Action[Action["ToggleEmulateFocusedPageFromCommandMenu"] = 129] = "ToggleEmulateFocusedPageFromCommandMenu";
    Action[Action["InsightGenerated"] = 130] = "InsightGenerated";
    Action[Action["InsightErroredApi"] = 131] = "InsightErroredApi";
    Action[Action["InsightErroredMarkdown"] = 132] = "InsightErroredMarkdown";
    Action[Action["ToggleShowWebVitals"] = 133] = "ToggleShowWebVitals";
    Action[Action["InsightErroredPermissionDenied"] = 134] = "InsightErroredPermissionDenied";
    Action[Action["InsightErroredCannotSend"] = 135] = "InsightErroredCannotSend";
    Action[Action["InsightErroredRequestFailed"] = 136] = "InsightErroredRequestFailed";
    Action[Action["InsightErroredCannotParseChunk"] = 137] = "InsightErroredCannotParseChunk";
    Action[Action["InsightErroredUnknownChunk"] = 138] = "InsightErroredUnknownChunk";
    Action[Action["InsightErroredOther"] = 139] = "InsightErroredOther";
    Action[Action["AutofillReceived"] = 140] = "AutofillReceived";
    Action[Action["AutofillReceivedAndTabAutoOpened"] = 141] = "AutofillReceivedAndTabAutoOpened";
    Action[Action["AnimationGroupSelected"] = 142] = "AnimationGroupSelected";
    Action[Action["ScrollDrivenAnimationGroupSelected"] = 143] = "ScrollDrivenAnimationGroupSelected";
    Action[Action["ScrollDrivenAnimationGroupScrubbed"] = 144] = "ScrollDrivenAnimationGroupScrubbed";
    Action[Action["AiAssistanceOpenedFromElementsPanel"] = 145] = "AiAssistanceOpenedFromElementsPanel";
    Action[Action["AiAssistanceOpenedFromStylesTab"] = 146] = "AiAssistanceOpenedFromStylesTab";
    Action[Action["ConsoleFilterByContext"] = 147] = "ConsoleFilterByContext";
    Action[Action["ConsoleFilterBySource"] = 148] = "ConsoleFilterBySource";
    Action[Action["ConsoleFilterByUrl"] = 149] = "ConsoleFilterByUrl";
    Action[Action["InsightConsentReminderShown"] = 150] = "InsightConsentReminderShown";
    Action[Action["InsightConsentReminderCanceled"] = 151] = "InsightConsentReminderCanceled";
    Action[Action["InsightConsentReminderConfirmed"] = 152] = "InsightConsentReminderConfirmed";
    Action[Action["InsightsOnboardingShown"] = 153] = "InsightsOnboardingShown";
    Action[Action["InsightsOnboardingCanceledOnPage1"] = 154] = "InsightsOnboardingCanceledOnPage1";
    Action[Action["InsightsOnboardingCanceledOnPage2"] = 155] = "InsightsOnboardingCanceledOnPage2";
    Action[Action["InsightsOnboardingConfirmed"] = 156] = "InsightsOnboardingConfirmed";
    Action[Action["InsightsOnboardingNextPage"] = 157] = "InsightsOnboardingNextPage";
    Action[Action["InsightsOnboardingPrevPage"] = 158] = "InsightsOnboardingPrevPage";
    Action[Action["InsightsOnboardingFeatureDisabled"] = 159] = "InsightsOnboardingFeatureDisabled";
    Action[Action["InsightsOptInTeaserShown"] = 160] = "InsightsOptInTeaserShown";
    Action[Action["InsightsOptInTeaserSettingsLinkClicked"] = 161] = "InsightsOptInTeaserSettingsLinkClicked";
    Action[Action["InsightsOptInTeaserConfirmedInSettings"] = 162] = "InsightsOptInTeaserConfirmedInSettings";
    Action[Action["InsightsReminderTeaserShown"] = 163] = "InsightsReminderTeaserShown";
    Action[Action["InsightsReminderTeaserConfirmed"] = 164] = "InsightsReminderTeaserConfirmed";
    Action[Action["InsightsReminderTeaserCanceled"] = 165] = "InsightsReminderTeaserCanceled";
    Action[Action["InsightsReminderTeaserSettingsLinkClicked"] = 166] = "InsightsReminderTeaserSettingsLinkClicked";
    Action[Action["InsightsReminderTeaserAbortedInSettings"] = 167] = "InsightsReminderTeaserAbortedInSettings";
    Action[Action["GeneratingInsightWithoutDisclaimer"] = 168] = "GeneratingInsightWithoutDisclaimer";
    Action[Action["AiAssistanceOpenedFromElementsPanelFloatingButton"] = 169] = "AiAssistanceOpenedFromElementsPanelFloatingButton";
    Action[Action["AiAssistanceOpenedFromNetworkPanel"] = 170] = "AiAssistanceOpenedFromNetworkPanel";
    Action[Action["AiAssistanceOpenedFromSourcesPanel"] = 171] = "AiAssistanceOpenedFromSourcesPanel";
    Action[Action["AiAssistanceOpenedFromSourcesPanelFloatingButton"] = 172] = "AiAssistanceOpenedFromSourcesPanelFloatingButton";
    Action[Action["AiAssistanceOpenedFromPerformancePanelCallTree"] = 173] = "AiAssistanceOpenedFromPerformancePanelCallTree";
    Action[Action["AiAssistanceOpenedFromNetworkPanelFloatingButton"] = 174] = "AiAssistanceOpenedFromNetworkPanelFloatingButton";
    Action[Action["AiAssistancePanelOpened"] = 175] = "AiAssistancePanelOpened";
    Action[Action["AiAssistanceQuerySubmitted"] = 176] = "AiAssistanceQuerySubmitted";
    Action[Action["AiAssistanceAnswerReceived"] = 177] = "AiAssistanceAnswerReceived";
    Action[Action["AiAssistanceDynamicSuggestionClicked"] = 178] = "AiAssistanceDynamicSuggestionClicked";
    Action[Action["AiAssistanceSideEffectConfirmed"] = 179] = "AiAssistanceSideEffectConfirmed";
    Action[Action["AiAssistanceSideEffectRejected"] = 180] = "AiAssistanceSideEffectRejected";
    Action[Action["AiAssistanceError"] = 181] = "AiAssistanceError";
    Action[Action["AiCodeCompletionResponseServedFromCache"] = 184] = "AiCodeCompletionResponseServedFromCache";
    Action[Action["AiCodeCompletionRequestTriggered"] = 185] = "AiCodeCompletionRequestTriggered";
    Action[Action["AiCodeCompletionSuggestionDisplayed"] = 186] = "AiCodeCompletionSuggestionDisplayed";
    Action[Action["AiCodeCompletionSuggestionAccepted"] = 187] = "AiCodeCompletionSuggestionAccepted";
    Action[Action["AiCodeCompletionError"] = 188] = "AiCodeCompletionError";
    Action[Action["AttributeLinkClicked"] = 189] = "AttributeLinkClicked";
    Action[Action["InsightRequestedViaTeaser"] = 190] = "InsightRequestedViaTeaser";
    Action[Action["InsightTeaserGenerationStarted"] = 191] = "InsightTeaserGenerationStarted";
    Action[Action["InsightTeaserGenerationCompleted"] = 192] = "InsightTeaserGenerationCompleted";
    Action[Action["InsightTeaserGenerationAborted"] = 193] = "InsightTeaserGenerationAborted";
    Action[Action["InsightTeaserGenerationErrored"] = 194] = "InsightTeaserGenerationErrored";
    Action[Action["AiCodeGenerationSuggestionDisplayed"] = 195] = "AiCodeGenerationSuggestionDisplayed";
    Action[Action["AiCodeGenerationSuggestionAccepted"] = 196] = "AiCodeGenerationSuggestionAccepted";
    Action[Action["InsightTeaserModelDownloadStarted"] = 197] = "InsightTeaserModelDownloadStarted";
    Action[Action["InsightTeaserModelDownloadCompleted"] = 198] = "InsightTeaserModelDownloadCompleted";
    Action[Action["AiCodeGenerationError"] = 199] = "AiCodeGenerationError";
    Action[Action["AiCodeGenerationRequestTriggered"] = 200] = "AiCodeGenerationRequestTriggered";
    Action[Action["MAX_VALUE"] = 201] = "MAX_VALUE";
})(Action || (Action = {}));
var PanelCodes;
(function (PanelCodes) {
    PanelCodes[PanelCodes["elements"] = 1] = "elements";
    PanelCodes[PanelCodes["resources"] = 2] = "resources";
    PanelCodes[PanelCodes["network"] = 3] = "network";
    PanelCodes[PanelCodes["sources"] = 4] = "sources";
    PanelCodes[PanelCodes["timeline"] = 5] = "timeline";
    PanelCodes[PanelCodes["heap-profiler"] = 6] = "heap-profiler";
    PanelCodes[PanelCodes["console"] = 8] = "console";
    PanelCodes[PanelCodes["layers"] = 9] = "layers";
    PanelCodes[PanelCodes["console-view"] = 10] = "console-view";
    PanelCodes[PanelCodes["animations"] = 11] = "animations";
    PanelCodes[PanelCodes["network.config"] = 12] = "network.config";
    PanelCodes[PanelCodes["rendering"] = 13] = "rendering";
    PanelCodes[PanelCodes["sensors"] = 14] = "sensors";
    PanelCodes[PanelCodes["sources.search"] = 15] = "sources.search";
    PanelCodes[PanelCodes["security"] = 16] = "security";
    PanelCodes[PanelCodes["js-profiler"] = 17] = "js-profiler";
    PanelCodes[PanelCodes["lighthouse"] = 18] = "lighthouse";
    PanelCodes[PanelCodes["coverage"] = 19] = "coverage";
    PanelCodes[PanelCodes["protocol-monitor"] = 20] = "protocol-monitor";
    PanelCodes[PanelCodes["remote-devices"] = 21] = "remote-devices";
    PanelCodes[PanelCodes["web-audio"] = 22] = "web-audio";
    PanelCodes[PanelCodes["changes.changes"] = 23] = "changes.changes";
    PanelCodes[PanelCodes["performance.monitor"] = 24] = "performance.monitor";
    PanelCodes[PanelCodes["release-note"] = 25] = "release-note";
    PanelCodes[PanelCodes["live-heap-profile"] = 26] = "live-heap-profile";
    PanelCodes[PanelCodes["sources.quick"] = 27] = "sources.quick";
    PanelCodes[PanelCodes["network.blocked-urls"] = 28] = "network.blocked-urls";
    PanelCodes[PanelCodes["settings-preferences"] = 29] = "settings-preferences";
    PanelCodes[PanelCodes["settings-workspace"] = 30] = "settings-workspace";
    PanelCodes[PanelCodes["settings-experiments"] = 31] = "settings-experiments";
    PanelCodes[PanelCodes["settings-blackbox"] = 32] = "settings-blackbox";
    PanelCodes[PanelCodes["settings-devices"] = 33] = "settings-devices";
    PanelCodes[PanelCodes["settings-throttling-conditions"] = 34] = "settings-throttling-conditions";
    PanelCodes[PanelCodes["settings-emulation-locations"] = 35] = "settings-emulation-locations";
    PanelCodes[PanelCodes["settings-shortcuts"] = 36] = "settings-shortcuts";
    PanelCodes[PanelCodes["issues-pane"] = 37] = "issues-pane";
    PanelCodes[PanelCodes["settings-keybinds"] = 38] = "settings-keybinds";
    PanelCodes[PanelCodes["cssoverview"] = 39] = "cssoverview";
    PanelCodes[PanelCodes["chrome-recorder"] = 40] = "chrome-recorder";
    PanelCodes[PanelCodes["trust-tokens"] = 41] = "trust-tokens";
    PanelCodes[PanelCodes["reporting-api"] = 42] = "reporting-api";
    PanelCodes[PanelCodes["interest-groups"] = 43] = "interest-groups";
    PanelCodes[PanelCodes["back-forward-cache"] = 44] = "back-forward-cache";
    PanelCodes[PanelCodes["service-worker-cache"] = 45] = "service-worker-cache";
    PanelCodes[PanelCodes["background-service-background-fetch"] = 46] = "background-service-background-fetch";
    PanelCodes[PanelCodes["background-service-background-sync"] = 47] = "background-service-background-sync";
    PanelCodes[PanelCodes["background-service-push-messaging"] = 48] = "background-service-push-messaging";
    PanelCodes[PanelCodes["background-service-notifications"] = 49] = "background-service-notifications";
    PanelCodes[PanelCodes["background-service-payment-handler"] = 50] = "background-service-payment-handler";
    PanelCodes[PanelCodes["background-service-periodic-background-sync"] = 51] = "background-service-periodic-background-sync";
    PanelCodes[PanelCodes["service-workers"] = 52] = "service-workers";
    PanelCodes[PanelCodes["app-manifest"] = 53] = "app-manifest";
    PanelCodes[PanelCodes["storage"] = 54] = "storage";
    PanelCodes[PanelCodes["cookies"] = 55] = "cookies";
    PanelCodes[PanelCodes["frame-details"] = 56] = "frame-details";
    PanelCodes[PanelCodes["frame-resource"] = 57] = "frame-resource";
    PanelCodes[PanelCodes["frame-window"] = 58] = "frame-window";
    PanelCodes[PanelCodes["frame-worker"] = 59] = "frame-worker";
    PanelCodes[PanelCodes["dom-storage"] = 60] = "dom-storage";
    PanelCodes[PanelCodes["indexed-db"] = 61] = "indexed-db";
    PanelCodes[PanelCodes["web-sql"] = 62] = "web-sql";
    PanelCodes[PanelCodes["performance-insights"] = 63] = "performance-insights";
    PanelCodes[PanelCodes["preloading"] = 64] = "preloading";
    PanelCodes[PanelCodes["bounce-tracking-mitigations"] = 65] = "bounce-tracking-mitigations";
    PanelCodes[PanelCodes["developer-resources"] = 66] = "developer-resources";
    PanelCodes[PanelCodes["autofill-view"] = 67] = "autofill-view";
    PanelCodes[PanelCodes["freestyler"] = 68] = "freestyler";
    PanelCodes[PanelCodes["MAX_VALUE"] = 69] = "MAX_VALUE";
})(PanelCodes || (PanelCodes = {}));
var MediaTypes;
(function (MediaTypes) {
    MediaTypes[MediaTypes["Unknown"] = 0] = "Unknown";
    MediaTypes[MediaTypes["text/css"] = 2] = "text/css";
    MediaTypes[MediaTypes["text/html"] = 3] = "text/html";
    MediaTypes[MediaTypes["application/xml"] = 4] = "application/xml";
    MediaTypes[MediaTypes["application/wasm"] = 5] = "application/wasm";
    MediaTypes[MediaTypes["application/manifest+json"] = 6] = "application/manifest+json";
    MediaTypes[MediaTypes["application/x-aspx"] = 7] = "application/x-aspx";
    MediaTypes[MediaTypes["application/jsp"] = 8] = "application/jsp";
    MediaTypes[MediaTypes["text/x-c++src"] = 9] = "text/x-c++src";
    MediaTypes[MediaTypes["text/x-coffeescript"] = 10] = "text/x-coffeescript";
    MediaTypes[MediaTypes["application/vnd.dart"] = 11] = "application/vnd.dart";
    MediaTypes[MediaTypes["text/typescript"] = 12] = "text/typescript";
    MediaTypes[MediaTypes["text/typescript-jsx"] = 13] = "text/typescript-jsx";
    MediaTypes[MediaTypes["application/json"] = 14] = "application/json";
    MediaTypes[MediaTypes["text/x-csharp"] = 15] = "text/x-csharp";
    MediaTypes[MediaTypes["text/x-java"] = 16] = "text/x-java";
    MediaTypes[MediaTypes["text/x-less"] = 17] = "text/x-less";
    MediaTypes[MediaTypes["application/x-httpd-php"] = 18] = "application/x-httpd-php";
    MediaTypes[MediaTypes["text/x-python"] = 19] = "text/x-python";
    MediaTypes[MediaTypes["text/x-sh"] = 20] = "text/x-sh";
    MediaTypes[MediaTypes["text/x-gss"] = 21] = "text/x-gss";
    MediaTypes[MediaTypes["text/x-sass"] = 22] = "text/x-sass";
    MediaTypes[MediaTypes["text/x-scss"] = 23] = "text/x-scss";
    MediaTypes[MediaTypes["text/markdown"] = 24] = "text/markdown";
    MediaTypes[MediaTypes["text/x-clojure"] = 25] = "text/x-clojure";
    MediaTypes[MediaTypes["text/jsx"] = 26] = "text/jsx";
    MediaTypes[MediaTypes["text/x-go"] = 27] = "text/x-go";
    MediaTypes[MediaTypes["text/x-kotlin"] = 28] = "text/x-kotlin";
    MediaTypes[MediaTypes["text/x-scala"] = 29] = "text/x-scala";
    MediaTypes[MediaTypes["text/x.svelte"] = 30] = "text/x.svelte";
    MediaTypes[MediaTypes["text/javascript+plain"] = 31] = "text/javascript+plain";
    MediaTypes[MediaTypes["text/javascript+minified"] = 32] = "text/javascript+minified";
    MediaTypes[MediaTypes["text/javascript+sourcemapped"] = 33] = "text/javascript+sourcemapped";
    MediaTypes[MediaTypes["text/x.angular"] = 34] = "text/x.angular";
    MediaTypes[MediaTypes["text/x.vue"] = 35] = "text/x.vue";
    MediaTypes[MediaTypes["text/javascript+snippet"] = 36] = "text/javascript+snippet";
    MediaTypes[MediaTypes["text/javascript+eval"] = 37] = "text/javascript+eval";
    MediaTypes[MediaTypes["MAX_VALUE"] = 38] = "MAX_VALUE";
})(MediaTypes || (MediaTypes = {}));
var KeybindSetSettings;
(function (KeybindSetSettings) {
    KeybindSetSettings[KeybindSetSettings["devToolsDefault"] = 0] = "devToolsDefault";
    KeybindSetSettings[KeybindSetSettings["vsCode"] = 1] = "vsCode";
    KeybindSetSettings[KeybindSetSettings["MAX_VALUE"] = 2] = "MAX_VALUE";
})(KeybindSetSettings || (KeybindSetSettings = {}));
var KeyboardShortcutAction;
(function (KeyboardShortcutAction) {
    KeyboardShortcutAction[KeyboardShortcutAction["OtherShortcut"] = 0] = "OtherShortcut";
    KeyboardShortcutAction[KeyboardShortcutAction["quick-open.show-command-menu"] = 1] = "quick-open.show-command-menu";
    KeyboardShortcutAction[KeyboardShortcutAction["console.clear"] = 2] = "console.clear";
    KeyboardShortcutAction[KeyboardShortcutAction["console.toggle"] = 3] = "console.toggle";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.step"] = 4] = "debugger.step";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.step-into"] = 5] = "debugger.step-into";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.step-out"] = 6] = "debugger.step-out";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.step-over"] = 7] = "debugger.step-over";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.toggle-breakpoint"] = 8] = "debugger.toggle-breakpoint";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.toggle-breakpoint-enabled"] = 9] = "debugger.toggle-breakpoint-enabled";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.toggle-pause"] = 10] = "debugger.toggle-pause";
    KeyboardShortcutAction[KeyboardShortcutAction["elements.edit-as-html"] = 11] = "elements.edit-as-html";
    KeyboardShortcutAction[KeyboardShortcutAction["elements.hide-element"] = 12] = "elements.hide-element";
    KeyboardShortcutAction[KeyboardShortcutAction["elements.redo"] = 13] = "elements.redo";
    KeyboardShortcutAction[KeyboardShortcutAction["elements.toggle-element-search"] = 14] = "elements.toggle-element-search";
    KeyboardShortcutAction[KeyboardShortcutAction["elements.undo"] = 15] = "elements.undo";
    KeyboardShortcutAction[KeyboardShortcutAction["main.search-in-panel.find"] = 16] = "main.search-in-panel.find";
    KeyboardShortcutAction[KeyboardShortcutAction["main.toggle-drawer"] = 17] = "main.toggle-drawer";
    KeyboardShortcutAction[KeyboardShortcutAction["network.hide-request-details"] = 18] = "network.hide-request-details";
    KeyboardShortcutAction[KeyboardShortcutAction["network.search"] = 19] = "network.search";
    KeyboardShortcutAction[KeyboardShortcutAction["network.toggle-recording"] = 20] = "network.toggle-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["quick-open.show"] = 21] = "quick-open.show";
    KeyboardShortcutAction[KeyboardShortcutAction["settings.show"] = 22] = "settings.show";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.search"] = 23] = "sources.search";
    KeyboardShortcutAction[KeyboardShortcutAction["background-service.toggle-recording"] = 24] = "background-service.toggle-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["components.collect-garbage"] = 25] = "components.collect-garbage";
    KeyboardShortcutAction[KeyboardShortcutAction["console.clear.history"] = 26] = "console.clear.history";
    KeyboardShortcutAction[KeyboardShortcutAction["console.create-pin"] = 27] = "console.create-pin";
    KeyboardShortcutAction[KeyboardShortcutAction["coverage.start-with-reload"] = 28] = "coverage.start-with-reload";
    KeyboardShortcutAction[KeyboardShortcutAction["coverage.toggle-recording"] = 29] = "coverage.toggle-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.breakpoint-input-window"] = 30] = "debugger.breakpoint-input-window";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.evaluate-selection"] = 31] = "debugger.evaluate-selection";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.next-call-frame"] = 32] = "debugger.next-call-frame";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.previous-call-frame"] = 33] = "debugger.previous-call-frame";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.run-snippet"] = 34] = "debugger.run-snippet";
    KeyboardShortcutAction[KeyboardShortcutAction["debugger.toggle-breakpoints-active"] = 35] = "debugger.toggle-breakpoints-active";
    KeyboardShortcutAction[KeyboardShortcutAction["elements.capture-area-screenshot"] = 36] = "elements.capture-area-screenshot";
    KeyboardShortcutAction[KeyboardShortcutAction["emulation.capture-full-height-screenshot"] = 37] = "emulation.capture-full-height-screenshot";
    KeyboardShortcutAction[KeyboardShortcutAction["emulation.capture-node-screenshot"] = 38] = "emulation.capture-node-screenshot";
    KeyboardShortcutAction[KeyboardShortcutAction["emulation.capture-screenshot"] = 39] = "emulation.capture-screenshot";
    KeyboardShortcutAction[KeyboardShortcutAction["emulation.show-sensors"] = 40] = "emulation.show-sensors";
    KeyboardShortcutAction[KeyboardShortcutAction["emulation.toggle-device-mode"] = 41] = "emulation.toggle-device-mode";
    KeyboardShortcutAction[KeyboardShortcutAction["help.release-notes"] = 42] = "help.release-notes";
    KeyboardShortcutAction[KeyboardShortcutAction["help.report-issue"] = 43] = "help.report-issue";
    KeyboardShortcutAction[KeyboardShortcutAction["input.start-replaying"] = 44] = "input.start-replaying";
    KeyboardShortcutAction[KeyboardShortcutAction["input.toggle-pause"] = 45] = "input.toggle-pause";
    KeyboardShortcutAction[KeyboardShortcutAction["input.toggle-recording"] = 46] = "input.toggle-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["inspector-main.focus-debuggee"] = 47] = "inspector-main.focus-debuggee";
    KeyboardShortcutAction[KeyboardShortcutAction["inspector-main.hard-reload"] = 48] = "inspector-main.hard-reload";
    KeyboardShortcutAction[KeyboardShortcutAction["inspector-main.reload"] = 49] = "inspector-main.reload";
    KeyboardShortcutAction[KeyboardShortcutAction["live-heap-profile.start-with-reload"] = 50] = "live-heap-profile.start-with-reload";
    KeyboardShortcutAction[KeyboardShortcutAction["live-heap-profile.toggle-recording"] = 51] = "live-heap-profile.toggle-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["main.debug-reload"] = 52] = "main.debug-reload";
    KeyboardShortcutAction[KeyboardShortcutAction["main.next-tab"] = 53] = "main.next-tab";
    KeyboardShortcutAction[KeyboardShortcutAction["main.previous-tab"] = 54] = "main.previous-tab";
    KeyboardShortcutAction[KeyboardShortcutAction["main.search-in-panel.cancel"] = 55] = "main.search-in-panel.cancel";
    KeyboardShortcutAction[KeyboardShortcutAction["main.search-in-panel.find-next"] = 56] = "main.search-in-panel.find-next";
    KeyboardShortcutAction[KeyboardShortcutAction["main.search-in-panel.find-previous"] = 57] = "main.search-in-panel.find-previous";
    KeyboardShortcutAction[KeyboardShortcutAction["main.toggle-dock"] = 58] = "main.toggle-dock";
    KeyboardShortcutAction[KeyboardShortcutAction["main.zoom-in"] = 59] = "main.zoom-in";
    KeyboardShortcutAction[KeyboardShortcutAction["main.zoom-out"] = 60] = "main.zoom-out";
    KeyboardShortcutAction[KeyboardShortcutAction["main.zoom-reset"] = 61] = "main.zoom-reset";
    KeyboardShortcutAction[KeyboardShortcutAction["network-conditions.network-low-end-mobile"] = 62] = "network-conditions.network-low-end-mobile";
    KeyboardShortcutAction[KeyboardShortcutAction["network-conditions.network-mid-tier-mobile"] = 63] = "network-conditions.network-mid-tier-mobile";
    KeyboardShortcutAction[KeyboardShortcutAction["network-conditions.network-offline"] = 64] = "network-conditions.network-offline";
    KeyboardShortcutAction[KeyboardShortcutAction["network-conditions.network-online"] = 65] = "network-conditions.network-online";
    KeyboardShortcutAction[KeyboardShortcutAction["profiler.heap-toggle-recording"] = 66] = "profiler.heap-toggle-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["profiler.js-toggle-recording"] = 67] = "profiler.js-toggle-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["resources.clear"] = 68] = "resources.clear";
    KeyboardShortcutAction[KeyboardShortcutAction["settings.documentation"] = 69] = "settings.documentation";
    KeyboardShortcutAction[KeyboardShortcutAction["settings.shortcuts"] = 70] = "settings.shortcuts";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.add-folder-to-workspace"] = 71] = "sources.add-folder-to-workspace";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.add-to-watch"] = 72] = "sources.add-to-watch";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.close-all"] = 73] = "sources.close-all";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.close-editor-tab"] = 74] = "sources.close-editor-tab";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.create-snippet"] = 75] = "sources.create-snippet";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.go-to-line"] = 76] = "sources.go-to-line";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.go-to-member"] = 77] = "sources.go-to-member";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.jump-to-next-location"] = 78] = "sources.jump-to-next-location";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.jump-to-previous-location"] = 79] = "sources.jump-to-previous-location";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.rename"] = 80] = "sources.rename";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.save"] = 81] = "sources.save";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.save-all"] = 82] = "sources.save-all";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.switch-file"] = 83] = "sources.switch-file";
    KeyboardShortcutAction[KeyboardShortcutAction["timeline.jump-to-next-frame"] = 84] = "timeline.jump-to-next-frame";
    KeyboardShortcutAction[KeyboardShortcutAction["timeline.jump-to-previous-frame"] = 85] = "timeline.jump-to-previous-frame";
    KeyboardShortcutAction[KeyboardShortcutAction["timeline.load-from-file"] = 86] = "timeline.load-from-file";
    KeyboardShortcutAction[KeyboardShortcutAction["timeline.next-recording"] = 87] = "timeline.next-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["timeline.previous-recording"] = 88] = "timeline.previous-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["timeline.record-reload"] = 89] = "timeline.record-reload";
    KeyboardShortcutAction[KeyboardShortcutAction["timeline.save-to-file"] = 90] = "timeline.save-to-file";
    KeyboardShortcutAction[KeyboardShortcutAction["timeline.show-history"] = 91] = "timeline.show-history";
    KeyboardShortcutAction[KeyboardShortcutAction["timeline.toggle-recording"] = 92] = "timeline.toggle-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.increment-css"] = 93] = "sources.increment-css";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.increment-css-by-ten"] = 94] = "sources.increment-css-by-ten";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.decrement-css"] = 95] = "sources.decrement-css";
    KeyboardShortcutAction[KeyboardShortcutAction["sources.decrement-css-by-ten"] = 96] = "sources.decrement-css-by-ten";
    KeyboardShortcutAction[KeyboardShortcutAction["layers.reset-view"] = 97] = "layers.reset-view";
    KeyboardShortcutAction[KeyboardShortcutAction["layers.pan-mode"] = 98] = "layers.pan-mode";
    KeyboardShortcutAction[KeyboardShortcutAction["layers.rotate-mode"] = 99] = "layers.rotate-mode";
    KeyboardShortcutAction[KeyboardShortcutAction["layers.zoom-in"] = 100] = "layers.zoom-in";
    KeyboardShortcutAction[KeyboardShortcutAction["layers.zoom-out"] = 101] = "layers.zoom-out";
    KeyboardShortcutAction[KeyboardShortcutAction["layers.up"] = 102] = "layers.up";
    KeyboardShortcutAction[KeyboardShortcutAction["layers.down"] = 103] = "layers.down";
    KeyboardShortcutAction[KeyboardShortcutAction["layers.left"] = 104] = "layers.left";
    KeyboardShortcutAction[KeyboardShortcutAction["layers.right"] = 105] = "layers.right";
    KeyboardShortcutAction[KeyboardShortcutAction["help.report-translation-issue"] = 106] = "help.report-translation-issue";
    KeyboardShortcutAction[KeyboardShortcutAction["rendering.toggle-prefers-color-scheme"] = 107] = "rendering.toggle-prefers-color-scheme";
    KeyboardShortcutAction[KeyboardShortcutAction["chrome-recorder.start-recording"] = 108] = "chrome-recorder.start-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["chrome-recorder.replay-recording"] = 109] = "chrome-recorder.replay-recording";
    KeyboardShortcutAction[KeyboardShortcutAction["chrome-recorder.toggle-code-view"] = 110] = "chrome-recorder.toggle-code-view";
    KeyboardShortcutAction[KeyboardShortcutAction["chrome-recorder.copy-recording-or-step"] = 111] = "chrome-recorder.copy-recording-or-step";
    KeyboardShortcutAction[KeyboardShortcutAction["elements.new-style-rule"] = 114] = "elements.new-style-rule";
    KeyboardShortcutAction[KeyboardShortcutAction["elements.refresh-event-listeners"] = 115] = "elements.refresh-event-listeners";
    KeyboardShortcutAction[KeyboardShortcutAction["coverage.clear"] = 116] = "coverage.clear";
    KeyboardShortcutAction[KeyboardShortcutAction["coverage.export"] = 117] = "coverage.export";
    KeyboardShortcutAction[KeyboardShortcutAction["timeline.dim-third-parties"] = 118] = "timeline.dim-third-parties";
    KeyboardShortcutAction[KeyboardShortcutAction["main.toggle-drawer-orientation"] = 119] = "main.toggle-drawer-orientation";
    KeyboardShortcutAction[KeyboardShortcutAction["MAX_VALUE"] = 120] = "MAX_VALUE";
})(KeyboardShortcutAction || (KeyboardShortcutAction = {}));
var DevtoolsExperiments;
(function (DevtoolsExperiments) {
    DevtoolsExperiments[DevtoolsExperiments["capture-node-creation-stacks"] = 1] = "capture-node-creation-stacks";
    DevtoolsExperiments[DevtoolsExperiments["live-heap-profile"] = 11] = "live-heap-profile";
    DevtoolsExperiments[DevtoolsExperiments["protocol-monitor"] = 13] = "protocol-monitor";
    DevtoolsExperiments[DevtoolsExperiments["sampling-heap-profiler-timeline"] = 17] = "sampling-heap-profiler-timeline";
    DevtoolsExperiments[DevtoolsExperiments["show-option-to-expose-internals-in-heap-snapshot"] = 18] = "show-option-to-expose-internals-in-heap-snapshot";
    DevtoolsExperiments[DevtoolsExperiments["timeline-invalidation-tracking"] = 26] = "timeline-invalidation-tracking";
    DevtoolsExperiments[DevtoolsExperiments["timeline-show-all-events"] = 27] = "timeline-show-all-events";
    DevtoolsExperiments[DevtoolsExperiments["timeline-v8-runtime-call-stats"] = 28] = "timeline-v8-runtime-call-stats";
    DevtoolsExperiments[DevtoolsExperiments["apca"] = 39] = "apca";
    DevtoolsExperiments[DevtoolsExperiments["font-editor"] = 41] = "font-editor";
    DevtoolsExperiments[DevtoolsExperiments["full-accessibility-tree"] = 42] = "full-accessibility-tree";
    DevtoolsExperiments[DevtoolsExperiments["contrast-issues"] = 44] = "contrast-issues";
    DevtoolsExperiments[DevtoolsExperiments["experimental-cookie-features"] = 45] = "experimental-cookie-features";
    DevtoolsExperiments[DevtoolsExperiments["instrumentation-breakpoints"] = 61] = "instrumentation-breakpoints";
    DevtoolsExperiments[DevtoolsExperiments["authored-deployed-grouping"] = 63] = "authored-deployed-grouping";
    DevtoolsExperiments[DevtoolsExperiments["just-my-code"] = 65] = "just-my-code";
    DevtoolsExperiments[DevtoolsExperiments["use-source-map-scopes"] = 76] = "use-source-map-scopes";
    DevtoolsExperiments[DevtoolsExperiments["timeline-show-postmessage-events"] = 86] = "timeline-show-postmessage-events";
    DevtoolsExperiments[DevtoolsExperiments["timeline-debug-mode"] = 93] = "timeline-debug-mode";
    DevtoolsExperiments[DevtoolsExperiments["durable-messages"] = 110] = "durable-messages";
    DevtoolsExperiments[DevtoolsExperiments["jpeg-xl"] = 111] = "jpeg-xl";
    DevtoolsExperiments[DevtoolsExperiments["MAX_VALUE"] = 112] = "MAX_VALUE";
})(DevtoolsExperiments || (DevtoolsExperiments = {}));
var IssueExpanded;
(function (IssueExpanded) {
    IssueExpanded[IssueExpanded["CrossOriginEmbedderPolicy"] = 0] = "CrossOriginEmbedderPolicy";
    IssueExpanded[IssueExpanded["MixedContent"] = 1] = "MixedContent";
    IssueExpanded[IssueExpanded["SameSiteCookie"] = 2] = "SameSiteCookie";
    IssueExpanded[IssueExpanded["HeavyAd"] = 3] = "HeavyAd";
    IssueExpanded[IssueExpanded["ContentSecurityPolicy"] = 4] = "ContentSecurityPolicy";
    IssueExpanded[IssueExpanded["Other"] = 5] = "Other";
    IssueExpanded[IssueExpanded["Generic"] = 6] = "Generic";
    IssueExpanded[IssueExpanded["ThirdPartyPhaseoutCookie"] = 7] = "ThirdPartyPhaseoutCookie";
    IssueExpanded[IssueExpanded["GenericCookie"] = 8] = "GenericCookie";
    IssueExpanded[IssueExpanded["MAX_VALUE"] = 9] = "MAX_VALUE";
})(IssueExpanded || (IssueExpanded = {}));
var IssueResourceOpened;
(function (IssueResourceOpened) {
    IssueResourceOpened[IssueResourceOpened["CrossOriginEmbedderPolicyRequest"] = 0] = "CrossOriginEmbedderPolicyRequest";
    IssueResourceOpened[IssueResourceOpened["CrossOriginEmbedderPolicyElement"] = 1] = "CrossOriginEmbedderPolicyElement";
    IssueResourceOpened[IssueResourceOpened["MixedContentRequest"] = 2] = "MixedContentRequest";
    IssueResourceOpened[IssueResourceOpened["SameSiteCookieCookie"] = 3] = "SameSiteCookieCookie";
    IssueResourceOpened[IssueResourceOpened["SameSiteCookieRequest"] = 4] = "SameSiteCookieRequest";
    IssueResourceOpened[IssueResourceOpened["HeavyAdElement"] = 5] = "HeavyAdElement";
    IssueResourceOpened[IssueResourceOpened["ContentSecurityPolicyDirective"] = 6] = "ContentSecurityPolicyDirective";
    IssueResourceOpened[IssueResourceOpened["ContentSecurityPolicyElement"] = 7] = "ContentSecurityPolicyElement";
    IssueResourceOpened[IssueResourceOpened["MAX_VALUE"] = 13] = "MAX_VALUE";
})(IssueResourceOpened || (IssueResourceOpened = {}));
var IssueCreated;
(function (IssueCreated) {
    IssueCreated[IssueCreated["MixedContentIssue"] = 0] = "MixedContentIssue";
    IssueCreated[IssueCreated["ContentSecurityPolicyIssue::kInlineViolation"] = 1] = "ContentSecurityPolicyIssue::kInlineViolation";
    IssueCreated[IssueCreated["ContentSecurityPolicyIssue::kEvalViolation"] = 2] = "ContentSecurityPolicyIssue::kEvalViolation";
    IssueCreated[IssueCreated["ContentSecurityPolicyIssue::kURLViolation"] = 3] = "ContentSecurityPolicyIssue::kURLViolation";
    IssueCreated[IssueCreated["ContentSecurityPolicyIssue::kTrustedTypesSinkViolation"] = 4] = "ContentSecurityPolicyIssue::kTrustedTypesSinkViolation";
    IssueCreated[IssueCreated["ContentSecurityPolicyIssue::kTrustedTypesPolicyViolation"] = 5] = "ContentSecurityPolicyIssue::kTrustedTypesPolicyViolation";
    IssueCreated[IssueCreated["HeavyAdIssue::NetworkTotalLimit"] = 6] = "HeavyAdIssue::NetworkTotalLimit";
    IssueCreated[IssueCreated["HeavyAdIssue::CpuTotalLimit"] = 7] = "HeavyAdIssue::CpuTotalLimit";
    IssueCreated[IssueCreated["HeavyAdIssue::CpuPeakLimit"] = 8] = "HeavyAdIssue::CpuPeakLimit";
    IssueCreated[IssueCreated["CrossOriginEmbedderPolicyIssue::CoepFrameResourceNeedsCoepHeader"] = 9] = "CrossOriginEmbedderPolicyIssue::CoepFrameResourceNeedsCoepHeader";
    IssueCreated[IssueCreated["CrossOriginEmbedderPolicyIssue::CoopSandboxedIFrameCannotNavigateToCoopPage"] = 10] = "CrossOriginEmbedderPolicyIssue::CoopSandboxedIFrameCannotNavigateToCoopPage";
    IssueCreated[IssueCreated["CrossOriginEmbedderPolicyIssue::CorpNotSameOrigin"] = 11] = "CrossOriginEmbedderPolicyIssue::CorpNotSameOrigin";
    IssueCreated[IssueCreated["CrossOriginEmbedderPolicyIssue::CorpNotSameOriginAfterDefaultedToSameOriginByCoep"] = 12] = "CrossOriginEmbedderPolicyIssue::CorpNotSameOriginAfterDefaultedToSameOriginByCoep";
    IssueCreated[IssueCreated["CrossOriginEmbedderPolicyIssue::CorpNotSameSite"] = 13] = "CrossOriginEmbedderPolicyIssue::CorpNotSameSite";
    IssueCreated[IssueCreated["CookieIssue::ExcludeSameSiteNoneInsecure::ReadCookie"] = 14] = "CookieIssue::ExcludeSameSiteNoneInsecure::ReadCookie";
    IssueCreated[IssueCreated["CookieIssue::ExcludeSameSiteNoneInsecure::SetCookie"] = 15] = "CookieIssue::ExcludeSameSiteNoneInsecure::SetCookie";
    IssueCreated[IssueCreated["CookieIssue::WarnSameSiteNoneInsecure::ReadCookie"] = 16] = "CookieIssue::WarnSameSiteNoneInsecure::ReadCookie";
    IssueCreated[IssueCreated["CookieIssue::WarnSameSiteNoneInsecure::SetCookie"] = 17] = "CookieIssue::WarnSameSiteNoneInsecure::SetCookie";
    IssueCreated[IssueCreated["CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Secure"] = 18] = "CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Secure";
    IssueCreated[IssueCreated["CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Insecure"] = 19] = "CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Insecure";
    IssueCreated[IssueCreated["CookieIssue::WarnCrossDowngrade::ReadCookie::Secure"] = 20] = "CookieIssue::WarnCrossDowngrade::ReadCookie::Secure";
    IssueCreated[IssueCreated["CookieIssue::WarnCrossDowngrade::ReadCookie::Insecure"] = 21] = "CookieIssue::WarnCrossDowngrade::ReadCookie::Insecure";
    IssueCreated[IssueCreated["CookieIssue::WarnCrossDowngrade::SetCookie::Secure"] = 22] = "CookieIssue::WarnCrossDowngrade::SetCookie::Secure";
    IssueCreated[IssueCreated["CookieIssue::WarnCrossDowngrade::SetCookie::Insecure"] = 23] = "CookieIssue::WarnCrossDowngrade::SetCookie::Insecure";
    IssueCreated[IssueCreated["CookieIssue::ExcludeNavigationContextDowngrade::Secure"] = 24] = "CookieIssue::ExcludeNavigationContextDowngrade::Secure";
    IssueCreated[IssueCreated["CookieIssue::ExcludeNavigationContextDowngrade::Insecure"] = 25] = "CookieIssue::ExcludeNavigationContextDowngrade::Insecure";
    IssueCreated[IssueCreated["CookieIssue::ExcludeContextDowngrade::ReadCookie::Secure"] = 26] = "CookieIssue::ExcludeContextDowngrade::ReadCookie::Secure";
    IssueCreated[IssueCreated["CookieIssue::ExcludeContextDowngrade::ReadCookie::Insecure"] = 27] = "CookieIssue::ExcludeContextDowngrade::ReadCookie::Insecure";
    IssueCreated[IssueCreated["CookieIssue::ExcludeContextDowngrade::SetCookie::Secure"] = 28] = "CookieIssue::ExcludeContextDowngrade::SetCookie::Secure";
    IssueCreated[IssueCreated["CookieIssue::ExcludeContextDowngrade::SetCookie::Insecure"] = 29] = "CookieIssue::ExcludeContextDowngrade::SetCookie::Insecure";
    IssueCreated[IssueCreated["CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::ReadCookie"] = 30] = "CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::ReadCookie";
    IssueCreated[IssueCreated["CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::SetCookie"] = 31] = "CookieIssue::ExcludeSameSiteUnspecifiedTreatedAsLax::SetCookie";
    IssueCreated[IssueCreated["CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::ReadCookie"] = 32] = "CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::ReadCookie";
    IssueCreated[IssueCreated["CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::SetCookie"] = 33] = "CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::SetCookie";
    IssueCreated[IssueCreated["CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::ReadCookie"] = 34] = "CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::ReadCookie";
    IssueCreated[IssueCreated["CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::SetCookie"] = 35] = "CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::SetCookie";
    IssueCreated[IssueCreated["SharedArrayBufferIssue::TransferIssue"] = 36] = "SharedArrayBufferIssue::TransferIssue";
    IssueCreated[IssueCreated["SharedArrayBufferIssue::CreationIssue"] = 37] = "SharedArrayBufferIssue::CreationIssue";
    IssueCreated[IssueCreated["LowTextContrastIssue"] = 41] = "LowTextContrastIssue";
    IssueCreated[IssueCreated["CorsIssue::InsecureLocalNetwork"] = 42] = "CorsIssue::InsecureLocalNetwork";
    IssueCreated[IssueCreated["CorsIssue::InvalidHeaders"] = 44] = "CorsIssue::InvalidHeaders";
    IssueCreated[IssueCreated["CorsIssue::WildcardOriginWithCredentials"] = 45] = "CorsIssue::WildcardOriginWithCredentials";
    IssueCreated[IssueCreated["CorsIssue::PreflightResponseInvalid"] = 46] = "CorsIssue::PreflightResponseInvalid";
    IssueCreated[IssueCreated["CorsIssue::OriginMismatch"] = 47] = "CorsIssue::OriginMismatch";
    IssueCreated[IssueCreated["CorsIssue::AllowCredentialsRequired"] = 48] = "CorsIssue::AllowCredentialsRequired";
    IssueCreated[IssueCreated["CorsIssue::MethodDisallowedByPreflightResponse"] = 49] = "CorsIssue::MethodDisallowedByPreflightResponse";
    IssueCreated[IssueCreated["CorsIssue::HeaderDisallowedByPreflightResponse"] = 50] = "CorsIssue::HeaderDisallowedByPreflightResponse";
    IssueCreated[IssueCreated["CorsIssue::RedirectContainsCredentials"] = 51] = "CorsIssue::RedirectContainsCredentials";
    IssueCreated[IssueCreated["CorsIssue::DisallowedByMode"] = 52] = "CorsIssue::DisallowedByMode";
    IssueCreated[IssueCreated["CorsIssue::CorsDisabledScheme"] = 53] = "CorsIssue::CorsDisabledScheme";
    IssueCreated[IssueCreated["CorsIssue::PreflightMissingAllowExternal"] = 54] = "CorsIssue::PreflightMissingAllowExternal";
    IssueCreated[IssueCreated["CorsIssue::PreflightInvalidAllowExternal"] = 55] = "CorsIssue::PreflightInvalidAllowExternal";
    IssueCreated[IssueCreated["CorsIssue::NoCorsRedirectModeNotFollow"] = 57] = "CorsIssue::NoCorsRedirectModeNotFollow";
    IssueCreated[IssueCreated["QuirksModeIssue::QuirksMode"] = 58] = "QuirksModeIssue::QuirksMode";
    IssueCreated[IssueCreated["QuirksModeIssue::LimitedQuirksMode"] = 59] = "QuirksModeIssue::LimitedQuirksMode";
    IssueCreated[IssueCreated["DeprecationIssue"] = 60] = "DeprecationIssue";
    IssueCreated[IssueCreated["ClientHintIssue::MetaTagAllowListInvalidOrigin"] = 61] = "ClientHintIssue::MetaTagAllowListInvalidOrigin";
    IssueCreated[IssueCreated["ClientHintIssue::MetaTagModifiedHTML"] = 62] = "ClientHintIssue::MetaTagModifiedHTML";
    IssueCreated[IssueCreated["GenericIssue::CrossOriginPortalPostMessageError"] = 64] = "GenericIssue::CrossOriginPortalPostMessageError";
    IssueCreated[IssueCreated["GenericIssue::FormLabelForNameError"] = 65] = "GenericIssue::FormLabelForNameError";
    IssueCreated[IssueCreated["GenericIssue::FormDuplicateIdForInputError"] = 66] = "GenericIssue::FormDuplicateIdForInputError";
    IssueCreated[IssueCreated["GenericIssue::FormInputWithNoLabelError"] = 67] = "GenericIssue::FormInputWithNoLabelError";
    IssueCreated[IssueCreated["GenericIssue::FormAutocompleteAttributeEmptyError"] = 68] = "GenericIssue::FormAutocompleteAttributeEmptyError";
    IssueCreated[IssueCreated["GenericIssue::FormEmptyIdAndNameAttributesForInputError"] = 69] = "GenericIssue::FormEmptyIdAndNameAttributesForInputError";
    IssueCreated[IssueCreated["GenericIssue::FormAriaLabelledByToNonExistingIdError"] = 70] = "GenericIssue::FormAriaLabelledByToNonExistingIdError";
    IssueCreated[IssueCreated["GenericIssue::FormInputAssignedAutocompleteValueToIdOrNameAttributeError"] = 71] = "GenericIssue::FormInputAssignedAutocompleteValueToIdOrNameAttributeError";
    IssueCreated[IssueCreated["GenericIssue::FormLabelHasNeitherForNorNestedInputError"] = 72] = "GenericIssue::FormLabelHasNeitherForNorNestedInputError";
    IssueCreated[IssueCreated["GenericIssue::FormLabelForMatchesNonExistingIdError"] = 73] = "GenericIssue::FormLabelForMatchesNonExistingIdError";
    IssueCreated[IssueCreated["GenericIssue::FormHasPasswordFieldWithoutUsernameFieldError"] = 74] = "GenericIssue::FormHasPasswordFieldWithoutUsernameFieldError";
    IssueCreated[IssueCreated["GenericIssue::FormInputHasWrongButWellIntendedAutocompleteValueError"] = 75] = "GenericIssue::FormInputHasWrongButWellIntendedAutocompleteValueError";
    IssueCreated[IssueCreated["StylesheetLoadingIssue::LateImportRule"] = 76] = "StylesheetLoadingIssue::LateImportRule";
    IssueCreated[IssueCreated["StylesheetLoadingIssue::RequestFailed"] = 77] = "StylesheetLoadingIssue::RequestFailed";
    IssueCreated[IssueCreated["CookieIssue::WarnThirdPartyPhaseout::ReadCookie"] = 82] = "CookieIssue::WarnThirdPartyPhaseout::ReadCookie";
    IssueCreated[IssueCreated["CookieIssue::WarnThirdPartyPhaseout::SetCookie"] = 83] = "CookieIssue::WarnThirdPartyPhaseout::SetCookie";
    IssueCreated[IssueCreated["CookieIssue::ExcludeThirdPartyPhaseout::ReadCookie"] = 84] = "CookieIssue::ExcludeThirdPartyPhaseout::ReadCookie";
    IssueCreated[IssueCreated["CookieIssue::ExcludeThirdPartyPhaseout::SetCookie"] = 85] = "CookieIssue::ExcludeThirdPartyPhaseout::SetCookie";
    IssueCreated[IssueCreated["ElementAccessibilityIssue::DisallowedSelectChild"] = 86] = "ElementAccessibilityIssue::DisallowedSelectChild";
    IssueCreated[IssueCreated["ElementAccessibilityIssue::DisallowedOptGroupChild"] = 87] = "ElementAccessibilityIssue::DisallowedOptGroupChild";
    IssueCreated[IssueCreated["ElementAccessibilityIssue::NonPhrasingContentOptionChild"] = 88] = "ElementAccessibilityIssue::NonPhrasingContentOptionChild";
    IssueCreated[IssueCreated["ElementAccessibilityIssue::InteractiveContentOptionChild"] = 89] = "ElementAccessibilityIssue::InteractiveContentOptionChild";
    IssueCreated[IssueCreated["ElementAccessibilityIssue::InteractiveContentLegendChild"] = 90] = "ElementAccessibilityIssue::InteractiveContentLegendChild";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::MissingSignatureHeader"] = 91] = "SRIMessageSignatureIssue::MissingSignatureHeader";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::MissingSignatureInputHeader"] = 92] = "SRIMessageSignatureIssue::MissingSignatureInputHeader";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::InvalidSignatureHeader"] = 93] = "SRIMessageSignatureIssue::InvalidSignatureHeader";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::InvalidSignatureInputHeader"] = 94] = "SRIMessageSignatureIssue::InvalidSignatureInputHeader";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureHeaderValueIsNotByteSequence"] = 95] = "SRIMessageSignatureIssue::SignatureHeaderValueIsNotByteSequence";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureHeaderValueIsParameterized"] = 96] = "SRIMessageSignatureIssue::SignatureHeaderValueIsParameterized";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureHeaderValueIsIncorrectLength"] = 97] = "SRIMessageSignatureIssue::SignatureHeaderValueIsIncorrectLength";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureInputHeaderMissingLabel"] = 98] = "SRIMessageSignatureIssue::SignatureInputHeaderMissingLabel";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureInputHeaderValueNotInnerList"] = 99] = "SRIMessageSignatureIssue::SignatureInputHeaderValueNotInnerList";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureInputHeaderValueMissingComponents"] = 100] = "SRIMessageSignatureIssue::SignatureInputHeaderValueMissingComponents";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentType"] = 101] = "SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentType";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentName"] = 102] = "SRIMessageSignatureIssue::SignatureInputHeaderInvalidComponentName";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureInputHeaderInvalidHeaderComponentParameter"] = 103] = "SRIMessageSignatureIssue::SignatureInputHeaderInvalidHeaderComponentParameter";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureInputHeaderInvalidDerivedComponentParameter"] = 104] = "SRIMessageSignatureIssue::SignatureInputHeaderInvalidDerivedComponentParameter";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureInputHeaderKeyIdLength"] = 105] = "SRIMessageSignatureIssue::SignatureInputHeaderKeyIdLength";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureInputHeaderInvalidParameter"] = 106] = "SRIMessageSignatureIssue::SignatureInputHeaderInvalidParameter";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::SignatureInputHeaderMissingRequiredParameters"] = 107] = "SRIMessageSignatureIssue::SignatureInputHeaderMissingRequiredParameters";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::ValidationFailedSignatureExpired"] = 108] = "SRIMessageSignatureIssue::ValidationFailedSignatureExpired";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::ValidationFailedInvalidLength"] = 109] = "SRIMessageSignatureIssue::ValidationFailedInvalidLength";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::ValidationFailedSignatureMismatch"] = 110] = "SRIMessageSignatureIssue::ValidationFailedSignatureMismatch";
    IssueCreated[IssueCreated["CorsIssue::LocalNetworkAccessPermissionDenied"] = 111] = "CorsIssue::LocalNetworkAccessPermissionDenied";
    IssueCreated[IssueCreated["SRIMessageSignatureIssue::ValidationFailedIntegrityMismatch"] = 112] = "SRIMessageSignatureIssue::ValidationFailedIntegrityMismatch";
    IssueCreated[IssueCreated["ElementAccessibilityIssue::InteractiveContentSummaryDescendant"] = 113] = "ElementAccessibilityIssue::InteractiveContentSummaryDescendant";
    IssueCreated[IssueCreated["CorsIssue::InvalidLocalNetworkAccess"] = 114] = "CorsIssue::InvalidLocalNetworkAccess";
    IssueCreated[IssueCreated["MAX_VALUE"] = 115] = "MAX_VALUE";
})(IssueCreated || (IssueCreated = {}));
var Language;
(function (Language) {
    Language[Language["af"] = 1] = "af";
    Language[Language["am"] = 2] = "am";
    Language[Language["ar"] = 3] = "ar";
    Language[Language["as"] = 4] = "as";
    Language[Language["az"] = 5] = "az";
    Language[Language["be"] = 6] = "be";
    Language[Language["bg"] = 7] = "bg";
    Language[Language["bn"] = 8] = "bn";
    Language[Language["bs"] = 9] = "bs";
    Language[Language["ca"] = 10] = "ca";
    Language[Language["cs"] = 11] = "cs";
    Language[Language["cy"] = 12] = "cy";
    Language[Language["da"] = 13] = "da";
    Language[Language["de"] = 14] = "de";
    Language[Language["el"] = 15] = "el";
    Language[Language["en-GB"] = 16] = "en-GB";
    Language[Language["en-US"] = 17] = "en-US";
    Language[Language["es-419"] = 18] = "es-419";
    Language[Language["es"] = 19] = "es";
    Language[Language["et"] = 20] = "et";
    Language[Language["eu"] = 21] = "eu";
    Language[Language["fa"] = 22] = "fa";
    Language[Language["fi"] = 23] = "fi";
    Language[Language["fil"] = 24] = "fil";
    Language[Language["fr-CA"] = 25] = "fr-CA";
    Language[Language["fr"] = 26] = "fr";
    Language[Language["gl"] = 27] = "gl";
    Language[Language["gu"] = 28] = "gu";
    Language[Language["he"] = 29] = "he";
    Language[Language["hi"] = 30] = "hi";
    Language[Language["hr"] = 31] = "hr";
    Language[Language["hu"] = 32] = "hu";
    Language[Language["hy"] = 33] = "hy";
    Language[Language["id"] = 34] = "id";
    Language[Language["is"] = 35] = "is";
    Language[Language["it"] = 36] = "it";
    Language[Language["ja"] = 37] = "ja";
    Language[Language["ka"] = 38] = "ka";
    Language[Language["kk"] = 39] = "kk";
    Language[Language["km"] = 40] = "km";
    Language[Language["kn"] = 41] = "kn";
    Language[Language["ko"] = 42] = "ko";
    Language[Language["ky"] = 43] = "ky";
    Language[Language["lo"] = 44] = "lo";
    Language[Language["lt"] = 45] = "lt";
    Language[Language["lv"] = 46] = "lv";
    Language[Language["mk"] = 47] = "mk";
    Language[Language["ml"] = 48] = "ml";
    Language[Language["mn"] = 49] = "mn";
    Language[Language["mr"] = 50] = "mr";
    Language[Language["ms"] = 51] = "ms";
    Language[Language["my"] = 52] = "my";
    Language[Language["ne"] = 53] = "ne";
    Language[Language["nl"] = 54] = "nl";
    Language[Language["no"] = 55] = "no";
    Language[Language["or"] = 56] = "or";
    Language[Language["pa"] = 57] = "pa";
    Language[Language["pl"] = 58] = "pl";
    Language[Language["pt-PT"] = 59] = "pt-PT";
    Language[Language["pt"] = 60] = "pt";
    Language[Language["ro"] = 61] = "ro";
    Language[Language["ru"] = 62] = "ru";
    Language[Language["si"] = 63] = "si";
    Language[Language["sk"] = 64] = "sk";
    Language[Language["sl"] = 65] = "sl";
    Language[Language["sq"] = 66] = "sq";
    Language[Language["sr-Latn"] = 67] = "sr-Latn";
    Language[Language["sr"] = 68] = "sr";
    Language[Language["sv"] = 69] = "sv";
    Language[Language["sw"] = 70] = "sw";
    Language[Language["ta"] = 71] = "ta";
    Language[Language["te"] = 72] = "te";
    Language[Language["th"] = 73] = "th";
    Language[Language["tr"] = 74] = "tr";
    Language[Language["uk"] = 75] = "uk";
    Language[Language["ur"] = 76] = "ur";
    Language[Language["uz"] = 77] = "uz";
    Language[Language["vi"] = 78] = "vi";
    Language[Language["zh"] = 79] = "zh";
    Language[Language["zh-HK"] = 80] = "zh-HK";
    Language[Language["zh-TW"] = 81] = "zh-TW";
    Language[Language["zu"] = 82] = "zu";
    Language[Language["MAX_VALUE"] = 83] = "MAX_VALUE";
})(Language || (Language = {}));
var ManifestSectionCodes;
(function (ManifestSectionCodes) {
    ManifestSectionCodes[ManifestSectionCodes["OtherSection"] = 0] = "OtherSection";
    ManifestSectionCodes[ManifestSectionCodes["Identity"] = 1] = "Identity";
    ManifestSectionCodes[ManifestSectionCodes["Presentation"] = 2] = "Presentation";
    ManifestSectionCodes[ManifestSectionCodes["Protocol Handlers"] = 3] = "Protocol Handlers";
    ManifestSectionCodes[ManifestSectionCodes["Icons"] = 4] = "Icons";
    ManifestSectionCodes[ManifestSectionCodes["Window Controls Overlay"] = 5] = "Window Controls Overlay";
    ManifestSectionCodes[ManifestSectionCodes["MAX_VALUE"] = 6] = "MAX_VALUE";
})(ManifestSectionCodes || (ManifestSectionCodes = {}));

// Copyright 2019 The Chromium Authors
const userMetrics = new UserMetrics();

// Copyright 2020 The Chromium Authors
class CSSFontFace {
    #fontFamily;
    #fontVariationAxes;
    #fontVariationAxesByTag = new Map();
    #src;
    #fontDisplay;
    constructor(payload) {
        this.#fontFamily = payload.fontFamily;
        this.#fontVariationAxes = payload.fontVariationAxes || [];
        this.#src = payload.src;
        this.#fontDisplay = payload.fontDisplay;
        for (const axis of this.#fontVariationAxes) {
            this.#fontVariationAxesByTag.set(axis.tag, axis);
        }
    }
    getFontFamily() {
        return this.#fontFamily;
    }
    getSrc() {
        return this.#src;
    }
    getFontDisplay() {
        return this.#fontDisplay;
    }
    getVariationAxisByTag(tag) {
        return this.#fontVariationAxesByTag.get(tag);
    }
}

// Copyright 2026 The Chromium Authors
const generatedProperties = [
    {
        "longhands": [
            "max-lines",
            "block-ellipsis",
            "continue"
        ],
        "name": "-alternative-webkit-line-clamp"
    },
    {
        "inherited": true,
        "name": "-webkit-border-horizontal-spacing"
    },
    {
        "name": "-webkit-border-image"
    },
    {
        "inherited": true,
        "name": "-webkit-border-vertical-spacing"
    },
    {
        "keywords": [
            "stretch",
            "start",
            "center",
            "end",
            "baseline"
        ],
        "name": "-webkit-box-align"
    },
    {
        "keywords": [
            "slice",
            "clone"
        ],
        "name": "-webkit-box-decoration-break"
    },
    {
        "keywords": [
            "normal",
            "reverse"
        ],
        "name": "-webkit-box-direction"
    },
    {
        "name": "-webkit-box-flex"
    },
    {
        "name": "-webkit-box-ordinal-group"
    },
    {
        "keywords": [
            "horizontal",
            "vertical"
        ],
        "name": "-webkit-box-orient"
    },
    {
        "keywords": [
            "start",
            "center",
            "end",
            "justify"
        ],
        "name": "-webkit-box-pack"
    },
    {
        "name": "-webkit-box-reflect"
    },
    {
        "longhands": [
            "break-after"
        ],
        "name": "-webkit-column-break-after"
    },
    {
        "longhands": [
            "break-before"
        ],
        "name": "-webkit-column-break-before"
    },
    {
        "longhands": [
            "break-inside"
        ],
        "name": "-webkit-column-break-inside"
    },
    {
        "inherited": true,
        "name": "-webkit-font-smoothing"
    },
    {
        "keywords": [
            "auto",
            "loose",
            "normal",
            "strict",
            "after-white-space"
        ],
        "name": "-webkit-line-break"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "-webkit-line-clamp"
    },
    {
        "inherited": true,
        "name": "-webkit-locale"
    },
    {
        "longhands": [
            "-webkit-mask-box-image-source",
            "-webkit-mask-box-image-slice",
            "-webkit-mask-box-image-width",
            "-webkit-mask-box-image-outset",
            "-webkit-mask-box-image-repeat"
        ],
        "name": "-webkit-mask-box-image"
    },
    {
        "name": "-webkit-mask-box-image-outset"
    },
    {
        "name": "-webkit-mask-box-image-repeat"
    },
    {
        "name": "-webkit-mask-box-image-slice"
    },
    {
        "name": "-webkit-mask-box-image-source"
    },
    {
        "name": "-webkit-mask-box-image-width"
    },
    {
        "name": "-webkit-mask-position-x"
    },
    {
        "name": "-webkit-mask-position-y"
    },
    {
        "name": "-webkit-perspective-origin-x"
    },
    {
        "name": "-webkit-perspective-origin-y"
    },
    {
        "inherited": true,
        "keywords": [
            "logical",
            "visual"
        ],
        "name": "-webkit-rtl-ordering"
    },
    {
        "inherited": true,
        "name": "-webkit-ruby-position"
    },
    {
        "inherited": true,
        "name": "-webkit-tap-highlight-color"
    },
    {
        "inherited": true,
        "name": "-webkit-text-combine"
    },
    {
        "inherited": true,
        "name": "-webkit-text-decorations-in-effect"
    },
    {
        "inherited": true,
        "name": "-webkit-text-fill-color"
    },
    {
        "inherited": true,
        "name": "-webkit-text-orientation"
    },
    {
        "inherited": true,
        "keywords": [
            "none",
            "disc",
            "circle",
            "square"
        ],
        "name": "-webkit-text-security"
    },
    {
        "inherited": true,
        "longhands": [
            "-webkit-text-stroke-width",
            "-webkit-text-stroke-color"
        ],
        "name": "-webkit-text-stroke"
    },
    {
        "inherited": true,
        "name": "-webkit-text-stroke-color"
    },
    {
        "inherited": true,
        "name": "-webkit-text-stroke-width"
    },
    {
        "name": "-webkit-transform-origin-x"
    },
    {
        "name": "-webkit-transform-origin-y"
    },
    {
        "name": "-webkit-transform-origin-z"
    },
    {
        "keywords": [
            "auto",
            "none",
            "element"
        ],
        "name": "-webkit-user-drag"
    },
    {
        "inherited": true,
        "keywords": [
            "read-only",
            "read-write",
            "read-write-plaintext-only"
        ],
        "name": "-webkit-user-modify"
    },
    {
        "inherited": true,
        "name": "-webkit-writing-mode"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "currentcolor"
        ],
        "name": "accent-color"
    },
    {
        "name": "additive-symbols"
    },
    {
        "name": "align-content"
    },
    {
        "name": "align-items"
    },
    {
        "name": "align-self"
    },
    {
        "keywords": [
            "auto",
            "baseline",
            "alphabetic",
            "ideographic",
            "middle",
            "central",
            "mathematical",
            "before-edge",
            "text-before-edge",
            "after-edge",
            "text-after-edge",
            "hanging"
        ],
        "name": "alignment-baseline"
    },
    {
        "longhands": [
            "-webkit-border-horizontal-spacing",
            "-webkit-border-vertical-spacing",
            "-webkit-box-align",
            "-webkit-box-decoration-break",
            "-webkit-box-direction",
            "-webkit-box-flex",
            "-webkit-box-ordinal-group",
            "-webkit-box-orient",
            "-webkit-box-pack",
            "-webkit-box-reflect",
            "-webkit-font-smoothing",
            "-webkit-line-break",
            "-webkit-line-clamp",
            "-webkit-locale",
            "-webkit-mask-box-image-outset",
            "-webkit-mask-box-image-repeat",
            "-webkit-mask-box-image-slice",
            "-webkit-mask-box-image-source",
            "-webkit-mask-box-image-width",
            "-webkit-mask-position-x",
            "-webkit-mask-position-y",
            "-webkit-rtl-ordering",
            "-webkit-ruby-position",
            "-webkit-tap-highlight-color",
            "-webkit-text-combine",
            "-webkit-text-decorations-in-effect",
            "-webkit-text-fill-color",
            "-webkit-text-orientation",
            "-webkit-text-security",
            "-webkit-text-stroke-color",
            "-webkit-text-stroke-width",
            "-webkit-user-drag",
            "-webkit-writing-mode",
            "accent-color",
            "additive-symbols",
            "align-content",
            "align-items",
            "align-self",
            "alignment-baseline",
            "anchor-name",
            "anchor-scope",
            "animation-composition",
            "animation-delay",
            "animation-direction",
            "animation-duration",
            "animation-fill-mode",
            "animation-iteration-count",
            "animation-name",
            "animation-play-state",
            "animation-range-end",
            "animation-range-start",
            "animation-timeline",
            "animation-timing-function",
            "animation-trigger",
            "app-region",
            "appearance",
            "ascent-override",
            "aspect-ratio",
            "backdrop-filter",
            "backface-visibility",
            "background-attachment",
            "background-blend-mode",
            "background-clip",
            "background-color",
            "background-image",
            "background-origin",
            "background-position-x",
            "background-position-y",
            "background-repeat",
            "background-size",
            "base-palette",
            "base-url",
            "baseline-shift",
            "baseline-source",
            "block-ellipsis",
            "block-size",
            "border-block-end-color",
            "border-block-end-style",
            "border-block-end-width",
            "border-block-start-color",
            "border-block-start-style",
            "border-block-start-width",
            "border-bottom-color",
            "border-bottom-left-radius",
            "border-bottom-right-radius",
            "border-bottom-style",
            "border-bottom-width",
            "border-collapse",
            "border-end-end-radius",
            "border-end-start-radius",
            "border-image-outset",
            "border-image-repeat",
            "border-image-slice",
            "border-image-source",
            "border-image-width",
            "border-inline-end-color",
            "border-inline-end-style",
            "border-inline-end-width",
            "border-inline-start-color",
            "border-inline-start-style",
            "border-inline-start-width",
            "border-left-color",
            "border-left-style",
            "border-left-width",
            "border-right-color",
            "border-right-style",
            "border-right-width",
            "border-shape",
            "border-start-end-radius",
            "border-start-start-radius",
            "border-top-color",
            "border-top-left-radius",
            "border-top-right-radius",
            "border-top-style",
            "border-top-width",
            "bottom",
            "box-decoration-break",
            "box-shadow",
            "box-sizing",
            "break-after",
            "break-before",
            "break-inside",
            "buffered-rendering",
            "caption-side",
            "caret-animation",
            "caret-color",
            "caret-shape",
            "clear",
            "clip",
            "clip-path",
            "clip-rule",
            "color",
            "color-interpolation",
            "color-interpolation-filters",
            "color-rendering",
            "color-scheme",
            "column-count",
            "column-fill",
            "column-gap",
            "column-height",
            "column-rule-break",
            "column-rule-color",
            "column-rule-edge-inset-end",
            "column-rule-edge-inset-start",
            "column-rule-interior-inset-end",
            "column-rule-interior-inset-start",
            "column-rule-style",
            "column-rule-visibility-items",
            "column-rule-width",
            "column-span",
            "column-width",
            "column-wrap",
            "contain",
            "contain-intrinsic-block-size",
            "contain-intrinsic-height",
            "contain-intrinsic-inline-size",
            "contain-intrinsic-width",
            "container-name",
            "container-type",
            "content",
            "content-visibility",
            "continue",
            "corner-bottom-left-shape",
            "corner-bottom-right-shape",
            "corner-end-end-shape",
            "corner-end-start-shape",
            "corner-start-end-shape",
            "corner-start-start-shape",
            "corner-top-left-shape",
            "corner-top-right-shape",
            "counter-increment",
            "counter-reset",
            "counter-set",
            "cursor",
            "cx",
            "cy",
            "d",
            "descent-override",
            "display",
            "dominant-baseline",
            "dynamic-range-limit",
            "empty-cells",
            "fallback",
            "field-sizing",
            "fill",
            "fill-opacity",
            "fill-rule",
            "filter",
            "flex-basis",
            "flex-direction",
            "flex-grow",
            "flex-shrink",
            "flex-wrap",
            "float",
            "flood-color",
            "flood-opacity",
            "flow-tolerance",
            "font-display",
            "font-family",
            "font-feature-settings",
            "font-kerning",
            "font-language-override",
            "font-optical-sizing",
            "font-palette",
            "font-size",
            "font-size-adjust",
            "font-stretch",
            "font-style",
            "font-synthesis-small-caps",
            "font-synthesis-style",
            "font-synthesis-weight",
            "font-variant-alternates",
            "font-variant-caps",
            "font-variant-east-asian",
            "font-variant-emoji",
            "font-variant-ligatures",
            "font-variant-numeric",
            "font-variant-position",
            "font-variation-settings",
            "font-weight",
            "forced-color-adjust",
            "frame-sizing",
            "grid-auto-columns",
            "grid-auto-flow",
            "grid-auto-rows",
            "grid-column-end",
            "grid-column-start",
            "grid-lanes-direction",
            "grid-lanes-pack",
            "grid-row-end",
            "grid-row-start",
            "grid-template-areas",
            "grid-template-columns",
            "grid-template-rows",
            "hash",
            "height",
            "hostname",
            "hyphenate-character",
            "hyphenate-limit-chars",
            "hyphens",
            "image-animation",
            "image-orientation",
            "image-rendering",
            "inherits",
            "initial-letter",
            "initial-value",
            "inline-size",
            "inset-block-end",
            "inset-block-start",
            "inset-inline-end",
            "inset-inline-start",
            "interactivity",
            "interest-delay-end",
            "interest-delay-start",
            "interpolate-size",
            "isolation",
            "justify-content",
            "justify-items",
            "justify-self",
            "left",
            "letter-spacing",
            "lighting-color",
            "line-break",
            "line-gap-override",
            "line-height",
            "list-style-image",
            "list-style-position",
            "list-style-type",
            "margin-block-end",
            "margin-block-start",
            "margin-bottom",
            "margin-inline-end",
            "margin-inline-start",
            "margin-left",
            "margin-right",
            "margin-top",
            "margin-trim",
            "marker-end",
            "marker-mid",
            "marker-start",
            "mask-clip",
            "mask-composite",
            "mask-image",
            "mask-mode",
            "mask-origin",
            "mask-repeat",
            "mask-size",
            "mask-type",
            "math-depth",
            "math-shift",
            "math-style",
            "max-block-size",
            "max-height",
            "max-inline-size",
            "max-lines",
            "max-width",
            "min-block-size",
            "min-height",
            "min-inline-size",
            "min-width",
            "mix-blend-mode",
            "navigation",
            "negative",
            "object-fit",
            "object-position",
            "object-view-box",
            "offset-anchor",
            "offset-distance",
            "offset-path",
            "offset-position",
            "offset-rotate",
            "opacity",
            "order",
            "origin-trial-test-property",
            "orphans",
            "outline-color",
            "outline-offset",
            "outline-style",
            "outline-width",
            "overflow-anchor",
            "overflow-block",
            "overflow-clip-margin",
            "overflow-inline",
            "overflow-wrap",
            "overflow-x",
            "overflow-y",
            "overlay",
            "override-colors",
            "overscroll-behavior-block",
            "overscroll-behavior-inline",
            "overscroll-behavior-x",
            "overscroll-behavior-y",
            "pad",
            "padding-block-end",
            "padding-block-start",
            "padding-bottom",
            "padding-inline-end",
            "padding-inline-start",
            "padding-left",
            "padding-right",
            "padding-top",
            "page",
            "page-margin-safety",
            "page-orientation",
            "paint-order",
            "pathname",
            "pattern",
            "perspective",
            "perspective-origin",
            "pointer-events",
            "port",
            "position",
            "position-anchor",
            "position-area",
            "position-try-fallbacks",
            "position-try-order",
            "position-visibility",
            "prefix",
            "print-color-adjust",
            "protocol",
            "quotes",
            "r",
            "range",
            "reading-flow",
            "reading-order",
            "resize",
            "result",
            "right",
            "rotate",
            "row-gap",
            "row-rule-break",
            "row-rule-color",
            "row-rule-edge-inset-end",
            "row-rule-edge-inset-start",
            "row-rule-interior-inset-end",
            "row-rule-interior-inset-start",
            "row-rule-style",
            "row-rule-visibility-items",
            "row-rule-width",
            "ruby-align",
            "ruby-overhang",
            "ruby-position",
            "rule-overlap",
            "rx",
            "ry",
            "scale",
            "scroll-behavior",
            "scroll-initial-target",
            "scroll-margin-block-end",
            "scroll-margin-block-start",
            "scroll-margin-bottom",
            "scroll-margin-inline-end",
            "scroll-margin-inline-start",
            "scroll-margin-left",
            "scroll-margin-right",
            "scroll-margin-top",
            "scroll-marker-group",
            "scroll-padding-block-end",
            "scroll-padding-block-start",
            "scroll-padding-bottom",
            "scroll-padding-inline-end",
            "scroll-padding-inline-start",
            "scroll-padding-left",
            "scroll-padding-right",
            "scroll-padding-top",
            "scroll-snap-align",
            "scroll-snap-stop",
            "scroll-snap-type",
            "scroll-target-group",
            "scroll-timeline-axis",
            "scroll-timeline-name",
            "scrollbar-color",
            "scrollbar-gutter",
            "scrollbar-width",
            "search",
            "shape-image-threshold",
            "shape-margin",
            "shape-outside",
            "shape-rendering",
            "size",
            "size-adjust",
            "speak",
            "speak-as",
            "src",
            "stop-color",
            "stop-opacity",
            "stroke",
            "stroke-dasharray",
            "stroke-dashoffset",
            "stroke-linecap",
            "stroke-linejoin",
            "stroke-miterlimit",
            "stroke-opacity",
            "stroke-width",
            "suffix",
            "symbols",
            "syntax",
            "system",
            "tab-size",
            "table-layout",
            "text-align",
            "text-align-last",
            "text-anchor",
            "text-autospace",
            "text-box-edge",
            "text-box-trim",
            "text-combine-upright",
            "text-decoration-color",
            "text-decoration-line",
            "text-decoration-skip-ink",
            "text-decoration-style",
            "text-decoration-thickness",
            "text-emphasis-color",
            "text-emphasis-position",
            "text-emphasis-style",
            "text-fit",
            "text-indent",
            "text-justify",
            "text-orientation",
            "text-overflow",
            "text-rendering",
            "text-shadow",
            "text-size-adjust",
            "text-spacing-trim",
            "text-transform",
            "text-underline-offset",
            "text-underline-position",
            "text-wrap-mode",
            "text-wrap-style",
            "timeline-scope",
            "timeline-trigger-activation-range-end",
            "timeline-trigger-activation-range-start",
            "timeline-trigger-active-range-end",
            "timeline-trigger-active-range-start",
            "timeline-trigger-name",
            "timeline-trigger-source",
            "top",
            "touch-action",
            "transform",
            "transform-box",
            "transform-origin",
            "transform-style",
            "transition-behavior",
            "transition-delay",
            "transition-duration",
            "transition-property",
            "transition-timing-function",
            "translate",
            "trigger-scope",
            "types",
            "unicode-range",
            "user-select",
            "vector-effect",
            "vertical-align",
            "view-timeline-axis",
            "view-timeline-inset",
            "view-timeline-name",
            "view-transition-class",
            "view-transition-group",
            "view-transition-name",
            "view-transition-scope",
            "visibility",
            "white-space-collapse",
            "widows",
            "width",
            "will-change",
            "word-break",
            "word-spacing",
            "writing-mode",
            "x",
            "y",
            "z-index",
            "zoom"
        ],
        "name": "all"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "anchor-name"
    },
    {
        "keywords": [
            "none",
            "all"
        ],
        "name": "anchor-scope"
    },
    {
        "longhands": [
            "animation-duration",
            "animation-timing-function",
            "animation-delay",
            "animation-iteration-count",
            "animation-direction",
            "animation-fill-mode",
            "animation-play-state",
            "animation-name",
            "animation-timeline",
            "animation-range-start",
            "animation-range-end"
        ],
        "name": "animation"
    },
    {
        "keywords": [
            "replace",
            "add",
            "accumulate"
        ],
        "name": "animation-composition"
    },
    {
        "name": "animation-delay"
    },
    {
        "keywords": [
            "normal",
            "reverse",
            "alternate",
            "alternate-reverse"
        ],
        "name": "animation-direction"
    },
    {
        "name": "animation-duration"
    },
    {
        "keywords": [
            "none",
            "forwards",
            "backwards",
            "both"
        ],
        "name": "animation-fill-mode"
    },
    {
        "keywords": [
            "infinite"
        ],
        "name": "animation-iteration-count"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "animation-name"
    },
    {
        "keywords": [
            "running",
            "paused"
        ],
        "name": "animation-play-state"
    },
    {
        "longhands": [
            "animation-range-start",
            "animation-range-end"
        ],
        "name": "animation-range"
    },
    {
        "name": "animation-range-end"
    },
    {
        "name": "animation-range-start"
    },
    {
        "keywords": [
            "none",
            "auto"
        ],
        "name": "animation-timeline"
    },
    {
        "keywords": [
            "linear",
            "ease",
            "ease-in",
            "ease-out",
            "ease-in-out",
            "jump-both",
            "jump-end",
            "jump-none",
            "jump-start",
            "step-start",
            "step-end"
        ],
        "name": "animation-timing-function"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "animation-trigger"
    },
    {
        "keywords": [
            "none",
            "drag",
            "no-drag"
        ],
        "name": "app-region"
    },
    {
        "name": "appearance"
    },
    {
        "name": "ascent-override"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "aspect-ratio"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "backdrop-filter"
    },
    {
        "keywords": [
            "visible",
            "hidden"
        ],
        "name": "backface-visibility"
    },
    {
        "longhands": [
            "background-image",
            "background-position-x",
            "background-position-y",
            "background-size",
            "background-repeat",
            "background-attachment",
            "background-origin",
            "background-clip",
            "background-color"
        ],
        "name": "background"
    },
    {
        "keywords": [
            "scroll",
            "fixed",
            "local"
        ],
        "name": "background-attachment"
    },
    {
        "keywords": [
            "normal",
            "multiply",
            "screen",
            "overlay",
            "darken",
            "lighten",
            "color-dodge",
            "color-burn",
            "hard-light",
            "soft-light",
            "difference",
            "exclusion",
            "hue",
            "saturation",
            "color",
            "luminosity"
        ],
        "name": "background-blend-mode"
    },
    {
        "keywords": [
            "border-box",
            "padding-box",
            "content-box",
            "text"
        ],
        "name": "background-clip"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "background-color"
    },
    {
        "keywords": [
            "auto",
            "none"
        ],
        "name": "background-image"
    },
    {
        "keywords": [
            "border-box",
            "padding-box",
            "content-box"
        ],
        "name": "background-origin"
    },
    {
        "longhands": [
            "background-position-x",
            "background-position-y"
        ],
        "name": "background-position"
    },
    {
        "name": "background-position-x"
    },
    {
        "name": "background-position-y"
    },
    {
        "name": "background-repeat"
    },
    {
        "keywords": [
            "auto",
            "cover",
            "contain"
        ],
        "name": "background-size"
    },
    {
        "name": "base-palette"
    },
    {
        "name": "base-url"
    },
    {
        "keywords": [
            "baseline",
            "sub",
            "super"
        ],
        "name": "baseline-shift"
    },
    {
        "keywords": [
            "auto",
            "first",
            "last"
        ],
        "name": "baseline-source"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "no-ellipsis"
        ],
        "name": "block-ellipsis"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "block-size"
    },
    {
        "longhands": [
            "border-top-color",
            "border-top-style",
            "border-top-width",
            "border-right-color",
            "border-right-style",
            "border-right-width",
            "border-bottom-color",
            "border-bottom-style",
            "border-bottom-width",
            "border-left-color",
            "border-left-style",
            "border-left-width",
            "border-image-source",
            "border-image-slice",
            "border-image-width",
            "border-image-outset",
            "border-image-repeat"
        ],
        "name": "border"
    },
    {
        "longhands": [
            "border-block-start-color",
            "border-block-start-style",
            "border-block-start-width",
            "border-block-end-color",
            "border-block-end-style",
            "border-block-end-width"
        ],
        "name": "border-block"
    },
    {
        "longhands": [
            "border-block-start-color",
            "border-block-end-color"
        ],
        "name": "border-block-color"
    },
    {
        "longhands": [
            "border-block-end-width",
            "border-block-end-style",
            "border-block-end-color"
        ],
        "name": "border-block-end"
    },
    {
        "name": "border-block-end-color"
    },
    {
        "name": "border-block-end-style"
    },
    {
        "name": "border-block-end-width"
    },
    {
        "longhands": [
            "border-block-start-width",
            "border-block-start-style",
            "border-block-start-color"
        ],
        "name": "border-block-start"
    },
    {
        "name": "border-block-start-color"
    },
    {
        "name": "border-block-start-style"
    },
    {
        "name": "border-block-start-width"
    },
    {
        "longhands": [
            "border-block-start-style",
            "border-block-end-style"
        ],
        "name": "border-block-style"
    },
    {
        "longhands": [
            "border-block-start-width",
            "border-block-end-width"
        ],
        "name": "border-block-width"
    },
    {
        "longhands": [
            "border-bottom-width",
            "border-bottom-style",
            "border-bottom-color"
        ],
        "name": "border-bottom"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "border-bottom-color"
    },
    {
        "name": "border-bottom-left-radius"
    },
    {
        "name": "border-bottom-right-radius"
    },
    {
        "keywords": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ],
        "name": "border-bottom-style"
    },
    {
        "keywords": [
            "thin",
            "medium",
            "thick"
        ],
        "name": "border-bottom-width"
    },
    {
        "inherited": true,
        "keywords": [
            "separate",
            "collapse"
        ],
        "name": "border-collapse"
    },
    {
        "longhands": [
            "border-top-color",
            "border-right-color",
            "border-bottom-color",
            "border-left-color"
        ],
        "name": "border-color"
    },
    {
        "name": "border-end-end-radius"
    },
    {
        "name": "border-end-start-radius"
    },
    {
        "longhands": [
            "border-image-source",
            "border-image-slice",
            "border-image-width",
            "border-image-outset",
            "border-image-repeat"
        ],
        "name": "border-image"
    },
    {
        "name": "border-image-outset"
    },
    {
        "keywords": [
            "stretch",
            "repeat",
            "round",
            "space"
        ],
        "name": "border-image-repeat"
    },
    {
        "name": "border-image-slice"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "border-image-source"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "border-image-width"
    },
    {
        "longhands": [
            "border-inline-start-color",
            "border-inline-start-style",
            "border-inline-start-width",
            "border-inline-end-color",
            "border-inline-end-style",
            "border-inline-end-width"
        ],
        "name": "border-inline"
    },
    {
        "longhands": [
            "border-inline-start-color",
            "border-inline-end-color"
        ],
        "name": "border-inline-color"
    },
    {
        "longhands": [
            "border-inline-end-width",
            "border-inline-end-style",
            "border-inline-end-color"
        ],
        "name": "border-inline-end"
    },
    {
        "name": "border-inline-end-color"
    },
    {
        "name": "border-inline-end-style"
    },
    {
        "name": "border-inline-end-width"
    },
    {
        "longhands": [
            "border-inline-start-width",
            "border-inline-start-style",
            "border-inline-start-color"
        ],
        "name": "border-inline-start"
    },
    {
        "name": "border-inline-start-color"
    },
    {
        "name": "border-inline-start-style"
    },
    {
        "name": "border-inline-start-width"
    },
    {
        "longhands": [
            "border-inline-start-style",
            "border-inline-end-style"
        ],
        "name": "border-inline-style"
    },
    {
        "longhands": [
            "border-inline-start-width",
            "border-inline-end-width"
        ],
        "name": "border-inline-width"
    },
    {
        "longhands": [
            "border-left-width",
            "border-left-style",
            "border-left-color"
        ],
        "name": "border-left"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "border-left-color"
    },
    {
        "keywords": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ],
        "name": "border-left-style"
    },
    {
        "keywords": [
            "thin",
            "medium",
            "thick"
        ],
        "name": "border-left-width"
    },
    {
        "longhands": [
            "border-top-left-radius",
            "border-top-right-radius",
            "border-bottom-right-radius",
            "border-bottom-left-radius"
        ],
        "name": "border-radius"
    },
    {
        "longhands": [
            "border-right-width",
            "border-right-style",
            "border-right-color"
        ],
        "name": "border-right"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "border-right-color"
    },
    {
        "keywords": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ],
        "name": "border-right-style"
    },
    {
        "keywords": [
            "thin",
            "medium",
            "thick"
        ],
        "name": "border-right-width"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "border-shape"
    },
    {
        "inherited": true,
        "longhands": [
            "-webkit-border-horizontal-spacing",
            "-webkit-border-vertical-spacing"
        ],
        "name": "border-spacing"
    },
    {
        "name": "border-start-end-radius"
    },
    {
        "name": "border-start-start-radius"
    },
    {
        "keywords": [
            "none"
        ],
        "longhands": [
            "border-top-style",
            "border-right-style",
            "border-bottom-style",
            "border-left-style"
        ],
        "name": "border-style"
    },
    {
        "longhands": [
            "border-top-width",
            "border-top-style",
            "border-top-color"
        ],
        "name": "border-top"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "border-top-color"
    },
    {
        "name": "border-top-left-radius"
    },
    {
        "name": "border-top-right-radius"
    },
    {
        "keywords": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ],
        "name": "border-top-style"
    },
    {
        "keywords": [
            "thin",
            "medium",
            "thick"
        ],
        "name": "border-top-width"
    },
    {
        "longhands": [
            "border-top-width",
            "border-right-width",
            "border-bottom-width",
            "border-left-width"
        ],
        "name": "border-width"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "bottom"
    },
    {
        "keywords": [
            "slice",
            "clone"
        ],
        "name": "box-decoration-break"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "box-shadow"
    },
    {
        "keywords": [
            "content-box",
            "border-box"
        ],
        "name": "box-sizing"
    },
    {
        "keywords": [
            "auto",
            "avoid",
            "avoid-column",
            "avoid-page",
            "column",
            "left",
            "page",
            "recto",
            "right",
            "verso"
        ],
        "name": "break-after"
    },
    {
        "keywords": [
            "auto",
            "avoid",
            "avoid-column",
            "avoid-page",
            "column",
            "left",
            "page",
            "recto",
            "right",
            "verso"
        ],
        "name": "break-before"
    },
    {
        "keywords": [
            "auto",
            "avoid",
            "avoid-column",
            "avoid-page"
        ],
        "name": "break-inside"
    },
    {
        "keywords": [
            "auto",
            "dynamic",
            "static"
        ],
        "name": "buffered-rendering"
    },
    {
        "inherited": true,
        "keywords": [
            "top",
            "bottom"
        ],
        "name": "caption-side"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "manual"
        ],
        "name": "caret-animation"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "currentcolor"
        ],
        "name": "caret-color"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "bar",
            "block",
            "underscore"
        ],
        "name": "caret-shape"
    },
    {
        "keywords": [
            "none",
            "left",
            "right",
            "both",
            "inline-start",
            "inline-end"
        ],
        "name": "clear"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "clip"
    },
    {
        "keywords": [
            "border-box",
            "padding-box",
            "content-box",
            "margin-box",
            "fill-box",
            "stroke-box",
            "view-box",
            "none"
        ],
        "name": "clip-path"
    },
    {
        "inherited": true,
        "keywords": [
            "nonzero",
            "evenodd"
        ],
        "name": "clip-rule"
    },
    {
        "inherited": true,
        "keywords": [
            "currentcolor"
        ],
        "name": "color"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "srgb",
            "linearrgb"
        ],
        "name": "color-interpolation"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "srgb",
            "linearrgb"
        ],
        "name": "color-interpolation-filters"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "optimizespeed",
            "optimizequality"
        ],
        "name": "color-rendering"
    },
    {
        "inherited": true,
        "name": "color-scheme"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "column-count"
    },
    {
        "keywords": [
            "balance",
            "auto"
        ],
        "name": "column-fill"
    },
    {
        "keywords": [
            "normal"
        ],
        "name": "column-gap"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "column-height"
    },
    {
        "longhands": [
            "column-rule-width",
            "column-rule-style",
            "column-rule-color"
        ],
        "name": "column-rule"
    },
    {
        "inherited": false,
        "keywords": [
            "none",
            "normal",
            "intersection"
        ],
        "name": "column-rule-break"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "column-rule-color"
    },
    {
        "longhands": [
            "column-rule-edge-inset-start",
            "column-rule-edge-inset-end"
        ],
        "name": "column-rule-edge-inset"
    },
    {
        "inherited": false,
        "name": "column-rule-edge-inset-end"
    },
    {
        "inherited": false,
        "name": "column-rule-edge-inset-start"
    },
    {
        "longhands": [
            "column-rule-edge-inset-start",
            "column-rule-edge-inset-end",
            "column-rule-interior-inset-start",
            "column-rule-interior-inset-end"
        ],
        "name": "column-rule-inset"
    },
    {
        "longhands": [
            "column-rule-edge-inset-end",
            "column-rule-interior-inset-end"
        ],
        "name": "column-rule-inset-end"
    },
    {
        "longhands": [
            "column-rule-edge-inset-start",
            "column-rule-interior-inset-start"
        ],
        "name": "column-rule-inset-start"
    },
    {
        "longhands": [
            "column-rule-interior-inset-start",
            "column-rule-interior-inset-end"
        ],
        "name": "column-rule-interior-inset"
    },
    {
        "inherited": false,
        "name": "column-rule-interior-inset-end"
    },
    {
        "inherited": false,
        "name": "column-rule-interior-inset-start"
    },
    {
        "keywords": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ],
        "name": "column-rule-style"
    },
    {
        "inherited": false,
        "keywords": [
            "all",
            "auto",
            "around",
            "between"
        ],
        "name": "column-rule-visibility-items"
    },
    {
        "keywords": [
            "thin",
            "medium",
            "thick"
        ],
        "name": "column-rule-width"
    },
    {
        "keywords": [
            "none",
            "all"
        ],
        "name": "column-span"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "column-width"
    },
    {
        "keywords": [
            "auto",
            "nowrap",
            "wrap"
        ],
        "name": "column-wrap"
    },
    {
        "longhands": [
            "column-width",
            "column-count",
            "column-height",
            "column-wrap"
        ],
        "name": "columns"
    },
    {
        "keywords": [
            "none",
            "strict",
            "content",
            "size",
            "layout",
            "style",
            "paint",
            "inline-size",
            "block-size"
        ],
        "name": "contain"
    },
    {
        "name": "contain-intrinsic-block-size"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "contain-intrinsic-height"
    },
    {
        "name": "contain-intrinsic-inline-size"
    },
    {
        "longhands": [
            "contain-intrinsic-width",
            "contain-intrinsic-height"
        ],
        "name": "contain-intrinsic-size"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "contain-intrinsic-width"
    },
    {
        "longhands": [
            "container-name",
            "container-type"
        ],
        "name": "container"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "container-name"
    },
    {
        "keywords": [
            "normal",
            "inline-size",
            "size",
            "scroll-state",
            "anchored"
        ],
        "name": "container-type"
    },
    {
        "name": "content"
    },
    {
        "keywords": [
            "visible",
            "auto",
            "hidden"
        ],
        "name": "content-visibility"
    },
    {
        "keywords": [
            "auto",
            "collapse",
            "-webkit-legacy"
        ],
        "name": "continue"
    },
    {
        "longhands": [
            "corner-end-start-shape",
            "corner-end-end-shape"
        ],
        "name": "corner-block-end-shape"
    },
    {
        "longhands": [
            "corner-start-start-shape",
            "corner-start-end-shape"
        ],
        "name": "corner-block-start-shape"
    },
    {
        "keywords": [
            "notch",
            "scoop",
            "bevel",
            "round",
            "squircle",
            "square"
        ],
        "name": "corner-bottom-left-shape"
    },
    {
        "keywords": [
            "notch",
            "scoop",
            "bevel",
            "round",
            "squircle",
            "square"
        ],
        "name": "corner-bottom-right-shape"
    },
    {
        "longhands": [
            "corner-bottom-left-shape",
            "corner-bottom-right-shape"
        ],
        "name": "corner-bottom-shape"
    },
    {
        "name": "corner-end-end-shape"
    },
    {
        "name": "corner-end-start-shape"
    },
    {
        "longhands": [
            "corner-start-end-shape",
            "corner-end-end-shape"
        ],
        "name": "corner-inline-end-shape"
    },
    {
        "longhands": [
            "corner-start-start-shape",
            "corner-end-start-shape"
        ],
        "name": "corner-inline-start-shape"
    },
    {
        "longhands": [
            "corner-top-left-shape",
            "corner-bottom-left-shape"
        ],
        "name": "corner-left-shape"
    },
    {
        "longhands": [
            "corner-top-right-shape",
            "corner-bottom-right-shape"
        ],
        "name": "corner-right-shape"
    },
    {
        "longhands": [
            "corner-top-left-shape",
            "corner-top-right-shape",
            "corner-bottom-right-shape",
            "corner-bottom-left-shape"
        ],
        "name": "corner-shape"
    },
    {
        "name": "corner-start-end-shape"
    },
    {
        "name": "corner-start-start-shape"
    },
    {
        "keywords": [
            "notch",
            "scoop",
            "bevel",
            "round",
            "squircle",
            "square"
        ],
        "name": "corner-top-left-shape"
    },
    {
        "keywords": [
            "notch",
            "scoop",
            "bevel",
            "round",
            "squircle",
            "square"
        ],
        "name": "corner-top-right-shape"
    },
    {
        "longhands": [
            "corner-top-left-shape",
            "corner-top-right-shape"
        ],
        "name": "corner-top-shape"
    },
    {
        "keywords": [
            "normal"
        ],
        "longhands": [
            "border-top-left-radius",
            "corner-top-left-shape",
            "border-top-right-radius",
            "corner-top-right-shape",
            "border-bottom-right-radius",
            "corner-bottom-right-shape",
            "border-bottom-left-radius",
            "corner-bottom-left-shape"
        ],
        "name": "corners"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "counter-increment"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "counter-reset"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "counter-set"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "default",
            "none",
            "context-menu",
            "help",
            "pointer",
            "progress",
            "wait",
            "cell",
            "crosshair",
            "text",
            "vertical-text",
            "alias",
            "copy",
            "move",
            "no-drop",
            "not-allowed",
            "e-resize",
            "n-resize",
            "ne-resize",
            "nw-resize",
            "s-resize",
            "se-resize",
            "sw-resize",
            "w-resize",
            "ew-resize",
            "ns-resize",
            "nesw-resize",
            "nwse-resize",
            "col-resize",
            "row-resize",
            "all-scroll",
            "zoom-in",
            "zoom-out",
            "grab",
            "grabbing"
        ],
        "name": "cursor"
    },
    {
        "name": "cx"
    },
    {
        "name": "cy"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "d"
    },
    {
        "name": "descent-override"
    },
    {
        "inherited": true,
        "keywords": [
            "ltr",
            "rtl"
        ],
        "name": "direction"
    },
    {
        "keywords": [
            "inline",
            "block",
            "list-item",
            "inline-block",
            "table",
            "inline-table",
            "table-row-group",
            "table-header-group",
            "table-footer-group",
            "table-row",
            "table-column-group",
            "table-column",
            "table-cell",
            "table-caption",
            "-webkit-box",
            "-webkit-inline-box",
            "flex",
            "inline-flex",
            "grid",
            "inline-grid",
            "contents",
            "flow-root",
            "none",
            "flow",
            "math",
            "ruby",
            "ruby-text",
            "grid-lanes",
            "inline-grid-lanes"
        ],
        "name": "display"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "alphabetic",
            "ideographic",
            "middle",
            "central",
            "mathematical",
            "hanging",
            "use-script",
            "no-change",
            "reset-size",
            "text-after-edge",
            "text-before-edge"
        ],
        "name": "dominant-baseline"
    },
    {
        "inherited": true,
        "keywords": [
            "standard",
            "no-limit",
            "constrained"
        ],
        "name": "dynamic-range-limit"
    },
    {
        "inherited": true,
        "keywords": [
            "show",
            "hide"
        ],
        "name": "empty-cells"
    },
    {
        "name": "fallback"
    },
    {
        "keywords": [
            "fixed",
            "content"
        ],
        "name": "field-sizing"
    },
    {
        "inherited": true,
        "name": "fill"
    },
    {
        "inherited": true,
        "name": "fill-opacity"
    },
    {
        "inherited": true,
        "keywords": [
            "nonzero",
            "evenodd"
        ],
        "name": "fill-rule"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "filter"
    },
    {
        "longhands": [
            "flex-grow",
            "flex-shrink",
            "flex-basis"
        ],
        "name": "flex"
    },
    {
        "keywords": [
            "auto",
            "fit-content",
            "min-content",
            "max-content",
            "content"
        ],
        "name": "flex-basis"
    },
    {
        "keywords": [
            "row",
            "row-reverse",
            "column",
            "column-reverse"
        ],
        "name": "flex-direction"
    },
    {
        "longhands": [
            "flex-direction",
            "flex-wrap"
        ],
        "name": "flex-flow"
    },
    {
        "name": "flex-grow"
    },
    {
        "name": "flex-shrink"
    },
    {
        "keywords": [
            "nowrap",
            "wrap",
            "wrap-reverse",
            "balance"
        ],
        "name": "flex-wrap"
    },
    {
        "keywords": [
            "none",
            "left",
            "right",
            "inline-start",
            "inline-end"
        ],
        "name": "float"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "flood-color"
    },
    {
        "name": "flood-opacity"
    },
    {
        "keywords": [
            "normal",
            "infinite"
        ],
        "name": "flow-tolerance"
    },
    {
        "inherited": true,
        "longhands": [
            "font-style",
            "font-variant-ligatures",
            "font-variant-caps",
            "font-variant-numeric",
            "font-variant-east-asian",
            "font-variant-alternates",
            "font-variant-position",
            "font-variant-emoji",
            "font-weight",
            "font-stretch",
            "font-size",
            "line-height",
            "font-family",
            "font-optical-sizing",
            "font-size-adjust",
            "font-kerning",
            "font-feature-settings",
            "font-variation-settings",
            "font-language-override"
        ],
        "name": "font"
    },
    {
        "name": "font-display"
    },
    {
        "inherited": true,
        "name": "font-family"
    },
    {
        "inherited": true,
        "keywords": [
            "normal"
        ],
        "name": "font-feature-settings"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "normal",
            "none"
        ],
        "name": "font-kerning"
    },
    {
        "inherited": true,
        "keywords": [
            "normal"
        ],
        "name": "font-language-override"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "none"
        ],
        "name": "font-optical-sizing"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "light",
            "dark"
        ],
        "name": "font-palette"
    },
    {
        "inherited": true,
        "keywords": [
            "xx-small",
            "x-small",
            "small",
            "medium",
            "large",
            "x-large",
            "xx-large",
            "xxx-large",
            "larger",
            "smaller",
            "-webkit-xxx-large"
        ],
        "name": "font-size"
    },
    {
        "inherited": true,
        "keywords": [
            "none",
            "ex-height",
            "cap-height",
            "ch-width",
            "ic-width",
            "ic-height",
            "from-font"
        ],
        "name": "font-size-adjust"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "ultra-condensed",
            "extra-condensed",
            "condensed",
            "semi-condensed",
            "semi-expanded",
            "expanded",
            "extra-expanded",
            "ultra-expanded"
        ],
        "name": "font-stretch"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "italic",
            "oblique"
        ],
        "name": "font-style"
    },
    {
        "inherited": true,
        "longhands": [
            "font-synthesis-weight",
            "font-synthesis-style",
            "font-synthesis-small-caps"
        ],
        "name": "font-synthesis"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "none"
        ],
        "name": "font-synthesis-small-caps"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "none"
        ],
        "name": "font-synthesis-style"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "none"
        ],
        "name": "font-synthesis-weight"
    },
    {
        "inherited": true,
        "longhands": [
            "font-variant-ligatures",
            "font-variant-caps",
            "font-variant-alternates",
            "font-variant-numeric",
            "font-variant-east-asian",
            "font-variant-position",
            "font-variant-emoji"
        ],
        "name": "font-variant"
    },
    {
        "inherited": true,
        "keywords": [
            "normal"
        ],
        "name": "font-variant-alternates"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "small-caps",
            "all-small-caps",
            "petite-caps",
            "all-petite-caps",
            "unicase",
            "titling-caps"
        ],
        "name": "font-variant-caps"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "jis78",
            "jis83",
            "jis90",
            "jis04",
            "simplified",
            "traditional",
            "full-width",
            "proportional-width",
            "ruby"
        ],
        "name": "font-variant-east-asian"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "text",
            "emoji",
            "unicode"
        ],
        "name": "font-variant-emoji"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "none",
            "common-ligatures",
            "no-common-ligatures",
            "discretionary-ligatures",
            "no-discretionary-ligatures",
            "historical-ligatures",
            "no-historical-ligatures",
            "contextual",
            "no-contextual"
        ],
        "name": "font-variant-ligatures"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "lining-nums",
            "oldstyle-nums",
            "proportional-nums",
            "tabular-nums",
            "diagonal-fractions",
            "stacked-fractions",
            "ordinal",
            "slashed-zero"
        ],
        "name": "font-variant-numeric"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "sub",
            "super"
        ],
        "name": "font-variant-position"
    },
    {
        "inherited": true,
        "keywords": [
            "normal"
        ],
        "name": "font-variation-settings"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "bold",
            "bolder",
            "lighter"
        ],
        "name": "font-weight"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "none",
            "preserve-parent-color"
        ],
        "name": "forced-color-adjust"
    },
    {
        "keywords": [
            "auto",
            "content-width",
            "content-height",
            "content-block-size",
            "content-inline-size"
        ],
        "name": "frame-sizing"
    },
    {
        "longhands": [
            "row-gap",
            "column-gap"
        ],
        "name": "gap"
    },
    {
        "longhands": [
            "grid-template-rows",
            "grid-template-columns",
            "grid-template-areas",
            "grid-auto-flow",
            "grid-auto-rows",
            "grid-auto-columns"
        ],
        "name": "grid"
    },
    {
        "longhands": [
            "grid-row-start",
            "grid-column-start",
            "grid-row-end",
            "grid-column-end"
        ],
        "name": "grid-area"
    },
    {
        "keywords": [
            "auto",
            "min-content",
            "max-content"
        ],
        "name": "grid-auto-columns"
    },
    {
        "keywords": [
            "row",
            "column"
        ],
        "name": "grid-auto-flow"
    },
    {
        "keywords": [
            "auto",
            "min-content",
            "max-content"
        ],
        "name": "grid-auto-rows"
    },
    {
        "longhands": [
            "grid-column-start",
            "grid-column-end"
        ],
        "name": "grid-column"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "grid-column-end"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "grid-column-start"
    },
    {
        "longhands": [
            "grid-template-areas",
            "grid-template-columns",
            "grid-template-rows",
            "grid-lanes-direction"
        ],
        "name": "grid-lanes"
    },
    {
        "keywords": [
            "normal",
            "row",
            "column",
            "fill-reverse",
            "track-reverse"
        ],
        "name": "grid-lanes-direction"
    },
    {
        "keywords": [
            "normal",
            "dense"
        ],
        "name": "grid-lanes-pack"
    },
    {
        "longhands": [
            "grid-row-start",
            "grid-row-end"
        ],
        "name": "grid-row"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "grid-row-end"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "grid-row-start"
    },
    {
        "longhands": [
            "grid-template-rows",
            "grid-template-columns",
            "grid-template-areas"
        ],
        "name": "grid-template"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "grid-template-areas"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "grid-template-columns"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "grid-template-rows"
    },
    {
        "name": "hash"
    },
    {
        "keywords": [
            "auto",
            "fit-content",
            "min-content",
            "max-content"
        ],
        "name": "height"
    },
    {
        "name": "hostname"
    },
    {
        "inherited": true,
        "name": "hyphenate-character"
    },
    {
        "inherited": true,
        "keywords": [
            "auto"
        ],
        "name": "hyphenate-limit-chars"
    },
    {
        "inherited": true,
        "keywords": [
            "none",
            "manual",
            "auto"
        ],
        "name": "hyphens"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "running",
            "paused"
        ],
        "name": "image-animation"
    },
    {
        "inherited": true,
        "name": "image-orientation"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "optimizespeed",
            "optimizequality",
            "-webkit-optimize-contrast",
            "pixelated"
        ],
        "name": "image-rendering"
    },
    {
        "name": "inherits"
    },
    {
        "inherited": false,
        "keywords": [
            "drop",
            "normal",
            "raise"
        ],
        "name": "initial-letter"
    },
    {
        "name": "initial-value"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "inline-size"
    },
    {
        "longhands": [
            "top",
            "right",
            "bottom",
            "left"
        ],
        "name": "inset"
    },
    {
        "longhands": [
            "inset-block-start",
            "inset-block-end"
        ],
        "name": "inset-block"
    },
    {
        "name": "inset-block-end"
    },
    {
        "name": "inset-block-start"
    },
    {
        "longhands": [
            "inset-inline-start",
            "inset-inline-end"
        ],
        "name": "inset-inline"
    },
    {
        "name": "inset-inline-end"
    },
    {
        "name": "inset-inline-start"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "inert"
        ],
        "name": "interactivity"
    },
    {
        "longhands": [
            "interest-delay-start",
            "interest-delay-end"
        ],
        "name": "interest-delay"
    },
    {
        "name": "interest-delay-end"
    },
    {
        "name": "interest-delay-start"
    },
    {
        "inherited": true,
        "keywords": [
            "numeric-only",
            "allow-keywords"
        ],
        "name": "interpolate-size"
    },
    {
        "keywords": [
            "auto",
            "isolate"
        ],
        "name": "isolation"
    },
    {
        "name": "justify-content"
    },
    {
        "name": "justify-items"
    },
    {
        "name": "justify-self"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "left"
    },
    {
        "inherited": true,
        "keywords": [
            "normal"
        ],
        "name": "letter-spacing"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "lighting-color"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "loose",
            "normal",
            "strict",
            "anywhere",
            "after-white-space"
        ],
        "name": "line-break"
    },
    {
        "longhands": [
            "max-lines",
            "block-ellipsis",
            "continue"
        ],
        "name": "line-clamp"
    },
    {
        "name": "line-gap-override"
    },
    {
        "inherited": true,
        "keywords": [
            "normal"
        ],
        "name": "line-height"
    },
    {
        "inherited": true,
        "longhands": [
            "list-style-position",
            "list-style-image",
            "list-style-type"
        ],
        "name": "list-style"
    },
    {
        "inherited": true,
        "keywords": [
            "none"
        ],
        "name": "list-style-image"
    },
    {
        "inherited": true,
        "keywords": [
            "outside",
            "inside"
        ],
        "name": "list-style-position"
    },
    {
        "inherited": true,
        "keywords": [
            "disc",
            "circle",
            "square",
            "disclosure-open",
            "disclosure-closed",
            "decimal",
            "none"
        ],
        "name": "list-style-type"
    },
    {
        "longhands": [
            "margin-top",
            "margin-right",
            "margin-bottom",
            "margin-left"
        ],
        "name": "margin"
    },
    {
        "longhands": [
            "margin-block-start",
            "margin-block-end"
        ],
        "name": "margin-block"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "margin-block-end"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "margin-block-start"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "margin-bottom"
    },
    {
        "longhands": [
            "margin-inline-start",
            "margin-inline-end"
        ],
        "name": "margin-inline"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "margin-inline-end"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "margin-inline-start"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "margin-left"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "margin-right"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "margin-top"
    },
    {
        "name": "margin-trim"
    },
    {
        "inherited": true,
        "longhands": [
            "marker-start",
            "marker-mid",
            "marker-end"
        ],
        "name": "marker"
    },
    {
        "inherited": true,
        "keywords": [
            "none"
        ],
        "name": "marker-end"
    },
    {
        "inherited": true,
        "keywords": [
            "none"
        ],
        "name": "marker-mid"
    },
    {
        "inherited": true,
        "keywords": [
            "none"
        ],
        "name": "marker-start"
    },
    {
        "longhands": [
            "mask-image",
            "-webkit-mask-position-x",
            "-webkit-mask-position-y",
            "mask-size",
            "mask-repeat",
            "mask-origin",
            "mask-clip",
            "mask-composite",
            "mask-mode"
        ],
        "name": "mask"
    },
    {
        "name": "mask-clip"
    },
    {
        "keywords": [
            "add",
            "subtract",
            "intersect",
            "exclude"
        ],
        "name": "mask-composite"
    },
    {
        "name": "mask-image"
    },
    {
        "keywords": [
            "alpha",
            "luminance",
            "match-source"
        ],
        "name": "mask-mode"
    },
    {
        "name": "mask-origin"
    },
    {
        "longhands": [
            "-webkit-mask-position-x",
            "-webkit-mask-position-y"
        ],
        "name": "mask-position"
    },
    {
        "name": "mask-repeat"
    },
    {
        "name": "mask-size"
    },
    {
        "keywords": [
            "luminance",
            "alpha"
        ],
        "name": "mask-type"
    },
    {
        "inherited": true,
        "name": "math-depth"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "compact"
        ],
        "name": "math-shift"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "compact"
        ],
        "name": "math-style"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "max-block-size"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "max-height"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "max-inline-size"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "max-lines"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "max-width"
    },
    {
        "name": "min-block-size"
    },
    {
        "name": "min-height"
    },
    {
        "name": "min-inline-size"
    },
    {
        "name": "min-width"
    },
    {
        "keywords": [
            "normal",
            "multiply",
            "screen",
            "overlay",
            "darken",
            "lighten",
            "color-dodge",
            "color-burn",
            "hard-light",
            "soft-light",
            "difference",
            "exclusion",
            "hue",
            "saturation",
            "color",
            "luminosity",
            "plus-lighter"
        ],
        "name": "mix-blend-mode"
    },
    {
        "name": "navigation"
    },
    {
        "name": "negative"
    },
    {
        "keywords": [
            "fill",
            "contain",
            "cover",
            "none",
            "scale-down"
        ],
        "name": "object-fit"
    },
    {
        "name": "object-position"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "object-view-box"
    },
    {
        "longhands": [
            "offset-position",
            "offset-path",
            "offset-distance",
            "offset-rotate",
            "offset-anchor"
        ],
        "name": "offset"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "offset-anchor"
    },
    {
        "name": "offset-distance"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "offset-path"
    },
    {
        "keywords": [
            "auto",
            "normal"
        ],
        "name": "offset-position"
    },
    {
        "keywords": [
            "auto",
            "reverse"
        ],
        "name": "offset-rotate"
    },
    {
        "name": "opacity"
    },
    {
        "name": "order"
    },
    {
        "keywords": [
            "normal",
            "none"
        ],
        "name": "origin-trial-test-property"
    },
    {
        "inherited": true,
        "name": "orphans"
    },
    {
        "longhands": [
            "outline-color",
            "outline-style",
            "outline-width"
        ],
        "name": "outline"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "outline-color"
    },
    {
        "name": "outline-offset"
    },
    {
        "keywords": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ],
        "name": "outline-style"
    },
    {
        "keywords": [
            "thin",
            "medium",
            "thick"
        ],
        "name": "outline-width"
    },
    {
        "longhands": [
            "overflow-x",
            "overflow-y"
        ],
        "name": "overflow"
    },
    {
        "inherited": false,
        "keywords": [
            "visible",
            "none",
            "auto"
        ],
        "name": "overflow-anchor"
    },
    {
        "name": "overflow-block"
    },
    {
        "keywords": [
            "border-box",
            "content-box",
            "padding-box"
        ],
        "name": "overflow-clip-margin"
    },
    {
        "name": "overflow-inline"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "break-word",
            "anywhere"
        ],
        "name": "overflow-wrap"
    },
    {
        "keywords": [
            "visible",
            "hidden",
            "scroll",
            "auto",
            "overlay",
            "clip"
        ],
        "name": "overflow-x"
    },
    {
        "keywords": [
            "visible",
            "hidden",
            "scroll",
            "auto",
            "overlay",
            "clip"
        ],
        "name": "overflow-y"
    },
    {
        "keywords": [
            "none",
            "auto"
        ],
        "name": "overlay"
    },
    {
        "name": "override-colors"
    },
    {
        "longhands": [
            "overscroll-behavior-x",
            "overscroll-behavior-y"
        ],
        "name": "overscroll-behavior"
    },
    {
        "name": "overscroll-behavior-block"
    },
    {
        "name": "overscroll-behavior-inline"
    },
    {
        "keywords": [
            "auto",
            "contain",
            "none"
        ],
        "name": "overscroll-behavior-x"
    },
    {
        "keywords": [
            "auto",
            "contain",
            "none"
        ],
        "name": "overscroll-behavior-y"
    },
    {
        "name": "pad"
    },
    {
        "longhands": [
            "padding-top",
            "padding-right",
            "padding-bottom",
            "padding-left"
        ],
        "name": "padding"
    },
    {
        "longhands": [
            "padding-block-start",
            "padding-block-end"
        ],
        "name": "padding-block"
    },
    {
        "name": "padding-block-end"
    },
    {
        "name": "padding-block-start"
    },
    {
        "name": "padding-bottom"
    },
    {
        "longhands": [
            "padding-inline-start",
            "padding-inline-end"
        ],
        "name": "padding-inline"
    },
    {
        "name": "padding-inline-end"
    },
    {
        "name": "padding-inline-start"
    },
    {
        "name": "padding-left"
    },
    {
        "name": "padding-right"
    },
    {
        "name": "padding-top"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "page"
    },
    {
        "longhands": [
            "break-after"
        ],
        "name": "page-break-after"
    },
    {
        "longhands": [
            "break-before"
        ],
        "name": "page-break-before"
    },
    {
        "longhands": [
            "break-inside"
        ],
        "name": "page-break-inside"
    },
    {
        "keywords": [
            "none",
            "clamp",
            "add"
        ],
        "name": "page-margin-safety"
    },
    {
        "name": "page-orientation"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "fill",
            "stroke",
            "markers"
        ],
        "name": "paint-order"
    },
    {
        "name": "pathname"
    },
    {
        "name": "pattern"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "perspective"
    },
    {
        "name": "perspective-origin"
    },
    {
        "longhands": [
            "align-content",
            "justify-content"
        ],
        "name": "place-content"
    },
    {
        "longhands": [
            "align-items",
            "justify-items"
        ],
        "name": "place-items"
    },
    {
        "longhands": [
            "align-self",
            "justify-self"
        ],
        "name": "place-self"
    },
    {
        "inherited": true,
        "keywords": [
            "none",
            "auto",
            "stroke",
            "fill",
            "painted",
            "visible",
            "visiblestroke",
            "visiblefill",
            "visiblepainted",
            "bounding-box",
            "all"
        ],
        "name": "pointer-events"
    },
    {
        "name": "port"
    },
    {
        "keywords": [
            "static",
            "relative",
            "absolute",
            "fixed",
            "sticky"
        ],
        "name": "position"
    },
    {
        "keywords": [
            "auto",
            "none"
        ],
        "name": "position-anchor"
    },
    {
        "keywords": [
            "none",
            "top",
            "bottom",
            "center",
            "left",
            "right",
            "x-start",
            "x-end",
            "y-start",
            "y-end",
            "start",
            "end",
            "self-start",
            "self-end",
            "all"
        ],
        "name": "position-area"
    },
    {
        "longhands": [
            "position-try-order",
            "position-try-fallbacks"
        ],
        "name": "position-try"
    },
    {
        "keywords": [
            "none",
            "flip-block",
            "flip-inline",
            "flip-start",
            "flip-x",
            "flip-y"
        ],
        "name": "position-try-fallbacks"
    },
    {
        "keywords": [
            "normal",
            "most-width",
            "most-height",
            "most-block-size",
            "most-inline-size"
        ],
        "name": "position-try-order"
    },
    {
        "keywords": [
            "always",
            "anchors-visible",
            "no-overflow"
        ],
        "name": "position-visibility"
    },
    {
        "name": "prefix"
    },
    {
        "inherited": true,
        "keywords": [
            "economy",
            "exact"
        ],
        "name": "print-color-adjust"
    },
    {
        "name": "protocol"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "none"
        ],
        "name": "quotes"
    },
    {
        "name": "r"
    },
    {
        "name": "range"
    },
    {
        "keywords": [
            "normal",
            "flex-visual",
            "flex-flow",
            "grid-rows",
            "grid-columns",
            "grid-order",
            "source-order"
        ],
        "name": "reading-flow"
    },
    {
        "name": "reading-order"
    },
    {
        "keywords": [
            "none",
            "both",
            "horizontal",
            "vertical",
            "block",
            "inline"
        ],
        "name": "resize"
    },
    {
        "name": "result"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "right"
    },
    {
        "name": "rotate"
    },
    {
        "keywords": [
            "normal"
        ],
        "name": "row-gap"
    },
    {
        "longhands": [
            "row-rule-width",
            "row-rule-style",
            "row-rule-color"
        ],
        "name": "row-rule"
    },
    {
        "inherited": false,
        "keywords": [
            "none",
            "normal",
            "intersection"
        ],
        "name": "row-rule-break"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "row-rule-color"
    },
    {
        "longhands": [
            "row-rule-edge-inset-start",
            "row-rule-edge-inset-end"
        ],
        "name": "row-rule-edge-inset"
    },
    {
        "inherited": false,
        "name": "row-rule-edge-inset-end"
    },
    {
        "inherited": false,
        "name": "row-rule-edge-inset-start"
    },
    {
        "longhands": [
            "row-rule-edge-inset-start",
            "row-rule-edge-inset-end",
            "row-rule-interior-inset-start",
            "row-rule-interior-inset-end"
        ],
        "name": "row-rule-inset"
    },
    {
        "longhands": [
            "row-rule-edge-inset-end",
            "row-rule-interior-inset-end"
        ],
        "name": "row-rule-inset-end"
    },
    {
        "longhands": [
            "row-rule-edge-inset-start",
            "row-rule-interior-inset-start"
        ],
        "name": "row-rule-inset-start"
    },
    {
        "longhands": [
            "row-rule-interior-inset-start",
            "row-rule-interior-inset-end"
        ],
        "name": "row-rule-interior-inset"
    },
    {
        "inherited": false,
        "name": "row-rule-interior-inset-end"
    },
    {
        "inherited": false,
        "name": "row-rule-interior-inset-start"
    },
    {
        "keywords": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ],
        "name": "row-rule-style"
    },
    {
        "inherited": false,
        "keywords": [
            "all",
            "auto",
            "around",
            "between"
        ],
        "name": "row-rule-visibility-items"
    },
    {
        "keywords": [
            "thin",
            "medium",
            "thick"
        ],
        "name": "row-rule-width"
    },
    {
        "inherited": true,
        "keywords": [
            "space-around",
            "start",
            "center",
            "space-between"
        ],
        "name": "ruby-align"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "none"
        ],
        "name": "ruby-overhang"
    },
    {
        "inherited": true,
        "keywords": [
            "over",
            "under"
        ],
        "name": "ruby-position"
    },
    {
        "longhands": [
            "column-rule-width",
            "column-rule-style",
            "column-rule-color",
            "row-rule-width",
            "row-rule-style",
            "row-rule-color"
        ],
        "name": "rule"
    },
    {
        "longhands": [
            "row-rule-break",
            "column-rule-break"
        ],
        "name": "rule-break"
    },
    {
        "longhands": [
            "column-rule-color",
            "row-rule-color"
        ],
        "name": "rule-color"
    },
    {
        "longhands": [
            "row-rule-edge-inset-start",
            "row-rule-edge-inset-end",
            "column-rule-edge-inset-start",
            "column-rule-edge-inset-end"
        ],
        "name": "rule-edge-inset"
    },
    {
        "longhands": [
            "row-rule-edge-inset-start",
            "row-rule-edge-inset-end",
            "row-rule-interior-inset-start",
            "row-rule-interior-inset-end",
            "column-rule-edge-inset-start",
            "column-rule-edge-inset-end",
            "column-rule-interior-inset-start",
            "column-rule-interior-inset-end"
        ],
        "name": "rule-inset"
    },
    {
        "longhands": [
            "column-rule-edge-inset-end",
            "column-rule-interior-inset-end",
            "row-rule-edge-inset-end",
            "row-rule-interior-inset-end"
        ],
        "name": "rule-inset-end"
    },
    {
        "longhands": [
            "column-rule-edge-inset-start",
            "column-rule-interior-inset-start",
            "row-rule-edge-inset-start",
            "row-rule-interior-inset-start"
        ],
        "name": "rule-inset-start"
    },
    {
        "longhands": [
            "row-rule-interior-inset-start",
            "row-rule-interior-inset-end",
            "column-rule-interior-inset-start",
            "column-rule-interior-inset-end"
        ],
        "name": "rule-interior-inset"
    },
    {
        "inherited": false,
        "keywords": [
            "row-over-column",
            "column-over-row"
        ],
        "name": "rule-overlap"
    },
    {
        "longhands": [
            "column-rule-style",
            "row-rule-style"
        ],
        "name": "rule-style"
    },
    {
        "longhands": [
            "column-rule-visibility-items",
            "row-rule-visibility-items"
        ],
        "name": "rule-visibility-items"
    },
    {
        "longhands": [
            "column-rule-width",
            "row-rule-width"
        ],
        "name": "rule-width"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "rx"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "ry"
    },
    {
        "name": "scale"
    },
    {
        "keywords": [
            "auto",
            "smooth"
        ],
        "name": "scroll-behavior"
    },
    {
        "keywords": [
            "none",
            "nearest"
        ],
        "name": "scroll-initial-target"
    },
    {
        "longhands": [
            "scroll-margin-top",
            "scroll-margin-right",
            "scroll-margin-bottom",
            "scroll-margin-left"
        ],
        "name": "scroll-margin"
    },
    {
        "longhands": [
            "scroll-margin-block-start",
            "scroll-margin-block-end"
        ],
        "name": "scroll-margin-block"
    },
    {
        "name": "scroll-margin-block-end"
    },
    {
        "name": "scroll-margin-block-start"
    },
    {
        "name": "scroll-margin-bottom"
    },
    {
        "longhands": [
            "scroll-margin-inline-start",
            "scroll-margin-inline-end"
        ],
        "name": "scroll-margin-inline"
    },
    {
        "name": "scroll-margin-inline-end"
    },
    {
        "name": "scroll-margin-inline-start"
    },
    {
        "name": "scroll-margin-left"
    },
    {
        "name": "scroll-margin-right"
    },
    {
        "name": "scroll-margin-top"
    },
    {
        "name": "scroll-marker-group"
    },
    {
        "longhands": [
            "scroll-padding-top",
            "scroll-padding-right",
            "scroll-padding-bottom",
            "scroll-padding-left"
        ],
        "name": "scroll-padding"
    },
    {
        "longhands": [
            "scroll-padding-block-start",
            "scroll-padding-block-end"
        ],
        "name": "scroll-padding-block"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "scroll-padding-block-end"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "scroll-padding-block-start"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "scroll-padding-bottom"
    },
    {
        "longhands": [
            "scroll-padding-inline-start",
            "scroll-padding-inline-end"
        ],
        "name": "scroll-padding-inline"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "scroll-padding-inline-end"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "scroll-padding-inline-start"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "scroll-padding-left"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "scroll-padding-right"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "scroll-padding-top"
    },
    {
        "keywords": [
            "none",
            "start",
            "end",
            "center"
        ],
        "name": "scroll-snap-align"
    },
    {
        "keywords": [
            "normal",
            "always"
        ],
        "name": "scroll-snap-stop"
    },
    {
        "keywords": [
            "none",
            "x",
            "y",
            "block",
            "inline",
            "both",
            "mandatory",
            "proximity"
        ],
        "name": "scroll-snap-type"
    },
    {
        "keywords": [
            "none",
            "auto"
        ],
        "name": "scroll-target-group"
    },
    {
        "longhands": [
            "scroll-timeline-name",
            "scroll-timeline-axis"
        ],
        "name": "scroll-timeline"
    },
    {
        "name": "scroll-timeline-axis"
    },
    {
        "name": "scroll-timeline-name"
    },
    {
        "inherited": true,
        "keywords": [
            "auto"
        ],
        "name": "scrollbar-color"
    },
    {
        "inherited": false,
        "keywords": [
            "auto",
            "stable",
            "both-edges"
        ],
        "name": "scrollbar-gutter"
    },
    {
        "inherited": false,
        "keywords": [
            "auto",
            "thin",
            "none"
        ],
        "name": "scrollbar-width"
    },
    {
        "name": "search"
    },
    {
        "name": "shape-image-threshold"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "shape-margin"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "shape-outside"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "optimizespeed",
            "crispedges",
            "geometricprecision"
        ],
        "name": "shape-rendering"
    },
    {
        "name": "size"
    },
    {
        "name": "size-adjust"
    },
    {
        "inherited": true,
        "keywords": [
            "none",
            "normal",
            "spell-out",
            "digits",
            "literal-punctuation",
            "no-punctuation"
        ],
        "name": "speak"
    },
    {
        "name": "speak-as"
    },
    {
        "name": "src"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "stop-color"
    },
    {
        "name": "stop-opacity"
    },
    {
        "inherited": true,
        "name": "stroke"
    },
    {
        "inherited": true,
        "keywords": [
            "none"
        ],
        "name": "stroke-dasharray"
    },
    {
        "inherited": true,
        "name": "stroke-dashoffset"
    },
    {
        "inherited": true,
        "keywords": [
            "butt",
            "round",
            "square"
        ],
        "name": "stroke-linecap"
    },
    {
        "inherited": true,
        "keywords": [
            "miter",
            "bevel",
            "round"
        ],
        "name": "stroke-linejoin"
    },
    {
        "inherited": true,
        "name": "stroke-miterlimit"
    },
    {
        "inherited": true,
        "name": "stroke-opacity"
    },
    {
        "inherited": true,
        "name": "stroke-width"
    },
    {
        "name": "suffix"
    },
    {
        "name": "symbols"
    },
    {
        "name": "syntax"
    },
    {
        "name": "system"
    },
    {
        "inherited": true,
        "name": "tab-size"
    },
    {
        "keywords": [
            "auto",
            "fixed"
        ],
        "name": "table-layout"
    },
    {
        "inherited": true,
        "keywords": [
            "left",
            "right",
            "center",
            "justify",
            "-webkit-left",
            "-webkit-right",
            "-webkit-center",
            "start",
            "end",
            "match-parent"
        ],
        "name": "text-align"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "start",
            "end",
            "left",
            "right",
            "center",
            "justify",
            "match-parent"
        ],
        "name": "text-align-last"
    },
    {
        "inherited": true,
        "keywords": [
            "start",
            "middle",
            "end"
        ],
        "name": "text-anchor"
    },
    {
        "inherited": true,
        "keywords": [
            "no-autospace",
            "normal"
        ],
        "name": "text-autospace"
    },
    {
        "longhands": [
            "text-box-trim",
            "text-box-edge"
        ],
        "name": "text-box"
    },
    {
        "inherited": true,
        "name": "text-box-edge"
    },
    {
        "keywords": [
            "none",
            "trim-start",
            "trim-end",
            "trim-both"
        ],
        "name": "text-box-trim"
    },
    {
        "inherited": true,
        "keywords": [
            "none",
            "all"
        ],
        "name": "text-combine-upright"
    },
    {
        "longhands": [
            "text-decoration-line",
            "text-decoration-thickness",
            "text-decoration-style",
            "text-decoration-color"
        ],
        "name": "text-decoration"
    },
    {
        "keywords": [
            "currentcolor"
        ],
        "name": "text-decoration-color"
    },
    {
        "keywords": [
            "none",
            "underline",
            "overline",
            "line-through",
            "blink",
            "spelling-error",
            "grammar-error"
        ],
        "name": "text-decoration-line"
    },
    {
        "inherited": true,
        "keywords": [
            "none",
            "auto",
            "all"
        ],
        "name": "text-decoration-skip-ink"
    },
    {
        "keywords": [
            "solid",
            "double",
            "dotted",
            "dashed",
            "wavy"
        ],
        "name": "text-decoration-style"
    },
    {
        "inherited": false,
        "keywords": [
            "auto",
            "from-font"
        ],
        "name": "text-decoration-thickness"
    },
    {
        "inherited": true,
        "longhands": [
            "text-emphasis-style",
            "text-emphasis-color"
        ],
        "name": "text-emphasis"
    },
    {
        "inherited": true,
        "keywords": [
            "currentcolor"
        ],
        "name": "text-emphasis-color"
    },
    {
        "inherited": true,
        "name": "text-emphasis-position"
    },
    {
        "inherited": true,
        "name": "text-emphasis-style"
    },
    {
        "name": "text-fit"
    },
    {
        "inherited": true,
        "name": "text-indent"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "none",
            "inter-word",
            "inter-character"
        ],
        "name": "text-justify"
    },
    {
        "inherited": true,
        "keywords": [
            "sideways",
            "mixed",
            "upright"
        ],
        "name": "text-orientation"
    },
    {
        "keywords": [
            "clip",
            "ellipsis"
        ],
        "name": "text-overflow"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "optimizespeed",
            "optimizelegibility",
            "geometricprecision"
        ],
        "name": "text-rendering"
    },
    {
        "inherited": true,
        "keywords": [
            "none"
        ],
        "name": "text-shadow"
    },
    {
        "inherited": true,
        "keywords": [
            "none",
            "auto"
        ],
        "name": "text-size-adjust"
    },
    {
        "inherited": true,
        "longhands": [
            "text-autospace",
            "text-spacing-trim"
        ],
        "name": "text-spacing"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "space-all",
            "space-first",
            "trim-start"
        ],
        "name": "text-spacing-trim"
    },
    {
        "inherited": true,
        "keywords": [
            "none",
            "capitalize",
            "uppercase",
            "lowercase",
            "full-width",
            "full-size-kana",
            "math-auto"
        ],
        "name": "text-transform"
    },
    {
        "inherited": true,
        "keywords": [
            "auto"
        ],
        "name": "text-underline-offset"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "from-font",
            "under",
            "left",
            "right"
        ],
        "name": "text-underline-position"
    },
    {
        "inherited": true,
        "longhands": [
            "text-wrap-mode",
            "text-wrap-style"
        ],
        "name": "text-wrap"
    },
    {
        "inherited": true,
        "keywords": [
            "wrap",
            "nowrap"
        ],
        "name": "text-wrap-mode"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "balance",
            "pretty",
            "stable"
        ],
        "name": "text-wrap-style"
    },
    {
        "name": "timeline-scope"
    },
    {
        "longhands": [
            "timeline-trigger-name",
            "timeline-trigger-source",
            "timeline-trigger-activation-range-start",
            "timeline-trigger-activation-range-end",
            "timeline-trigger-active-range-start",
            "timeline-trigger-active-range-end"
        ],
        "name": "timeline-trigger"
    },
    {
        "longhands": [
            "timeline-trigger-activation-range-start",
            "timeline-trigger-activation-range-end"
        ],
        "name": "timeline-trigger-activation-range"
    },
    {
        "name": "timeline-trigger-activation-range-end"
    },
    {
        "name": "timeline-trigger-activation-range-start"
    },
    {
        "longhands": [
            "timeline-trigger-active-range-start",
            "timeline-trigger-active-range-end"
        ],
        "name": "timeline-trigger-active-range"
    },
    {
        "name": "timeline-trigger-active-range-end"
    },
    {
        "name": "timeline-trigger-active-range-start"
    },
    {
        "name": "timeline-trigger-name"
    },
    {
        "keywords": [
            "none",
            "auto"
        ],
        "name": "timeline-trigger-source"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "top"
    },
    {
        "keywords": [
            "auto",
            "none",
            "pan-x",
            "pan-left",
            "pan-right",
            "pan-y",
            "pan-up",
            "pan-down",
            "pinch-zoom",
            "manipulation"
        ],
        "name": "touch-action"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "transform"
    },
    {
        "keywords": [
            "content-box",
            "border-box",
            "fill-box",
            "stroke-box",
            "view-box"
        ],
        "name": "transform-box"
    },
    {
        "name": "transform-origin"
    },
    {
        "keywords": [
            "flat",
            "preserve-3d"
        ],
        "name": "transform-style"
    },
    {
        "longhands": [
            "transition-property",
            "transition-duration",
            "transition-timing-function",
            "transition-delay",
            "transition-behavior"
        ],
        "name": "transition"
    },
    {
        "keywords": [
            "normal",
            "allow-discrete"
        ],
        "name": "transition-behavior"
    },
    {
        "name": "transition-delay"
    },
    {
        "name": "transition-duration"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "transition-property"
    },
    {
        "keywords": [
            "linear",
            "ease",
            "ease-in",
            "ease-out",
            "ease-in-out",
            "jump-both",
            "jump-end",
            "jump-none",
            "jump-start",
            "step-start",
            "step-end"
        ],
        "name": "transition-timing-function"
    },
    {
        "name": "translate"
    },
    {
        "keywords": [
            "none",
            "all"
        ],
        "name": "trigger-scope"
    },
    {
        "name": "types"
    },
    {
        "keywords": [
            "normal",
            "embed",
            "bidi-override",
            "isolate",
            "plaintext",
            "isolate-override"
        ],
        "name": "unicode-bidi"
    },
    {
        "name": "unicode-range"
    },
    {
        "inherited": true,
        "keywords": [
            "auto",
            "none",
            "text",
            "all",
            "contain"
        ],
        "name": "user-select"
    },
    {
        "keywords": [
            "none",
            "non-scaling-stroke"
        ],
        "name": "vector-effect"
    },
    {
        "keywords": [
            "baseline",
            "sub",
            "super",
            "text-top",
            "text-bottom",
            "middle"
        ],
        "name": "vertical-align"
    },
    {
        "longhands": [
            "view-timeline-name",
            "view-timeline-axis",
            "view-timeline-inset"
        ],
        "name": "view-timeline"
    },
    {
        "name": "view-timeline-axis"
    },
    {
        "name": "view-timeline-inset"
    },
    {
        "name": "view-timeline-name"
    },
    {
        "keywords": [
            "none"
        ],
        "name": "view-transition-class"
    },
    {
        "keywords": [
            "normal",
            "contain",
            "nearest"
        ],
        "name": "view-transition-group"
    },
    {
        "keywords": [
            "none",
            "auto"
        ],
        "name": "view-transition-name"
    },
    {
        "inherited": false,
        "keywords": [
            "none",
            "auto"
        ],
        "name": "view-transition-scope"
    },
    {
        "inherited": true,
        "keywords": [
            "visible",
            "hidden",
            "collapse"
        ],
        "name": "visibility"
    },
    {
        "inherited": true,
        "longhands": [
            "white-space-collapse",
            "text-wrap-mode"
        ],
        "name": "white-space"
    },
    {
        "inherited": true,
        "keywords": [
            "collapse",
            "preserve",
            "preserve-breaks",
            "break-spaces"
        ],
        "name": "white-space-collapse"
    },
    {
        "inherited": true,
        "name": "widows"
    },
    {
        "keywords": [
            "auto",
            "fit-content",
            "min-content",
            "max-content"
        ],
        "name": "width"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "will-change"
    },
    {
        "inherited": true,
        "keywords": [
            "normal",
            "break-all",
            "keep-all",
            "break-word",
            "auto-phrase"
        ],
        "name": "word-break"
    },
    {
        "inherited": true,
        "keywords": [
            "normal"
        ],
        "name": "word-spacing"
    },
    {
        "inherited": true,
        "keywords": [
            "horizontal-tb",
            "vertical-rl",
            "vertical-lr",
            "sideways-rl",
            "sideways-lr"
        ],
        "name": "writing-mode"
    },
    {
        "name": "x"
    },
    {
        "name": "y"
    },
    {
        "keywords": [
            "auto"
        ],
        "name": "z-index"
    },
    {
        "name": "zoom"
    }
];
const generatedPropertyValues = {
    "-webkit-box-align": {
        "values": [
            "stretch",
            "start",
            "center",
            "end",
            "baseline"
        ]
    },
    "-webkit-box-decoration-break": {
        "values": [
            "slice",
            "clone"
        ]
    },
    "-webkit-box-direction": {
        "values": [
            "normal",
            "reverse"
        ]
    },
    "-webkit-box-orient": {
        "values": [
            "horizontal",
            "vertical"
        ]
    },
    "-webkit-box-pack": {
        "values": [
            "start",
            "center",
            "end",
            "justify"
        ]
    },
    "-webkit-line-break": {
        "values": [
            "auto",
            "loose",
            "normal",
            "strict",
            "after-white-space"
        ]
    },
    "-webkit-line-clamp": {
        "values": [
            "none"
        ]
    },
    "-webkit-rtl-ordering": {
        "values": [
            "logical",
            "visual"
        ]
    },
    "-webkit-text-security": {
        "values": [
            "none",
            "disc",
            "circle",
            "square"
        ]
    },
    "-webkit-user-drag": {
        "values": [
            "auto",
            "none",
            "element"
        ]
    },
    "-webkit-user-modify": {
        "values": [
            "read-only",
            "read-write",
            "read-write-plaintext-only"
        ]
    },
    "accent-color": {
        "values": [
            "auto",
            "currentcolor"
        ]
    },
    "alignment-baseline": {
        "values": [
            "auto",
            "baseline",
            "alphabetic",
            "ideographic",
            "middle",
            "central",
            "mathematical",
            "before-edge",
            "text-before-edge",
            "after-edge",
            "text-after-edge",
            "hanging"
        ]
    },
    "anchor-name": {
        "values": [
            "none"
        ]
    },
    "anchor-scope": {
        "values": [
            "none",
            "all"
        ]
    },
    "animation-composition": {
        "values": [
            "replace",
            "add",
            "accumulate"
        ]
    },
    "animation-direction": {
        "values": [
            "normal",
            "reverse",
            "alternate",
            "alternate-reverse"
        ]
    },
    "animation-fill-mode": {
        "values": [
            "none",
            "forwards",
            "backwards",
            "both"
        ]
    },
    "animation-iteration-count": {
        "values": [
            "infinite"
        ]
    },
    "animation-name": {
        "values": [
            "none"
        ]
    },
    "animation-play-state": {
        "values": [
            "running",
            "paused"
        ]
    },
    "animation-timeline": {
        "values": [
            "none",
            "auto"
        ]
    },
    "animation-timing-function": {
        "values": [
            "linear",
            "ease",
            "ease-in",
            "ease-out",
            "ease-in-out",
            "jump-both",
            "jump-end",
            "jump-none",
            "jump-start",
            "step-start",
            "step-end"
        ]
    },
    "animation-trigger": {
        "values": [
            "none"
        ]
    },
    "app-region": {
        "values": [
            "none",
            "drag",
            "no-drag"
        ]
    },
    "aspect-ratio": {
        "values": [
            "auto"
        ]
    },
    "backdrop-filter": {
        "values": [
            "none"
        ]
    },
    "backface-visibility": {
        "values": [
            "visible",
            "hidden"
        ]
    },
    "background-attachment": {
        "values": [
            "scroll",
            "fixed",
            "local"
        ]
    },
    "background-blend-mode": {
        "values": [
            "normal",
            "multiply",
            "screen",
            "overlay",
            "darken",
            "lighten",
            "color-dodge",
            "color-burn",
            "hard-light",
            "soft-light",
            "difference",
            "exclusion",
            "hue",
            "saturation",
            "color",
            "luminosity"
        ]
    },
    "background-clip": {
        "values": [
            "border-box",
            "padding-box",
            "content-box",
            "text"
        ]
    },
    "background-color": {
        "values": [
            "currentcolor"
        ]
    },
    "background-image": {
        "values": [
            "auto",
            "none"
        ]
    },
    "background-origin": {
        "values": [
            "border-box",
            "padding-box",
            "content-box"
        ]
    },
    "background-size": {
        "values": [
            "auto",
            "cover",
            "contain"
        ]
    },
    "baseline-shift": {
        "values": [
            "baseline",
            "sub",
            "super"
        ]
    },
    "baseline-source": {
        "values": [
            "auto",
            "first",
            "last"
        ]
    },
    "block-ellipsis": {
        "values": [
            "auto",
            "no-ellipsis"
        ]
    },
    "block-size": {
        "values": [
            "auto"
        ]
    },
    "border-bottom-color": {
        "values": [
            "currentcolor"
        ]
    },
    "border-bottom-style": {
        "values": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ]
    },
    "border-bottom-width": {
        "values": [
            "thin",
            "medium",
            "thick"
        ]
    },
    "border-collapse": {
        "values": [
            "separate",
            "collapse"
        ]
    },
    "border-image-repeat": {
        "values": [
            "stretch",
            "repeat",
            "round",
            "space"
        ]
    },
    "border-image-source": {
        "values": [
            "none"
        ]
    },
    "border-image-width": {
        "values": [
            "auto"
        ]
    },
    "border-left-color": {
        "values": [
            "currentcolor"
        ]
    },
    "border-left-style": {
        "values": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ]
    },
    "border-left-width": {
        "values": [
            "thin",
            "medium",
            "thick"
        ]
    },
    "border-right-color": {
        "values": [
            "currentcolor"
        ]
    },
    "border-right-style": {
        "values": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ]
    },
    "border-right-width": {
        "values": [
            "thin",
            "medium",
            "thick"
        ]
    },
    "border-shape": {
        "values": [
            "none"
        ]
    },
    "border-style": {
        "values": [
            "none"
        ]
    },
    "border-top-color": {
        "values": [
            "currentcolor"
        ]
    },
    "border-top-style": {
        "values": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ]
    },
    "border-top-width": {
        "values": [
            "thin",
            "medium",
            "thick"
        ]
    },
    "bottom": {
        "values": [
            "auto"
        ]
    },
    "box-decoration-break": {
        "values": [
            "slice",
            "clone"
        ]
    },
    "box-shadow": {
        "values": [
            "none"
        ]
    },
    "box-sizing": {
        "values": [
            "content-box",
            "border-box"
        ]
    },
    "break-after": {
        "values": [
            "auto",
            "avoid",
            "avoid-column",
            "avoid-page",
            "column",
            "left",
            "page",
            "recto",
            "right",
            "verso"
        ]
    },
    "break-before": {
        "values": [
            "auto",
            "avoid",
            "avoid-column",
            "avoid-page",
            "column",
            "left",
            "page",
            "recto",
            "right",
            "verso"
        ]
    },
    "break-inside": {
        "values": [
            "auto",
            "avoid",
            "avoid-column",
            "avoid-page"
        ]
    },
    "buffered-rendering": {
        "values": [
            "auto",
            "dynamic",
            "static"
        ]
    },
    "caption-side": {
        "values": [
            "top",
            "bottom"
        ]
    },
    "caret-animation": {
        "values": [
            "auto",
            "manual"
        ]
    },
    "caret-color": {
        "values": [
            "auto",
            "currentcolor"
        ]
    },
    "caret-shape": {
        "values": [
            "auto",
            "bar",
            "block",
            "underscore"
        ]
    },
    "clear": {
        "values": [
            "none",
            "left",
            "right",
            "both",
            "inline-start",
            "inline-end"
        ]
    },
    "clip": {
        "values": [
            "auto"
        ]
    },
    "clip-path": {
        "values": [
            "border-box",
            "padding-box",
            "content-box",
            "margin-box",
            "fill-box",
            "stroke-box",
            "view-box",
            "none"
        ]
    },
    "clip-rule": {
        "values": [
            "nonzero",
            "evenodd"
        ]
    },
    "color": {
        "values": [
            "currentcolor"
        ]
    },
    "color-interpolation": {
        "values": [
            "auto",
            "srgb",
            "linearrgb"
        ]
    },
    "color-interpolation-filters": {
        "values": [
            "auto",
            "srgb",
            "linearrgb"
        ]
    },
    "color-rendering": {
        "values": [
            "auto",
            "optimizespeed",
            "optimizequality"
        ]
    },
    "column-count": {
        "values": [
            "auto"
        ]
    },
    "column-fill": {
        "values": [
            "balance",
            "auto"
        ]
    },
    "column-gap": {
        "values": [
            "normal"
        ]
    },
    "column-height": {
        "values": [
            "auto"
        ]
    },
    "column-rule-break": {
        "values": [
            "none",
            "normal",
            "intersection"
        ]
    },
    "column-rule-color": {
        "values": [
            "currentcolor"
        ]
    },
    "column-rule-style": {
        "values": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ]
    },
    "column-rule-visibility-items": {
        "values": [
            "all",
            "auto",
            "around",
            "between"
        ]
    },
    "column-rule-width": {
        "values": [
            "thin",
            "medium",
            "thick"
        ]
    },
    "column-span": {
        "values": [
            "none",
            "all"
        ]
    },
    "column-width": {
        "values": [
            "auto"
        ]
    },
    "column-wrap": {
        "values": [
            "auto",
            "nowrap",
            "wrap"
        ]
    },
    "contain": {
        "values": [
            "none",
            "strict",
            "content",
            "size",
            "layout",
            "style",
            "paint",
            "inline-size",
            "block-size"
        ]
    },
    "contain-intrinsic-height": {
        "values": [
            "none"
        ]
    },
    "contain-intrinsic-width": {
        "values": [
            "none"
        ]
    },
    "container-name": {
        "values": [
            "none"
        ]
    },
    "container-type": {
        "values": [
            "normal",
            "inline-size",
            "size",
            "scroll-state",
            "anchored"
        ]
    },
    "content-visibility": {
        "values": [
            "visible",
            "auto",
            "hidden"
        ]
    },
    "continue": {
        "values": [
            "auto",
            "collapse",
            "-webkit-legacy"
        ]
    },
    "corner-bottom-left-shape": {
        "values": [
            "notch",
            "scoop",
            "bevel",
            "round",
            "squircle",
            "square"
        ]
    },
    "corner-bottom-right-shape": {
        "values": [
            "notch",
            "scoop",
            "bevel",
            "round",
            "squircle",
            "square"
        ]
    },
    "corner-top-left-shape": {
        "values": [
            "notch",
            "scoop",
            "bevel",
            "round",
            "squircle",
            "square"
        ]
    },
    "corner-top-right-shape": {
        "values": [
            "notch",
            "scoop",
            "bevel",
            "round",
            "squircle",
            "square"
        ]
    },
    "corners": {
        "values": [
            "normal"
        ]
    },
    "counter-increment": {
        "values": [
            "none"
        ]
    },
    "counter-reset": {
        "values": [
            "none"
        ]
    },
    "counter-set": {
        "values": [
            "none"
        ]
    },
    "cursor": {
        "values": [
            "auto",
            "default",
            "none",
            "context-menu",
            "help",
            "pointer",
            "progress",
            "wait",
            "cell",
            "crosshair",
            "text",
            "vertical-text",
            "alias",
            "copy",
            "move",
            "no-drop",
            "not-allowed",
            "e-resize",
            "n-resize",
            "ne-resize",
            "nw-resize",
            "s-resize",
            "se-resize",
            "sw-resize",
            "w-resize",
            "ew-resize",
            "ns-resize",
            "nesw-resize",
            "nwse-resize",
            "col-resize",
            "row-resize",
            "all-scroll",
            "zoom-in",
            "zoom-out",
            "grab",
            "grabbing"
        ]
    },
    "d": {
        "values": [
            "none"
        ]
    },
    "direction": {
        "values": [
            "ltr",
            "rtl"
        ]
    },
    "display": {
        "values": [
            "inline",
            "block",
            "list-item",
            "inline-block",
            "table",
            "inline-table",
            "table-row-group",
            "table-header-group",
            "table-footer-group",
            "table-row",
            "table-column-group",
            "table-column",
            "table-cell",
            "table-caption",
            "-webkit-box",
            "-webkit-inline-box",
            "flex",
            "inline-flex",
            "grid",
            "inline-grid",
            "contents",
            "flow-root",
            "none",
            "flow",
            "math",
            "ruby",
            "ruby-text",
            "grid-lanes",
            "inline-grid-lanes"
        ]
    },
    "dominant-baseline": {
        "values": [
            "auto",
            "alphabetic",
            "ideographic",
            "middle",
            "central",
            "mathematical",
            "hanging",
            "use-script",
            "no-change",
            "reset-size",
            "text-after-edge",
            "text-before-edge"
        ]
    },
    "dynamic-range-limit": {
        "values": [
            "standard",
            "no-limit",
            "constrained"
        ]
    },
    "empty-cells": {
        "values": [
            "show",
            "hide"
        ]
    },
    "field-sizing": {
        "values": [
            "fixed",
            "content"
        ]
    },
    "fill-rule": {
        "values": [
            "nonzero",
            "evenodd"
        ]
    },
    "filter": {
        "values": [
            "none"
        ]
    },
    "flex-basis": {
        "values": [
            "auto",
            "fit-content",
            "min-content",
            "max-content",
            "content"
        ]
    },
    "flex-direction": {
        "values": [
            "row",
            "row-reverse",
            "column",
            "column-reverse"
        ]
    },
    "flex-wrap": {
        "values": [
            "nowrap",
            "wrap",
            "wrap-reverse",
            "balance"
        ]
    },
    "float": {
        "values": [
            "none",
            "left",
            "right",
            "inline-start",
            "inline-end"
        ]
    },
    "flood-color": {
        "values": [
            "currentcolor"
        ]
    },
    "flow-tolerance": {
        "values": [
            "normal",
            "infinite"
        ]
    },
    "font-feature-settings": {
        "values": [
            "normal"
        ]
    },
    "font-kerning": {
        "values": [
            "auto",
            "normal",
            "none"
        ]
    },
    "font-language-override": {
        "values": [
            "normal"
        ]
    },
    "font-optical-sizing": {
        "values": [
            "auto",
            "none"
        ]
    },
    "font-palette": {
        "values": [
            "normal",
            "light",
            "dark"
        ]
    },
    "font-size": {
        "values": [
            "xx-small",
            "x-small",
            "small",
            "medium",
            "large",
            "x-large",
            "xx-large",
            "xxx-large",
            "larger",
            "smaller",
            "-webkit-xxx-large"
        ]
    },
    "font-size-adjust": {
        "values": [
            "none",
            "ex-height",
            "cap-height",
            "ch-width",
            "ic-width",
            "ic-height",
            "from-font"
        ]
    },
    "font-stretch": {
        "values": [
            "normal",
            "ultra-condensed",
            "extra-condensed",
            "condensed",
            "semi-condensed",
            "semi-expanded",
            "expanded",
            "extra-expanded",
            "ultra-expanded"
        ]
    },
    "font-style": {
        "values": [
            "normal",
            "italic",
            "oblique"
        ]
    },
    "font-synthesis-small-caps": {
        "values": [
            "auto",
            "none"
        ]
    },
    "font-synthesis-style": {
        "values": [
            "auto",
            "none"
        ]
    },
    "font-synthesis-weight": {
        "values": [
            "auto",
            "none"
        ]
    },
    "font-variant-alternates": {
        "values": [
            "normal"
        ]
    },
    "font-variant-caps": {
        "values": [
            "normal",
            "small-caps",
            "all-small-caps",
            "petite-caps",
            "all-petite-caps",
            "unicase",
            "titling-caps"
        ]
    },
    "font-variant-east-asian": {
        "values": [
            "normal",
            "jis78",
            "jis83",
            "jis90",
            "jis04",
            "simplified",
            "traditional",
            "full-width",
            "proportional-width",
            "ruby"
        ]
    },
    "font-variant-emoji": {
        "values": [
            "normal",
            "text",
            "emoji",
            "unicode"
        ]
    },
    "font-variant-ligatures": {
        "values": [
            "normal",
            "none",
            "common-ligatures",
            "no-common-ligatures",
            "discretionary-ligatures",
            "no-discretionary-ligatures",
            "historical-ligatures",
            "no-historical-ligatures",
            "contextual",
            "no-contextual"
        ]
    },
    "font-variant-numeric": {
        "values": [
            "normal",
            "lining-nums",
            "oldstyle-nums",
            "proportional-nums",
            "tabular-nums",
            "diagonal-fractions",
            "stacked-fractions",
            "ordinal",
            "slashed-zero"
        ]
    },
    "font-variant-position": {
        "values": [
            "normal",
            "sub",
            "super"
        ]
    },
    "font-variation-settings": {
        "values": [
            "normal"
        ]
    },
    "font-weight": {
        "values": [
            "normal",
            "bold",
            "bolder",
            "lighter"
        ]
    },
    "forced-color-adjust": {
        "values": [
            "auto",
            "none",
            "preserve-parent-color"
        ]
    },
    "frame-sizing": {
        "values": [
            "auto",
            "content-width",
            "content-height",
            "content-block-size",
            "content-inline-size"
        ]
    },
    "grid-auto-columns": {
        "values": [
            "auto",
            "min-content",
            "max-content"
        ]
    },
    "grid-auto-flow": {
        "values": [
            "row",
            "column"
        ]
    },
    "grid-auto-rows": {
        "values": [
            "auto",
            "min-content",
            "max-content"
        ]
    },
    "grid-column-end": {
        "values": [
            "auto"
        ]
    },
    "grid-column-start": {
        "values": [
            "auto"
        ]
    },
    "grid-lanes-direction": {
        "values": [
            "normal",
            "row",
            "column",
            "fill-reverse",
            "track-reverse"
        ]
    },
    "grid-lanes-pack": {
        "values": [
            "normal",
            "dense"
        ]
    },
    "grid-row-end": {
        "values": [
            "auto"
        ]
    },
    "grid-row-start": {
        "values": [
            "auto"
        ]
    },
    "grid-template-areas": {
        "values": [
            "none"
        ]
    },
    "grid-template-columns": {
        "values": [
            "none"
        ]
    },
    "grid-template-rows": {
        "values": [
            "none"
        ]
    },
    "height": {
        "values": [
            "auto",
            "fit-content",
            "min-content",
            "max-content"
        ]
    },
    "hyphenate-limit-chars": {
        "values": [
            "auto"
        ]
    },
    "hyphens": {
        "values": [
            "none",
            "manual",
            "auto"
        ]
    },
    "image-animation": {
        "values": [
            "normal",
            "running",
            "paused"
        ]
    },
    "image-rendering": {
        "values": [
            "auto",
            "optimizespeed",
            "optimizequality",
            "-webkit-optimize-contrast",
            "pixelated"
        ]
    },
    "initial-letter": {
        "values": [
            "drop",
            "normal",
            "raise"
        ]
    },
    "inline-size": {
        "values": [
            "auto"
        ]
    },
    "interactivity": {
        "values": [
            "auto",
            "inert"
        ]
    },
    "interpolate-size": {
        "values": [
            "numeric-only",
            "allow-keywords"
        ]
    },
    "isolation": {
        "values": [
            "auto",
            "isolate"
        ]
    },
    "left": {
        "values": [
            "auto"
        ]
    },
    "letter-spacing": {
        "values": [
            "normal"
        ]
    },
    "lighting-color": {
        "values": [
            "currentcolor"
        ]
    },
    "line-break": {
        "values": [
            "auto",
            "loose",
            "normal",
            "strict",
            "anywhere",
            "after-white-space"
        ]
    },
    "line-height": {
        "values": [
            "normal"
        ]
    },
    "list-style-image": {
        "values": [
            "none"
        ]
    },
    "list-style-position": {
        "values": [
            "outside",
            "inside"
        ]
    },
    "list-style-type": {
        "values": [
            "disc",
            "circle",
            "square",
            "disclosure-open",
            "disclosure-closed",
            "decimal",
            "none"
        ]
    },
    "margin-block-end": {
        "values": [
            "auto"
        ]
    },
    "margin-block-start": {
        "values": [
            "auto"
        ]
    },
    "margin-bottom": {
        "values": [
            "auto"
        ]
    },
    "margin-inline-end": {
        "values": [
            "auto"
        ]
    },
    "margin-inline-start": {
        "values": [
            "auto"
        ]
    },
    "margin-left": {
        "values": [
            "auto"
        ]
    },
    "margin-right": {
        "values": [
            "auto"
        ]
    },
    "margin-top": {
        "values": [
            "auto"
        ]
    },
    "marker-end": {
        "values": [
            "none"
        ]
    },
    "marker-mid": {
        "values": [
            "none"
        ]
    },
    "marker-start": {
        "values": [
            "none"
        ]
    },
    "mask-composite": {
        "values": [
            "add",
            "subtract",
            "intersect",
            "exclude"
        ]
    },
    "mask-mode": {
        "values": [
            "alpha",
            "luminance",
            "match-source"
        ]
    },
    "mask-type": {
        "values": [
            "luminance",
            "alpha"
        ]
    },
    "math-shift": {
        "values": [
            "normal",
            "compact"
        ]
    },
    "math-style": {
        "values": [
            "normal",
            "compact"
        ]
    },
    "max-block-size": {
        "values": [
            "none"
        ]
    },
    "max-height": {
        "values": [
            "none"
        ]
    },
    "max-inline-size": {
        "values": [
            "none"
        ]
    },
    "max-lines": {
        "values": [
            "none"
        ]
    },
    "max-width": {
        "values": [
            "none"
        ]
    },
    "mix-blend-mode": {
        "values": [
            "normal",
            "multiply",
            "screen",
            "overlay",
            "darken",
            "lighten",
            "color-dodge",
            "color-burn",
            "hard-light",
            "soft-light",
            "difference",
            "exclusion",
            "hue",
            "saturation",
            "color",
            "luminosity",
            "plus-lighter"
        ]
    },
    "object-fit": {
        "values": [
            "fill",
            "contain",
            "cover",
            "none",
            "scale-down"
        ]
    },
    "object-view-box": {
        "values": [
            "none"
        ]
    },
    "offset-anchor": {
        "values": [
            "auto"
        ]
    },
    "offset-path": {
        "values": [
            "none"
        ]
    },
    "offset-position": {
        "values": [
            "auto",
            "normal"
        ]
    },
    "offset-rotate": {
        "values": [
            "auto",
            "reverse"
        ]
    },
    "origin-trial-test-property": {
        "values": [
            "normal",
            "none"
        ]
    },
    "outline-color": {
        "values": [
            "currentcolor"
        ]
    },
    "outline-style": {
        "values": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ]
    },
    "outline-width": {
        "values": [
            "thin",
            "medium",
            "thick"
        ]
    },
    "overflow-anchor": {
        "values": [
            "visible",
            "none",
            "auto"
        ]
    },
    "overflow-clip-margin": {
        "values": [
            "border-box",
            "content-box",
            "padding-box"
        ]
    },
    "overflow-wrap": {
        "values": [
            "normal",
            "break-word",
            "anywhere"
        ]
    },
    "overflow-x": {
        "values": [
            "visible",
            "hidden",
            "scroll",
            "auto",
            "overlay",
            "clip"
        ]
    },
    "overflow-y": {
        "values": [
            "visible",
            "hidden",
            "scroll",
            "auto",
            "overlay",
            "clip"
        ]
    },
    "overlay": {
        "values": [
            "none",
            "auto"
        ]
    },
    "overscroll-behavior-x": {
        "values": [
            "auto",
            "contain",
            "none"
        ]
    },
    "overscroll-behavior-y": {
        "values": [
            "auto",
            "contain",
            "none"
        ]
    },
    "page": {
        "values": [
            "auto"
        ]
    },
    "page-margin-safety": {
        "values": [
            "none",
            "clamp",
            "add"
        ]
    },
    "paint-order": {
        "values": [
            "normal",
            "fill",
            "stroke",
            "markers"
        ]
    },
    "perspective": {
        "values": [
            "none"
        ]
    },
    "pointer-events": {
        "values": [
            "none",
            "auto",
            "stroke",
            "fill",
            "painted",
            "visible",
            "visiblestroke",
            "visiblefill",
            "visiblepainted",
            "bounding-box",
            "all"
        ]
    },
    "position": {
        "values": [
            "static",
            "relative",
            "absolute",
            "fixed",
            "sticky"
        ]
    },
    "position-anchor": {
        "values": [
            "auto",
            "none"
        ]
    },
    "position-area": {
        "values": [
            "none",
            "top",
            "bottom",
            "center",
            "left",
            "right",
            "x-start",
            "x-end",
            "y-start",
            "y-end",
            "start",
            "end",
            "self-start",
            "self-end",
            "all"
        ]
    },
    "position-try-fallbacks": {
        "values": [
            "none",
            "flip-block",
            "flip-inline",
            "flip-start",
            "flip-x",
            "flip-y"
        ]
    },
    "position-try-order": {
        "values": [
            "normal",
            "most-width",
            "most-height",
            "most-block-size",
            "most-inline-size"
        ]
    },
    "position-visibility": {
        "values": [
            "always",
            "anchors-visible",
            "no-overflow"
        ]
    },
    "print-color-adjust": {
        "values": [
            "economy",
            "exact"
        ]
    },
    "quotes": {
        "values": [
            "auto",
            "none"
        ]
    },
    "reading-flow": {
        "values": [
            "normal",
            "flex-visual",
            "flex-flow",
            "grid-rows",
            "grid-columns",
            "grid-order",
            "source-order"
        ]
    },
    "resize": {
        "values": [
            "none",
            "both",
            "horizontal",
            "vertical",
            "block",
            "inline"
        ]
    },
    "right": {
        "values": [
            "auto"
        ]
    },
    "row-gap": {
        "values": [
            "normal"
        ]
    },
    "row-rule-break": {
        "values": [
            "none",
            "normal",
            "intersection"
        ]
    },
    "row-rule-color": {
        "values": [
            "currentcolor"
        ]
    },
    "row-rule-style": {
        "values": [
            "none",
            "hidden",
            "inset",
            "groove",
            "outset",
            "ridge",
            "dotted",
            "dashed",
            "solid",
            "double"
        ]
    },
    "row-rule-visibility-items": {
        "values": [
            "all",
            "auto",
            "around",
            "between"
        ]
    },
    "row-rule-width": {
        "values": [
            "thin",
            "medium",
            "thick"
        ]
    },
    "ruby-align": {
        "values": [
            "space-around",
            "start",
            "center",
            "space-between"
        ]
    },
    "ruby-overhang": {
        "values": [
            "auto",
            "none"
        ]
    },
    "ruby-position": {
        "values": [
            "over",
            "under"
        ]
    },
    "rule-overlap": {
        "values": [
            "row-over-column",
            "column-over-row"
        ]
    },
    "rx": {
        "values": [
            "auto"
        ]
    },
    "ry": {
        "values": [
            "auto"
        ]
    },
    "scroll-behavior": {
        "values": [
            "auto",
            "smooth"
        ]
    },
    "scroll-initial-target": {
        "values": [
            "none",
            "nearest"
        ]
    },
    "scroll-padding-block-end": {
        "values": [
            "auto"
        ]
    },
    "scroll-padding-block-start": {
        "values": [
            "auto"
        ]
    },
    "scroll-padding-bottom": {
        "values": [
            "auto"
        ]
    },
    "scroll-padding-inline-end": {
        "values": [
            "auto"
        ]
    },
    "scroll-padding-inline-start": {
        "values": [
            "auto"
        ]
    },
    "scroll-padding-left": {
        "values": [
            "auto"
        ]
    },
    "scroll-padding-right": {
        "values": [
            "auto"
        ]
    },
    "scroll-padding-top": {
        "values": [
            "auto"
        ]
    },
    "scroll-snap-align": {
        "values": [
            "none",
            "start",
            "end",
            "center"
        ]
    },
    "scroll-snap-stop": {
        "values": [
            "normal",
            "always"
        ]
    },
    "scroll-snap-type": {
        "values": [
            "none",
            "x",
            "y",
            "block",
            "inline",
            "both",
            "mandatory",
            "proximity"
        ]
    },
    "scroll-target-group": {
        "values": [
            "none",
            "auto"
        ]
    },
    "scrollbar-color": {
        "values": [
            "auto"
        ]
    },
    "scrollbar-gutter": {
        "values": [
            "auto",
            "stable",
            "both-edges"
        ]
    },
    "scrollbar-width": {
        "values": [
            "auto",
            "thin",
            "none"
        ]
    },
    "shape-margin": {
        "values": [
            "none"
        ]
    },
    "shape-outside": {
        "values": [
            "none"
        ]
    },
    "shape-rendering": {
        "values": [
            "auto",
            "optimizespeed",
            "crispedges",
            "geometricprecision"
        ]
    },
    "speak": {
        "values": [
            "none",
            "normal",
            "spell-out",
            "digits",
            "literal-punctuation",
            "no-punctuation"
        ]
    },
    "stop-color": {
        "values": [
            "currentcolor"
        ]
    },
    "stroke-dasharray": {
        "values": [
            "none"
        ]
    },
    "stroke-linecap": {
        "values": [
            "butt",
            "round",
            "square"
        ]
    },
    "stroke-linejoin": {
        "values": [
            "miter",
            "bevel",
            "round"
        ]
    },
    "table-layout": {
        "values": [
            "auto",
            "fixed"
        ]
    },
    "text-align": {
        "values": [
            "left",
            "right",
            "center",
            "justify",
            "-webkit-left",
            "-webkit-right",
            "-webkit-center",
            "start",
            "end",
            "match-parent"
        ]
    },
    "text-align-last": {
        "values": [
            "auto",
            "start",
            "end",
            "left",
            "right",
            "center",
            "justify",
            "match-parent"
        ]
    },
    "text-anchor": {
        "values": [
            "start",
            "middle",
            "end"
        ]
    },
    "text-autospace": {
        "values": [
            "no-autospace",
            "normal"
        ]
    },
    "text-box-trim": {
        "values": [
            "none",
            "trim-start",
            "trim-end",
            "trim-both"
        ]
    },
    "text-combine-upright": {
        "values": [
            "none",
            "all"
        ]
    },
    "text-decoration-color": {
        "values": [
            "currentcolor"
        ]
    },
    "text-decoration-line": {
        "values": [
            "none",
            "underline",
            "overline",
            "line-through",
            "blink",
            "spelling-error",
            "grammar-error"
        ]
    },
    "text-decoration-skip-ink": {
        "values": [
            "none",
            "auto",
            "all"
        ]
    },
    "text-decoration-style": {
        "values": [
            "solid",
            "double",
            "dotted",
            "dashed",
            "wavy"
        ]
    },
    "text-decoration-thickness": {
        "values": [
            "auto",
            "from-font"
        ]
    },
    "text-emphasis-color": {
        "values": [
            "currentcolor"
        ]
    },
    "text-justify": {
        "values": [
            "auto",
            "none",
            "inter-word",
            "inter-character"
        ]
    },
    "text-orientation": {
        "values": [
            "sideways",
            "mixed",
            "upright"
        ]
    },
    "text-overflow": {
        "values": [
            "clip",
            "ellipsis"
        ]
    },
    "text-rendering": {
        "values": [
            "auto",
            "optimizespeed",
            "optimizelegibility",
            "geometricprecision"
        ]
    },
    "text-shadow": {
        "values": [
            "none"
        ]
    },
    "text-size-adjust": {
        "values": [
            "none",
            "auto"
        ]
    },
    "text-spacing-trim": {
        "values": [
            "normal",
            "space-all",
            "space-first",
            "trim-start"
        ]
    },
    "text-transform": {
        "values": [
            "none",
            "capitalize",
            "uppercase",
            "lowercase",
            "full-width",
            "full-size-kana",
            "math-auto"
        ]
    },
    "text-underline-offset": {
        "values": [
            "auto"
        ]
    },
    "text-underline-position": {
        "values": [
            "auto",
            "from-font",
            "under",
            "left",
            "right"
        ]
    },
    "text-wrap-mode": {
        "values": [
            "wrap",
            "nowrap"
        ]
    },
    "text-wrap-style": {
        "values": [
            "auto",
            "balance",
            "pretty",
            "stable"
        ]
    },
    "timeline-trigger-source": {
        "values": [
            "none",
            "auto"
        ]
    },
    "top": {
        "values": [
            "auto"
        ]
    },
    "touch-action": {
        "values": [
            "auto",
            "none",
            "pan-x",
            "pan-left",
            "pan-right",
            "pan-y",
            "pan-up",
            "pan-down",
            "pinch-zoom",
            "manipulation"
        ]
    },
    "transform": {
        "values": [
            "none"
        ]
    },
    "transform-box": {
        "values": [
            "content-box",
            "border-box",
            "fill-box",
            "stroke-box",
            "view-box"
        ]
    },
    "transform-style": {
        "values": [
            "flat",
            "preserve-3d"
        ]
    },
    "transition-behavior": {
        "values": [
            "normal",
            "allow-discrete"
        ]
    },
    "transition-property": {
        "values": [
            "none"
        ]
    },
    "transition-timing-function": {
        "values": [
            "linear",
            "ease",
            "ease-in",
            "ease-out",
            "ease-in-out",
            "jump-both",
            "jump-end",
            "jump-none",
            "jump-start",
            "step-start",
            "step-end"
        ]
    },
    "trigger-scope": {
        "values": [
            "none",
            "all"
        ]
    },
    "unicode-bidi": {
        "values": [
            "normal",
            "embed",
            "bidi-override",
            "isolate",
            "plaintext",
            "isolate-override"
        ]
    },
    "user-select": {
        "values": [
            "auto",
            "none",
            "text",
            "all",
            "contain"
        ]
    },
    "vector-effect": {
        "values": [
            "none",
            "non-scaling-stroke"
        ]
    },
    "vertical-align": {
        "values": [
            "baseline",
            "sub",
            "super",
            "text-top",
            "text-bottom",
            "middle"
        ]
    },
    "view-transition-class": {
        "values": [
            "none"
        ]
    },
    "view-transition-group": {
        "values": [
            "normal",
            "contain",
            "nearest"
        ]
    },
    "view-transition-name": {
        "values": [
            "none",
            "auto"
        ]
    },
    "view-transition-scope": {
        "values": [
            "none",
            "auto"
        ]
    },
    "visibility": {
        "values": [
            "visible",
            "hidden",
            "collapse"
        ]
    },
    "white-space-collapse": {
        "values": [
            "collapse",
            "preserve",
            "preserve-breaks",
            "break-spaces"
        ]
    },
    "width": {
        "values": [
            "auto",
            "fit-content",
            "min-content",
            "max-content"
        ]
    },
    "will-change": {
        "values": [
            "auto"
        ]
    },
    "word-break": {
        "values": [
            "normal",
            "break-all",
            "keep-all",
            "break-word",
            "auto-phrase"
        ]
    },
    "word-spacing": {
        "values": [
            "normal"
        ]
    },
    "writing-mode": {
        "values": [
            "horizontal-tb",
            "vertical-rl",
            "vertical-lr",
            "sideways-rl",
            "sideways-lr"
        ]
    },
    "z-index": {
        "values": [
            "auto"
        ]
    }
};
const generatedAliasesFor = new Map([
    [
        "-epub-caption-side",
        "caption-side"
    ],
    [
        "-epub-text-combine",
        "-webkit-text-combine"
    ],
    [
        "-epub-text-emphasis",
        "text-emphasis"
    ],
    [
        "-epub-text-emphasis-color",
        "text-emphasis-color"
    ],
    [
        "-epub-text-emphasis-style",
        "text-emphasis-style"
    ],
    [
        "-epub-text-orientation",
        "-webkit-text-orientation"
    ],
    [
        "-epub-text-transform",
        "text-transform"
    ],
    [
        "-epub-word-break",
        "word-break"
    ],
    [
        "-epub-writing-mode",
        "-webkit-writing-mode"
    ],
    [
        "-webkit-align-content",
        "align-content"
    ],
    [
        "-webkit-align-items",
        "align-items"
    ],
    [
        "-webkit-align-self",
        "align-self"
    ],
    [
        "-webkit-animation",
        "animation"
    ],
    [
        "-webkit-animation-delay",
        "animation-delay"
    ],
    [
        "-webkit-animation-direction",
        "animation-direction"
    ],
    [
        "-webkit-animation-duration",
        "animation-duration"
    ],
    [
        "-webkit-animation-fill-mode",
        "animation-fill-mode"
    ],
    [
        "-webkit-animation-iteration-count",
        "animation-iteration-count"
    ],
    [
        "-webkit-animation-name",
        "animation-name"
    ],
    [
        "-webkit-animation-play-state",
        "animation-play-state"
    ],
    [
        "-webkit-animation-timing-function",
        "animation-timing-function"
    ],
    [
        "-webkit-app-region",
        "app-region"
    ],
    [
        "-webkit-appearance",
        "appearance"
    ],
    [
        "-webkit-backface-visibility",
        "backface-visibility"
    ],
    [
        "-webkit-background-clip",
        "background-clip"
    ],
    [
        "-webkit-background-origin",
        "background-origin"
    ],
    [
        "-webkit-background-size",
        "background-size"
    ],
    [
        "-webkit-border-after",
        "border-block-end"
    ],
    [
        "-webkit-border-after-color",
        "border-block-end-color"
    ],
    [
        "-webkit-border-after-style",
        "border-block-end-style"
    ],
    [
        "-webkit-border-after-width",
        "border-block-end-width"
    ],
    [
        "-webkit-border-before",
        "border-block-start"
    ],
    [
        "-webkit-border-before-color",
        "border-block-start-color"
    ],
    [
        "-webkit-border-before-style",
        "border-block-start-style"
    ],
    [
        "-webkit-border-before-width",
        "border-block-start-width"
    ],
    [
        "-webkit-border-bottom-left-radius",
        "border-bottom-left-radius"
    ],
    [
        "-webkit-border-bottom-right-radius",
        "border-bottom-right-radius"
    ],
    [
        "-webkit-border-end",
        "border-inline-end"
    ],
    [
        "-webkit-border-end-color",
        "border-inline-end-color"
    ],
    [
        "-webkit-border-end-style",
        "border-inline-end-style"
    ],
    [
        "-webkit-border-end-width",
        "border-inline-end-width"
    ],
    [
        "-webkit-border-radius",
        "border-radius"
    ],
    [
        "-webkit-border-start",
        "border-inline-start"
    ],
    [
        "-webkit-border-start-color",
        "border-inline-start-color"
    ],
    [
        "-webkit-border-start-style",
        "border-inline-start-style"
    ],
    [
        "-webkit-border-start-width",
        "border-inline-start-width"
    ],
    [
        "-webkit-border-top-left-radius",
        "border-top-left-radius"
    ],
    [
        "-webkit-border-top-right-radius",
        "border-top-right-radius"
    ],
    [
        "-webkit-box-shadow",
        "box-shadow"
    ],
    [
        "-webkit-box-sizing",
        "box-sizing"
    ],
    [
        "-webkit-clip-path",
        "clip-path"
    ],
    [
        "-webkit-column-count",
        "column-count"
    ],
    [
        "-webkit-column-gap",
        "column-gap"
    ],
    [
        "-webkit-column-rule",
        "column-rule"
    ],
    [
        "-webkit-column-rule-color",
        "column-rule-color"
    ],
    [
        "-webkit-column-rule-style",
        "column-rule-style"
    ],
    [
        "-webkit-column-rule-width",
        "column-rule-width"
    ],
    [
        "-webkit-column-span",
        "column-span"
    ],
    [
        "-webkit-column-width",
        "column-width"
    ],
    [
        "-webkit-columns",
        "columns"
    ],
    [
        "-webkit-filter",
        "filter"
    ],
    [
        "-webkit-flex",
        "flex"
    ],
    [
        "-webkit-flex-basis",
        "flex-basis"
    ],
    [
        "-webkit-flex-direction",
        "flex-direction"
    ],
    [
        "-webkit-flex-flow",
        "flex-flow"
    ],
    [
        "-webkit-flex-grow",
        "flex-grow"
    ],
    [
        "-webkit-flex-shrink",
        "flex-shrink"
    ],
    [
        "-webkit-flex-wrap",
        "flex-wrap"
    ],
    [
        "-webkit-font-feature-settings",
        "font-feature-settings"
    ],
    [
        "-webkit-hyphenate-character",
        "hyphenate-character"
    ],
    [
        "-webkit-justify-content",
        "justify-content"
    ],
    [
        "-webkit-logical-height",
        "block-size"
    ],
    [
        "-webkit-logical-width",
        "inline-size"
    ],
    [
        "-webkit-margin-after",
        "margin-block-end"
    ],
    [
        "-webkit-margin-before",
        "margin-block-start"
    ],
    [
        "-webkit-margin-end",
        "margin-inline-end"
    ],
    [
        "-webkit-margin-start",
        "margin-inline-start"
    ],
    [
        "-webkit-mask",
        "mask"
    ],
    [
        "-webkit-mask-clip",
        "mask-clip"
    ],
    [
        "-webkit-mask-composite",
        "mask-composite"
    ],
    [
        "-webkit-mask-image",
        "mask-image"
    ],
    [
        "-webkit-mask-origin",
        "mask-origin"
    ],
    [
        "-webkit-mask-position",
        "mask-position"
    ],
    [
        "-webkit-mask-repeat",
        "mask-repeat"
    ],
    [
        "-webkit-mask-size",
        "mask-size"
    ],
    [
        "-webkit-max-logical-height",
        "max-block-size"
    ],
    [
        "-webkit-max-logical-width",
        "max-inline-size"
    ],
    [
        "-webkit-min-logical-height",
        "min-block-size"
    ],
    [
        "-webkit-min-logical-width",
        "min-inline-size"
    ],
    [
        "-webkit-opacity",
        "opacity"
    ],
    [
        "-webkit-order",
        "order"
    ],
    [
        "-webkit-padding-after",
        "padding-block-end"
    ],
    [
        "-webkit-padding-before",
        "padding-block-start"
    ],
    [
        "-webkit-padding-end",
        "padding-inline-end"
    ],
    [
        "-webkit-padding-start",
        "padding-inline-start"
    ],
    [
        "-webkit-perspective",
        "perspective"
    ],
    [
        "-webkit-perspective-origin",
        "perspective-origin"
    ],
    [
        "-webkit-print-color-adjust",
        "print-color-adjust"
    ],
    [
        "-webkit-shape-image-threshold",
        "shape-image-threshold"
    ],
    [
        "-webkit-shape-margin",
        "shape-margin"
    ],
    [
        "-webkit-shape-outside",
        "shape-outside"
    ],
    [
        "-webkit-text-emphasis",
        "text-emphasis"
    ],
    [
        "-webkit-text-emphasis-color",
        "text-emphasis-color"
    ],
    [
        "-webkit-text-emphasis-position",
        "text-emphasis-position"
    ],
    [
        "-webkit-text-emphasis-style",
        "text-emphasis-style"
    ],
    [
        "-webkit-text-size-adjust",
        "text-size-adjust"
    ],
    [
        "-webkit-transform",
        "transform"
    ],
    [
        "-webkit-transform-origin",
        "transform-origin"
    ],
    [
        "-webkit-transform-style",
        "transform-style"
    ],
    [
        "-webkit-transition",
        "transition"
    ],
    [
        "-webkit-transition-delay",
        "transition-delay"
    ],
    [
        "-webkit-transition-duration",
        "transition-duration"
    ],
    [
        "-webkit-transition-property",
        "transition-property"
    ],
    [
        "-webkit-transition-timing-function",
        "transition-timing-function"
    ],
    [
        "-webkit-user-select",
        "user-select"
    ],
    [
        "grid-column-gap",
        "column-gap"
    ],
    [
        "grid-gap",
        "gap"
    ],
    [
        "grid-row-gap",
        "row-gap"
    ],
    [
        "word-wrap",
        "overflow-wrap"
    ]
]);

// Copyright 2021 The Chromium Authors
class CSSMetadata {
    #values = [];
    #longhands = new Map();
    #shorthands = new Map();
    #inherited = new Set();
    #svgProperties = new Set();
    #propertyValues = new Map();
    #aliasesFor = new Map();
    #nameValuePresets = [];
    #nameValuePresetsIncludingSVG = [];
    #valuesSet;
    constructor(properties, aliasesFor) {
        this.#aliasesFor = aliasesFor;
        for (let i = 0; i < properties.length; ++i) {
            const property = properties[i];
            const propertyName = property.name;
            if (!CSS.supports(propertyName, 'initial')) {
                continue;
            }
            this.#values.push(propertyName);
            if (property.inherited) {
                this.#inherited.add(propertyName);
            }
            if (property.svg) {
                this.#svgProperties.add(propertyName);
            }
            const longhands = properties[i].longhands;
            if (longhands) {
                this.#longhands.set(propertyName, longhands);
                for (let j = 0; j < longhands.length; ++j) {
                    const longhandName = longhands[j];
                    let shorthands = this.#shorthands.get(longhandName);
                    if (!shorthands) {
                        shorthands = [];
                        this.#shorthands.set(longhandName, shorthands);
                    }
                    shorthands.push(propertyName);
                }
            }
        }
        this.#values.sort(CSSMetadata.sortPrefixesAndCSSWideKeywordsToEnd);
        this.#valuesSet = new Set(this.#values);
        const propertyValueSets = new Map();
        for (const [propertyName, basisValueObj] of Object.entries(generatedPropertyValues)) {
            propertyValueSets.set(propertyName, new Set(basisValueObj.values));
        }
        for (const [propertyName, extraValues] of extraPropertyValues) {
            const propertyValueSet = propertyValueSets.get(propertyName);
            if (propertyValueSet) {
                propertyValueSets.set(propertyName, propertyValueSet.union(extraValues));
            }
            else {
                propertyValueSets.set(propertyName, extraValues);
            }
        }
        for (const [propertyName, values] of propertyValueSets) {
            for (const commonKeyword of CommonKeywords) {
                if (!values.has(commonKeyword) && CSS.supports(propertyName, commonKeyword)) {
                    values.add(commonKeyword);
                }
            }
            this.#propertyValues.set(propertyName, [...values]);
        }
        for (const name of this.#valuesSet) {
            const values = this.specificPropertyValues(name)
                .filter(value => CSS.supports(name, value))
                .sort(CSSMetadata.sortPrefixesAndCSSWideKeywordsToEnd);
            const presets = values.map(value => `${name}: ${value}`);
            if (!this.isSVGProperty(name)) {
                this.#nameValuePresets.push(...presets);
            }
            this.#nameValuePresetsIncludingSVG.push(...presets);
        }
    }
    static isCSSWideKeyword(a) {
        return CSSWideKeywords.includes(a);
    }
    static isPositionTryOrderKeyword(a) {
        return PositionTryOrderKeywords.includes(a);
    }
    static sortPrefixesAndCSSWideKeywordsToEnd(a, b) {
        const aIsCSSWideKeyword = CSSMetadata.isCSSWideKeyword(a);
        const bIsCSSWideKeyword = CSSMetadata.isCSSWideKeyword(b);
        if (aIsCSSWideKeyword && !bIsCSSWideKeyword) {
            return 1;
        }
        if (!aIsCSSWideKeyword && bIsCSSWideKeyword) {
            return -1;
        }
        const aIsPrefixed = a.startsWith('-webkit-');
        const bIsPrefixed = b.startsWith('-webkit-');
        if (aIsPrefixed && !bIsPrefixed) {
            return 1;
        }
        if (!aIsPrefixed && bIsPrefixed) {
            return -1;
        }
        return a < b ? -1 : (a > b ? 1 : 0);
    }
    allProperties() {
        return this.#values;
    }
    aliasesFor() {
        return this.#aliasesFor;
    }
    nameValuePresets(includeSVG) {
        return includeSVG ? this.#nameValuePresetsIncludingSVG : this.#nameValuePresets;
    }
    isSVGProperty(name) {
        name = name.toLowerCase();
        return this.#svgProperties.has(name);
    }
    getLonghands(shorthand) {
        return this.#longhands.get(shorthand) || null;
    }
    getShorthands(longhand) {
        return this.#shorthands.get(longhand) || null;
    }
    isColorAwareProperty(propertyName) {
        return colorAwareProperties.has(propertyName.toLowerCase()) || this.isCustomProperty(propertyName.toLowerCase());
    }
    isFontFamilyProperty(propertyName) {
        return propertyName.toLowerCase() === 'font-family';
    }
    isAngleAwareProperty(propertyName) {
        const lowerCasedName = propertyName.toLowerCase();
        return colorAwareProperties.has(lowerCasedName) || angleAwareProperties.has(lowerCasedName);
    }
    isGridAreaDefiningProperty(propertyName) {
        propertyName = propertyName.toLowerCase();
        return propertyName === 'grid' || propertyName === 'grid-template' || propertyName === 'grid-template-areas';
    }
    isGridColumnNameAwareProperty(propertyName) {
        propertyName = propertyName.toLowerCase();
        return ['grid-column', 'grid-column-start', 'grid-column-end'].includes(propertyName);
    }
    isGridRowNameAwareProperty(propertyName) {
        propertyName = propertyName.toLowerCase();
        return ['grid-row', 'grid-row-start', 'grid-row-end'].includes(propertyName);
    }
    isGridAreaNameAwareProperty(propertyName) {
        propertyName = propertyName.toLowerCase();
        return propertyName === 'grid-area';
    }
    isGridNameAwareProperty(propertyName) {
        return this.isGridAreaNameAwareProperty(propertyName) || this.isGridColumnNameAwareProperty(propertyName) ||
            this.isGridRowNameAwareProperty(propertyName);
    }
    isLengthProperty(propertyName) {
        propertyName = propertyName.toLowerCase();
        if (propertyName === 'line-height') {
            return false;
        }
        return distanceProperties.has(propertyName) || propertyName.startsWith('margin') ||
            propertyName.startsWith('padding') || propertyName.indexOf('width') !== -1 ||
            propertyName.indexOf('height') !== -1;
    }
    isBezierAwareProperty(propertyName) {
        propertyName = propertyName.toLowerCase();
        return bezierAwareProperties.has(propertyName) || this.isCustomProperty(propertyName);
    }
    isFontAwareProperty(propertyName) {
        propertyName = propertyName.toLowerCase();
        return fontAwareProperties.has(propertyName) || this.isCustomProperty(propertyName);
    }
    isCustomProperty(propertyName) {
        return propertyName.startsWith('--');
    }
    isShadowProperty(propertyName) {
        propertyName = propertyName.toLowerCase();
        return propertyName === 'box-shadow' || propertyName === 'text-shadow' || propertyName === '-webkit-box-shadow';
    }
    isStringProperty(propertyName) {
        propertyName = propertyName.toLowerCase();
        return propertyName === 'content';
    }
    canonicalPropertyName(name) {
        if (this.isCustomProperty(name)) {
            return name;
        }
        name = name.toLowerCase();
        const aliasFor = this.#aliasesFor.get(name);
        if (aliasFor) {
            return aliasFor;
        }
        if (!name || name.length < 9 || name.charAt(0) !== '-') {
            return name;
        }
        const match = name.match(/(?:-webkit-)(.+)/);
        if (!match || !this.#valuesSet.has(match[1])) {
            return name;
        }
        return match[1];
    }
    isCSSPropertyName(propertyName) {
        propertyName = propertyName.toLowerCase();
        if ((propertyName.startsWith('--') && propertyName.length > 2) || propertyName.startsWith('-moz-') ||
            propertyName.startsWith('-ms-') || propertyName.startsWith('-o-') || propertyName.startsWith('-webkit-')) {
            return true;
        }
        return this.#valuesSet.has(propertyName);
    }
    isPropertyInherited(propertyName) {
        propertyName = propertyName.toLowerCase();
        return propertyName.startsWith('--') || this.#inherited.has(this.canonicalPropertyName(propertyName)) ||
            this.#inherited.has(propertyName);
    }
    specificPropertyValues(propertyName) {
        const unprefixedName = propertyName.replace(/^-webkit-/, '');
        const propertyValues = this.#propertyValues;
        let keywords = propertyValues.get(propertyName) || propertyValues.get(unprefixedName);
        if (!keywords) {
            keywords = [];
            for (const commonKeyword of CommonKeywords) {
                if (CSS.supports(propertyName, commonKeyword)) {
                    keywords.push(commonKeyword);
                }
            }
            propertyValues.set(propertyName, keywords);
        }
        return keywords;
    }
    getPropertyValues(propertyName) {
        propertyName = propertyName.toLowerCase();
        const acceptedKeywords = [...this.specificPropertyValues(propertyName), ...CSSWideKeywords];
        if (this.isColorAwareProperty(propertyName)) {
            acceptedKeywords.push('currentColor');
            for (const color of Nicknames.keys()) {
                acceptedKeywords.push(color);
            }
        }
        return acceptedKeywords.sort(CSSMetadata.sortPrefixesAndCSSWideKeywordsToEnd);
    }
    propertyUsageWeight(property) {
        return Weight.get(property) || Weight.get(this.canonicalPropertyName(property)) || 0;
    }
    getValuePreset(key, value) {
        const values = valuePresets.get(key);
        let text = values ? values.get(value) : null;
        if (!text) {
            return null;
        }
        let startColumn = text.length;
        let endColumn = text.length;
        if (text) {
            startColumn = text.indexOf('|');
            endColumn = text.lastIndexOf('|');
            endColumn = startColumn === endColumn ? endColumn : endColumn - 1;
            text = text.replace(/\|/g, '');
        }
        return { text, startColumn, endColumn };
    }
    isHighlightPseudoType(pseudoType) {
        return (pseudoType === "highlight"  || pseudoType === "selection"  ||
            pseudoType === "target-text"  || pseudoType === "grammar-error"  ||
            pseudoType === "spelling-error" );
    }
}
const CubicBezierKeywordValues = new Map([
    ['linear', 'cubic-bezier(0, 0, 1, 1)'],
    ['ease', 'cubic-bezier(0.25, 0.1, 0.25, 1)'],
    ['ease-in', 'cubic-bezier(0.42, 0, 1, 1)'],
    ['ease-in-out', 'cubic-bezier(0.42, 0, 0.58, 1)'],
    ['ease-out', 'cubic-bezier(0, 0, 0.58, 1)'],
]);
const CSSWideKeywords = [
    "inherit" ,
    "initial" ,
    "revert" ,
    "revert-layer" ,
    "revert-rule" ,
    "unset" ,
];
const PositionTryOrderKeywords = [
    "normal" ,
    "most-height" ,
    "most-width" ,
    "most-block-size" ,
    "most-inline-size" ,
];
const GridAreaRowRegex = /((?:\[[\w\- ]+\]\s*)*(?:"[^"]+"|'[^']+'))[^'"\[]*\[?[^'"\[]*/;
let cssMetadataInstance = null;
function cssMetadata() {
    if (!cssMetadataInstance) {
        const supportedProperties = generatedProperties;
        cssMetadataInstance = new CSSMetadata(supportedProperties, generatedAliasesFor);
    }
    return cssMetadataInstance;
}
const imageValuePresetMap = new Map([
    ['linear-gradient', 'linear-gradient(|45deg, black, transparent|)'],
    ['radial-gradient', 'radial-gradient(|black, transparent|)'],
    ['repeating-linear-gradient', 'repeating-linear-gradient(|45deg, black, transparent 100px|)'],
    ['repeating-radial-gradient', 'repeating-radial-gradient(|black, transparent 100px|)'],
    ['url', 'url(||)'],
]);
const filterValuePresetMap = new Map([
    ['blur', 'blur(|1px|)'],
    ['brightness', 'brightness(|0.5|)'],
    ['contrast', 'contrast(|0.5|)'],
    ['drop-shadow', 'drop-shadow(|2px 4px 6px black|)'],
    ['grayscale', 'grayscale(|1|)'],
    ['hue-rotate', 'hue-rotate(|45deg|)'],
    ['invert', 'invert(|1|)'],
    ['opacity', 'opacity(|0.5|)'],
    ['saturate', 'saturate(|0.5|)'],
    ['sepia', 'sepia(|1|)'],
    ['url', 'url(||)'],
]);
const cornerShapeValuePresetMap = new Map([
    ['superellipse(0.5)', 'superellipse(|0.5|)'],
    ['superellipse(infinity)', 'superellipse(|infinity|)'],
]);
const valuePresets = new Map([
    ['filter', filterValuePresetMap], ['backdrop-filter', filterValuePresetMap], ['background', imageValuePresetMap],
    ['background-image', imageValuePresetMap], ['-webkit-mask-image', imageValuePresetMap],
    [
        'transform',
        new Map([
            ['scale', 'scale(|1.5|)'],
            ['scaleX', 'scaleX(|1.5|)'],
            ['scaleY', 'scaleY(|1.5|)'],
            ['scale3d', 'scale3d(|1.5, 1.5, 1.5|)'],
            ['rotate', 'rotate(|45deg|)'],
            ['rotateX', 'rotateX(|45deg|)'],
            ['rotateY', 'rotateY(|45deg|)'],
            ['rotateZ', 'rotateZ(|45deg|)'],
            ['rotate3d', 'rotate3d(|1, 1, 1, 45deg|)'],
            ['skew', 'skew(|10deg, 10deg|)'],
            ['skewX', 'skewX(|10deg|)'],
            ['skewY', 'skewY(|10deg|)'],
            ['translate', 'translate(|10px, 10px|)'],
            ['translateX', 'translateX(|10px|)'],
            ['translateY', 'translateY(|10px|)'],
            ['translateZ', 'translateZ(|10px|)'],
            ['translate3d', 'translate3d(|10px, 10px, 10px|)'],
            ['matrix', 'matrix(|1, 0, 0, 1, 0, 0|)'],
            ['matrix3d', 'matrix3d(|1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1|)'],
            ['perspective', 'perspective(|10px|)'],
        ]),
    ],
    ['corner-shape', cornerShapeValuePresetMap],
    [
        'font-variant-alternates',
        new Map([
            ['stylistic', 'stylistic(||)'],
            ['styleset', 'styleset(||)'],
            ['character-variant', 'character-variant(||)'],
            ['swash', 'swash(||)'],
            ['ornaments', 'ornaments(||)'],
            ['annotation', 'annotation(||)'],
        ]),
    ]
]);
const distanceProperties = new Set([
    'background-position',
    'border-spacing',
    'bottom',
    'font-size',
    'height',
    'left',
    'letter-spacing',
    'max-height',
    'max-width',
    'min-height',
    'min-width',
    'right',
    'text-indent',
    'top',
    'width',
    'word-spacing',
    'grid-row-gap',
    'grid-column-gap',
    'row-gap',
]);
const bezierAwareProperties = new Set([
    'animation',
    'animation-timing-function',
    'transition',
    'transition-timing-function',
    '-webkit-animation',
    '-webkit-animation-timing-function',
    '-webkit-transition',
    '-webkit-transition-timing-function',
]);
const fontAwareProperties = new Set(['font-size', 'line-height', 'font-weight', 'font-family', 'letter-spacing']);
const colorAwareProperties = new Set([
    'accent-color',
    'background',
    'background-color',
    'background-image',
    'border',
    'border-color',
    'border-image',
    'border-image-source',
    'border-bottom',
    'border-bottom-color',
    'border-left',
    'border-left-color',
    'border-right',
    'border-right-color',
    'border-top',
    'border-top-color',
    'border-block',
    'border-block-color',
    'border-block-end',
    'border-block-end-color',
    'border-block-start',
    'border-block-start-color',
    'border-inline',
    'border-inline-color',
    'border-inline-end',
    'border-inline-end-color',
    'border-inline-start',
    'border-inline-start-color',
    'box-shadow',
    'caret-color',
    'color',
    'column-rule',
    'column-rule-color',
    'content',
    'fill',
    'list-style-image',
    'mask',
    'mask-image',
    'mask-border',
    'mask-border-source',
    'outline',
    'outline-color',
    'scrollbar-color',
    'stop-color',
    'stroke',
    'text-decoration-color',
    'text-shadow',
    'text-emphasis',
    'text-emphasis-color',
    '-webkit-border-after',
    '-webkit-border-after-color',
    '-webkit-border-before',
    '-webkit-border-before-color',
    '-webkit-border-end',
    '-webkit-border-end-color',
    '-webkit-border-start',
    '-webkit-border-start-color',
    '-webkit-box-reflect',
    '-webkit-box-shadow',
    '-webkit-column-rule-color',
    '-webkit-mask',
    '-webkit-mask-box-image',
    '-webkit-mask-box-image-source',
    '-webkit-mask-image',
    '-webkit-tap-highlight-color',
    '-webkit-text-emphasis',
    '-webkit-text-emphasis-color',
    '-webkit-text-fill-color',
    '-webkit-text-stroke',
    '-webkit-text-stroke-color',
    'flood-color',
    'lighting-color',
    'stop-color',
]);
const angleAwareProperties = new Set([
    '-webkit-border-image',
    'transform',
    '-webkit-transform',
    'rotate',
    'filter',
    '-webkit-filter',
    'backdrop-filter',
    'offset',
    'offset-rotate',
    'font-style',
]);
const textEmphasisPosition = new Set([
    'over',
    'under',
    'over right',
    'over left',
    'under right',
    'under left',
]);
const textEmphasisStyle = new Set([
    'none', 'dot', 'circle', 'double-circle', 'triangle', 'sesame', 'filled', 'open', 'dot open', 'circle open',
    'double-circle open', 'triangle open', 'sesame open',
    '"❤️"',
]);
const extraPropertyValues = new Map([
    ['background-repeat', new Set(['repeat', 'repeat-x', 'repeat-y', 'no-repeat', 'space', 'round'])],
    ['content', new Set(['normal', 'close-quote', 'no-close-quote', 'no-open-quote', 'open-quote'])],
    ['baseline-shift', new Set(['baseline'])],
    ['max-height', new Set(['min-content', 'max-content', '-webkit-fill-available', 'fit-content', 'stretch'])],
    ['color', new Set(['black'])],
    ['background-color', new Set(['white'])],
    ['box-shadow', new Set(['inset'])],
    ['text-shadow', new Set(['0 0 black'])],
    ['-webkit-writing-mode', new Set(['horizontal-tb', 'vertical-rl', 'vertical-lr'])],
    ['writing-mode', new Set(['lr', 'rl', 'tb', 'lr-tb', 'rl-tb', 'tb-rl'])],
    ['page-break-inside', new Set(['avoid'])],
    ['cursor', new Set(['-webkit-zoom-in', '-webkit-zoom-out', '-webkit-grab', '-webkit-grabbing'])],
    ['border-width', new Set(['medium', 'thick', 'thin'])],
    ['border-style', new Set(['hidden', 'inset', 'groove', 'ridge', 'outset', 'dotted', 'dashed', 'solid', 'double'])],
    ['size', new Set(['a3', 'a4', 'a5', 'b4', 'b5', 'landscape', 'ledger', 'legal', 'letter', 'portrait'])],
    ['overflow', new Set(['hidden', 'visible', 'overlay', 'scroll', 'clip'])],
    ['overscroll-behavior', new Set(['contain'])],
    ['text-rendering', new Set(['optimizeSpeed', 'optimizeLegibility', 'geometricPrecision'])],
    ['text-align', new Set(['-webkit-auto', '-webkit-match-parent'])],
    ['clip-path', new Set(['circle', 'ellipse', 'inset', 'polygon', 'url'])],
    ['color-interpolation', new Set(['sRGB', 'linearRGB'])],
    ['word-wrap', new Set(['normal', 'break-word'])],
    ['font-weight', new Set(['100', '200', '300', '400', '500', '600', '700', '800', '900'])],
    ['text-emphasis', textEmphasisStyle],
    ['-webkit-text-emphasis', textEmphasisStyle],
    ['color-rendering', new Set(['optimizeSpeed', 'optimizeQuality'])],
    ['-webkit-text-combine', new Set(['horizontal'])],
    ['text-orientation', new Set(['sideways-right'])],
    [
        'outline',
        new Set(['inset', 'groove', 'ridge', 'outset', 'dotted', 'dashed', 'solid', 'double', 'medium', 'thick', 'thin']),
    ],
    [
        'font',
        new Set([
            'caption',
            'icon',
            'menu',
            'message-box',
            'small-caption',
            '-webkit-mini-control',
            '-webkit-small-control',
            '-webkit-control',
            'status-bar',
        ]),
    ],
    ['dominant-baseline', new Set(['text-before-edge', 'text-after-edge', 'use-script', 'no-change', 'reset-size'])],
    ['text-emphasis-position', textEmphasisPosition],
    ['-webkit-text-emphasis-position', textEmphasisPosition],
    ['alignment-baseline', new Set(['before-edge', 'after-edge', 'text-before-edge', 'text-after-edge', 'hanging'])],
    ['page-break-before', new Set(['left', 'right', 'always', 'avoid'])],
    ['border-image', new Set(['repeat', 'stretch', 'space', 'round'])],
    [
        'text-decoration',
        new Set(['blink', 'line-through', 'overline', 'underline', 'wavy', 'double', 'solid', 'dashed', 'dotted']),
    ],
    [
        'font-family',
        new Set([
            'serif',
            'sans-serif',
            'cursive',
            'fantasy',
            'monospace',
            'system-ui',
            'emoji',
            'math',
            'fangsong',
            'ui-serif',
            'ui-sans-serif',
            'ui-monospace',
            'ui-rounded',
            '-webkit-body',
        ]),
    ],
    ['zoom', new Set(['normal'])],
    ['max-width', new Set(['min-content', 'max-content', '-webkit-fill-available', 'fit-content', 'stretch'])],
    ['-webkit-font-smoothing', new Set(['antialiased', 'subpixel-antialiased'])],
    [
        'border',
        new Set([
            'hidden',
            'inset',
            'groove',
            'ridge',
            'outset',
            'dotted',
            'dashed',
            'solid',
            'double',
            'medium',
            'thick',
            'thin',
        ]),
    ],
    [
        'font-variant',
        new Set([
            'small-caps',
            'normal',
            'common-ligatures',
            'no-common-ligatures',
            'discretionary-ligatures',
            'no-discretionary-ligatures',
            'historical-ligatures',
            'no-historical-ligatures',
            'contextual',
            'no-contextual',
            'all-small-caps',
            'petite-caps',
            'all-petite-caps',
            'unicase',
            'titling-caps',
            'lining-nums',
            'oldstyle-nums',
            'proportional-nums',
            'tabular-nums',
            'diagonal-fractions',
            'stacked-fractions',
            'ordinal',
            'slashed-zero',
            'jis78',
            'jis83',
            'jis90',
            'jis04',
            'simplified',
            'traditional',
            'full-width',
            'proportional-width',
            'ruby',
        ]),
    ],
    [
        'font-variant-alternates',
        new Set(['historical-forms', 'stylistic', 'styleset', 'character-variant', 'swash', 'ornaments', 'annotation'])
    ],
    ['vertical-align', new Set(['top', 'bottom', '-webkit-baseline-middle'])],
    ['page-break-after', new Set(['left', 'right', 'always', 'avoid'])],
    ['text-emphasis-style', textEmphasisStyle],
    ['-webkit-text-emphasis-style', textEmphasisStyle],
    [
        'transform',
        new Set([
            'scale', 'scaleX', 'scaleY', 'scale3d', 'rotate', 'rotateX', 'rotateY',
            'rotateZ', 'rotate3d', 'skew', 'skewX', 'skewY', 'translate', 'translateX',
            'translateY', 'translateZ', 'translate3d', 'matrix', 'matrix3d', 'perspective',
        ]),
    ],
    [
        'align-content',
        new Set([
            'normal',
            'baseline',
            'space-between',
            'space-around',
            'space-evenly',
            'stretch',
            'center',
            'start',
            'end',
            'flex-start',
            'flex-end',
        ]),
    ],
    [
        'justify-content',
        new Set([
            'normal',
            'space-between',
            'space-around',
            'space-evenly',
            'stretch',
            'center',
            'start',
            'end',
            'flex-start',
            'flex-end',
            'left',
            'right',
        ]),
    ],
    [
        'place-content',
        new Set([
            'normal',
            'space-between',
            'space-around',
            'space-evenly',
            'stretch',
            'center',
            'start',
            'end',
            'flex-start',
            'flex-end',
            'baseline',
        ]),
    ],
    [
        'align-items',
        new Set([
            'normal',
            'stretch',
            'baseline',
            'center',
            'start',
            'end',
            'self-start',
            'self-end',
            'flex-start',
            'flex-end',
            'anchor-center',
        ]),
    ],
    [
        'justify-items',
        new Set([
            'normal',
            'stretch',
            'baseline',
            'center',
            'start',
            'end',
            'self-start',
            'self-end',
            'flex-start',
            'flex-end',
            'left',
            'right',
            'legacy',
            'anchor-center',
        ]),
    ],
    [
        'place-items',
        new Set([
            'normal',
            'stretch',
            'baseline',
            'center',
            'start',
            'end',
            'self-start',
            'self-end',
            'flex-start',
            'flex-end',
            'anchor-center',
        ]),
    ],
    [
        'align-self',
        new Set([
            'normal',
            'stretch',
            'baseline',
            'center',
            'start',
            'end',
            'self-start',
            'self-end',
            'flex-start',
            'flex-end',
            'anchor-center',
        ]),
    ],
    [
        'justify-self',
        new Set([
            'normal',
            'stretch',
            'baseline',
            'center',
            'start',
            'end',
            'self-start',
            'self-end',
            'flex-start',
            'flex-end',
            'left',
            'right',
            'anchor-center',
        ]),
    ],
    [
        'place-self',
        new Set([
            'normal',
            'stretch',
            'baseline',
            'center',
            'start',
            'end',
            'self-start',
            'self-end',
            'flex-start',
            'flex-end',
            'anchor-center',
        ]),
    ],
    ['perspective-origin', new Set(['left', 'center', 'right', 'top', 'bottom'])],
    ['transform-origin', new Set(['left', 'center', 'right', 'top', 'bottom'])],
    ['transition-timing-function', new Set(['cubic-bezier', 'steps'])],
    ['animation-timing-function', new Set(['cubic-bezier', 'steps'])],
    ['-webkit-backface-visibility', new Set(['visible', 'hidden'])],
    ['-webkit-column-break-after', new Set(['always', 'avoid'])],
    ['-webkit-column-break-before', new Set(['always', 'avoid'])],
    ['-webkit-column-break-inside', new Set(['avoid'])],
    ['-webkit-column-span', new Set(['all'])],
    ['-webkit-column-gap', new Set(['normal'])],
    [
        'filter',
        new Set([
            'url',
            'blur',
            'brightness',
            'contrast',
            'drop-shadow',
            'grayscale',
            'hue-rotate',
            'invert',
            'opacity',
            'saturate',
            'sepia',
        ]),
    ],
    [
        'backdrop-filter',
        new Set([
            'url',
            'blur',
            'brightness',
            'contrast',
            'drop-shadow',
            'grayscale',
            'hue-rotate',
            'invert',
            'opacity',
            'saturate',
            'sepia',
        ]),
    ],
    ['grid-template-columns', new Set(['min-content', 'max-content'])],
    ['grid-template-rows', new Set(['min-content', 'max-content'])],
    ['grid-auto-flow', new Set(['dense'])],
    [
        'background',
        new Set([
            'repeat',
            'repeat-x',
            'repeat-y',
            'no-repeat',
            'top',
            'bottom',
            'left',
            'right',
            'center',
            'fixed',
            'local',
            'scroll',
            'space',
            'round',
            'border-box',
            'content-box',
            'padding-box',
            'linear-gradient',
            'radial-gradient',
            'repeating-linear-gradient',
            'repeating-radial-gradient',
            'url',
        ]),
    ],
    [
        'background-image',
        new Set(['linear-gradient', 'radial-gradient', 'repeating-linear-gradient', 'repeating-radial-gradient', 'url']),
    ],
    ['background-position', new Set(['top', 'bottom', 'left', 'right', 'center'])],
    ['background-position-x', new Set(['left', 'right', 'center'])],
    ['background-position-y', new Set(['top', 'bottom', 'center'])],
    ['background-repeat-x', new Set(['repeat', 'no-repeat'])],
    ['background-repeat-y', new Set(['repeat', 'no-repeat'])],
    [
        'border-bottom',
        new Set([
            'hidden',
            'inset',
            'groove',
            'outset',
            'ridge',
            'dotted',
            'dashed',
            'solid',
            'double',
            'medium',
            'thick',
            'thin',
        ]),
    ],
    [
        'border-left',
        new Set([
            'hidden',
            'inset',
            'groove',
            'outset',
            'ridge',
            'dotted',
            'dashed',
            'solid',
            'double',
            'medium',
            'thick',
            'thin',
        ]),
    ],
    [
        'border-right',
        new Set([
            'hidden',
            'inset',
            'groove',
            'outset',
            'ridge',
            'dotted',
            'dashed',
            'solid',
            'double',
            'medium',
            'thick',
            'thin',
        ]),
    ],
    [
        'border-top',
        new Set([
            'hidden',
            'inset',
            'groove',
            'outset',
            'ridge',
            'dotted',
            'dashed',
            'solid',
            'double',
            'medium',
            'thick',
            'thin',
        ]),
    ],
    ['buffered-rendering', new Set(['static', 'dynamic'])],
    ['color-interpolation-filters', new Set(['srgb', 'linearrgb'])],
    [
        'column-rule',
        new Set([
            'hidden',
            'inset',
            'groove',
            'outset',
            'ridge',
            'dotted',
            'dashed',
            'solid',
            'double',
            'medium',
            'thick',
            'thin',
        ]),
    ],
    ['flex-flow', new Set(['nowrap', 'row', 'row-reverse', 'column', 'column-reverse', 'wrap', 'wrap-reverse'])],
    ['height', new Set(['-webkit-fill-available', 'stretch'])],
    ['inline-size', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content'])],
    [
        'list-style',
        new Set([
            'outside',
            'inside',
            'disc',
            'circle',
            'square',
            'decimal',
            'decimal-leading-zero',
            'arabic-indic',
            'bengali',
            'cambodian',
            'khmer',
            'devanagari',
            'gujarati',
            'gurmukhi',
            'kannada',
            'lao',
            'malayalam',
            'mongolian',
            'myanmar',
            'oriya',
            'persian',
            'urdu',
            'telugu',
            'tibetan',
            'thai',
            'lower-roman',
            'upper-roman',
            'lower-greek',
            'lower-alpha',
            'lower-latin',
            'upper-alpha',
            'upper-latin',
            'cjk-earthly-branch',
            'cjk-heavenly-stem',
            'ethiopic-halehame',
            'ethiopic-halehame-am',
            'ethiopic-halehame-ti-er',
            'ethiopic-halehame-ti-et',
            'hangul',
            'hangul-consonant',
            'korean-hangul-formal',
            'korean-hanja-formal',
            'korean-hanja-informal',
            'hebrew',
            'armenian',
            'lower-armenian',
            'upper-armenian',
            'georgian',
            'cjk-ideographic',
            'simp-chinese-formal',
            'simp-chinese-informal',
            'trad-chinese-formal',
            'trad-chinese-informal',
            'hiragana',
            'katakana',
            'hiragana-iroha',
            'katakana-iroha',
        ]),
    ],
    ['max-block-size', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content'])],
    ['max-inline-size', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content'])],
    ['min-block-size', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content'])],
    ['min-height', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content', 'stretch'])],
    ['min-inline-size', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content'])],
    ['min-width', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content', 'stretch'])],
    ['object-position', new Set(['top', 'bottom', 'left', 'right', 'center'])],
    ['shape-outside', new Set(['border-box', 'content-box', 'padding-box', 'margin-box'])],
    [
        '-webkit-appearance',
        new Set([
            'checkbox',
            'radio',
            'push-button',
            'square-button',
            'button',
            'inner-spin-button',
            'listbox',
            'media-slider',
            'media-sliderthumb',
            'media-volume-slider',
            'media-volume-sliderthumb',
            'menulist',
            'menulist-button',
            'meter',
            'progress-bar',
            'slider-horizontal',
            'slider-vertical',
            'sliderthumb-horizontal',
            'sliderthumb-vertical',
            'searchfield',
            'searchfield-cancel-button',
            'textfield',
            'textarea',
        ]),
    ],
    [
        '-webkit-border-after',
        new Set([
            'hidden',
            'inset',
            'groove',
            'outset',
            'ridge',
            'dotted',
            'dashed',
            'solid',
            'double',
            'medium',
            'thick',
            'thin',
        ]),
    ],
    [
        '-webkit-border-after-style',
        new Set(['hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']),
    ],
    ['-webkit-border-after-width', new Set(['medium', 'thick', 'thin'])],
    [
        '-webkit-border-before',
        new Set([
            'hidden',
            'inset',
            'groove',
            'outset',
            'ridge',
            'dotted',
            'dashed',
            'solid',
            'double',
            'medium',
            'thick',
            'thin',
        ]),
    ],
    [
        '-webkit-border-before-style',
        new Set(['hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']),
    ],
    ['-webkit-border-before-width', new Set(['medium', 'thick', 'thin'])],
    [
        '-webkit-border-end',
        new Set([
            'hidden',
            'inset',
            'groove',
            'outset',
            'ridge',
            'dotted',
            'dashed',
            'solid',
            'double',
            'medium',
            'thick',
            'thin',
        ]),
    ],
    [
        '-webkit-border-end-style',
        new Set(['hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']),
    ],
    ['-webkit-border-end-width', new Set(['medium', 'thick', 'thin'])],
    [
        '-webkit-border-start',
        new Set([
            'hidden',
            'inset',
            'groove',
            'outset',
            'ridge',
            'dotted',
            'dashed',
            'solid',
            'double',
            'medium',
            'thick',
            'thin',
        ]),
    ],
    [
        '-webkit-border-start-style',
        new Set(['hidden', 'inset', 'groove', 'outset', 'ridge', 'dotted', 'dashed', 'solid', 'double']),
    ],
    ['-webkit-border-start-width', new Set(['medium', 'thick', 'thin'])],
    ['-webkit-logical-height', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content'])],
    ['-webkit-logical-width', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content'])],
    ['-webkit-mask-box-image', new Set(['repeat', 'stretch', 'space', 'round'])],
    ['-webkit-mask-box-image-repeat', new Set(['repeat', 'stretch', 'space', 'round'])],
    ['-webkit-mask-clip', new Set(['text', 'border', 'border-box', 'content', 'content-box', 'padding', 'padding-box'])],
    [
        '-webkit-mask-composite',
        new Set([
            'clear',
            'copy',
            'source-over',
            'source-in',
            'source-out',
            'source-atop',
            'destination-over',
            'destination-in',
            'destination-out',
            'destination-atop',
            'xor',
            'plus-lighter',
        ]),
    ],
    [
        '-webkit-mask-image',
        new Set(['linear-gradient', 'radial-gradient', 'repeating-linear-gradient', 'repeating-radial-gradient', 'url']),
    ],
    ['-webkit-mask-origin', new Set(['border', 'border-box', 'content', 'content-box', 'padding', 'padding-box'])],
    ['-webkit-mask-position', new Set(['top', 'bottom', 'left', 'right', 'center'])],
    ['-webkit-mask-position-x', new Set(['left', 'right', 'center'])],
    ['-webkit-mask-position-y', new Set(['top', 'bottom', 'center'])],
    ['-webkit-mask-repeat', new Set(['repeat', 'repeat-x', 'repeat-y', 'no-repeat', 'space', 'round'])],
    ['-webkit-mask-size', new Set(['contain', 'cover'])],
    ['-webkit-max-logical-height', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content'])],
    ['-webkit-max-logical-width', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content'])],
    ['-webkit-min-logical-height', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content'])],
    ['-webkit-min-logical-width', new Set(['-webkit-fill-available', 'min-content', 'max-content', 'fit-content'])],
    ['-webkit-perspective-origin-x', new Set(['left', 'right', 'center'])],
    ['-webkit-perspective-origin-y', new Set(['top', 'bottom', 'center'])],
    ['-webkit-text-decorations-in-effect', new Set(['blink', 'line-through', 'overline', 'underline'])],
    ['-webkit-text-stroke', new Set(['medium', 'thick', 'thin'])],
    ['-webkit-text-stroke-width', new Set(['medium', 'thick', 'thin'])],
    ['-webkit-transform-origin-x', new Set(['left', 'right', 'center'])],
    ['-webkit-transform-origin-y', new Set(['top', 'bottom', 'center'])],
    ['width', new Set(['-webkit-fill-available', 'stretch'])],
    [
        'animation-trigger',
        new Set([
            'play',
            'pause',
            'play-once',
            'play-alternate',
            'play-forwards',
            'play-backwards',
            'play-pause',
            'replay',
        ]),
    ],
    ['timeline-trigger-activation-range-start', new Set(['normal'])],
    ['timeline-trigger-activation-range-end', new Set(['normal'])],
    ['timeline-trigger-active-range-start', new Set(['normal'])],
    ['timeline-trigger-active-range-end', new Set(['normal'])],
    ['contain-intrinsic-width', new Set(['auto none', 'auto 100px'])],
    ['contain-intrinsic-height', new Set(['auto none', 'auto 100px'])],
    ['contain-intrinsic-size', new Set(['auto none', 'auto 100px'])],
    ['contain-intrinsic-inline-size', new Set(['auto none', 'auto 100px'])],
    ['contain-intrinsic-block-size', new Set(['auto none', 'auto 100px'])],
    [
        'white-space',
        new Set([
            'normal',
            'pre',
            'pre-wrap',
            'pre-line',
            'nowrap',
            'break-spaces',
        ]),
    ],
    [
        'text-box-edge',
        new Set([
            'auto',
            'text',
            'cap',
            'ex',
            'text alphabetic',
            'cap alphabetic',
            'ex alphabetic',
        ]),
    ],
    [
        'corner-shape',
        new Set([
            'round',
            'scoop',
            'bevel',
            'notch',
            'square',
            'squircle',
            'superellipse(0.5)',
            'superellipse(infinity)',
        ]),
    ],
]);
const Weight = new Map([
    ['align-content', 57],
    ['align-items', 129],
    ['align-self', 55],
    ['animation', 175],
    ['animation-delay', 114],
    ['animation-direction', 113],
    ['animation-duration', 137],
    ['animation-fill-mode', 132],
    ['animation-iteration-count', 124],
    ['animation-name', 139],
    ['animation-play-state', 104],
    ['animation-timing-function', 141],
    ['backface-visibility', 123],
    ['background', 260],
    ['background-attachment', 119],
    ['background-clip', 165],
    ['background-color', 259],
    ['background-image', 246],
    ['background-origin', 107],
    ['background-position', 237],
    ['background-position-x', 108],
    ['background-position-y', 93],
    ['background-repeat', 234],
    ['background-size', 203],
    ['border', 263],
    ['border-bottom', 233],
    ['border-bottom-color', 190],
    ['border-bottom-left-radius', 186],
    ['border-bottom-right-radius', 185],
    ['border-bottom-style', 150],
    ['border-bottom-width', 179],
    ['border-collapse', 209],
    ['border-color', 226],
    ['border-image', 89],
    ['border-image-outset', 50],
    ['border-image-repeat', 49],
    ['border-image-slice', 58],
    ['border-image-source', 32],
    ['border-image-width', 52],
    ['border-left', 221],
    ['border-left-color', 174],
    ['border-left-style', 142],
    ['border-left-width', 172],
    ['border-radius', 224],
    ['border-right', 223],
    ['border-right-color', 182],
    ['border-right-style', 130],
    ['border-right-width', 178],
    ['border-spacing', 198],
    ['border-style', 206],
    ['border-top', 231],
    ['border-top-color', 192],
    ['border-top-left-radius', 187],
    ['border-top-right-radius', 189],
    ['border-top-style', 152],
    ['border-top-width', 180],
    ['border-width', 214],
    ['bottom', 227],
    ['box-shadow', 213],
    ['box-sizing', 216],
    ['caption-side', 96],
    ['clear', 229],
    ['clip', 173],
    ['clip-rule', 5],
    ['color', 256],
    ['content', 219],
    ['counter-increment', 111],
    ['counter-reset', 110],
    ['cursor', 250],
    ['direction', 176],
    ['display', 262],
    ['empty-cells', 99],
    ['fill', 140],
    ['fill-opacity', 82],
    ['fill-rule', 22],
    ['filter', 160],
    ['flex', 133],
    ['flex-basis', 66],
    ['flex-direction', 85],
    ['flex-flow', 94],
    ['flex-grow', 112],
    ['flex-shrink', 61],
    ['flex-wrap', 68],
    ['float', 252],
    ['font', 211],
    ['font-family', 254],
    ['font-kerning', 18],
    ['font-size', 264],
    ['font-stretch', 77],
    ['font-style', 220],
    ['font-variant', 161],
    ['font-weight', 257],
    ['height', 266],
    ['image-rendering', 90],
    ['justify-content', 127],
    ['left', 248],
    ['letter-spacing', 188],
    ['line-height', 244],
    ['list-style', 215],
    ['list-style-image', 145],
    ['list-style-position', 149],
    ['list-style-type', 199],
    ['margin', 267],
    ['margin-bottom', 241],
    ['margin-left', 243],
    ['margin-right', 238],
    ['margin-top', 253],
    ['mask', 20],
    ['max-height', 205],
    ['max-width', 225],
    ['min-height', 217],
    ['min-width', 218],
    ['object-fit', 33],
    ['opacity', 251],
    ['order', 117],
    ['orphans', 146],
    ['outline', 222],
    ['outline-color', 153],
    ['outline-offset', 147],
    ['outline-style', 151],
    ['outline-width', 148],
    ['overflow', 255],
    ['overflow-wrap', 105],
    ['overflow-x', 184],
    ['overflow-y', 196],
    ['padding', 265],
    ['padding-bottom', 230],
    ['padding-left', 235],
    ['padding-right', 232],
    ['padding-top', 240],
    ['page', 8],
    ['page-break-after', 120],
    ['page-break-before', 69],
    ['page-break-inside', 121],
    ['perspective', 92],
    ['perspective-origin', 103],
    ['pointer-events', 183],
    ['position', 261],
    ['quotes', 158],
    ['resize', 168],
    ['right', 245],
    ['shape-rendering', 38],
    ['size', 64],
    ['speak', 118],
    ['src', 170],
    ['stop-color', 42],
    ['stop-opacity', 31],
    ['stroke', 98],
    ['stroke-dasharray', 36],
    ['stroke-dashoffset', 3],
    ['stroke-linecap', 30],
    ['stroke-linejoin', 21],
    ['stroke-miterlimit', 12],
    ['stroke-opacity', 34],
    ['stroke-width', 87],
    ['table-layout', 171],
    ['tab-size', 46],
    ['text-align', 260],
    ['text-anchor', 35],
    ['text-decoration', 247],
    ['text-indent', 207],
    ['text-overflow', 204],
    ['text-rendering', 155],
    ['text-shadow', 208],
    ['text-transform', 202],
    ['top', 258],
    ['touch-action', 80],
    ['transform', 181],
    ['transform-origin', 162],
    ['transform-style', 86],
    ['transition', 193],
    ['transition-delay', 134],
    ['transition-duration', 135],
    ['transition-property', 131],
    ['transition-timing-function', 122],
    ['unicode-bidi', 156],
    ['unicode-range', 136],
    ['vertical-align', 236],
    ['visibility', 242],
    ['-webkit-appearance', 191],
    ['-webkit-backface-visibility', 154],
    ['-webkit-background-clip', 164],
    ['-webkit-background-origin', 40],
    ['-webkit-background-size', 163],
    ['-webkit-border-end', 9],
    ['-webkit-border-horizontal-spacing', 81],
    ['-webkit-border-image', 75],
    ['-webkit-border-radius', 212],
    ['-webkit-border-start', 10],
    ['-webkit-border-start-color', 16],
    ['-webkit-border-start-width', 13],
    ['-webkit-border-vertical-spacing', 43],
    ['-webkit-box-align', 101],
    ['-webkit-box-direction', 51],
    ['-webkit-box-flex', 128],
    ['-webkit-box-ordinal-group', 91],
    ['-webkit-box-orient', 144],
    ['-webkit-box-pack', 106],
    ['-webkit-box-reflect', 39],
    ['-webkit-box-shadow', 210],
    ['-webkit-column-break-inside', 60],
    ['-webkit-column-count', 84],
    ['-webkit-column-gap', 76],
    ['-webkit-column-rule', 25],
    ['-webkit-column-rule-color', 23],
    ['-webkit-columns', 44],
    ['-webkit-column-span', 29],
    ['-webkit-column-width', 47],
    ['-webkit-filter', 159],
    ['-webkit-font-feature-settings', 59],
    ['-webkit-font-smoothing', 177],
    ['-webkit-line-break', 45],
    ['-webkit-line-clamp', 126],
    ['-webkit-margin-after', 67],
    ['-webkit-margin-before', 70],
    ['-webkit-margin-collapse', 14],
    ['-webkit-margin-end', 65],
    ['-webkit-margin-start', 100],
    ['-webkit-mask', 19],
    ['-webkit-mask-box-image', 72],
    ['-webkit-mask-image', 88],
    ['-webkit-mask-position', 54],
    ['-webkit-mask-repeat', 63],
    ['-webkit-mask-size', 79],
    ['-webkit-padding-after', 15],
    ['-webkit-padding-before', 28],
    ['-webkit-padding-end', 48],
    ['-webkit-padding-start', 73],
    ['-webkit-print-color-adjust', 83],
    ['-webkit-rtl-ordering', 7],
    ['-webkit-tap-highlight-color', 169],
    ['-webkit-text-emphasis-color', 11],
    ['-webkit-text-fill-color', 71],
    ['-webkit-text-security', 17],
    ['-webkit-text-stroke', 56],
    ['-webkit-text-stroke-color', 37],
    ['-webkit-text-stroke-width', 53],
    ['-webkit-user-drag', 95],
    ['-webkit-user-modify', 62],
    ['-webkit-user-select', 194],
    ['-webkit-writing-mode', 4],
    ['white-space', 228],
    ['widows', 115],
    ['width', 268],
    ['will-change', 74],
    ['word-break', 166],
    ['word-spacing', 157],
    ['word-wrap', 197],
    ['writing-mode', 41],
    ['z-index', 239],
    ['zoom', 200],
]);
const CommonKeywords = ['auto', 'none'];

// Copyright 2023 The Chromium Authors
class BaseVariableMatch {
    text;
    node;
    name;
    fallback;
    matching;
    computedTextCallback;
    constructor(text, node, name, fallback, matching, computedTextCallback) {
        this.text = text;
        this.node = node;
        this.name = name;
        this.fallback = fallback;
        this.matching = matching;
        this.computedTextCallback = computedTextCallback;
    }
    computedText() {
        return this.computedTextCallback(this, this.matching);
    }
    fallbackValue() {
        if (!this.fallback) {
            return null;
        }
        if (this.fallback.length === 0) {
            return '';
        }
        if (this.matching.hasUnresolvedSubstitutionsRange(this.fallback[0], this.fallback[this.fallback.length - 1])) {
            return null;
        }
        return this.matching.getComputedTextRange(this.fallback[0], this.fallback[this.fallback.length - 1]);
    }
}
class BaseVariableMatcher extends matcherBase(BaseVariableMatch) {
    #computedTextCallback;
    constructor(computedTextCallback) {
        super();
        this.#computedTextCallback = computedTextCallback;
    }
    matches(node, matching) {
        const callee = node.getChild('Callee');
        if (node.name !== 'CallExpression' || !callee || (matching.ast.text(callee) !== 'var')) {
            return null;
        }
        const args = ASTUtils.callArgs(node).map(args => Array.from(ASTUtils.stripComments(args)));
        if (args.length < 1 || args[0].length !== 1) {
            return null;
        }
        const nameNode = args[0][0];
        const fallback = args.length === 2 ? args[1] : undefined;
        if (nameNode?.name !== 'VariableName') {
            return null;
        }
        const varName = matching.ast.text(nameNode);
        if (!varName.startsWith('--')) {
            return null;
        }
        return new BaseVariableMatch(matching.ast.text(node), node, varName, fallback, matching, this.#computedTextCallback);
    }
}
class VariableMatch extends BaseVariableMatch {
    matchedStyles;
    style;
    constructor(text, node, name, fallback, matching, matchedStyles, style) {
        super(text, node, name, fallback, matching, () => this.resolveVariable()?.value ?? this.fallbackValue());
        this.matchedStyles = matchedStyles;
        this.style = style;
    }
    resolveVariable() {
        return this.matchedStyles.computeCSSVariable(this.style, this.name);
    }
}
class VariableMatcher extends matcherBase(VariableMatch) {
    matchedStyles;
    style;
    constructor(matchedStyles, style) {
        super();
        this.matchedStyles = matchedStyles;
        this.style = style;
    }
    matches(node, matching) {
        const match = new BaseVariableMatcher(() => null).matches(node, matching);
        return match ?
            new VariableMatch(match.text, match.node, match.name, match.fallback, match.matching, this.matchedStyles, this.style) :
            null;
    }
}
class AttributeMatch extends BaseVariableMatch {
    type;
    isCSSTokens;
    isValidType;
    rawValue;
    substitutionText;
    matchedStyles;
    style;
    constructor(text, node, name, fallback, matching, type, isCSSTokens, isValidType, rawValue, substitutionText, matchedStyles, style, computedTextCallback) {
        super(text, node, name, fallback, matching, (_, matching) => computedTextCallback(this, matching));
        this.type = type;
        this.isCSSTokens = isCSSTokens;
        this.isValidType = isValidType;
        this.rawValue = rawValue;
        this.substitutionText = substitutionText;
        this.matchedStyles = matchedStyles;
        this.style = style;
    }
    rawAttributeValue() {
        return this.rawValue;
    }
    cssType() {
        return this.type ?? RAW_STRING_TYPE;
    }
    resolveAttributeValue() {
        return this.matchedStyles.computeAttribute(this.style, this.name, { type: this.cssType(), isCSSTokens: this.isCSSTokens });
    }
}
let cssEvaluationElement = null;
function getCssEvaluationElement() {
    const id = 'css-evaluation-element';
    if (!cssEvaluationElement) {
        cssEvaluationElement = document.getElementById(id);
        if (!cssEvaluationElement) {
            cssEvaluationElement = document.createElement('div');
            cssEvaluationElement.setAttribute('id', id);
            cssEvaluationElement.setAttribute('style', 'hidden: true; --evaluation: attr(data-custom-expr type(*))');
            document.body.appendChild(cssEvaluationElement);
        }
    }
    return cssEvaluationElement;
}
function localEvalCSS(value, type) {
    const element = getCssEvaluationElement();
    element.setAttribute('data-value', value);
    element.setAttribute('data-custom-expr', `attr(data-value ${type})`);
    return element.computedStyleMap().get('--evaluation')?.toString() ?? null;
}
function isValidCSSType(type) {
    const element = getCssEvaluationElement();
    element.setAttribute('data-custom-expr', `attr(data-nonexistent ${type}, "good")`);
    return '"good"' === (element.computedStyleMap().get('--evaluation')?.toString() ?? null);
}
function defaultValueForCSSType(type) {
    const element = getCssEvaluationElement();
    element.setAttribute('data-custom-expr', `attr(data-nonexistent ${type ?? ''})`);
    return element.computedStyleMap().get('--evaluation')?.toString() ?? null;
}
const RAW_STRING_TYPE = 'raw-string';
class AttributeMatcher extends matcherBase(AttributeMatch) {
    matchedStyles;
    style;
    computedTextCallback;
    constructor(matchedStyles, style, computedTextCallback) {
        super();
        this.matchedStyles = matchedStyles;
        this.style = style;
        this.computedTextCallback = computedTextCallback;
    }
    matches(node, matching) {
        const callee = node.getChild('Callee');
        if (node.name !== 'CallExpression' || !callee || (matching.ast.text(callee) !== 'attr')) {
            return null;
        }
        const args = ASTUtils.callArgs(node).map(args => Array.from(ASTUtils.stripComments(args)));
        if (args.length < 1) {
            return null;
        }
        const nameNode = args[0][0];
        if (args[0].length < 1 || args[0].length > 2 || nameNode?.name !== 'ValueName') {
            return null;
        }
        const fallback = args.length === 2 ? args[1] : undefined;
        let type = null;
        let isCSSTokens = false;
        if (args[0].length === 2) {
            const typeNode = args[0][1];
            type = matching.ast.text(typeNode);
            if (typeNode.name === 'CallExpression') {
                if (matching.ast.text(typeNode.getChild('Callee')) !== 'type') {
                    return null;
                }
                isCSSTokens = true;
            }
            else if (typeNode.name !== 'ValueName' && type !== '%') {
                return null;
            }
        }
        const isValidType = type === null || isValidCSSType(type);
        isCSSTokens = isCSSTokens && isValidType;
        const attrName = matching.ast.text(nameNode);
        const rawValue = this.matchedStyles.rawAttributeValueFromStyle(this.style, attrName);
        let substitutionText = null;
        if (rawValue !== null) {
            substitutionText = isCSSTokens ? rawValue : localEvalCSS(rawValue, type ?? RAW_STRING_TYPE);
        }
        else if (!fallback) {
            substitutionText = defaultValueForCSSType(type);
        }
        return new AttributeMatch(matching.ast.text(node), node, attrName, fallback, matching, type, isCSSTokens, isValidType, rawValue, substitutionText, this.matchedStyles, this.style, this.computedTextCallback ?? defaultComputeText);
        function defaultComputeText(match, _matching) {
            return match.resolveAttributeValue() ??
                (isValidType ? match.fallbackValue() : defaultValueForCSSType(match.type));
        }
    }
}
class BinOpMatch {
    text;
    node;
    constructor(text, node) {
        this.text = text;
        this.node = node;
    }
}
class BinOpMatcher extends matcherBase(BinOpMatch) {
    accepts() {
        return true;
    }
    matches(node, matching) {
        return node.name === 'BinaryExpression' ? new BinOpMatch(matching.ast.text(node), node) : null;
    }
}
class TextMatch {
    text;
    node;
    computedText;
    constructor(text, node) {
        this.text = text;
        this.node = node;
        if (node.name === 'Comment') {
            this.computedText = () => '';
        }
    }
    render() {
        const span = document.createElement('span');
        span.appendChild(document.createTextNode(this.text));
        return [span];
    }
}
class TextMatcher extends matcherBase(TextMatch) {
    accepts() {
        return true;
    }
    matches(node, matching) {
        if (!node.firstChild || node.name === 'NumberLiteral' ) {
            const text = matching.ast.text(node);
            if (text.length) {
                return new TextMatch(text, node);
            }
        }
        return null;
    }
}
class AngleMatch {
    text;
    node;
    constructor(text, node) {
        this.text = text;
        this.node = node;
    }
    computedText() {
        return this.text;
    }
}
class AngleMatcher extends matcherBase(AngleMatch) {
    accepts(propertyName) {
        return cssMetadata().isAngleAwareProperty(propertyName);
    }
    matches(node, matching) {
        if (node.name !== 'NumberLiteral') {
            return null;
        }
        const unit = node.getChild('Unit');
        if (!unit || !['deg', 'grad', 'rad', 'turn'].includes(matching.ast.text(unit))) {
            return null;
        }
        return new AngleMatch(matching.ast.text(node), node);
    }
}
function literalToNumber(node, ast) {
    if (node.type.name !== 'NumberLiteral') {
        return null;
    }
    const text = ast.text(node);
    return Number(text.substring(0, text.length - ast.text(node.getChild('Unit')).length));
}
class ColorMixMatch {
    text;
    node;
    space;
    color1;
    color2;
    constructor(text, node, space, color1, color2) {
        this.text = text;
        this.node = node;
        this.space = space;
        this.color1 = color1;
        this.color2 = color2;
    }
}
class ColorMixMatcher extends matcherBase(ColorMixMatch) {
    accepts(propertyName) {
        return cssMetadata().isColorAwareProperty(propertyName);
    }
    matches(node, matching) {
        if (node.name !== 'CallExpression' || matching.ast.text(node.getChild('Callee')) !== 'color-mix') {
            return null;
        }
        const computedValueTree = tokenizeDeclaration('--property', matching.getComputedText(node));
        if (!computedValueTree) {
            return null;
        }
        const value = ASTUtils.declValue(computedValueTree.tree);
        if (!value) {
            return null;
        }
        const computedValueArgs = ASTUtils.callArgs(value);
        if (computedValueArgs.length !== 3) {
            return null;
        }
        const [space, color1, color2] = computedValueArgs;
        if (space.length < 2 || computedValueTree.text(ASTUtils.stripComments(space).next().value) !== 'in' ||
            color1.length < 1 || color2.length < 1) {
            return null;
        }
        const p1 = color1.filter(n => n.type.name === 'NumberLiteral' && computedValueTree.text(n.getChild('Unit')) === '%');
        const p2 = color2.filter(n => n.type.name === 'NumberLiteral' && computedValueTree.text(n.getChild('Unit')) === '%');
        if (p1.length > 1 || p2.length > 1) {
            return null;
        }
        if (p1[0] && p2[0] && (literalToNumber(p1[0], computedValueTree) ?? 0) === 0 &&
            (literalToNumber(p2[0], computedValueTree) ?? 0) === 0) {
            return null;
        }
        const args = ASTUtils.callArgs(node);
        if (args.length !== 3) {
            return null;
        }
        return new ColorMixMatch(matching.ast.text(node), node, args[0], args[1], args[2]);
    }
}
class URLMatch {
    url;
    text;
    node;
    constructor(url, text, node) {
        this.url = url;
        this.text = text;
        this.node = node;
    }
}
class URLMatcher extends matcherBase(URLMatch) {
    matches(node, matching) {
        if (node.name !== 'CallLiteral') {
            return null;
        }
        const callee = node.getChild('CallTag');
        if (!callee || matching.ast.text(callee) !== 'url') {
            return null;
        }
        const [, lparenNode, urlNode, rparenNode] = ASTUtils.siblings(callee);
        if (matching.ast.text(lparenNode) !== '(' ||
            (urlNode.name !== 'ParenthesizedContent' && urlNode.name !== 'StringLiteral') ||
            matching.ast.text(rparenNode) !== ')') {
            return null;
        }
        const text = matching.ast.text(urlNode);
        const url = (urlNode.name === 'StringLiteral' ? text.substr(1, text.length - 2) : text.trim());
        return new URLMatch(url, matching.ast.text(node), node);
    }
}
class LinearGradientMatch {
    text;
    node;
    constructor(text, node) {
        this.text = text;
        this.node = node;
    }
}
class LinearGradientMatcher extends matcherBase(LinearGradientMatch) {
    matches(node, matching) {
        const text = matching.ast.text(node);
        if (node.name === 'CallExpression' && matching.ast.text(node.getChild('Callee')) === 'linear-gradient') {
            return new LinearGradientMatch(text, node);
        }
        return null;
    }
    accepts(propertyName) {
        return ['background', 'background-image', '-webkit-mask-image'].includes(propertyName);
    }
}
class ColorMatch {
    text;
    node;
    currentColorCallback;
    relativeColor;
    computedText;
    constructor(text, node, currentColorCallback, relativeColor) {
        this.text = text;
        this.node = node;
        this.currentColorCallback = currentColorCallback;
        this.relativeColor = relativeColor;
        this.computedText = currentColorCallback;
    }
}
class ColorMatcher extends matcherBase(ColorMatch) {
    currentColorCallback;
    constructor(currentColorCallback) {
        super();
        this.currentColorCallback = currentColorCallback;
    }
    accepts(propertyName) {
        return cssMetadata().isColorAwareProperty(propertyName);
    }
    matches(node, matching) {
        const text = matching.ast.text(node);
        if (node.name === 'ColorLiteral') {
            return new ColorMatch(text, node);
        }
        if (node.name === 'ValueName') {
            if (Nicknames.has(text)) {
                return new ColorMatch(text, node);
            }
            if (text.toLowerCase() === 'currentcolor' && this.currentColorCallback) {
                const callback = this.currentColorCallback;
                return new ColorMatch(text, node, () => callback() ?? text);
            }
        }
        if (node.name === 'CallExpression') {
            const callee = node.getChild('Callee');
            const colorFunc = matching.ast.text(callee).toLowerCase();
            if (callee && colorFunc.match(/^(rgba?|hsla?|hwba?|lab|lch|oklab|oklch|color)$/)) {
                const args = ASTUtils.children(node.getChild('ArgList'));
                const colorText = args.length >= 2 ? matching.getComputedTextRange(args[0], args[args.length - 1]) : '';
                const isRelativeColorSyntax = Boolean(colorText.match(/^[^)]*\(\W*from\W+/) && !matching.hasUnresolvedSubstitutions(node) &&
                    CSS.supports('color', colorFunc + colorText));
                if (!isRelativeColorSyntax) {
                    return new ColorMatch(text, node);
                }
                const tokenized = matchDeclaration('--color', '--colorFunc' + colorText, [new ColorMatcher()]);
                if (!tokenized) {
                    return null;
                }
                const [colorArgs] = ASTUtils.callArgs(ASTUtils.declValue(tokenized.ast.tree));
                if (colorArgs.length !== (colorFunc === 'color' ? 6 : 5)) {
                    return null;
                }
                const colorSpace = getFormat(colorFunc !== 'color' ? colorFunc : matching.ast.text(colorArgs[2]));
                if (!colorSpace) {
                    return null;
                }
                const baseColor = tokenized.getMatch(colorArgs[1]);
                if (tokenized.ast.text(colorArgs[0]) !== 'from' || !(baseColor instanceof ColorMatch)) {
                    return null;
                }
                return new ColorMatch(text, node, undefined, { colorSpace, baseColor });
            }
        }
        return null;
    }
}
function isRelativeColorChannelName(channel) {
    const maybeChannel = channel;
    switch (maybeChannel) {
        case "a" :
        case "alpha" :
        case "b" :
        case "c" :
        case "g" :
        case "h" :
        case "l" :
        case "r" :
        case "s" :
        case "w" :
        case "x" :
        case "y" :
        case "z" :
            return true;
    }
    return false;
}
class RelativeColorChannelMatch {
    text;
    node;
    constructor(text, node) {
        this.text = text;
        this.node = node;
    }
    getColorChannelValue(relativeColor) {
        const color = parse$2(relativeColor.baseColor.text)?.as(relativeColor.colorSpace);
        if (color instanceof ColorFunction) {
            switch (this.text) {
                case "r" :
                    return color.isXYZ() ? null : color.p0;
                case "g" :
                    return color.isXYZ() ? null : color.p1;
                case "b" :
                    return color.isXYZ() ? null : color.p2;
                case "x" :
                    return color.isXYZ() ? color.p0 : null;
                case "y" :
                    return color.isXYZ() ? color.p1 : null;
                case "z" :
                    return color.isXYZ() ? color.p2 : null;
                case "alpha" :
                    return color.alpha;
            }
        }
        else if (color instanceof Legacy) {
            switch (this.text) {
                case "r" :
                    return color.rgba()[0];
                case "g" :
                    return color.rgba()[1];
                case "b" :
                    return color.rgba()[2];
                case "alpha" :
                    return color.rgba()[3];
            }
        }
        else if (color && this.text in color) {
            return color[this.text];
        }
        return null;
    }
    computedText() {
        return this.text;
    }
}
class RelativeColorChannelMatcher extends matcherBase(RelativeColorChannelMatch) {
    accepts(propertyName) {
        return cssMetadata().isColorAwareProperty(propertyName);
    }
    matches(node, matching) {
        const text = matching.ast.text(node);
        if (node.name === 'ValueName' && isRelativeColorChannelName(text)) {
            return new RelativeColorChannelMatch(text, node);
        }
        return null;
    }
}
class LightDarkColorMatch {
    text;
    node;
    light;
    dark;
    style;
    constructor(text, node, light, dark, style) {
        this.text = text;
        this.node = node;
        this.light = light;
        this.dark = dark;
        this.style = style;
    }
}
class LightDarkColorMatcher extends matcherBase(LightDarkColorMatch) {
    style;
    constructor(style) {
        super();
        this.style = style;
    }
    accepts(propertyName) {
        return cssMetadata().isColorAwareProperty(propertyName);
    }
    matches(node, matching) {
        if (node.name !== 'CallExpression' || matching.ast.text(node.getChild('Callee')) !== 'light-dark') {
            return null;
        }
        const args = ASTUtils.callArgs(node);
        if (args.length !== 2 || args[0].length === 0 || args[1].length === 0) {
            return null;
        }
        return new LightDarkColorMatch(matching.ast.text(node), node, args[0], args[1], this.style);
    }
}
class AutoBaseMatch {
    text;
    node;
    auto;
    base;
    constructor(text, node, auto, base) {
        this.text = text;
        this.node = node;
        this.auto = auto;
        this.base = base;
    }
}
class AutoBaseMatcher extends matcherBase(AutoBaseMatch) {
    matches(node, matching) {
        if (node.name !== 'CallExpression' || matching.ast.text(node.getChild('Callee')) !== '-internal-auto-base') {
            return null;
        }
        const args = ASTUtils.callArgs(node);
        if (args.length !== 2 || args[0].length === 0 || args[1].length === 0) {
            return null;
        }
        return new AutoBaseMatch(matching.ast.text(node), node, args[0], args[1]);
    }
}
class LinkableNameMatch {
    text;
    node;
    propertyName;
    constructor(text, node, propertyName) {
        this.text = text;
        this.node = node;
        this.propertyName = propertyName;
    }
}
class LinkableNameMatcher extends matcherBase(LinkableNameMatch) {
    static isLinkableNameProperty(propertyName) {
        const names = [
            "animation" ,
            "animation-name" ,
            "font-palette" ,
            "position-try-fallbacks" ,
            "position-try" ,
        ];
        return names.includes(propertyName);
    }
    static identifierAnimationLonghandMap = new Map(Object.entries({
        normal: "direction" ,
        alternate: "direction" ,
        reverse: "direction" ,
        'alternate-reverse': "direction" ,
        none: "fill-mode" ,
        forwards: "fill-mode" ,
        backwards: "fill-mode" ,
        both: "fill-mode" ,
        running: "play-state" ,
        paused: "play-state" ,
        infinite: "iteration-count" ,
        linear: "easing-function" ,
        ease: "easing-function" ,
        'ease-in': "easing-function" ,
        'ease-out': "easing-function" ,
        'ease-in-out': "easing-function" ,
        steps: "easing-function" ,
        'step-start': "easing-function" ,
        'step-end': "easing-function" ,
    }));
    matchAnimationNameInShorthand(node, matching) {
        const text = matching.ast.text(node);
        if (!LinkableNameMatcher.identifierAnimationLonghandMap.has(text)) {
            return new LinkableNameMatch(text, node, "animation" );
        }
        const declarations = ASTUtils.split(ASTUtils.siblings(ASTUtils.declValue(matching.ast.tree)));
        const currentDeclarationNodes = declarations.find(declaration => declaration[0].from <= node.from && declaration[declaration.length - 1].to >= node.to);
        if (!currentDeclarationNodes) {
            return null;
        }
        const computedText = matching.getComputedTextRange(currentDeclarationNodes[0], node);
        const tokenized = tokenizeDeclaration('--p', computedText);
        if (!tokenized) {
            return null;
        }
        const identifierCategory = LinkableNameMatcher.identifierAnimationLonghandMap.get(text);
        for (let itNode = ASTUtils.declValue(tokenized.tree); itNode?.nextSibling; itNode = itNode.nextSibling) {
            if (itNode.name === 'ValueName') {
                const categoryValue = LinkableNameMatcher.identifierAnimationLonghandMap.get(tokenized.text(itNode));
                if (categoryValue && categoryValue === identifierCategory) {
                    return new LinkableNameMatch(text, node, "animation" );
                }
            }
        }
        return null;
    }
    matches(node, matching) {
        const { propertyName } = matching.ast;
        const text = matching.ast.text(node);
        const parentNode = node.parent;
        if (!parentNode) {
            return null;
        }
        if (!(propertyName && LinkableNameMatcher.isLinkableNameProperty(propertyName))) {
            return null;
        }
        const isParentADeclaration = parentNode.name === 'Declaration';
        const isInsideVarCall = parentNode.name === 'ArgList' && parentNode.prevSibling?.name === 'Callee' &&
            matching.ast.text(parentNode.prevSibling) === 'var';
        const isAParentDeclarationOrVarCall = isParentADeclaration || isInsideVarCall;
        const shouldMatchOnlyVariableName = propertyName === "position-try"  ||
            propertyName === "position-try-fallbacks" ;
        if (!propertyName || (node.name !== 'ValueName' && node.name !== 'VariableName') ||
            !isAParentDeclarationOrVarCall || (node.name === 'ValueName' && shouldMatchOnlyVariableName)) {
            return null;
        }
        if (propertyName === 'animation') {
            return this.matchAnimationNameInShorthand(node, matching);
        }
        return new LinkableNameMatch(text, node, propertyName);
    }
}
class BezierMatch {
    text;
    node;
    constructor(text, node) {
        this.text = text;
        this.node = node;
    }
}
class BezierMatcher extends matcherBase(BezierMatch) {
    accepts(propertyName) {
        return cssMetadata().isBezierAwareProperty(propertyName);
    }
    matches(node, matching) {
        const text = matching.ast.text(node);
        const isCubicBezierKeyword = node.name === 'ValueName' && CubicBezierKeywordValues.has(text);
        const isCubicBezierOrLinearFunction = node.name === 'CallExpression' &&
            ['cubic-bezier', 'linear'].includes(matching.ast.text(node.getChild('Callee')));
        if (!isCubicBezierKeyword && !isCubicBezierOrLinearFunction) {
            return null;
        }
        return new BezierMatch(text, node);
    }
}
class StringMatch {
    text;
    node;
    constructor(text, node) {
        this.text = text;
        this.node = node;
    }
}
class StringMatcher extends matcherBase(StringMatch) {
    matches(node, matching) {
        return node.name === 'StringLiteral' ? new StringMatch(matching.ast.text(node), node) : null;
    }
}
class ShadowMatch {
    text;
    node;
    shadowType;
    constructor(text, node, shadowType) {
        this.text = text;
        this.node = node;
        this.shadowType = shadowType;
    }
}
class ShadowMatcher extends matcherBase(ShadowMatch) {
    accepts(propertyName) {
        return cssMetadata().isShadowProperty(propertyName);
    }
    matches(node, matching) {
        if (node.name !== 'Declaration') {
            return null;
        }
        const valueNodes = ASTUtils.siblings(ASTUtils.declValue(node));
        if (valueNodes.length === 0) {
            return null;
        }
        const valueText = matching.ast.textRange(valueNodes[0], valueNodes[valueNodes.length - 1]);
        return new ShadowMatch(valueText, node, matching.ast.propertyName === 'text-shadow' ? "textShadow"  : "boxShadow" );
    }
}
class FontMatch {
    text;
    node;
    constructor(text, node) {
        this.text = text;
        this.node = node;
    }
}
class FontMatcher extends matcherBase(FontMatch) {
    accepts(propertyName) {
        return cssMetadata().isFontAwareProperty(propertyName);
    }
    matches(node, matching) {
        if (node.name !== 'Declaration') {
            return null;
        }
        const valueNodes = ASTUtils.siblings(ASTUtils.declValue(node));
        if (valueNodes.length === 0) {
            return null;
        }
        const validNodes = matching.ast.propertyName === 'font-family' ? ['ValueName', 'StringLiteral', 'Comment', ','] :
            ['Comment', 'ValueName', 'NumberLiteral'];
        if (valueNodes.some(node => !validNodes.includes(node.name))) {
            return null;
        }
        const valueText = matching.ast.textRange(valueNodes[0], valueNodes[valueNodes.length - 1]);
        return new FontMatch(valueText, node);
    }
}
class LengthMatch {
    text;
    node;
    unit;
    constructor(text, node, unit) {
        this.text = text;
        this.node = node;
        this.unit = unit;
    }
}
class LengthMatcher extends matcherBase(LengthMatch) {
    static LENGTH_UNITS = new Set([
        'em', 'ex', 'ch', 'cap', 'ic', 'lh', 'rem', 'rex', 'rch', 'rlh', 'ric', 'rcap', 'pt', 'pc',
        'in', 'cm', 'mm', 'Q', 'vw', 'vh', 'vi', 'vb', 'vmin', 'vmax', 'dvw', 'dvh', 'dvi', 'dvb',
        'dvmin', 'dvmax', 'svw', 'svh', 'svi', 'svb', 'svmin', 'svmax', 'lvw', 'lvh', 'lvi', 'lvb', 'lvmin', 'lvmax',
        'cqw', 'cqh', 'cqi', 'cqb', 'cqmin', 'cqmax', 'cqem', 'cqlh', 'cqex', 'cqch', '%'
    ]);
    matches(node, matching) {
        if (node.name !== 'NumberLiteral') {
            return null;
        }
        const unit = matching.ast.text(node.getChild('Unit'));
        if (!LengthMatcher.LENGTH_UNITS.has(unit)) {
            return null;
        }
        const text = matching.ast.text(node);
        return new LengthMatch(text, node, unit);
    }
}
class BaseFunctionMatch {
    text;
    node;
    func;
    args;
    constructor(text, node, func, args) {
        this.text = text;
        this.node = node;
        this.func = func;
        this.args = args;
    }
}
class MathFunctionMatch extends BaseFunctionMatch {
    isArithmeticFunctionCall() {
        const func = this.func;
        switch (func) {
            case "calc" :
            case "sibling-count" :
            case "sibling-index" :
            case "round" :
            case "mod" :
            case "rem" :
                return true;
        }
        return false;
    }
}
class MathFunctionMatcher extends matcherBase(MathFunctionMatch) {
    static getFunctionType(callee) {
        const maybeFunc = callee;
        switch (maybeFunc) {
            case null:
            case "min" :
            case "max" :
            case "clamp" :
            case "calc" :
            case "sibling-count" :
            case "sibling-index" :
            case "round" :
            case "mod" :
            case "rem" :
                return maybeFunc;
        }
        return null;
    }
    matches(node, matching) {
        if (node.name !== 'CallExpression') {
            return null;
        }
        const callee = MathFunctionMatcher.getFunctionType(matching.ast.text(node.getChild('Callee')));
        if (!callee) {
            return null;
        }
        const args = ASTUtils.callArgs(node);
        if (args.some(arg => arg.length === 0 || matching.hasUnresolvedSubstitutionsRange(arg[0], arg[arg.length - 1]))) {
            return null;
        }
        const text = matching.ast.text(node);
        const match = new MathFunctionMatch(text, node, callee, args);
        if (!match.isArithmeticFunctionCall() && args.length === 0) {
            return null;
        }
        return match;
    }
}
class CustomFunctionMatch extends BaseFunctionMatch {
}
class CustomFunctionMatcher extends matcherBase(CustomFunctionMatch) {
    matches(node, matching) {
        if (node.name !== 'CallExpression') {
            return null;
        }
        const callee = matching.ast.text(node.getChild('VariableName'));
        if (!callee?.startsWith('--')) {
            return null;
        }
        const args = ASTUtils.callArgs(node);
        if (args.some(arg => arg.length === 0 || matching.hasUnresolvedSubstitutionsRange(arg[0], arg[arg.length - 1]))) {
            return null;
        }
        const text = matching.ast.text(node);
        return new CustomFunctionMatch(text, node, callee, args);
    }
}
class FlexGridGridLanesMatch {
    text;
    node;
    layoutType;
    constructor(text, node, layoutType) {
        this.text = text;
        this.node = node;
        this.layoutType = layoutType;
    }
}
class FlexGridGridLanesMatcher extends matcherBase(FlexGridGridLanesMatch) {
    static FLEX = ['flex', 'inline-flex', 'block flex', 'inline flex'];
    static GRID = ['grid', 'inline-grid', 'block grid', 'inline grid'];
    static GRID_LANES = ['grid-lanes', 'inline-grid-lanes', 'block grid-lanes', 'inline grid-lanes'];
    accepts(propertyName) {
        return propertyName === 'display';
    }
    matches(node, matching) {
        if (node.name !== 'Declaration') {
            return null;
        }
        const valueNodes = ASTUtils.siblings(ASTUtils.declValue(node));
        if (valueNodes.length < 1) {
            return null;
        }
        const values = valueNodes.filter(node => node.name !== 'Important')
            .map(node => matching.getComputedText(node).trim())
            .filter(value => value);
        const text = values.join(' ');
        if (FlexGridGridLanesMatcher.FLEX.includes(text)) {
            return new FlexGridGridLanesMatch(matching.ast.text(node), node, "flex" );
        }
        if (FlexGridGridLanesMatcher.GRID.includes(text)) {
            return new FlexGridGridLanesMatch(matching.ast.text(node), node, "grid" );
        }
        if (FlexGridGridLanesMatcher.GRID_LANES.includes(text)) {
            return new FlexGridGridLanesMatch(matching.ast.text(node), node, "grid-lanes" );
        }
        return null;
    }
}
class GridTemplateMatch {
    text;
    node;
    lines;
    constructor(text, node, lines) {
        this.text = text;
        this.node = node;
        this.lines = lines;
    }
}
class GridTemplateMatcher extends matcherBase(GridTemplateMatch) {
    accepts(propertyName) {
        return cssMetadata().isGridAreaDefiningProperty(propertyName);
    }
    matches(node, matching) {
        if (node.name !== 'Declaration' || matching.hasUnresolvedSubstitutions(node)) {
            return null;
        }
        const lines = [];
        let curLine = [];
        let hasLeadingLineNames = false;
        let needClosingLineNames = false;
        function parseNodes(nodes, varParsingMode = false) {
            for (const curNode of nodes) {
                if (matching.getMatch(curNode) instanceof BaseVariableMatch) {
                    const computedValueTree = tokenizeDeclaration('--property', matching.getComputedText(curNode));
                    if (!computedValueTree) {
                        continue;
                    }
                    const varNodes = ASTUtils.siblings(ASTUtils.declValue(computedValueTree.tree));
                    if (varNodes.length === 0) {
                        continue;
                    }
                    if ((varNodes[0].name === 'StringLiteral' && !hasLeadingLineNames) ||
                        (varNodes[0].name === 'BracketedValue' && !needClosingLineNames)) {
                        lines.push(curLine);
                        curLine = [curNode];
                    }
                    else {
                        curLine.push(curNode);
                    }
                    parseNodes(varNodes, true);
                }
                else if (curNode.name === 'BinaryExpression') {
                    parseNodes(ASTUtils.siblings(curNode.firstChild));
                }
                else if (curNode.name === 'StringLiteral') {
                    if (!varParsingMode) {
                        if (hasLeadingLineNames) {
                            curLine.push(curNode);
                        }
                        else {
                            lines.push(curLine);
                            curLine = [curNode];
                        }
                    }
                    needClosingLineNames = true;
                    hasLeadingLineNames = false;
                }
                else if (curNode.name === 'BracketedValue') {
                    if (!varParsingMode) {
                        if (needClosingLineNames) {
                            curLine.push(curNode);
                        }
                        else {
                            lines.push(curLine);
                            curLine = [curNode];
                        }
                    }
                    hasLeadingLineNames = !needClosingLineNames;
                    needClosingLineNames = !needClosingLineNames;
                }
                else if (!varParsingMode) {
                    curLine.push(curNode);
                }
            }
        }
        const valueNodes = ASTUtils.siblings(ASTUtils.declValue(node));
        if (valueNodes.length === 0) {
            return null;
        }
        parseNodes(valueNodes);
        lines.push(curLine);
        const valueText = matching.ast.textRange(valueNodes[0], valueNodes[valueNodes.length - 1]);
        return new GridTemplateMatch(valueText, node, lines.filter(line => line.length > 0));
    }
}
class AnchorFunctionMatch {
    text;
    node;
    functionName;
    constructor(text, node, functionName) {
        this.text = text;
        this.node = node;
        this.functionName = functionName;
    }
}
class AnchorFunctionMatcher extends matcherBase(AnchorFunctionMatch) {
    anchorFunction(node, matching) {
        if (node.name !== 'CallExpression') {
            return null;
        }
        const calleeText = matching.ast.text(node.getChild('Callee'));
        if (calleeText === 'anchor' || calleeText === 'anchor-size') {
            return calleeText;
        }
        return null;
    }
    matches(node, matching) {
        if (node.name === 'VariableName') {
            let parent = node.parent;
            if (parent?.name !== 'ArgList') {
                return null;
            }
            parent = parent.parent;
            if (!parent || !this.anchorFunction(parent, matching)) {
                return null;
            }
            return new AnchorFunctionMatch(matching.ast.text(node), node, null);
        }
        const calleeText = this.anchorFunction(node, matching);
        if (!calleeText) {
            return null;
        }
        const args = ASTUtils.children(node.getChild('ArgList'));
        if (calleeText === 'anchor' && args.length <= 2) {
            return null;
        }
        if (args.find(arg => arg.name === 'VariableName')) {
            return null;
        }
        return new AnchorFunctionMatch(matching.ast.text(node), node, calleeText);
    }
}
class PositionAnchorMatch {
    text;
    matching;
    node;
    constructor(text, matching, node) {
        this.text = text;
        this.matching = matching;
        this.node = node;
    }
}
class PositionAnchorMatcher extends matcherBase(PositionAnchorMatch) {
    accepts(propertyName) {
        return propertyName === 'position-anchor';
    }
    matches(node, matching) {
        if (node.name !== 'VariableName') {
            return null;
        }
        const dashedIdentifier = matching.ast.text(node);
        return new PositionAnchorMatch(dashedIdentifier, matching, node);
    }
}
class CSSWideKeywordMatch {
    text;
    node;
    property;
    matchedStyles;
    constructor(text, node, property, matchedStyles) {
        this.text = text;
        this.node = node;
        this.property = property;
        this.matchedStyles = matchedStyles;
    }
    resolveProperty() {
        return this.matchedStyles.resolveGlobalKeyword(this.property, this.text);
    }
    computedText() {
        return this.resolveProperty()?.value ?? null;
    }
}
class CSSWideKeywordMatcher extends matcherBase(CSSWideKeywordMatch) {
    property;
    matchedStyles;
    constructor(property, matchedStyles) {
        super();
        this.property = property;
        this.matchedStyles = matchedStyles;
    }
    matches(node, matching) {
        const parentNode = node.parent;
        if (node.name !== 'ValueName' || parentNode?.name !== 'Declaration') {
            return null;
        }
        if (Array.from(ASTUtils.stripComments(ASTUtils.siblings(ASTUtils.declValue(parentNode))))
            .some(child => !ASTUtils.equals(child, node))) {
            return null;
        }
        const text = matching.ast.text(node);
        if (!CSSMetadata.isCSSWideKeyword(text)) {
            return null;
        }
        return new CSSWideKeywordMatch(text, node, this.property, this.matchedStyles);
    }
}
class PositionTryMatch {
    text;
    node;
    preamble;
    fallbacks;
    constructor(text, node, preamble, fallbacks) {
        this.text = text;
        this.node = node;
        this.preamble = preamble;
        this.fallbacks = fallbacks;
    }
}
class PositionTryMatcher extends matcherBase(PositionTryMatch) {
    accepts(propertyName) {
        return propertyName === "position-try"  ||
            propertyName === "position-try-fallbacks" ;
    }
    matches(node, matching) {
        if (node.name !== 'Declaration') {
            return null;
        }
        let preamble = [];
        const valueNodes = ASTUtils.siblings(ASTUtils.declValue(node));
        const fallbacks = ASTUtils.split(valueNodes);
        if (matching.ast.propertyName === "position-try" ) {
            for (const [i, n] of fallbacks[0].entries()) {
                const computedText = matching.getComputedText(n);
                if (CSSMetadata.isCSSWideKeyword(computedText)) {
                    return null;
                }
                if (CSSMetadata.isPositionTryOrderKeyword(computedText)) {
                    preamble = fallbacks[0].splice(0, i + 1);
                    break;
                }
            }
        }
        const valueText = matching.ast.textRange(valueNodes[0], valueNodes[valueNodes.length - 1]);
        return new PositionTryMatch(valueText, node, preamble, fallbacks);
    }
}
class EnvFunctionMatch {
    text;
    node;
    varName;
    value;
    varNameIsValid;
    constructor(text, node, varName, value, varNameIsValid) {
        this.text = text;
        this.node = node;
        this.varName = varName;
        this.value = value;
        this.varNameIsValid = varNameIsValid;
    }
    computedText() {
        return this.value;
    }
}
class EnvFunctionMatcher extends matcherBase(EnvFunctionMatch) {
    matchedStyles;
    constructor(matchedStyles) {
        super();
        this.matchedStyles = matchedStyles;
    }
    matches(node, matching) {
        if (node.name !== 'CallExpression' || matching.ast.text(node.getChild('Callee')) !== 'env') {
            return null;
        }
        const [valueNodes, ...fallbackNodes] = ASTUtils.callArgs(node);
        if (!valueNodes?.length) {
            return null;
        }
        const fallbackValue = fallbackNodes.length > 0 ? matching.getComputedTextRange(...ASTUtils.range(fallbackNodes.flat())) : undefined;
        const varName = matching.getComputedTextRange(...ASTUtils.range(valueNodes)).trim();
        const value = this.matchedStyles.environmentVariable(varName);
        return new EnvFunctionMatch(matching.ast.text(node), node, varName, value ?? fallbackValue ?? null, Boolean(value));
    }
}

// Copyright 2020 The Chromium Authors
function stripComments(value) {
    return value.replaceAll(/(\/\*(?:.|\s)*?\*\/)/g, '');
}
function nodeText(node, text) {
    return nodeTextRange(node, node, text);
}
function nodeTextRange(from, to, text) {
    return text.substring(from.from, to.to);
}
class SyntaxTree {
    propertyValue;
    rule;
    tree;
    trailingNodes;
    propertyName;
    constructor(propertyValue, rule, tree, propertyName, trailingNodes = []) {
        this.propertyName = propertyName;
        this.propertyValue = propertyValue;
        this.rule = rule;
        this.tree = tree;
        this.trailingNodes = trailingNodes;
    }
    text(node) {
        if (node === null) {
            return '';
        }
        return nodeText(node ?? this.tree, this.rule);
    }
    textRange(from, to) {
        if (!from || !to) {
            return '';
        }
        return nodeTextRange(from, to, this.rule);
    }
    subtree(node) {
        return new SyntaxTree(this.propertyValue, this.rule, node);
    }
}
class TreeWalker {
    ast;
    constructor(ast) {
        this.ast = ast;
    }
    static walkExcludingSuccessors(propertyValue, ...args) {
        const instance = new this(propertyValue, ...args);
        if (propertyValue.tree.name === 'Declaration') {
            instance.iterateDeclaration(propertyValue.tree);
        }
        else {
            instance.iterateExcludingSuccessors(propertyValue.tree);
        }
        return instance;
    }
    static walk(propertyValue, ...args) {
        const instance = new this(propertyValue, ...args);
        if (propertyValue.tree.name === 'Declaration') {
            instance.iterateDeclaration(propertyValue.tree);
        }
        else {
            instance.iterate(propertyValue.tree);
        }
        return instance;
    }
    iterateDeclaration(tree) {
        if (tree.name !== 'Declaration') {
            return;
        }
        if (this.enter(tree)) {
            for (const sibling of ASTUtils.siblings(ASTUtils.declValue(tree))) {
                sibling.cursor().iterate(this.enter.bind(this), this.leave.bind(this));
            }
        }
        this.leave(tree);
    }
    iterate(tree) {
        for (const sibling of ASTUtils.siblings(tree)) {
            sibling.cursor().iterate(this.enter.bind(this), this.leave.bind(this));
        }
    }
    iterateExcludingSuccessors(tree) {
        tree.cursor().iterate(this.enter.bind(this), this.leave.bind(this));
    }
    enter(_node) {
        return true;
    }
    leave(_node) {
    }
}
function matcherBase(matchT) {
    class MatcherBase {
        matchType = matchT;
        accepts(_propertyName) {
            return true;
        }
        matches(_node, _matching) {
            return null;
        }
    }
    return MatcherBase;
}
class BottomUpTreeMatching extends TreeWalker {
    #matchers = [];
    #matchedNodes = new Map();
    computedText;
    #key(node) {
        return `${node.from}:${node.to}`;
    }
    constructor(ast, matchers) {
        super(ast);
        this.computedText = new ComputedText(ast.rule.substring(ast.tree.from));
        this.#matchers.push(...matchers.filter(m => !ast.propertyName || m.accepts(ast.propertyName)));
        this.#matchers.push(new TextMatcher());
    }
    leave({ node }) {
        for (const matcher of this.#matchers) {
            const match = matcher.matches(node, this);
            if (match) {
                this.computedText.push(match, node.from - this.ast.tree.from);
                this.#matchedNodes.set(this.#key(node), match);
                break;
            }
        }
    }
    matchText(node) {
        const matchers = this.#matchers.splice(0);
        this.#matchers.push(new TextMatcher());
        this.iterateExcludingSuccessors(node);
        this.#matchers.push(...matchers);
    }
    hasMatches(...matchTypes) {
        return Boolean(this.#matchedNodes.values().find(match => matchTypes.some(matchType => match instanceof matchType)));
    }
    getMatch(node) {
        return this.#matchedNodes.get(this.#key(node));
    }
    hasUnresolvedSubstitutions(node) {
        return this.hasUnresolvedSubstitutionsRange(node, node);
    }
    hasUnresolvedSubstitutionsRange(from, to) {
        return this.computedText.hasUnresolvedSubstitutions(from.from - this.ast.tree.from, to.to - this.ast.tree.from);
    }
    getComputedText(node, substitutionHook) {
        return this.getComputedTextRange(node, node, substitutionHook);
    }
    getLonghandValuesCount() {
        const [from, to] = ASTUtils.range(ASTUtils.siblings(ASTUtils.declValue(this.ast.tree)));
        if (!from || !to) {
            return 0;
        }
        return this.computedText.countTopLevelValues(from.from - this.ast.tree.from, to.to - this.ast.tree.from);
    }
    getComputedLonghandName(to) {
        const from = ASTUtils.declValue(this.ast.tree) ?? this.ast.tree;
        return this.computedText.countTopLevelValues(from.from - this.ast.tree.from, to.from - this.ast.tree.from);
    }
    getComputedPropertyValueText(substitutionHook) {
        const [from, to] = ASTUtils.range(ASTUtils.siblings(ASTUtils.declValue(this.ast.tree)));
        return this.getComputedTextRange(from ?? this.ast.tree, to ?? this.ast.tree, substitutionHook);
    }
    getComputedTextRange(from, to, substitutionHook) {
        if (!from || !to) {
            return '';
        }
        return this.computedText.get(from.from - this.ast.tree.from, to.to - this.ast.tree.from, substitutionHook);
    }
}
class ComputedTextChunk {
    match;
    offset;
    #cachedComputedText = null;
    #topLevelValueCount = null;
    constructor(match, offset) {
        this.match = match;
        this.offset = offset;
    }
    get end() {
        return this.offset + this.length;
    }
    get length() {
        return this.match.text.length;
    }
    get computedText() {
        if (this.#cachedComputedText === null) {
            this.#cachedComputedText = this.match.computedText();
        }
        return this.#cachedComputedText;
    }
    get topLevelValueCount() {
        if (this.match.node.parent?.name !== 'Declaration') {
            return 0;
        }
        const computedText = this.computedText;
        if (computedText === '') {
            return 0;
        }
        if (this.#topLevelValueCount === null) {
            this.#topLevelValueCount =
                ASTUtils
                    .siblings(ASTUtils.declValue(tokenizeDeclaration('--p', computedText ?? this.match.text)?.tree ?? null))
                    .length;
        }
        return this.#topLevelValueCount;
    }
}
class ComputedText {
    #chunks = [];
    text;
    #topLevelValueCounts = new Map();
    #sorted = true;
    constructor(text) {
        this.text = text;
    }
    clear() {
        this.#chunks.splice(0);
        this.#topLevelValueCounts.clear();
    }
    get chunkCount() {
        return this.#chunks.length;
    }
    #sortIfNecessary() {
        if (this.#sorted) {
            return;
        }
        this.#chunks.sort((a, b) => {
            if (a.offset < b.offset) {
                return -1;
            }
            if (b.offset < a.offset) {
                return 1;
            }
            if (a.end > b.end) {
                return -1;
            }
            if (a.end < b.end) {
                return 1;
            }
            return 0;
        });
        this.#sorted = true;
    }
    push(match, offset) {
        function hasComputedText(match) {
            return Boolean(match.computedText);
        }
        if (!hasComputedText(match) || offset < 0 || offset >= this.text.length) {
            return;
        }
        const chunk = new ComputedTextChunk(match, offset);
        if (chunk.end > this.text.length) {
            return;
        }
        this.#sorted = false;
        this.#chunks.push(chunk);
    }
    *#range(begin, end) {
        this.#sortIfNecessary();
        let i = this.#chunks.findIndex(c => c.offset >= begin);
        while (i >= 0 && i < this.#chunks.length && this.#chunks[i].end > begin && begin < end) {
            if (this.#chunks[i].end > end) {
                i++;
                continue;
            }
            yield this.#chunks[i];
            begin = this.#chunks[i].end;
            while (begin < end && i < this.#chunks.length && this.#chunks[i].offset < begin) {
                i++;
            }
        }
    }
    hasUnresolvedSubstitutions(begin, end) {
        for (const chunk of this.#range(begin, end)) {
            if (chunk.computedText === null) {
                return true;
            }
        }
        return false;
    }
    *#getPieces(begin, end) {
        for (const chunk of this.#range(begin, end)) {
            const piece = this.text.substring(begin, Math.min(chunk.offset, end));
            yield piece;
            if (end >= chunk.end) {
                yield chunk;
            }
            begin = chunk.end;
        }
        if (begin < end) {
            const piece = this.text.substring(begin, end);
            yield piece;
        }
    }
    get(begin, end, substitutionHook) {
        const pieces = [];
        const getText = (piece) => {
            if (typeof piece === 'string') {
                return piece;
            }
            const substitution = substitutionHook?.(piece.match) ?? null;
            if (substitution !== null) {
                return getText(substitution);
            }
            return piece.computedText ?? piece.match.text;
        };
        for (const piece of this.#getPieces(begin, end)) {
            const text = getText(piece);
            if (text.length === 0) {
                continue;
            }
            if (pieces.length > 0 && requiresSpace(pieces[pieces.length - 1], text)) {
                pieces.push(' ');
            }
            pieces.push(text);
        }
        return pieces.join('');
    }
    #countTopLevelValuesInStringPiece(piece) {
        let count = this.#topLevelValueCounts.get(piece);
        if (count === undefined) {
            count = ASTUtils.siblings(ASTUtils.declValue(tokenizeDeclaration('--p', piece)?.tree ?? null)).length;
            this.#topLevelValueCounts.set(piece, count);
        }
        return count;
    }
    countTopLevelValues(begin, end) {
        const pieces = Array.from(this.#getPieces(begin, end));
        const counts = pieces.map(chunk => (chunk instanceof ComputedTextChunk ? chunk.topLevelValueCount :
            this.#countTopLevelValuesInStringPiece(chunk)));
        const count = counts.reduce((sum, v) => sum + v, 0);
        return count;
    }
}
function requiresSpace(a, b) {
    const tail = Array.isArray(a) ? a.findLast(node => node.textContent)?.textContent : a;
    const head = Array.isArray(b) ? b.find(node => node.textContent)?.textContent : b;
    const trailingChar = tail ? tail[tail.length - 1] : '';
    const leadingChar = head ? head[0] : '';
    const noSpaceAfter = ['', '(', '{', '}', ';', '['];
    const noSpaceBefore = ['', '(', ')', ',', ':', '*', '{', ';', ']'];
    return !/\s/.test(trailingChar) && !/\s/.test(leadingChar) && !noSpaceAfter.includes(trailingChar) &&
        !noSpaceBefore.includes(leadingChar);
}
var ASTUtils;
(function (ASTUtils) {
    function siblings(node) {
        const result = [];
        while (node) {
            result.push(node);
            node = node.nextSibling;
        }
        return result;
    }
    ASTUtils.siblings = siblings;
    function children(node) {
        return siblings(node?.firstChild ?? null);
    }
    ASTUtils.children = children;
    function range(node) {
        return [node[0], node[node.length - 1]];
    }
    ASTUtils.range = range;
    function declValue(node) {
        if (node?.name !== 'Declaration') {
            return null;
        }
        return children(node).find(node => node.name === ':')?.nextSibling ?? null;
    }
    ASTUtils.declValue = declValue;
    function* stripComments(nodes) {
        for (const node of nodes) {
            if (node.type.name !== 'Comment') {
                yield node;
            }
        }
    }
    ASTUtils.stripComments = stripComments;
    function split(nodes) {
        const result = [];
        let current = [];
        for (const node of nodes) {
            if (node.name === ',') {
                result.push(current);
                current = [];
            }
            else {
                current.push(node);
            }
        }
        if (nodes.length > 0) {
            result.push(current);
        }
        return result;
    }
    ASTUtils.split = split;
    function callArgs(node) {
        const args = children(node?.getChild('ArgList') ?? null);
        const openParen = args.splice(0, 1)[0];
        const closingParen = args.pop();
        if (openParen?.name !== '(' || closingParen?.name !== ')') {
            return [];
        }
        return split(args);
    }
    ASTUtils.callArgs = callArgs;
    function equals(a, b) {
        return a.name === b.name && a.from === b.from && a.to === b.to;
    }
    ASTUtils.equals = equals;
})(ASTUtils || (ASTUtils = {}));
function declaration(rule) {
    const cssParser = undefined.cssLanguage.parser;
    return cssParser.parse(rule).topNode.getChild('RuleSet')?.getChild('Block')?.getChild('Declaration') ?? null;
}
function tokenizeDeclaration(propertyName, propertyValue) {
    const name = tokenizePropertyName(propertyName);
    if (!name) {
        return null;
    }
    const rule = `*{${name}: ${propertyValue};}`;
    const decl = declaration(rule);
    if (!decl || decl.type.isError) {
        return null;
    }
    const childNodes = ASTUtils.children(decl);
    if (childNodes.length < 2) {
        return null;
    }
    const [varName, colon, tree] = childNodes;
    if (!varName || varName.type.isError || !colon || colon.type.isError || tree?.type.isError) {
        return null;
    }
    const trailingNodes = ASTUtils.siblings(decl).slice(1);
    const [semicolon, brace] = trailingNodes.splice(trailingNodes.length - 2, 2);
    if (semicolon?.name !== ';' && brace?.name !== '}') {
        return null;
    }
    const ast = new SyntaxTree(propertyValue, rule, decl, name, trailingNodes);
    if (ast.text(varName) !== name || colon.name !== ':') {
        return null;
    }
    return ast;
}
function tokenizePropertyName(name) {
    const rule = `*{${name}: inherit;}`;
    const decl = declaration(rule);
    if (!decl || decl.type.isError) {
        return null;
    }
    const propertyName = decl.getChild('PropertyName') ?? decl.getChild('VariableName');
    if (!propertyName) {
        return null;
    }
    return nodeText(propertyName, rule);
}
function matchDeclaration(name, value, matchers) {
    const ast = tokenizeDeclaration(name, value);
    const matchedResult = ast && BottomUpTreeMatching.walk(ast, matchers);
    ast?.trailingNodes.forEach(n => matchedResult?.matchText(n));
    return matchedResult;
}

// Copyright 2016 The Chromium Authors
class CSSProperty extends ObjectWrapper {
    ownerStyle;
    index;
    name;
    value;
    important;
    disabled;
    parsedOk;
    implicit;
    text;
    range;
    #active = true;
    #nameRange = null;
    #valueRange = null;
    #invalidString;
    #longhandProperties = [];
    constructor(ownerStyle, index, name, value, important, disabled, parsedOk, implicit, text, range, longhandProperties) {
        super();
        this.ownerStyle = ownerStyle;
        this.index = index;
        this.name = name;
        this.value = value;
        this.important = important;
        this.disabled = disabled;
        this.parsedOk = parsedOk;
        this.implicit = implicit;
        this.text = text;
        this.range = range ? TextRange.fromObject(range) : null;
        if (longhandProperties && longhandProperties.length > 0) {
            for (const property of longhandProperties) {
                this.#longhandProperties.push(new CSSProperty(ownerStyle, ++index, property.name, property.value, important, disabled, parsedOk, true));
            }
        }
        else {
            const longhandNames = cssMetadata().getLonghands(name);
            for (const longhandName of longhandNames || []) {
                this.#longhandProperties.push(new CSSProperty(ownerStyle, ++index, longhandName, '', important, disabled, parsedOk, true));
            }
        }
    }
    static parsePayload(ownerStyle, index, payload) {
        const result = new CSSProperty(ownerStyle, index, payload.name, payload.value, payload.important || false, payload.disabled || false, ('parsedOk' in payload) ? Boolean(payload.parsedOk) : true, Boolean(payload.implicit), payload.text, payload.range, payload.longhandProperties);
        return result;
    }
    parseExpression(expression, matchedStyles, computedStyles) {
        if (!this.parsedOk) {
            return null;
        }
        return matchDeclaration(this.name, expression, this.#matchers(matchedStyles, computedStyles));
    }
    parseValue(matchedStyles, computedStyles) {
        if (!this.parsedOk) {
            return null;
        }
        return matchDeclaration(this.name, this.value, this.#matchers(matchedStyles, computedStyles));
    }
    #matchers(matchedStyles, computedStyles) {
        const matchers = matchedStyles.propertyMatchers(this.ownerStyle, computedStyles);
        matchers.push(new CSSWideKeywordMatcher(this, matchedStyles));
        if (experiments.isEnabled(ExperimentName.FONT_EDITOR)) {
            matchers.push(new FontMatcher());
        }
        return matchers;
    }
    ensureRanges() {
        if (this.#nameRange && this.#valueRange) {
            return;
        }
        const range = this.range;
        const text = this.text ? new Text(this.text) : null;
        if (!range || !text) {
            return;
        }
        const nameIndex = text.value().indexOf(this.name);
        const valueIndex = text.value().lastIndexOf(this.value);
        if (nameIndex === -1 || valueIndex === -1 || nameIndex > valueIndex) {
            return;
        }
        const nameSourceRange = new SourceRange(nameIndex, this.name.length);
        const valueSourceRange = new SourceRange(valueIndex, this.value.length);
        this.#nameRange = rebase(text.toTextRange(nameSourceRange), range.startLine, range.startColumn);
        this.#valueRange = rebase(text.toTextRange(valueSourceRange), range.startLine, range.startColumn);
        function rebase(oneLineRange, lineOffset, columnOffset) {
            if (oneLineRange.startLine === 0) {
                oneLineRange.startColumn += columnOffset;
                oneLineRange.endColumn += columnOffset;
            }
            oneLineRange.startLine += lineOffset;
            oneLineRange.endLine += lineOffset;
            return oneLineRange;
        }
    }
    nameRange() {
        this.ensureRanges();
        return this.#nameRange;
    }
    valueRange() {
        this.ensureRanges();
        return this.#valueRange;
    }
    rebase(edit) {
        if (this.ownerStyle.styleSheetId !== edit.styleSheetId) {
            return;
        }
        if (this.range) {
            this.range = this.range.rebaseAfterTextEdit(edit.oldRange, edit.newRange);
        }
    }
    setActive(active) {
        this.#active = active;
    }
    get propertyText() {
        if (this.text !== undefined) {
            return this.text;
        }
        if (this.name === '') {
            return '';
        }
        return this.name + ': ' + this.value + (this.important ? ' !important' : '') + ';';
    }
    activeInStyle() {
        return this.#active;
    }
    async setText(propertyText, majorChange, overwrite) {
        if (!this.ownerStyle) {
            throw new Error('No ownerStyle for property');
        }
        if (!this.ownerStyle.styleSheetId) {
            throw new Error('No owner style id');
        }
        if (!this.range || !this.ownerStyle.range) {
            throw new Error('Style not editable');
        }
        if (majorChange) {
            userMetrics.actionTaken(Action.StyleRuleEdited);
            if (this.ownerStyle.parentRule?.isKeyframeRule()) {
                userMetrics.actionTaken(Action.StylePropertyInsideKeyframeEdited);
            }
            if (this.name.startsWith('--')) {
                userMetrics.actionTaken(Action.CustomPropertyEdited);
            }
        }
        if (overwrite && propertyText === this.propertyText) {
            this.ownerStyle.cssModel().domModel().markUndoableState(!majorChange);
            return true;
        }
        const range = this.range.relativeTo(this.ownerStyle.range.startLine, this.ownerStyle.range.startColumn);
        const indentation = this.ownerStyle.cssText ?
            this.detectIndentation(this.ownerStyle.cssText) :
            Settings.instance().moduleSetting('text-editor-indent').get();
        const endIndentation = this.ownerStyle.cssText ? indentation.substring(0, this.ownerStyle.range.endColumn) : '';
        const text = new Text(this.ownerStyle.cssText || '');
        const newStyleText = text.replaceRange(range, sprintf(';%s;', propertyText));
        const styleText = await CSSProperty.formatStyle(newStyleText, indentation, endIndentation);
        return await this.ownerStyle.setText(styleText, majorChange);
    }
    static async formatStyle(styleText, indentation, endIndentation) {
        const doubleIndent = indentation.substring(endIndentation.length) + indentation;
        if (indentation) {
            indentation = '\n' + indentation;
        }
        let result = '';
        let propertyName = '';
        let propertyText = '';
        let insideProperty = false;
        let needsSemi = false;
        const tokenize = createCssTokenizer();
        await tokenize('*{' + styleText + '}', processToken);
        if (insideProperty) {
            result += propertyText;
        }
        result = result.substring(2, result.length - 1).trimEnd();
        return result + (indentation ? '\n' + endIndentation : '');
        function processToken(token, tokenType) {
            if (!insideProperty) {
                const disabledProperty = tokenType?.includes('comment') && isDisabledProperty(token);
                const isPropertyStart = (tokenType?.includes('def') || tokenType?.includes('string') || tokenType?.includes('meta') ||
                    tokenType?.includes('property') ||
                    (tokenType?.includes('variableName') && tokenType !== ('variableName.function')));
                if (disabledProperty) {
                    result = result.trimEnd() + indentation + token;
                }
                else if (isPropertyStart) {
                    insideProperty = true;
                    propertyText = token;
                }
                else if (token !== ';' || needsSemi) {
                    result += token;
                    if (token.trim() && !(tokenType?.includes('comment'))) {
                        needsSemi = token !== ';';
                    }
                }
                if (token === '{' && !tokenType) {
                    needsSemi = false;
                }
                return;
            }
            if (token === '}' || token === ';') {
                const trimmedPropertyText = propertyText.trim();
                result = result.trimEnd() + indentation + trimmedPropertyText + (trimmedPropertyText.endsWith(':') ? ' ' : '') +
                    token;
                needsSemi = false;
                insideProperty = false;
                propertyName = '';
                return;
            }
            if (cssMetadata().isGridAreaDefiningProperty(propertyName)) {
                const rowResult = GridAreaRowRegex.exec(token);
                if (rowResult?.index === 0 && !propertyText.trimEnd().endsWith(']')) {
                    propertyText = propertyText.trimEnd() + '\n' + doubleIndent;
                }
            }
            if (!propertyName && token === ':') {
                propertyName = propertyText;
            }
            propertyText += token;
        }
        function isDisabledProperty(text) {
            const colon = text.indexOf(':');
            if (colon === -1) {
                return false;
            }
            const propertyName = text.substring(2, colon).trim();
            return cssMetadata().isCSSPropertyName(propertyName);
        }
    }
    detectIndentation(text) {
        const lines = text.split('\n');
        if (lines.length < 2) {
            return '';
        }
        return Utils.lineIndent(lines[1]);
    }
    setValue(newValue, majorChange, overwrite, userCallback) {
        const text = this.name + ': ' + newValue + (this.important ? ' !important' : '') + ';';
        void this.setText(text, majorChange, overwrite).then(userCallback);
    }
    setLocalValue(value) {
        this.value = value;
        this.dispatchEventToListeners("localValueUpdated" );
    }
    async setDisabled(disabled) {
        if (!this.ownerStyle) {
            return false;
        }
        if (disabled === this.disabled) {
            return true;
        }
        if (!this.text) {
            return true;
        }
        const propertyText = this.text.trim();
        const appendSemicolonIfMissing = (propertyText) => propertyText + (propertyText.endsWith(';') ? '' : ';');
        let text;
        if (disabled) {
            text = '/* ' + appendSemicolonIfMissing(stripComments(propertyText)) + ' */';
        }
        else {
            text = appendSemicolonIfMissing(this.text.substring(2, propertyText.length - 2).trim());
        }
        return await this.setText(text, true, true);
    }
    setDisplayedStringForInvalidProperty(invalidString) {
        this.#invalidString = invalidString;
    }
    getInvalidStringForInvalidProperty() {
        return this.#invalidString;
    }
    getLonghandProperties() {
        return this.#longhandProperties;
    }
    ignoreErrors() {
        function hasUnknownVendorPrefix(string) {
            return !string.startsWith('-webkit-') && /^[-_][\w\d]+-\w/.test(string);
        }
        const name = this.name.toLowerCase();
        if (name.charAt(0) === '_') {
            return true;
        }
        if (name === 'filter') {
            return true;
        }
        if (name.startsWith('scrollbar-')) {
            return true;
        }
        if (hasUnknownVendorPrefix(name)) {
            return true;
        }
        const value = this.value.toLowerCase();
        if (value.endsWith('\\9')) {
            return true;
        }
        if (hasUnknownVendorPrefix(value)) {
            return true;
        }
        return false;
    }
}

// Copyright 2021 The Chromium Authors
class CSSQuery {
    text = '';
    range;
    styleSheetId;
    cssModel;
    constructor(cssModel) {
        this.cssModel = cssModel;
    }
    rebase(edit) {
        if (this.styleSheetId !== edit.styleSheetId || !this.range) {
            return;
        }
        if (edit.oldRange.equal(this.range)) {
            this.reinitialize(edit.payload);
        }
        else {
            this.range = this.range.rebaseAfterTextEdit(edit.oldRange, edit.newRange);
        }
    }
    equal(other) {
        if (!this.styleSheetId || !this.range || !other.range) {
            return false;
        }
        return this.styleSheetId === other.styleSheetId && this.range.equal(other.range);
    }
    lineNumberInSource() {
        if (!this.range) {
            return undefined;
        }
        return this.header()?.lineNumberInSource(this.range.startLine);
    }
    columnNumberInSource() {
        if (!this.range) {
            return undefined;
        }
        return this.header()?.columnNumberInSource(this.range.startLine, this.range.startColumn);
    }
    header() {
        return this.styleSheetId ? this.cssModel.styleSheetHeaderForId(this.styleSheetId) : null;
    }
    rawLocation() {
        const header = this.header();
        if (!header || this.lineNumberInSource() === undefined) {
            return null;
        }
        const lineNumber = Number(this.lineNumberInSource());
        return new CSSLocation(header, lineNumber, this.columnNumberInSource());
    }
}

// Copyright 2021 The Chromium Authors
class CSSContainerQuery extends CSSQuery {
    name;
    physicalAxes;
    logicalAxes;
    queriesScrollState;
    queriesAnchored;
    static parseContainerQueriesPayload(cssModel, payload) {
        return payload.map(cq => new CSSContainerQuery(cssModel, cq));
    }
    constructor(cssModel, payload) {
        super(cssModel);
        this.reinitialize(payload);
    }
    reinitialize(payload) {
        this.text = payload.text;
        this.range = payload.range ? TextRange.fromObject(payload.range) : null;
        this.styleSheetId = payload.styleSheetId;
        this.name = payload.name;
        this.physicalAxes = payload.physicalAxes;
        this.logicalAxes = payload.logicalAxes;
        this.queriesScrollState = payload.queriesScrollState;
        this.queriesAnchored = payload.queriesAnchored;
    }
    active() {
        return true;
    }
    async getContainerForNode(nodeId) {
        const containerNode = await this.cssModel.domModel().getContainerForNode(nodeId, this.name, this.physicalAxes, this.logicalAxes, this.queriesScrollState, this.queriesAnchored);
        if (!containerNode) {
            return;
        }
        return new CSSContainerQueryContainer(containerNode);
    }
}
class CSSContainerQueryContainer {
    containerNode;
    constructor(containerNode) {
        this.containerNode = containerNode;
    }
    async getContainerSizeDetails() {
        const styles = await this.containerNode.domModel().cssModel().getComputedStyle(this.containerNode.id);
        if (!styles) {
            return;
        }
        const containerType = styles.get('container-type');
        const writingMode = styles.get('writing-mode');
        if (!containerType || !writingMode) {
            return;
        }
        const queryAxis = getQueryAxisFromContainerType(`${containerType}`);
        const physicalAxis = getPhysicalAxisFromQueryAxis(queryAxis, writingMode);
        let width, height;
        if (physicalAxis === "Both"  || physicalAxis === "Horizontal" ) {
            width = styles.get('width');
        }
        if (physicalAxis === "Both"  || physicalAxis === "Vertical" ) {
            height = styles.get('height');
        }
        return {
            queryAxis,
            physicalAxis,
            width,
            height,
        };
    }
}
const getQueryAxisFromContainerType = (propertyValue) => {
    const segments = propertyValue.split(' ');
    let isInline = false;
    for (const segment of segments) {
        if (segment === 'size') {
            return "size" ;
        }
        isInline = isInline || segment === 'inline-size';
    }
    if (isInline) {
        return "inline-size" ;
    }
    return "" ;
};
const getPhysicalAxisFromQueryAxis = (queryAxis, writingMode) => {
    const isVerticalWritingMode = writingMode.startsWith('vertical');
    switch (queryAxis) {
        case "" :
            return "" ;
        case "size" :
            return "Both" ;
        case "inline-size" :
            return isVerticalWritingMode ? "Vertical"  : "Horizontal" ;
        case "block-size" :
            return isVerticalWritingMode ? "Horizontal"  : "Vertical" ;
    }
};

// Copyright 2022 The Chromium Authors
class CSSLayer extends CSSQuery {
    static parseLayerPayload(cssModel, payload) {
        return payload.map(supports => new CSSLayer(cssModel, supports));
    }
    constructor(cssModel, payload) {
        super(cssModel);
        this.reinitialize(payload);
    }
    reinitialize(payload) {
        this.text = payload.text;
        this.range = payload.range ? TextRange.fromObject(payload.range) : null;
        this.styleSheetId = payload.styleSheetId;
    }
    active() {
        return true;
    }
}

// Copyright 2016 The Chromium Authors
class CSSMediaQuery {
    #active;
    #expressions;
    constructor(payload) {
        this.#active = payload.active;
        this.#expressions = [];
        for (let j = 0; j < payload.expressions.length; ++j) {
            this.#expressions.push(CSSMediaQueryExpression.parsePayload(payload.expressions[j]));
        }
    }
    static parsePayload(payload) {
        return new CSSMediaQuery(payload);
    }
    active() {
        return this.#active;
    }
    expressions() {
        return this.#expressions;
    }
}
class CSSMediaQueryExpression {
    #value;
    #unit;
    #feature;
    #valueRange;
    #computedLength;
    constructor(payload) {
        this.#value = payload.value;
        this.#unit = payload.unit;
        this.#feature = payload.feature;
        this.#valueRange = payload.valueRange ? TextRange.fromObject(payload.valueRange) : null;
        this.#computedLength = payload.computedLength || null;
    }
    static parsePayload(payload) {
        return new CSSMediaQueryExpression(payload);
    }
    value() {
        return this.#value;
    }
    unit() {
        return this.#unit;
    }
    feature() {
        return this.#feature;
    }
    valueRange() {
        return this.#valueRange;
    }
    computedLength() {
        return this.#computedLength;
    }
}
class CSSMedia extends CSSQuery {
    source;
    sourceURL;
    mediaList;
    static parseMediaArrayPayload(cssModel, payload) {
        return payload.map(mq => new CSSMedia(cssModel, mq));
    }
    constructor(cssModel, payload) {
        super(cssModel);
        this.reinitialize(payload);
    }
    reinitialize(payload) {
        this.text = payload.text;
        this.source = payload.source;
        this.sourceURL = payload.sourceURL || '';
        this.range = payload.range ? TextRange.fromObject(payload.range) : null;
        this.styleSheetId = payload.styleSheetId;
        this.mediaList = null;
        if (payload.mediaList) {
            this.mediaList = [];
            for (let i = 0; i < payload.mediaList.length; ++i) {
                this.mediaList.push(CSSMediaQuery.parsePayload(payload.mediaList[i]));
            }
        }
    }
    active() {
        if (!this.mediaList) {
            return true;
        }
        for (let i = 0; i < this.mediaList.length; ++i) {
            if (this.mediaList[i].active()) {
                return true;
            }
        }
        return false;
    }
}

// Copyright 2022 The Chromium Authors
class CSSScope extends CSSQuery {
    static parseScopesPayload(cssModel, payload) {
        return payload.map(scope => new CSSScope(cssModel, scope));
    }
    constructor(cssModel, payload) {
        super(cssModel);
        this.reinitialize(payload);
    }
    reinitialize(payload) {
        this.text = payload.text;
        this.range = payload.range ? TextRange.fromObject(payload.range) : null;
        this.styleSheetId = payload.styleSheetId;
    }
    active() {
        return true;
    }
}

// Copyright 2025 The Chromium Authors
class CSSStartingStyle extends CSSQuery {
    static parseStartingStylePayload(cssModel, payload) {
        return payload.map(p => new CSSStartingStyle(cssModel, p));
    }
    constructor(cssModel, payload) {
        super(cssModel);
        this.reinitialize(payload);
    }
    reinitialize(payload) {
        this.range = payload.range ? TextRange.fromObject(payload.range) : null;
        this.styleSheetId = payload.styleSheetId;
    }
    active() {
        return true;
    }
}

// Copyright 2016 The Chromium Authors
class CSSStyleDeclaration {
    #cssModel;
    parentRule;
    #allProperties = [];
    styleSheetId;
    range = null;
    cssText;
    #shorthandValues = new Map();
    #shorthandIsImportant = new Set();
    #activePropertyMap = new Map();
    #leadingProperties = null;
    type;
    #animationName;
    constructor(cssModel, parentRule, payload, type, animationName) {
        this.#cssModel = cssModel;
        this.parentRule = parentRule;
        this.#reinitialize(payload);
        this.type = type;
        this.#animationName = animationName;
    }
    rebase(edit) {
        if (this.styleSheetId !== edit.styleSheetId || !this.range) {
            return;
        }
        if (edit.oldRange.equal(this.range)) {
            this.#reinitialize(edit.payload);
        }
        else {
            this.range = this.range.rebaseAfterTextEdit(edit.oldRange, edit.newRange);
            for (let i = 0; i < this.#allProperties.length; ++i) {
                this.#allProperties[i].rebase(edit);
            }
        }
    }
    animationName() {
        return this.#animationName;
    }
    #reinitialize(payload) {
        this.styleSheetId = payload.styleSheetId;
        this.range = payload.range ? TextRange.fromObject(payload.range) : null;
        const shorthandEntries = payload.shorthandEntries;
        this.#shorthandValues = new Map();
        this.#shorthandIsImportant = new Set();
        for (let i = 0; i < shorthandEntries.length; ++i) {
            this.#shorthandValues.set(shorthandEntries[i].name, shorthandEntries[i].value);
            if (shorthandEntries[i].important) {
                this.#shorthandIsImportant.add(shorthandEntries[i].name);
            }
        }
        this.#allProperties = [];
        if (payload.cssText && this.range) {
            const longhands = [];
            for (const cssProperty of payload.cssProperties) {
                const range = cssProperty.range;
                if (!range) {
                    continue;
                }
                const parsedProperty = CSSProperty.parsePayload(this, this.#allProperties.length, cssProperty);
                this.#allProperties.push(parsedProperty);
                for (const longhand of parsedProperty.getLonghandProperties()) {
                    longhands.push(longhand);
                }
            }
            for (const longhand of longhands) {
                longhand.index = this.#allProperties.length;
                this.#allProperties.push(longhand);
            }
        }
        else {
            for (const cssProperty of payload.cssProperties) {
                this.#allProperties.push(CSSProperty.parsePayload(this, this.#allProperties.length, cssProperty));
            }
        }
        this.#generateSyntheticPropertiesIfNeeded();
        this.#computeInactiveProperties();
        this.#activePropertyMap = new Map();
        for (const property of this.#allProperties) {
            if (!property.activeInStyle()) {
                continue;
            }
            this.#activePropertyMap.set(property.name, property);
        }
        this.cssText = payload.cssText;
        this.#leadingProperties = null;
    }
    #generateSyntheticPropertiesIfNeeded() {
        if (this.range) {
            return;
        }
        if (!this.#shorthandValues.size) {
            return;
        }
        const propertiesSet = new Set();
        for (const property of this.#allProperties) {
            propertiesSet.add(property.name);
        }
        const generatedProperties = [];
        for (const property of this.#allProperties) {
            const shorthands = cssMetadata().getShorthands(property.name) || [];
            for (const shorthand of shorthands) {
                if (propertiesSet.has(shorthand)) {
                    continue;
                }
                const shorthandValue = this.#shorthandValues.get(shorthand);
                if (!shorthandValue) {
                    continue;
                }
                const shorthandImportance = Boolean(this.#shorthandIsImportant.has(shorthand));
                const shorthandProperty = new CSSProperty(this, this.allProperties().length, shorthand, shorthandValue, shorthandImportance, false, true, false);
                generatedProperties.push(shorthandProperty);
                propertiesSet.add(shorthand);
            }
        }
        this.#allProperties = this.#allProperties.concat(generatedProperties);
    }
    #computeLeadingProperties() {
        function propertyHasRange(property) {
            return Boolean(property.range);
        }
        if (this.range) {
            return this.#allProperties.filter(propertyHasRange);
        }
        const leadingProperties = [];
        for (const property of this.#allProperties) {
            const shorthands = cssMetadata().getShorthands(property.name) || [];
            let belongToAnyShorthand = false;
            for (const shorthand of shorthands) {
                if (this.#shorthandValues.get(shorthand)) {
                    belongToAnyShorthand = true;
                    break;
                }
            }
            if (!belongToAnyShorthand) {
                leadingProperties.push(property);
            }
        }
        return leadingProperties;
    }
    leadingProperties() {
        if (!this.#leadingProperties) {
            this.#leadingProperties = this.#computeLeadingProperties();
        }
        return this.#leadingProperties;
    }
    target() {
        return this.#cssModel.target();
    }
    cssModel() {
        return this.#cssModel;
    }
    #computeInactiveProperties() {
        const activeProperties = new Map();
        const processedLonghands = new Set();
        for (const property of this.#allProperties) {
            const metadata = cssMetadata();
            const canonicalName = metadata.canonicalPropertyName(property.name);
            if (property.disabled || !property.parsedOk) {
                if (!property.disabled && metadata.isCustomProperty(property.name)) {
                    activeProperties.get(canonicalName)?.setActive(false);
                    activeProperties.delete(canonicalName);
                }
                property.setActive(false);
                continue;
            }
            if (processedLonghands.has(property)) {
                continue;
            }
            for (const longhand of property.getLonghandProperties()) {
                const activeLonghand = activeProperties.get(longhand.name);
                if (!activeLonghand) {
                    activeProperties.set(longhand.name, longhand);
                }
                else if (!activeLonghand.important || longhand.important) {
                    activeLonghand.setActive(false);
                    activeProperties.set(longhand.name, longhand);
                }
                else {
                    longhand.setActive(false);
                }
                processedLonghands.add(longhand);
            }
            const activeProperty = activeProperties.get(canonicalName);
            if (!activeProperty) {
                activeProperties.set(canonicalName, property);
            }
            else if (!activeProperty.important || property.important) {
                activeProperty.setActive(false);
                activeProperties.set(canonicalName, property);
            }
            else {
                property.setActive(false);
            }
        }
    }
    allProperties() {
        return this.#allProperties;
    }
    hasActiveProperty(name) {
        return this.#activePropertyMap.has(name);
    }
    getPropertyValue(name) {
        const property = this.#activePropertyMap.get(name);
        return property ? property.value : '';
    }
    isPropertyImplicit(name) {
        const property = this.#activePropertyMap.get(name);
        return property ? property.implicit : false;
    }
    propertyAt(index) {
        return (index < this.allProperties().length) ? this.allProperties()[index] : null;
    }
    pastLastSourcePropertyIndex() {
        for (let i = this.allProperties().length - 1; i >= 0; --i) {
            if (this.allProperties()[i].range) {
                return i + 1;
            }
        }
        return 0;
    }
    #insertionRange(index) {
        const property = this.propertyAt(index);
        if (property?.range) {
            return property.range.collapseToStart();
        }
        if (!this.range) {
            throw new Error('CSSStyleDeclaration.range is null');
        }
        return this.range.collapseToEnd();
    }
    newBlankProperty(index) {
        index = (typeof index === 'undefined') ? this.pastLastSourcePropertyIndex() : index;
        const property = new CSSProperty(this, index, '', '', false, false, true, false, '', this.#insertionRange(index));
        return property;
    }
    setText(text, majorChange) {
        if (!this.range || !this.styleSheetId) {
            return Promise.resolve(false);
        }
        return this.#cssModel.setStyleText(this.styleSheetId, this.range, text, majorChange);
    }
    insertPropertyAt(index, name, value, userCallback) {
        void this.newBlankProperty(index).setText(name + ': ' + value + ';', false, true).then(userCallback);
    }
    appendProperty(name, value, userCallback) {
        this.insertPropertyAt(this.allProperties().length, name, value, userCallback);
    }
}
var Type$3;
(function (Type) {
    Type["Regular"] = "Regular";
    Type["Inline"] = "Inline";
    Type["Attributes"] = "Attributes";
    Type["Pseudo"] = "Pseudo";
    Type["Transition"] = "Transition";
    Type["Animation"] = "Animation";
})(Type$3 || (Type$3 = {}));

// Copyright 2022 The Chromium Authors
class CSSSupports extends CSSQuery {
    static parseSupportsPayload(cssModel, payload) {
        return payload.map(supports => new CSSSupports(cssModel, supports));
    }
    #active = true;
    constructor(cssModel, payload) {
        super(cssModel);
        this.reinitialize(payload);
    }
    reinitialize(payload) {
        this.text = payload.text;
        this.range = payload.range ? TextRange.fromObject(payload.range) : null;
        this.styleSheetId = payload.styleSheetId;
        this.#active = payload.active;
    }
    active() {
        return this.#active;
    }
}

// Copyright 2016 The Chromium Authors
function styleSheetHeaderForRule(cssModel, { styleSheetId }) {
    return styleSheetId && cssModel.styleSheetHeaderForId(styleSheetId) || null;
}
class CSSRule {
    cssModelInternal;
    origin;
    style;
    header;
    treeScope;
    constructor(cssModel, payload) {
        this.header = payload.header;
        this.cssModelInternal = cssModel;
        this.origin = payload.origin;
        this.treeScope = payload.originTreeScopeNodeId;
        this.style = new CSSStyleDeclaration(this.cssModelInternal, this, payload.style, Type$3.Regular);
    }
    get sourceURL() {
        return this.header?.sourceURL;
    }
    rebase(edit) {
        if (this.header?.id !== edit.styleSheetId) {
            return;
        }
        this.style.rebase(edit);
    }
    resourceURL() {
        return this.header?.resourceURL() ?? EmptyUrlString;
    }
    isUserAgent() {
        return this.origin === "user-agent" ;
    }
    isInjected() {
        return this.origin === "injected" ;
    }
    isViaInspector() {
        return this.origin === "inspector" ;
    }
    isRegular() {
        return this.origin === "regular" ;
    }
    isKeyframeRule() {
        return false;
    }
    cssModel() {
        return this.cssModelInternal;
    }
}
class CSSValue {
    text;
    range;
    specificity;
    constructor(payload) {
        this.text = payload.text;
        if (payload.range) {
            this.range = TextRange.fromObject(payload.range);
        }
        if (payload.specificity) {
            this.specificity = payload.specificity;
        }
    }
    rebase(edit) {
        if (!this.range) {
            return;
        }
        this.range = this.range.rebaseAfterTextEdit(edit.oldRange, edit.newRange);
    }
}
class CSSStyleRule extends CSSRule {
    selectors;
    nestingSelectors;
    media;
    containerQueries;
    supports;
    scopes;
    layers;
    ruleTypes;
    startingStyles;
    wasUsed;
    constructor(cssModel, payload, wasUsed) {
        super(cssModel, {
            origin: payload.origin,
            style: payload.style,
            header: styleSheetHeaderForRule(cssModel, payload),
            originTreeScopeNodeId: payload.originTreeScopeNodeId
        });
        this.reinitializeSelectors(payload.selectorList);
        this.nestingSelectors = payload.nestingSelectors;
        this.media = payload.media ? CSSMedia.parseMediaArrayPayload(cssModel, payload.media) : [];
        this.containerQueries = payload.containerQueries ?
            CSSContainerQuery.parseContainerQueriesPayload(cssModel, payload.containerQueries) :
            [];
        this.scopes = payload.scopes ? CSSScope.parseScopesPayload(cssModel, payload.scopes) : [];
        this.supports = payload.supports ? CSSSupports.parseSupportsPayload(cssModel, payload.supports) : [];
        this.layers = payload.layers ? CSSLayer.parseLayerPayload(cssModel, payload.layers) : [];
        this.startingStyles =
            payload.startingStyles ? CSSStartingStyle.parseStartingStylePayload(cssModel, payload.startingStyles) : [];
        this.ruleTypes = payload.ruleTypes || [];
        this.wasUsed = wasUsed || false;
    }
    static createDummyRule(cssModel, selectorText) {
        const dummyPayload = {
            selectorList: {
                text: '',
                selectors: [{ text: selectorText }],
            },
            style: {
                styleSheetId: '0',
                range: new TextRange(0, 0, 0, 0),
                shorthandEntries: [],
                cssProperties: [],
            },
            origin: "inspector" ,
        };
        return new CSSStyleRule(cssModel, dummyPayload);
    }
    reinitializeSelectors(selectorList) {
        this.selectors = [];
        for (let i = 0; i < selectorList.selectors.length; ++i) {
            this.selectors.push(new CSSValue(selectorList.selectors[i]));
        }
    }
    setSelectorText(newSelector) {
        const styleSheetId = this.header?.id;
        if (!styleSheetId) {
            throw new Error('No rule stylesheet id');
        }
        const range = this.selectorRange();
        if (!range) {
            throw new Error('Rule selector is not editable');
        }
        return this.cssModelInternal.setSelectorText(styleSheetId, range, newSelector);
    }
    selectorText() {
        return this.selectors.map(selector => selector.text).join(', ');
    }
    selectorRange() {
        if (this.selectors.length === 0) {
            return null;
        }
        const firstRange = this.selectors[0].range;
        const lastRange = this.selectors[this.selectors.length - 1].range;
        if (!firstRange || !lastRange) {
            return null;
        }
        return new TextRange(firstRange.startLine, firstRange.startColumn, lastRange.endLine, lastRange.endColumn);
    }
    lineNumberInSource(selectorIndex) {
        const selector = this.selectors[selectorIndex];
        if (!selector?.range || !this.header) {
            return 0;
        }
        return this.header.lineNumberInSource(selector.range.startLine);
    }
    columnNumberInSource(selectorIndex) {
        const selector = this.selectors[selectorIndex];
        if (!selector?.range || !this.header) {
            return undefined;
        }
        return this.header.columnNumberInSource(selector.range.startLine, selector.range.startColumn);
    }
    rebase(edit) {
        if (this.header?.id !== edit.styleSheetId) {
            return;
        }
        const range = this.selectorRange();
        if (range?.equal(edit.oldRange)) {
            this.reinitializeSelectors(edit.payload);
        }
        else {
            for (let i = 0; i < this.selectors.length; ++i) {
                this.selectors[i].rebase(edit);
            }
        }
        this.media.forEach(media => media.rebase(edit));
        this.containerQueries.forEach(cq => cq.rebase(edit));
        this.scopes.forEach(scope => scope.rebase(edit));
        this.supports.forEach(supports => supports.rebase(edit));
        super.rebase(edit);
    }
}
class CSSPropertyRule extends CSSRule {
    #name;
    constructor(cssModel, payload) {
        super(cssModel, {
            origin: payload.origin,
            style: payload.style,
            header: styleSheetHeaderForRule(cssModel, payload),
        });
        this.#name = new CSSValue(payload.propertyName);
    }
    propertyName() {
        return this.#name;
    }
    initialValue() {
        return this.style.hasActiveProperty('initial-value') ? this.style.getPropertyValue('initial-value') : null;
    }
    syntax() {
        return this.style.getPropertyValue('syntax');
    }
    inherits() {
        return this.style.getPropertyValue('inherits') === 'true';
    }
    setPropertyName(newPropertyName) {
        const styleSheetId = this.header?.id;
        if (!styleSheetId) {
            throw new Error('No rule stylesheet id');
        }
        const range = this.#name.range;
        if (!range) {
            throw new Error('Property name is not editable');
        }
        return this.cssModelInternal.setPropertyRulePropertyName(styleSheetId, range, newPropertyName);
    }
}
class CSSAtRule extends CSSRule {
    #name;
    #type;
    #subsection;
    constructor(cssModel, payload) {
        super(cssModel, {
            origin: payload.origin,
            style: payload.style,
            header: styleSheetHeaderForRule(cssModel, payload),
        });
        this.#name = payload.name ? new CSSValue(payload.name) : null;
        this.#type = payload.type;
        this.#subsection = payload.subsection ?? null;
    }
    name() {
        return this.#name;
    }
    type() {
        return this.#type;
    }
    subsection() {
        return this.#subsection;
    }
}
class CSSKeyframesRule {
    #animationName;
    #keyframes;
    constructor(cssModel, payload) {
        this.#animationName = new CSSValue(payload.animationName);
        this.#keyframes =
            payload.keyframes.map(keyframeRule => new CSSKeyframeRule(cssModel, keyframeRule, this.#animationName.text));
    }
    name() {
        return this.#animationName;
    }
    keyframes() {
        return this.#keyframes;
    }
}
class CSSKeyframeRule extends CSSRule {
    #keyText;
    #parentRuleName;
    constructor(cssModel, payload, parentRuleName) {
        super(cssModel, {
            origin: payload.origin,
            style: payload.style,
            header: styleSheetHeaderForRule(cssModel, payload),
        });
        this.reinitializeKey(payload.keyText);
        this.#parentRuleName = parentRuleName;
    }
    parentRuleName() {
        return this.#parentRuleName;
    }
    key() {
        return this.#keyText;
    }
    reinitializeKey(payload) {
        this.#keyText = new CSSValue(payload);
    }
    rebase(edit) {
        if (this.header?.id !== edit.styleSheetId || !this.#keyText.range) {
            return;
        }
        if (edit.oldRange.equal(this.#keyText.range)) {
            this.reinitializeKey(edit.payload);
        }
        else {
            this.#keyText.rebase(edit);
        }
        super.rebase(edit);
    }
    isKeyframeRule() {
        return true;
    }
    setKeyText(newKeyText) {
        const styleSheetId = this.header?.id;
        if (!styleSheetId) {
            throw new Error('No rule stylesheet id');
        }
        const range = this.#keyText.range;
        if (!range) {
            throw new Error('Keyframe key is not editable');
        }
        return this.cssModelInternal.setKeyframeKey(styleSheetId, range, newKeyText);
    }
}
class CSSPositionTryRule extends CSSRule {
    #name;
    #active;
    constructor(cssModel, payload) {
        super(cssModel, {
            origin: payload.origin,
            style: payload.style,
            header: styleSheetHeaderForRule(cssModel, payload),
        });
        this.#name = new CSSValue(payload.name);
        this.#active = payload.active;
    }
    name() {
        return this.#name;
    }
    active() {
        return this.#active;
    }
}
class CSSFunctionRule extends CSSRule {
    #name;
    #parameters;
    #children;
    constructor(cssModel, payload) {
        super(cssModel, {
            origin: payload.origin,
            style: { cssProperties: [], shorthandEntries: [] },
            header: styleSheetHeaderForRule(cssModel, payload),
        });
        this.#name = new CSSValue(payload.name);
        this.#parameters = payload.parameters.map(({ name }) => name);
        this.#children = this.protocolNodesToNestedStyles(payload.children);
    }
    functionName() {
        return this.#name;
    }
    parameters() {
        return this.#parameters;
    }
    children() {
        return this.#children;
    }
    nameWithParameters() {
        return `${this.functionName().text}(${this.parameters().join(', ')})`;
    }
    protocolNodesToNestedStyles(nodes) {
        const result = [];
        for (const node of nodes) {
            const nestedStyle = this.protocolNodeToNestedStyle(node);
            if (nestedStyle) {
                result.push(nestedStyle);
            }
        }
        return result;
    }
    protocolNodeToNestedStyle(node) {
        if (node.style) {
            return { style: new CSSStyleDeclaration(this.cssModelInternal, this, node.style, Type$3.Regular) };
        }
        if (node.condition) {
            const children = this.protocolNodesToNestedStyles(node.condition.children);
            if (node.condition.media) {
                return { children, media: new CSSMedia(this.cssModelInternal, node.condition.media) };
            }
            if (node.condition.containerQueries) {
                return {
                    children,
                    container: new CSSContainerQuery(this.cssModelInternal, node.condition.containerQueries),
                };
            }
            if (node.condition.supports) {
                return {
                    children,
                    supports: new CSSSupports(this.cssModelInternal, node.condition.supports),
                };
            }
            console.error('A function rule condition must have a media, container, or supports');
            return;
        }
        console.error('A function rule node must have a style or condition');
        return;
    }
}

// Copyright 2016 The Chromium Authors
function containsStyle(styles, query) {
    if (!query.styleSheetId || !query.range) {
        return false;
    }
    for (const style of styles) {
        if (query.styleSheetId === style.styleSheetId && style.range && query.range.equal(style.range)) {
            return true;
        }
    }
    return false;
}
function containsCustomProperties(style) {
    const properties = style.allProperties();
    return properties.some(property => cssMetadata().isCustomProperty(property.name));
}
function containsInherited(style) {
    const properties = style.allProperties();
    for (let i = 0; i < properties.length; ++i) {
        const property = properties[i];
        if (property.activeInStyle() && cssMetadata().isPropertyInherited(property.name)) {
            return true;
        }
    }
    return false;
}
function cleanUserAgentPayload(payload) {
    for (const ruleMatch of payload) {
        cleanUserAgentSelectors(ruleMatch);
    }
    const cleanMatchedPayload = [];
    for (const ruleMatch of payload) {
        const lastMatch = cleanMatchedPayload[cleanMatchedPayload.length - 1];
        if (!lastMatch || ruleMatch.rule.origin !== 'user-agent' || lastMatch.rule.origin !== 'user-agent' ||
            ruleMatch.rule.selectorList.text !== lastMatch.rule.selectorList.text ||
            mediaText(ruleMatch) !== mediaText(lastMatch)) {
            cleanMatchedPayload.push(ruleMatch);
            continue;
        }
        mergeRule(ruleMatch, lastMatch);
    }
    return cleanMatchedPayload;
    function mergeRule(from, to) {
        const shorthands = new Map();
        const properties = new Map();
        for (const entry of to.rule.style.shorthandEntries) {
            shorthands.set(entry.name, entry.value);
        }
        for (const entry of to.rule.style.cssProperties) {
            properties.set(entry.name, entry.value);
        }
        for (const entry of from.rule.style.shorthandEntries) {
            shorthands.set(entry.name, entry.value);
        }
        for (const entry of from.rule.style.cssProperties) {
            properties.set(entry.name, entry.value);
        }
        to.rule.style.shorthandEntries = [...shorthands.entries()].map(([name, value]) => ({ name, value }));
        to.rule.style.cssProperties = [...properties.entries()].map(([name, value]) => ({ name, value }));
    }
    function mediaText(ruleMatch) {
        if (!ruleMatch.rule.media) {
            return null;
        }
        return ruleMatch.rule.media.map(media => media.text).join(', ');
    }
    function cleanUserAgentSelectors(ruleMatch) {
        const { matchingSelectors, rule } = ruleMatch;
        if (rule.origin !== 'user-agent' || !matchingSelectors.length) {
            return;
        }
        rule.selectorList.selectors = rule.selectorList.selectors.filter((_, i) => matchingSelectors.includes(i));
        rule.selectorList.text = rule.selectorList.selectors.map(item => item.text).join(', ');
        ruleMatch.matchingSelectors = matchingSelectors.map((_, i) => i);
    }
}
function customHighlightNamesToMatchingSelectorIndices(ruleMatch) {
    const highlightNamesToMatchingSelectors = new Map();
    for (let i = 0; i < ruleMatch.matchingSelectors.length; i++) {
        const matchingSelectorIndex = ruleMatch.matchingSelectors[i];
        const selectorText = ruleMatch.rule.selectorList.selectors[matchingSelectorIndex].text;
        const highlightNameMatch = selectorText.match(/::highlight\((.*)\)/);
        if (highlightNameMatch) {
            const highlightName = highlightNameMatch[1];
            const selectorsForName = highlightNamesToMatchingSelectors.get(highlightName);
            if (selectorsForName) {
                selectorsForName.push(matchingSelectorIndex);
            }
            else {
                highlightNamesToMatchingSelectors.set(highlightName, [matchingSelectorIndex]);
            }
        }
    }
    return highlightNamesToMatchingSelectors;
}
function queryMatches(style) {
    if (!style.parentRule) {
        return true;
    }
    const parentRule = style.parentRule;
    const queries = [...parentRule.media, ...parentRule.containerQueries, ...parentRule.supports, ...parentRule.scopes];
    for (const query of queries) {
        if (!query.active()) {
            return false;
        }
    }
    return true;
}
class CSSRegisteredProperty {
    #registration;
    #cssModel;
    #style;
    constructor(cssModel, registration) {
        this.#cssModel = cssModel;
        this.#registration = registration;
    }
    propertyName() {
        return this.#registration instanceof CSSPropertyRule ? this.#registration.propertyName().text :
            this.#registration.propertyName;
    }
    initialValue() {
        return this.#registration instanceof CSSPropertyRule ? this.#registration.initialValue() :
            this.#registration.initialValue?.text ?? null;
    }
    inherits() {
        return this.#registration instanceof CSSPropertyRule ? this.#registration.inherits() : this.#registration.inherits;
    }
    syntax() {
        return this.#registration instanceof CSSPropertyRule ? this.#registration.syntax() :
            `"${this.#registration.syntax}"`;
    }
    parseValue(matchedStyles, computedStyles) {
        const value = this.initialValue();
        if (!value) {
            return null;
        }
        return matchDeclaration(this.propertyName(), value, matchedStyles.propertyMatchers(this.style(), computedStyles));
    }
    #asCSSProperties() {
        if (this.#registration instanceof CSSPropertyRule) {
            return [];
        }
        const { inherits, initialValue, syntax } = this.#registration;
        const properties = [
            { name: 'inherits', value: `${inherits}` },
            { name: 'syntax', value: `"${syntax}"` },
        ];
        if (initialValue !== undefined) {
            properties.push({ name: 'initial-value', value: initialValue.text });
        }
        return properties;
    }
    style() {
        if (!this.#style) {
            this.#style = this.#registration instanceof CSSPropertyRule ?
                this.#registration.style :
                new CSSStyleDeclaration(this.#cssModel, null, { cssProperties: this.#asCSSProperties(), shorthandEntries: [] }, Type$3.Pseudo);
        }
        return this.#style;
    }
}
class CSSMatchedStyles {
    #cssModel;
    #node;
    #addedStyles = new Map();
    #matchingSelectors = new Map();
    #keyframes = [];
    #registeredProperties;
    #registeredPropertyMap = new Map();
    #nodeForStyle = new Map();
    #inheritedStyles = new Set();
    #styleToDOMCascade = new Map();
    #parentLayoutNodeId;
    #positionTryRules;
    #activePositionFallbackIndex;
    #mainDOMCascade;
    #pseudoDOMCascades;
    #customHighlightPseudoDOMCascades;
    #functionRules;
    #atRules;
    #functionRuleMap = new Map();
    #environmentVariables = {};
    static async create(payload) {
        const cssMatchedStyles = new CSSMatchedStyles(payload);
        await cssMatchedStyles.init(payload);
        return cssMatchedStyles;
    }
    constructor({ cssModel, node, animationsPayload, parentLayoutNodeId, positionTryRules, propertyRules, cssPropertyRegistrations, activePositionFallbackIndex, functionRules, atRules, }) {
        this.#cssModel = cssModel;
        this.#node = node;
        this.#registeredProperties = [
            ...propertyRules.map(rule => new CSSPropertyRule(cssModel, rule)),
            ...cssPropertyRegistrations,
        ].map(r => new CSSRegisteredProperty(cssModel, r));
        if (animationsPayload) {
            this.#keyframes = animationsPayload.map(rule => new CSSKeyframesRule(cssModel, rule));
        }
        this.#positionTryRules = positionTryRules.map(rule => new CSSPositionTryRule(cssModel, rule));
        this.#parentLayoutNodeId = parentLayoutNodeId;
        this.#activePositionFallbackIndex = activePositionFallbackIndex;
        this.#functionRules = functionRules.map(rule => new CSSFunctionRule(cssModel, rule));
        this.#atRules = atRules.map(rule => new CSSAtRule(cssModel, rule));
    }
    async init({ matchedPayload, inheritedPayload, inlinePayload, attributesPayload, pseudoPayload, inheritedPseudoPayload, animationStylesPayload, transitionsStylePayload, inheritedAnimatedPayload, }) {
        matchedPayload = cleanUserAgentPayload(matchedPayload);
        for (const inheritedResult of inheritedPayload) {
            inheritedResult.matchedCSSRules = cleanUserAgentPayload(inheritedResult.matchedCSSRules);
        }
        this.#environmentVariables = await this.cssModel().getEnvironmentVariables();
        this.#mainDOMCascade = await this.buildMainCascade(inlinePayload, attributesPayload, matchedPayload, inheritedPayload, animationStylesPayload, transitionsStylePayload, inheritedAnimatedPayload);
        [this.#pseudoDOMCascades, this.#customHighlightPseudoDOMCascades] =
            this.buildPseudoCascades(pseudoPayload, inheritedPseudoPayload);
        for (const domCascade of Array.from(this.#customHighlightPseudoDOMCascades.values())
            .concat(Array.from(this.#pseudoDOMCascades.values()))
            .concat(this.#mainDOMCascade)) {
            for (const style of domCascade.styles()) {
                this.#styleToDOMCascade.set(style, domCascade);
            }
        }
        for (const prop of this.#registeredProperties) {
            this.#registeredPropertyMap.set(prop.propertyName(), prop);
        }
        for (const rule of this.#functionRules) {
            this.#functionRuleMap.set(rule.functionName().text, rule);
        }
    }
    async buildMainCascade(inlinePayload, attributesPayload, matchedPayload, inheritedPayload, animationStylesPayload, transitionsStylePayload, inheritedAnimatedPayload) {
        const nodeCascades = [];
        const nodeStyles = [];
        function addAttributesStyle() {
            if (!attributesPayload) {
                return;
            }
            const style = new CSSStyleDeclaration(this.#cssModel, null, attributesPayload, Type$3.Attributes);
            this.#nodeForStyle.set(style, this.#node);
            nodeStyles.push(style);
        }
        if (transitionsStylePayload) {
            const style = new CSSStyleDeclaration(this.#cssModel, null, transitionsStylePayload, Type$3.Transition);
            this.#nodeForStyle.set(style, this.#node);
            nodeStyles.push(style);
        }
        for (const animationsStyle of animationStylesPayload) {
            const style = new CSSStyleDeclaration(this.#cssModel, null, animationsStyle.style, Type$3.Animation, animationsStyle.name);
            this.#nodeForStyle.set(style, this.#node);
            nodeStyles.push(style);
        }
        if (inlinePayload && this.#node.nodeType() === Node.ELEMENT_NODE) {
            const style = new CSSStyleDeclaration(this.#cssModel, null, inlinePayload, Type$3.Inline);
            this.#nodeForStyle.set(style, this.#node);
            nodeStyles.push(style);
        }
        let addedAttributesStyle;
        for (let i = matchedPayload.length - 1; i >= 0; --i) {
            const rule = new CSSStyleRule(this.#cssModel, matchedPayload[i].rule);
            if ((rule.isInjected() || rule.isUserAgent()) && !addedAttributesStyle) {
                addedAttributesStyle = true;
                addAttributesStyle.call(this);
            }
            this.#nodeForStyle.set(rule.style, this.#node);
            nodeStyles.push(rule.style);
            this.addMatchingSelectors(this.#node, rule, matchedPayload[i].matchingSelectors);
        }
        if (!addedAttributesStyle) {
            addAttributesStyle.call(this);
        }
        nodeCascades.push(new NodeCascade(this, nodeStyles, this.#node, false ));
        let parentNode = this.#node.parentNode;
        const traverseParentInFlatTree = async (node) => {
            if (node.hasAssignedSlot()) {
                return await node.assignedSlot?.deferredNode.resolvePromise() ?? null;
            }
            return node.parentNode;
        };
        for (let i = 0; parentNode && inheritedPayload && i < inheritedPayload.length; ++i) {
            const inheritedStyles = [];
            const entryPayload = inheritedPayload[i];
            const inheritedAnimatedEntryPayload = inheritedAnimatedPayload[i];
            const inheritedInlineStyle = entryPayload.inlineStyle ?
                new CSSStyleDeclaration(this.#cssModel, null, entryPayload.inlineStyle, Type$3.Inline) :
                null;
            const inheritedTransitionsStyle = inheritedAnimatedEntryPayload?.transitionsStyle ?
                new CSSStyleDeclaration(this.#cssModel, null, inheritedAnimatedEntryPayload?.transitionsStyle, Type$3.Transition) :
                null;
            const inheritedAnimationStyles = inheritedAnimatedEntryPayload?.animationStyles?.map(animationStyle => new CSSStyleDeclaration(this.#cssModel, null, animationStyle.style, Type$3.Animation, animationStyle.name)) ??
                [];
            if (inheritedTransitionsStyle && containsInherited(inheritedTransitionsStyle)) {
                this.#nodeForStyle.set(inheritedTransitionsStyle, parentNode);
                inheritedStyles.push(inheritedTransitionsStyle);
                this.#inheritedStyles.add(inheritedTransitionsStyle);
            }
            for (const inheritedAnimationsStyle of inheritedAnimationStyles) {
                if (!containsInherited(inheritedAnimationsStyle)) {
                    continue;
                }
                this.#nodeForStyle.set(inheritedAnimationsStyle, parentNode);
                inheritedStyles.push(inheritedAnimationsStyle);
                this.#inheritedStyles.add(inheritedAnimationsStyle);
            }
            if (inheritedInlineStyle && containsInherited(inheritedInlineStyle)) {
                this.#nodeForStyle.set(inheritedInlineStyle, parentNode);
                inheritedStyles.push(inheritedInlineStyle);
                this.#inheritedStyles.add(inheritedInlineStyle);
            }
            const inheritedMatchedCSSRules = entryPayload.matchedCSSRules || [];
            for (let j = inheritedMatchedCSSRules.length - 1; j >= 0; --j) {
                const inheritedRule = new CSSStyleRule(this.#cssModel, inheritedMatchedCSSRules[j].rule);
                this.addMatchingSelectors(parentNode, inheritedRule, inheritedMatchedCSSRules[j].matchingSelectors);
                if (!containsInherited(inheritedRule.style)) {
                    continue;
                }
                if (!containsCustomProperties(inheritedRule.style)) {
                    if (containsStyle(nodeStyles, inheritedRule.style) ||
                        containsStyle(this.#inheritedStyles, inheritedRule.style)) {
                        continue;
                    }
                }
                this.#nodeForStyle.set(inheritedRule.style, parentNode);
                inheritedStyles.push(inheritedRule.style);
                this.#inheritedStyles.add(inheritedRule.style);
            }
            const node = parentNode;
            parentNode = await traverseParentInFlatTree(parentNode);
            nodeCascades.push(new NodeCascade(this, inheritedStyles, node, true ));
        }
        return new DOMInheritanceCascade(this, nodeCascades, this.#registeredProperties);
    }
    buildSplitCustomHighlightCascades(rules, node, isInherited, pseudoCascades) {
        const splitHighlightRules = new Map();
        for (let j = rules.length - 1; j >= 0; --j) {
            const highlightNamesToMatchingSelectorIndices = customHighlightNamesToMatchingSelectorIndices(rules[j]);
            for (const [highlightName, matchingSelectors] of highlightNamesToMatchingSelectorIndices) {
                const pseudoRule = new CSSStyleRule(this.#cssModel, rules[j].rule);
                this.#nodeForStyle.set(pseudoRule.style, node);
                if (isInherited) {
                    this.#inheritedStyles.add(pseudoRule.style);
                }
                this.addMatchingSelectors(node, pseudoRule, matchingSelectors);
                const ruleListForHighlightName = splitHighlightRules.get(highlightName);
                if (ruleListForHighlightName) {
                    ruleListForHighlightName.push(pseudoRule.style);
                }
                else {
                    splitHighlightRules.set(highlightName, [pseudoRule.style]);
                }
            }
        }
        for (const [highlightName, highlightStyles] of splitHighlightRules) {
            const nodeCascade = new NodeCascade(this, highlightStyles, node, isInherited, true );
            const cascadeListForHighlightName = pseudoCascades.get(highlightName);
            if (cascadeListForHighlightName) {
                cascadeListForHighlightName.push(nodeCascade);
            }
            else {
                pseudoCascades.set(highlightName, [nodeCascade]);
            }
        }
    }
    buildPseudoCascades(pseudoPayload, inheritedPseudoPayload) {
        const pseudoInheritanceCascades = new Map();
        const customHighlightPseudoInheritanceCascades = new Map();
        if (!pseudoPayload) {
            return [pseudoInheritanceCascades, customHighlightPseudoInheritanceCascades];
        }
        const pseudoCascades = new Map();
        const customHighlightPseudoCascades = new Map();
        for (let i = 0; i < pseudoPayload.length; ++i) {
            const entryPayload = pseudoPayload[i];
            const pseudoElement = this.#node.pseudoElements().get(entryPayload.pseudoType)?.at(-1) || null;
            const pseudoStyles = [];
            const rules = entryPayload.matches || [];
            if (entryPayload.pseudoType === "highlight" ) {
                this.buildSplitCustomHighlightCascades(rules, this.#node, false , customHighlightPseudoCascades);
            }
            else {
                for (let j = rules.length - 1; j >= 0; --j) {
                    const pseudoRule = new CSSStyleRule(this.#cssModel, rules[j].rule);
                    pseudoStyles.push(pseudoRule.style);
                    const nodeForStyle = cssMetadata().isHighlightPseudoType(entryPayload.pseudoType) ? this.#node : pseudoElement;
                    this.#nodeForStyle.set(pseudoRule.style, nodeForStyle);
                    if (nodeForStyle) {
                        this.addMatchingSelectors(nodeForStyle, pseudoRule, rules[j].matchingSelectors);
                    }
                }
                const isHighlightPseudoCascade = cssMetadata().isHighlightPseudoType(entryPayload.pseudoType);
                const nodeCascade = new NodeCascade(this, pseudoStyles, this.#node, false , isHighlightPseudoCascade );
                pseudoCascades.set(entryPayload.pseudoType, [nodeCascade]);
            }
        }
        if (inheritedPseudoPayload) {
            let parentNode = this.#node.parentNode;
            for (let i = 0; parentNode && i < inheritedPseudoPayload.length; ++i) {
                const inheritedPseudoMatches = inheritedPseudoPayload[i].pseudoElements;
                for (let j = 0; j < inheritedPseudoMatches.length; ++j) {
                    const inheritedEntryPayload = inheritedPseudoMatches[j];
                    const rules = inheritedEntryPayload.matches || [];
                    if (inheritedEntryPayload.pseudoType === "highlight" ) {
                        this.buildSplitCustomHighlightCascades(rules, parentNode, true , customHighlightPseudoCascades);
                    }
                    else {
                        const pseudoStyles = [];
                        for (let k = rules.length - 1; k >= 0; --k) {
                            const pseudoRule = new CSSStyleRule(this.#cssModel, rules[k].rule);
                            pseudoStyles.push(pseudoRule.style);
                            this.#nodeForStyle.set(pseudoRule.style, parentNode);
                            this.#inheritedStyles.add(pseudoRule.style);
                            this.addMatchingSelectors(parentNode, pseudoRule, rules[k].matchingSelectors);
                        }
                        const isHighlightPseudoCascade = cssMetadata().isHighlightPseudoType(inheritedEntryPayload.pseudoType);
                        const nodeCascade = new NodeCascade(this, pseudoStyles, parentNode, true , isHighlightPseudoCascade );
                        const cascadeListForPseudoType = pseudoCascades.get(inheritedEntryPayload.pseudoType);
                        if (cascadeListForPseudoType) {
                            cascadeListForPseudoType.push(nodeCascade);
                        }
                        else {
                            pseudoCascades.set(inheritedEntryPayload.pseudoType, [nodeCascade]);
                        }
                    }
                }
                parentNode = parentNode.parentNode;
            }
        }
        for (const [pseudoType, nodeCascade] of pseudoCascades.entries()) {
            pseudoInheritanceCascades.set(pseudoType, new DOMInheritanceCascade(this, nodeCascade, this.#registeredProperties, this.#mainDOMCascade));
        }
        for (const [highlightName, nodeCascade] of customHighlightPseudoCascades.entries()) {
            customHighlightPseudoInheritanceCascades.set(highlightName, new DOMInheritanceCascade(this, nodeCascade, this.#registeredProperties, this.#mainDOMCascade));
        }
        return [pseudoInheritanceCascades, customHighlightPseudoInheritanceCascades];
    }
    addMatchingSelectors(node, rule, matchingSelectorIndices) {
        for (const matchingSelectorIndex of matchingSelectorIndices) {
            const selector = rule.selectors[matchingSelectorIndex];
            if (selector) {
                this.setSelectorMatches(node, selector.text, true);
            }
        }
    }
    node() {
        return this.#node;
    }
    cssModel() {
        return this.#cssModel;
    }
    hasMatchingSelectors(rule) {
        return (rule.selectors.length === 0 || this.getMatchingSelectors(rule).length > 0) && queryMatches(rule.style);
    }
    getParentLayoutNodeId() {
        return this.#parentLayoutNodeId;
    }
    getMatchingSelectors(rule) {
        const node = this.nodeForStyle(rule.style);
        if (!node || typeof node.id !== 'number') {
            return [];
        }
        const map = this.#matchingSelectors.get(node.id);
        if (!map) {
            return [];
        }
        const result = [];
        for (let i = 0; i < rule.selectors.length; ++i) {
            if (map.get(rule.selectors[i].text)) {
                result.push(i);
            }
        }
        return result;
    }
    async recomputeMatchingSelectors(rule) {
        const node = this.nodeForStyle(rule.style);
        if (!node) {
            return;
        }
        const promises = [];
        for (const selector of rule.selectors) {
            promises.push(querySelector.call(this, node, selector.text));
        }
        await Promise.all(promises);
        async function querySelector(node, selectorText) {
            const ownerDocument = node.ownerDocument;
            if (!ownerDocument) {
                return;
            }
            if (typeof node.id === 'number') {
                const map = this.#matchingSelectors.get(node.id);
                if (map?.has(selectorText)) {
                    return;
                }
            }
            if (typeof ownerDocument.id !== 'number') {
                return;
            }
            const matchingNodeIds = await this.#node.domModel().querySelectorAll(ownerDocument.id, selectorText);
            if (matchingNodeIds) {
                if (typeof node.id === 'number') {
                    this.setSelectorMatches(node, selectorText, matchingNodeIds.indexOf(node.id) !== -1);
                }
                else {
                    this.setSelectorMatches(node, selectorText, false);
                }
            }
        }
    }
    addNewRule(rule, node) {
        this.#addedStyles.set(rule.style, node);
        return this.recomputeMatchingSelectors(rule);
    }
    setSelectorMatches(node, selectorText, value) {
        if (typeof node.id !== 'number') {
            return;
        }
        let map = this.#matchingSelectors.get(node.id);
        if (!map) {
            map = new Map();
            this.#matchingSelectors.set(node.id, map);
        }
        map.set(selectorText, value);
    }
    nodeStyles() {
        assertNotNullOrUndefined(this.#mainDOMCascade);
        return this.#mainDOMCascade.styles();
    }
    inheritedStyles() {
        return this.#mainDOMCascade?.styles().filter(style => this.isInherited(style)) ?? [];
    }
    animationStyles() {
        return this.#mainDOMCascade?.styles().filter(style => !this.isInherited(style) && style.type === Type$3.Animation) ??
            [];
    }
    transitionsStyle() {
        return this.#mainDOMCascade?.styles().find(style => !this.isInherited(style) && style.type === Type$3.Transition) ??
            null;
    }
    registeredProperties() {
        return this.#registeredProperties;
    }
    getRegisteredProperty(name) {
        return this.#registeredPropertyMap.get(name);
    }
    getRegisteredFunction(name) {
        const functionRule = this.#functionRuleMap.get(name);
        return functionRule ? functionRule.nameWithParameters() : undefined;
    }
    functionRules() {
        return this.#functionRules;
    }
    atRules() {
        return this.#atRules;
    }
    keyframes() {
        return this.#keyframes;
    }
    positionTryRules() {
        return this.#positionTryRules;
    }
    activePositionFallbackIndex() {
        return this.#activePositionFallbackIndex;
    }
    pseudoStyles(pseudoType) {
        assertNotNullOrUndefined(this.#pseudoDOMCascades);
        const domCascade = this.#pseudoDOMCascades.get(pseudoType);
        return domCascade ? domCascade.styles() : [];
    }
    pseudoTypes() {
        assertNotNullOrUndefined(this.#pseudoDOMCascades);
        return new Set(this.#pseudoDOMCascades.keys());
    }
    customHighlightPseudoStyles(highlightName) {
        assertNotNullOrUndefined(this.#customHighlightPseudoDOMCascades);
        const domCascade = this.#customHighlightPseudoDOMCascades.get(highlightName);
        return domCascade ? domCascade.styles() : [];
    }
    customHighlightPseudoNames() {
        assertNotNullOrUndefined(this.#customHighlightPseudoDOMCascades);
        return new Set(this.#customHighlightPseudoDOMCascades.keys());
    }
    nodeForStyle(style) {
        return this.#addedStyles.get(style) || this.#nodeForStyle.get(style) || null;
    }
    availableCSSVariables(style) {
        const domCascade = this.#styleToDOMCascade.get(style);
        return domCascade ? domCascade.findAvailableCSSVariables(style) : [];
    }
    computeCSSVariable(style, variableName) {
        if (style.parentRule instanceof CSSKeyframeRule) {
            const keyframeName = style.parentRule.parentRuleName();
            const activeStyle = this.#mainDOMCascade?.styles().find(searchStyle => {
                return searchStyle.allProperties().some(property => property.name === 'animation-name' && property.value === keyframeName &&
                    this.#mainDOMCascade?.propertyState(property) === "Active" );
            });
            if (!activeStyle) {
                return null;
            }
            style = activeStyle;
        }
        const domCascade = this.#styleToDOMCascade.get(style);
        return domCascade ? domCascade.computeCSSVariable(style, variableName) : null;
    }
    computeAttribute(style, attributeName, type) {
        const domCascade = this.#styleToDOMCascade.get(style);
        return domCascade ? domCascade.computeAttribute(style, attributeName, type) : null;
    }
    originatingNodeForStyle(style) {
        let node = this.nodeForStyle(style) ?? this.node();
        while (node?.pseudoType()) {
            node = node.parentNode;
        }
        return node;
    }
    rawAttributeValueFromStyle(style, attributeName) {
        const node = this.originatingNodeForStyle(style);
        if (!node) {
            return null;
        }
        return node.getAttribute(attributeName) ?? null;
    }
    resolveProperty(name, ownerStyle) {
        return this.#styleToDOMCascade.get(ownerStyle)?.resolveProperty(name, ownerStyle) ?? null;
    }
    resolveGlobalKeyword(property, keyword) {
        const resolved = this.#styleToDOMCascade.get(property.ownerStyle)?.resolveGlobalKeyword(property, keyword);
        return resolved ? new CSSValueSource(resolved) : null;
    }
    isInherited(style) {
        return this.#inheritedStyles.has(style);
    }
    propertyState(property) {
        const domCascade = this.#styleToDOMCascade.get(property.ownerStyle);
        return domCascade ? domCascade.propertyState(property) : null;
    }
    isPropertyOverriddenByAnimation(property) {
        const domCascade = this.#styleToDOMCascade.get(property.ownerStyle);
        return domCascade?.isPropertyOverriddenByAnimation(property) ?? false;
    }
    resetActiveProperties() {
        assertNotNullOrUndefined(this.#mainDOMCascade);
        assertNotNullOrUndefined(this.#pseudoDOMCascades);
        assertNotNullOrUndefined(this.#customHighlightPseudoDOMCascades);
        this.#mainDOMCascade.reset();
        for (const domCascade of this.#pseudoDOMCascades.values()) {
            domCascade.reset();
        }
        for (const domCascade of this.#customHighlightPseudoDOMCascades.values()) {
            domCascade.reset();
        }
    }
    propertyMatchers(style, computedStyles) {
        return [
            new VariableMatcher(this, style),
            new ColorMatcher(() => computedStyles?.get('color') ?? null),
            new ColorMixMatcher(),
            new URLMatcher(),
            new AngleMatcher(),
            new LinkableNameMatcher(),
            new BezierMatcher(),
            new StringMatcher(),
            new ShadowMatcher(),
            new LightDarkColorMatcher(style),
            new GridTemplateMatcher(),
            new LinearGradientMatcher(),
            new AnchorFunctionMatcher(),
            new PositionAnchorMatcher(),
            new FlexGridGridLanesMatcher(),
            new PositionTryMatcher(),
            new LengthMatcher(),
            new MathFunctionMatcher(),
            new CustomFunctionMatcher(),
            new AutoBaseMatcher(),
            new BinOpMatcher(),
            new RelativeColorChannelMatcher(),
            new AttributeMatcher(this, style),
            new EnvFunctionMatcher(this),
        ];
    }
    environmentVariable(name) {
        return this.#environmentVariables[name];
    }
}
class NodeCascade {
    isHighlightPseudoCascade;
    #matchedStyles;
    styles;
    #isInherited;
    propertiesState = new Map();
    propertiesOverriddenByAnimation = new Set();
    activeProperties = new Map();
    #node;
    constructor(matchedStyles, styles, node, isInherited, isHighlightPseudoCascade = false) {
        this.isHighlightPseudoCascade = isHighlightPseudoCascade;
        this.#matchedStyles = matchedStyles;
        this.styles = styles;
        this.#isInherited = isInherited;
        this.#node = node;
    }
    computeActiveProperties() {
        this.propertiesState.clear();
        this.propertiesOverriddenByAnimation.clear();
        this.activeProperties.clear();
        for (let i = this.styles.length - 1; i >= 0; i--) {
            const style = this.styles[i];
            const rule = style.parentRule;
            if (rule && !(rule instanceof CSSStyleRule)) {
                continue;
            }
            if (rule && !this.#matchedStyles.hasMatchingSelectors(rule)) {
                continue;
            }
            for (const property of style.allProperties()) {
                const metadata = cssMetadata();
                if (this.#isInherited) {
                    if (this.isHighlightPseudoCascade) {
                        if (property.name.startsWith('--')) {
                            continue;
                        }
                    }
                    else if (!metadata.isPropertyInherited(property.name)) {
                        continue;
                    }
                }
                if (style.range && !property.range) {
                    continue;
                }
                if (!property.activeInStyle()) {
                    this.propertiesState.set(property, "Overloaded" );
                    continue;
                }
                if (this.#isInherited) {
                    const registration = this.#matchedStyles.getRegisteredProperty(property.name);
                    if (registration && !registration.inherits()) {
                        this.propertiesState.set(property, "Overloaded" );
                        continue;
                    }
                }
                const canonicalName = metadata.canonicalPropertyName(property.name);
                this.updatePropertyState(property, canonicalName);
                for (const longhand of property.getLonghandProperties()) {
                    if (metadata.isCSSPropertyName(longhand.name)) {
                        this.updatePropertyState(longhand, longhand.name);
                    }
                }
            }
        }
    }
    #treeScopeDistance(property) {
        if (!property.ownerStyle.parentRule && property.ownerStyle.type !== Type$3.Inline) {
            return -1;
        }
        const root = this.#node.getTreeRoot();
        const nodeId = property.ownerStyle.parentRule?.treeScope ?? root?.backendNodeId();
        if (nodeId === undefined) {
            return -1;
        }
        let distance = 0;
        for (let ancestor = this.#node; ancestor; ancestor = ancestor.parentNode) {
            if (ancestor.backendNodeId() === nodeId) {
                return distance;
            }
            distance++;
        }
        return -1;
    }
    #needsCascadeContextStep() {
        if (!this.#node.isInShadowTree()) {
            return false;
        }
        if (this.#node.ancestorShadowRoot()?.shadowRootType() === 'user-agent') {
            const pseudoElement = this.#node.getAttribute('pseudo');
            return !pseudoElement?.startsWith('-webkit-') && !pseudoElement?.startsWith('-internal-');
        }
        return true;
    }
    updatePropertyState(propertyWithHigherSpecificity, canonicalName) {
        const activeProperty = this.activeProperties.get(canonicalName);
        if (activeProperty?.important && !propertyWithHigherSpecificity.important ||
            activeProperty && this.#needsCascadeContextStep() &&
                this.#treeScopeDistance(activeProperty) > this.#treeScopeDistance(propertyWithHigherSpecificity)) {
            this.propertiesState.set(propertyWithHigherSpecificity, "Overloaded" );
            return;
        }
        if (activeProperty) {
            this.propertiesState.set(activeProperty, "Overloaded" );
            if (propertyWithHigherSpecificity.ownerStyle.type === Type$3.Animation ||
                propertyWithHigherSpecificity.ownerStyle.type === Type$3.Transition) {
                this.propertiesOverriddenByAnimation.add(activeProperty);
            }
        }
        this.propertiesState.set(propertyWithHigherSpecificity, "Active" );
        this.activeProperties.set(canonicalName, propertyWithHigherSpecificity);
    }
}
function isRegular(declaration) {
    return 'ownerStyle' in declaration;
}
class CSSValueSource {
    declaration;
    constructor(declaration) {
        this.declaration = declaration;
    }
    get value() {
        return isRegular(this.declaration) ? this.declaration.value : this.declaration.initialValue();
    }
    get style() {
        return isRegular(this.declaration) ? this.declaration.ownerStyle : this.declaration.style();
    }
    get name() {
        return isRegular(this.declaration) ? this.declaration.name : this.declaration.propertyName();
    }
}
class SCCRecordEntry {
    nodeCascade;
    name;
    discoveryTime;
    rootDiscoveryTime;
    get isRootEntry() {
        return this.rootDiscoveryTime === this.discoveryTime;
    }
    updateRoot(neighbor) {
        this.rootDiscoveryTime = Math.min(this.rootDiscoveryTime, neighbor.rootDiscoveryTime);
    }
    constructor(nodeCascade, name, discoveryTime) {
        this.nodeCascade = nodeCascade;
        this.name = name;
        this.discoveryTime = discoveryTime;
        this.rootDiscoveryTime = discoveryTime;
    }
}
class SCCRecord {
    #time = 0;
    #stack = [];
    #entries = new Map();
    get(nodeCascade, variable) {
        return this.#entries.get(nodeCascade)?.get(variable);
    }
    add(nodeCascade, variable) {
        const existing = this.get(nodeCascade, variable);
        if (existing) {
            return existing;
        }
        const entry = new SCCRecordEntry(nodeCascade, variable, this.#time++);
        this.#stack.push(entry);
        let map = this.#entries.get(nodeCascade);
        if (!map) {
            map = new Map();
            this.#entries.set(nodeCascade, map);
        }
        map.set(variable, entry);
        return entry;
    }
    isInInProgressSCC(childRecord) {
        return this.#stack.includes(childRecord);
    }
    finishSCC(root) {
        const startIndex = this.#stack.lastIndexOf(root);
        console.assert(startIndex >= 0, 'Root is not an in-progress scc');
        return this.#stack.splice(startIndex);
    }
}
function* forEach(array, startAfter) {
    const startIdx = startAfter !== undefined ? array.indexOf(startAfter) + 1 : 0;
    for (let i = startIdx; i < array.length; ++i) {
        yield array[i];
    }
}
class DOMInheritanceCascade {
    #propertiesState = new Map();
    #propertiesOverriddenByAnimation = new Set();
    #availableCSSVariables = new Map();
    #computedCSSVariables = new Map();
    #styleToNodeCascade = new Map();
    #initialized = false;
    #nodeCascades;
    #registeredProperties;
    #matchedStyles;
    #fallbackCascade = null;
    #styles = [];
    constructor(matchedStyles, nodeCascades, registeredProperties, fallbackCascade = null) {
        this.#nodeCascades = nodeCascades;
        this.#matchedStyles = matchedStyles;
        this.#registeredProperties = registeredProperties;
        this.#fallbackCascade = fallbackCascade;
        for (const nodeCascade of nodeCascades) {
            for (const style of nodeCascade.styles) {
                this.#styleToNodeCascade.set(style, nodeCascade);
                this.#styles.push(style);
            }
        }
        if (fallbackCascade) {
            for (const [style, nodeCascade] of fallbackCascade.#styleToNodeCascade) {
                if (!this.#styles.includes(style)) {
                    this.#styleToNodeCascade.set(style, nodeCascade);
                }
            }
        }
    }
    findAvailableCSSVariables(style) {
        const nodeCascade = this.#styleToNodeCascade.get(style);
        if (!nodeCascade) {
            return [];
        }
        this.ensureInitialized();
        const availableCSSVariables = this.#availableCSSVariables.get(nodeCascade);
        if (!availableCSSVariables) {
            return [];
        }
        return Array.from(availableCSSVariables.keys());
    }
    #findPropertyInPreviousStyle(property, filter) {
        const cascade = this.#styleToNodeCascade.get(property.ownerStyle);
        if (!cascade) {
            return null;
        }
        for (const style of forEach(cascade.styles, property.ownerStyle)) {
            const candidate = style.allProperties().findLast(candidate => candidate.name === property.name && filter(candidate));
            if (candidate) {
                return candidate;
            }
        }
        return null;
    }
    resolveProperty(name, ownerStyle) {
        const cascade = this.#styleToNodeCascade.get(ownerStyle);
        if (!cascade) {
            return null;
        }
        for (const style of cascade.styles) {
            const candidate = style.allProperties().findLast(candidate => candidate.name === name);
            if (candidate) {
                return candidate;
            }
        }
        return this.#findPropertyInParentCascadeIfInherited({ name, ownerStyle });
    }
    #findPropertyInParentCascade(property) {
        const nodeCascade = this.#styleToNodeCascade.get(property.ownerStyle);
        if (!nodeCascade) {
            return null;
        }
        for (const cascade of forEach(this.#nodeCascades, nodeCascade)) {
            for (const style of cascade.styles) {
                const inheritedProperty = style.allProperties().findLast(inheritedProperty => inheritedProperty.name === property.name);
                if (inheritedProperty) {
                    return inheritedProperty;
                }
            }
        }
        if (this.#fallbackCascade && (!nodeCascade.isHighlightPseudoCascade || property.name.startsWith('--'))) {
            return this.#fallbackCascade.resolveProperty(property.name, property.ownerStyle);
        }
        return null;
    }
    #findPropertyInParentCascadeIfInherited(property) {
        if (!cssMetadata().isPropertyInherited(property.name) ||
            !(this.#findCustomPropertyRegistration(property.name)?.inherits() ?? true)) {
            return null;
        }
        return this.#findPropertyInParentCascade(property);
    }
    #findCustomPropertyRegistration(property) {
        const registration = this.#registeredProperties.find(registration => registration.propertyName() === property);
        return registration ? registration : null;
    }
    resolveGlobalKeyword(property, keyword) {
        const isPreviousLayer = (other) => {
            if (!(other.ownerStyle.parentRule instanceof CSSStyleRule)) {
                return false;
            }
            if (property.ownerStyle.type === Type$3.Inline) {
                return true;
            }
            if (property.ownerStyle.parentRule instanceof CSSStyleRule &&
                other.ownerStyle.parentRule?.origin === "regular" ) {
                return JSON.stringify(other.ownerStyle.parentRule.layers) !==
                    JSON.stringify(property.ownerStyle.parentRule.layers);
            }
            return false;
        };
        switch (keyword) {
            case "initial" :
                return this.#findCustomPropertyRegistration(property.name);
            case "inherit" :
                return this.#findPropertyInParentCascade(property) ?? this.#findCustomPropertyRegistration(property.name);
            case "revert" :
                return this.#findPropertyInPreviousStyle(property, other => other.ownerStyle.parentRule !== null &&
                    other.ownerStyle.parentRule.origin !==
                        (property.ownerStyle.parentRule?.origin ?? "regular" )) ??
                    this.resolveGlobalKeyword(property, "unset" );
            case "revert-layer" :
                return this.#findPropertyInPreviousStyle(property, isPreviousLayer) ??
                    this.resolveGlobalKeyword(property, "revert" );
            case "revert-rule" :
                return this.#findPropertyInPreviousStyle(property, () => true) ??
                    this.resolveGlobalKeyword(property, "unset" );
            case "unset" :
                return this.#findPropertyInParentCascadeIfInherited(property) ??
                    this.#findCustomPropertyRegistration(property.name);
        }
    }
    computeCSSVariable(style, variableName) {
        this.ensureInitialized();
        const nodeCascade = this.#styleToNodeCascade.get(style);
        if (!nodeCascade) {
            return null;
        }
        return this.#computeCSSVariable(nodeCascade, variableName);
    }
    #computeCSSVariable(nodeCascade, variableName, sccRecord = new SCCRecord()) {
        const availableCSSVariables = this.#availableCSSVariables.get(nodeCascade);
        const computedCSSVariables = this.#computedCSSVariables.get(nodeCascade);
        if (!computedCSSVariables || !availableCSSVariables?.has(variableName)) {
            return null;
        }
        if (computedCSSVariables?.has(variableName)) {
            return computedCSSVariables.get(variableName) || null;
        }
        let definedValue = availableCSSVariables.get(variableName);
        if (definedValue === undefined || definedValue === null) {
            return null;
        }
        if (definedValue.declaration.declaration instanceof CSSProperty && definedValue.declaration.value &&
            CSSMetadata.isCSSWideKeyword(definedValue.declaration.value)) {
            const resolvedProperty = this.resolveGlobalKeyword(definedValue.declaration.declaration, definedValue.declaration.value);
            if (!resolvedProperty) {
                return definedValue;
            }
            const declaration = new CSSValueSource(resolvedProperty);
            const { value } = declaration;
            if (!value) {
                return definedValue;
            }
            definedValue = { declaration, value };
        }
        const ast = tokenizeDeclaration(`--${variableName}`, definedValue.value);
        if (!ast) {
            return null;
        }
        return this.#walkTree(nodeCascade, ast, definedValue.declaration.style, variableName, sccRecord, definedValue.declaration);
    }
    computeAttribute(style, attributeName, type) {
        this.ensureInitialized();
        const nodeCascade = this.#styleToNodeCascade.get(style);
        if (!nodeCascade) {
            return null;
        }
        return this.#computeAttribute(nodeCascade, style, attributeName, type, new SCCRecord());
    }
    attributeValueAsType(style, attributeName, type) {
        const rawValue = this.#matchedStyles.rawAttributeValueFromStyle(style, attributeName);
        if (rawValue === null) {
            return null;
        }
        return localEvalCSS(rawValue, type);
    }
    attributeValueWithSubstitutions(nodeCascade, style, attributeName, sccRecord) {
        const rawValue = this.#matchedStyles.rawAttributeValueFromStyle(style, attributeName);
        if (rawValue === null) {
            return null;
        }
        const ast = tokenizeDeclaration('--property', rawValue);
        if (!ast) {
            return null;
        }
        return this.#walkTree(nodeCascade, ast, style, `attr(${attributeName})`, sccRecord)?.value ?? null;
    }
    #computeAttribute(nodeCascade, style, attributeName, type, sccRecord = new SCCRecord()) {
        if (type.isCSSTokens) {
            const value = this.attributeValueWithSubstitutions(nodeCascade, style, attributeName, sccRecord);
            if (value !== null && localEvalCSS(value, type.type) !== null) {
                return value;
            }
            return null;
        }
        return this.attributeValueAsType(style, attributeName, type.type);
    }
    #walkTree(outerNodeCascade, ast, parentStyle, substitutionName, sccRecord, declaration) {
        const record = sccRecord.add(outerNodeCascade, substitutionName);
        const computedCSSVariablesMap = this.#computedCSSVariables;
        const innerNodeCascade = this.#styleToNodeCascade.get(parentStyle);
        const matching = BottomUpTreeMatching.walk(ast, [
            new BaseVariableMatcher(match => {
                const { value, mayFallback } = recurseWithCycleDetection(match.name, nodeCascade => this.#computeCSSVariable(nodeCascade, match.name, sccRecord)?.value ?? null);
                if (!mayFallback || value !== null) {
                    return value;
                }
                if (!match.fallback) {
                    return null;
                }
                return evaluateFallback(match.fallback, match.matching);
            }),
            new EnvFunctionMatcher(this.#matchedStyles),
            new AttributeMatcher(this.#matchedStyles, parentStyle, match => {
                const recordName = `attr(${match.name})`;
                let attributeValue = null;
                if (!match.isCSSTokens) {
                    const { value, mayFallback } = recurseWithCycleDetection(recordName, () => this.attributeValueAsType(parentStyle, match.name, match.cssType()));
                    if (value === null && !mayFallback) {
                        return null;
                    }
                    attributeValue = value;
                }
                else {
                    const { value, mayFallback } = recurseWithCycleDetection(recordName, nodeCascade => this.attributeValueWithSubstitutions(nodeCascade, parentStyle, match.name, sccRecord));
                    if (value === null && !mayFallback) {
                        return null;
                    }
                    if (value !== null && localEvalCSS(value, match.cssType()) !== null) {
                        attributeValue = value;
                    }
                }
                if (attributeValue !== null) {
                    return attributeValue;
                }
                if (!match.fallback || !match.isValidType) {
                    return defaultValueForCSSType(match.type);
                }
                return evaluateFallback(match.fallback, match.matching);
            })
        ]);
        const decl = ASTUtils.siblings(ASTUtils.declValue(matching.ast.tree));
        const declText = decl.length > 0 ? matching.getComputedTextRange(decl[0], decl[decl.length - 1]) : '';
        const hasUnresolvedSubstitutions = decl.length > 0 && matching.hasUnresolvedSubstitutionsRange(decl[0], decl[decl.length - 1]);
        const computedText = hasUnresolvedSubstitutions ? null : declText;
        const outerComputedCSSVariables = computedCSSVariablesMap.get(outerNodeCascade);
        if (!outerComputedCSSVariables) {
            return null;
        }
        if (record.isRootEntry) {
            const scc = sccRecord.finishSCC(record);
            if (scc.length > 1) {
                for (const entry of scc) {
                    console.assert(entry.nodeCascade === outerNodeCascade, 'Circles should be within the cascade');
                    outerComputedCSSVariables.set(entry.name, null);
                }
                return null;
            }
        }
        if (computedText === null) {
            outerComputedCSSVariables.set(substitutionName, null);
            return null;
        }
        const cssVariableValue = { value: computedText, declaration };
        outerComputedCSSVariables.set(substitutionName, cssVariableValue);
        return cssVariableValue;
        function recurseWithCycleDetection(recordName, func) {
            if (!innerNodeCascade) {
                return { value: null, mayFallback: false };
            }
            const childRecord = sccRecord.get(innerNodeCascade, recordName);
            if (childRecord) {
                if (sccRecord.isInInProgressSCC(childRecord)) {
                    record.updateRoot(childRecord);
                    return { value: null, mayFallback: false };
                }
                return {
                    value: computedCSSVariablesMap.get(innerNodeCascade)?.get(recordName)?.value ?? null,
                    mayFallback: false
                };
            }
            const value = func(innerNodeCascade);
            const newChildRecord = sccRecord.get(innerNodeCascade, recordName);
            newChildRecord && record.updateRoot(newChildRecord);
            return { value, mayFallback: true };
        }
        function evaluateFallback(fallback, matching) {
            if (fallback.length === 0) {
                return '';
            }
            if (matching.hasUnresolvedSubstitutionsRange(fallback[0], fallback[fallback.length - 1])) {
                return null;
            }
            return matching.getComputedTextRange(fallback[0], fallback[fallback.length - 1]);
        }
    }
    styles() {
        return this.#styles;
    }
    propertyState(property) {
        this.ensureInitialized();
        return this.#propertiesState.get(property) || null;
    }
    isPropertyOverriddenByAnimation(property) {
        this.ensureInitialized();
        return this.#propertiesOverriddenByAnimation.has(property);
    }
    reset() {
        this.#initialized = false;
        this.#propertiesState.clear();
        this.#propertiesOverriddenByAnimation.clear();
        this.#availableCSSVariables.clear();
        this.#computedCSSVariables.clear();
    }
    ensureInitialized() {
        if (this.#initialized) {
            return;
        }
        this.#initialized = true;
        const activeProperties = new Map();
        for (const nodeCascade of this.#nodeCascades) {
            nodeCascade.computeActiveProperties();
            for (const [property, state] of nodeCascade.propertiesState) {
                if (state === "Overloaded" ) {
                    this.#propertiesState.set(property, "Overloaded" );
                    if (nodeCascade.propertiesOverriddenByAnimation.has(property)) {
                        this.#propertiesOverriddenByAnimation.add(property);
                    }
                    continue;
                }
                const canonicalName = cssMetadata().canonicalPropertyName(property.name);
                if (activeProperties.has(canonicalName)) {
                    this.#propertiesState.set(property, "Overloaded" );
                    const activeProperty = activeProperties.get(canonicalName);
                    if (activeProperty &&
                        (activeProperty.ownerStyle.type === Type$3.Animation ||
                            activeProperty.ownerStyle.type === Type$3.Transition)) {
                        this.#propertiesOverriddenByAnimation.add(property);
                    }
                    continue;
                }
                activeProperties.set(canonicalName, property);
                this.#propertiesState.set(property, "Active" );
            }
        }
        for (const [canonicalName, shorthandProperty] of activeProperties) {
            const shorthandStyle = shorthandProperty.ownerStyle;
            const longhands = shorthandProperty.getLonghandProperties();
            if (!longhands.length) {
                continue;
            }
            let hasActiveLonghands = false;
            for (const longhand of longhands) {
                const longhandCanonicalName = cssMetadata().canonicalPropertyName(longhand.name);
                const longhandActiveProperty = activeProperties.get(longhandCanonicalName);
                if (!longhandActiveProperty) {
                    continue;
                }
                if (longhandActiveProperty.ownerStyle === shorthandStyle) {
                    hasActiveLonghands = true;
                    break;
                }
            }
            if (hasActiveLonghands) {
                continue;
            }
            activeProperties.delete(canonicalName);
            this.#propertiesState.set(shorthandProperty, "Overloaded" );
        }
        const accumulatedCSSVariables = new Map();
        for (const rule of this.#registeredProperties) {
            const initialValue = rule.initialValue();
            accumulatedCSSVariables.set(rule.propertyName(), initialValue !== null ? { value: initialValue, declaration: new CSSValueSource(rule) } : null);
        }
        if (this.#fallbackCascade) {
            this.#fallbackCascade.ensureInitialized();
            for (const [cascade, available] of this.#fallbackCascade.#availableCSSVariables) {
                this.#availableCSSVariables.set(cascade, available);
            }
            for (const [cascade, computed] of this.#fallbackCascade.#computedCSSVariables) {
                this.#computedCSSVariables.set(cascade, computed);
            }
            for (const [key, value] of this.#fallbackCascade.#availableCSSVariables.get(this.#fallbackCascade.#nodeCascades[0]) ??
                []) {
                accumulatedCSSVariables.set(key, value);
            }
        }
        for (let i = this.#nodeCascades.length - 1; i >= 0; --i) {
            const nodeCascade = this.#nodeCascades[i];
            const variableNames = [];
            for (const entry of nodeCascade.activeProperties.entries()) {
                const propertyName = entry[0];
                const property = entry[1];
                if (propertyName.startsWith('--')) {
                    accumulatedCSSVariables.set(propertyName, { value: property.value, declaration: new CSSValueSource(property) });
                    variableNames.push(propertyName);
                }
            }
            const availableCSSVariablesMap = new Map(accumulatedCSSVariables);
            const computedVariablesMap = new Map();
            this.#availableCSSVariables.set(nodeCascade, availableCSSVariablesMap);
            this.#computedCSSVariables.set(nodeCascade, computedVariablesMap);
            for (const variableName of variableNames) {
                const prevValue = accumulatedCSSVariables.get(variableName);
                accumulatedCSSVariables.delete(variableName);
                const computedValue = this.#computeCSSVariable(nodeCascade, variableName);
                if (prevValue && computedValue?.value === prevValue.value) {
                    computedValue.declaration = prevValue.declaration;
                }
                accumulatedCSSVariables.set(variableName, computedValue);
            }
        }
    }
}

// Copyright 2016 The Chromium Authors
const UIStrings$15 = {
    couldNotFindTheOriginalStyle: 'Could not find the original style sheet.',
    thereWasAnErrorRetrievingThe: 'There was an error retrieving the source styles.',
};
const str_$14 = registerUIStrings('core/sdk/CSSStyleSheetHeader.ts', UIStrings$15);
const i18nString$O = getLocalizedString.bind(undefined, str_$14);
class CSSStyleSheetHeader {
    #cssModel;
    id;
    frameId;
    sourceURL;
    hasSourceURL;
    origin;
    title;
    disabled;
    isInline;
    isMutable;
    isConstructed;
    startLine;
    startColumn;
    endLine;
    endColumn;
    contentLength;
    ownerNode;
    sourceMapURL;
    loadingFailed;
    #originalContentProvider;
    constructor(cssModel, payload) {
        this.#cssModel = cssModel;
        this.id = payload.styleSheetId;
        this.frameId = payload.frameId;
        this.sourceURL = payload.sourceURL;
        this.hasSourceURL = Boolean(payload.hasSourceURL);
        this.origin = payload.origin;
        this.title = payload.title;
        this.disabled = payload.disabled;
        this.isInline = payload.isInline;
        this.isMutable = payload.isMutable;
        this.isConstructed = payload.isConstructed;
        this.startLine = payload.startLine;
        this.startColumn = payload.startColumn;
        this.endLine = payload.endLine;
        this.endColumn = payload.endColumn;
        this.contentLength = payload.length;
        if (payload.ownerNode) {
            this.ownerNode = new DeferredDOMNode(cssModel.target(), payload.ownerNode);
        }
        this.sourceMapURL = payload.sourceMapURL;
        this.loadingFailed = payload.loadingFailed ?? false;
        this.#originalContentProvider = null;
    }
    originalContentProvider() {
        if (!this.#originalContentProvider) {
            const lazyContent = (async () => {
                const originalText = await this.#cssModel.originalStyleSheetText(this);
                if (originalText === null) {
                    return { error: i18nString$O(UIStrings$15.couldNotFindTheOriginalStyle) };
                }
                return new ContentData(originalText,  false, 'text/css');
            });
            this.#originalContentProvider =
                new StaticContentProvider(this.contentURL(), this.contentType(), lazyContent);
        }
        return this.#originalContentProvider;
    }
    setSourceMapURL(sourceMapURL) {
        this.sourceMapURL = sourceMapURL;
    }
    cssModel() {
        return this.#cssModel;
    }
    isAnonymousInlineStyleSheet() {
        return !this.resourceURL() && !this.#cssModel.sourceMapManager().sourceMapForClient(this);
    }
    isConstructedByNew() {
        return this.isConstructed && this.sourceURL.length === 0;
    }
    resourceURL() {
        return this.isViaInspector() ? this.viaInspectorResourceURL() : this.sourceURL;
    }
    getFrameURLPath() {
        const model = this.#cssModel.target().model(ResourceTreeModel);
        console.assert(Boolean(model));
        if (!model) {
            return '';
        }
        const frame = model.frameForId(this.frameId);
        if (!frame) {
            return '';
        }
        console.assert(Boolean(frame));
        const parsedURL = new ParsedURL(frame.url);
        let urlPath = parsedURL.host;
        if (parsedURL.port) {
            urlPath += ':' + parsedURL.port;
        }
        urlPath += parsedURL.folderPathComponents;
        if (!urlPath.endsWith('/')) {
            urlPath += '/';
        }
        return urlPath;
    }
    viaInspectorResourceURL() {
        return `inspector://${this.getFrameURLPath()}inspector-stylesheet#${this.id}`;
    }
    lineNumberInSource(lineNumberInStyleSheet) {
        return this.startLine + lineNumberInStyleSheet;
    }
    columnNumberInSource(lineNumberInStyleSheet, columnNumberInStyleSheet) {
        return (lineNumberInStyleSheet ? 0 : this.startColumn) + columnNumberInStyleSheet;
    }
    containsLocation(lineNumber, columnNumber) {
        const afterStart = (lineNumber === this.startLine && columnNumber >= this.startColumn) || lineNumber > this.startLine;
        const beforeEnd = lineNumber < this.endLine || (lineNumber === this.endLine && columnNumber <= this.endColumn);
        return afterStart && beforeEnd;
    }
    contentURL() {
        return this.resourceURL();
    }
    contentType() {
        return resourceTypes.Stylesheet;
    }
    async requestContentData() {
        const cssText = await this.#cssModel.getStyleSheetText(this.id);
        if (cssText === null) {
            return { error: i18nString$O(UIStrings$15.thereWasAnErrorRetrievingThe) };
        }
        return new ContentData(cssText,  false, 'text/css');
    }
    async searchInContent(query, caseSensitive, isRegex) {
        const contentData = await this.requestContentData();
        return performSearchInContentData(contentData, query, caseSensitive, isRegex);
    }
    isViaInspector() {
        return this.origin === 'inspector';
    }
    createPageResourceLoadInitiator() {
        return {
            target: this.#cssModel.target(),
            frameId: this.frameId,
            initiatorUrl: this.hasSourceURL ? EmptyUrlString : this.sourceURL,
        };
    }
    debugId() {
        return null;
    }
}

// Copyright 2019 The Chromium Authors
const registeredModels = new Map();
class SDKModel extends ObjectWrapper {
    #target;
    constructor(target) {
        super();
        this.#target = target;
    }
    target() {
        return this.#target;
    }
    async preSuspendModel(_reason) {
    }
    async suspendModel(_reason) {
    }
    async resumeModel() {
    }
    async postResumeModel() {
    }
    dispose() {
    }
    static register(modelClass, registrationInfo) {
        if (registrationInfo.early && !registrationInfo.autostart) {
            throw new Error(`Error registering model ${modelClass.name}: early models must be autostarted.`);
        }
        registeredModels.set(modelClass, registrationInfo);
    }
    static get registeredModels() {
        return registeredModels;
    }
}

// Copyright 2020 The Chromium Authors
class IOModel extends SDKModel {
    async read(handle, size, offset) {
        const result = await this.target().ioAgent().invoke_read({ handle, offset, size });
        if (result.getError()) {
            throw new Error(result.getError());
        }
        if (result.eof) {
            return null;
        }
        if (result.base64Encoded) {
            return decode$1(result.data);
        }
        return result.data;
    }
    async close(handle) {
        await this.target().ioAgent().invoke_close({ handle });
    }
    async resolveBlob(objectOrObjectId) {
        const objectId = objectOrObjectId instanceof RemoteObject$1 ? objectOrObjectId.objectId : objectOrObjectId;
        if (!objectId) {
            throw new Error('Remote object has undefined objectId');
        }
        const result = await this.target().ioAgent().invoke_resolveBlob({ objectId });
        if (result.getError()) {
            throw new Error(result.getError());
        }
        return `blob:${result.uuid}`;
    }
    async readToString(handle) {
        const strings = [];
        const decoder = new TextDecoder();
        for (;;) {
            const data = await this.read(handle, 1024 * 1024);
            if (data === null) {
                strings.push(decoder.decode());
                break;
            }
            if (data instanceof Uint8Array) {
                strings.push(decoder.decode(data, { stream: true }));
            }
            else {
                strings.push(data);
            }
        }
        return strings.join('');
    }
    async readToBuffer(handle) {
        const items = [];
        for (;;) {
            const data = await this.read(handle, 1024 * 1024);
            if (data === null) {
                break;
            }
            if (data instanceof Uint8Array) {
                items.push(data);
            }
            else {
                throw new Error('Unexpected stream data type: expected binary, got a string');
            }
        }
        let length = 0;
        for (const item of items) {
            length += item.length;
        }
        const result = new Uint8Array(length);
        let offset = 0;
        for (const item of items) {
            result.set(item, offset);
            offset += item.length;
        }
        return result;
    }
}
SDKModel.register(IOModel, { capabilities: 131072 , autostart: true });

// Copyright 2019 The Chromium Authors
const OPAQUE_PARTITION_KEY = '<opaque>';
class Cookie {
    #name;
    #value;
    #type;
    #attributes = new Map();
    #size = 0;
    #priority;
    #cookieLine = null;
    #partitionKey;
    constructor(name, value, type, priority, partitionKey) {
        this.#name = name;
        this.#value = value;
        this.#type = type;
        this.#priority = (priority || 'Medium');
        this.#partitionKey = partitionKey;
    }
    static fromProtocolCookie(protocolCookie) {
        const cookie = new Cookie(protocolCookie.name, protocolCookie.value, null, protocolCookie.priority);
        cookie.addAttribute("domain" , protocolCookie['domain']);
        cookie.addAttribute("path" , protocolCookie['path']);
        if (protocolCookie['expires']) {
            cookie.addAttribute("expires" , protocolCookie['expires'] * 1000);
        }
        if (protocolCookie['httpOnly']) {
            cookie.addAttribute("http-only" );
        }
        if (protocolCookie['secure']) {
            cookie.addAttribute("secure" );
        }
        if (protocolCookie['sameSite']) {
            cookie.addAttribute("same-site" , protocolCookie['sameSite']);
        }
        if ('sourcePort' in protocolCookie) {
            cookie.addAttribute("source-port" , protocolCookie.sourcePort);
        }
        if ('sourceScheme' in protocolCookie) {
            cookie.addAttribute("source-scheme" , protocolCookie.sourceScheme);
        }
        if ('partitionKey' in protocolCookie) {
            if (protocolCookie.partitionKey) {
                cookie.setPartitionKey(protocolCookie.partitionKey.topLevelSite, protocolCookie.partitionKey.hasCrossSiteAncestor);
            }
        }
        if ('partitionKeyOpaque' in protocolCookie && protocolCookie.partitionKeyOpaque) {
            cookie.addAttribute("partition-key" , OPAQUE_PARTITION_KEY);
        }
        cookie.setSize(protocolCookie['size']);
        return cookie;
    }
    key() {
        return (this.domain() || '-') + ' ' + this.name() + ' ' + (this.path() || '-') + ' ' +
            (this.partitionKey() ?
                (this.topLevelSite() + ' ' + (this.hasCrossSiteAncestor() ? 'cross_site' : 'same_site')) :
                '-');
    }
    name() {
        return this.#name;
    }
    value() {
        return this.#value;
    }
    type() {
        return this.#type;
    }
    httpOnly() {
        return this.#attributes.has("http-only" );
    }
    secure() {
        return this.#attributes.has("secure" );
    }
    partitioned() {
        return this.#attributes.has("partitioned" ) || Boolean(this.partitionKey()) || this.partitionKeyOpaque();
    }
    sameSite() {
        return this.#attributes.get("same-site" );
    }
    partitionKey() {
        return this.#partitionKey;
    }
    setPartitionKey(topLevelSite, hasCrossSiteAncestor) {
        this.#partitionKey = { topLevelSite, hasCrossSiteAncestor };
        if (!this.#attributes.has("partitioned" )) {
            this.addAttribute("partitioned" );
        }
    }
    topLevelSite() {
        if (!this.#partitionKey) {
            return '';
        }
        return this.#partitionKey?.topLevelSite;
    }
    setTopLevelSite(topLevelSite, hasCrossSiteAncestor) {
        this.setPartitionKey(topLevelSite, hasCrossSiteAncestor);
    }
    hasCrossSiteAncestor() {
        if (!this.#partitionKey) {
            return false;
        }
        return this.#partitionKey?.hasCrossSiteAncestor;
    }
    setHasCrossSiteAncestor(hasCrossSiteAncestor) {
        if (!this.partitionKey() || !Boolean(this.topLevelSite())) {
            return;
        }
        this.setPartitionKey(this.topLevelSite(), hasCrossSiteAncestor);
    }
    partitionKeyOpaque() {
        if (!this.#partitionKey) {
            return false;
        }
        return (this.topLevelSite() === OPAQUE_PARTITION_KEY);
    }
    setPartitionKeyOpaque() {
        this.addAttribute("partition-key" , OPAQUE_PARTITION_KEY);
        this.setPartitionKey(OPAQUE_PARTITION_KEY, false);
    }
    priority() {
        return this.#priority;
    }
    session() {
        return !(this.#attributes.has("expires" ) || this.#attributes.has("max-age" ));
    }
    path() {
        return this.#attributes.get("path" );
    }
    domain() {
        return this.#attributes.get("domain" );
    }
    expires() {
        return this.#attributes.get("expires" );
    }
    maxAge() {
        return this.#attributes.get("max-age" );
    }
    sourcePort() {
        return this.#attributes.get("source-port" );
    }
    sourceScheme() {
        return this.#attributes.get("source-scheme" );
    }
    size() {
        return this.#size;
    }
    url() {
        if (!this.domain() || !this.path()) {
            return null;
        }
        let port = '';
        const sourcePort = this.sourcePort();
        if (sourcePort && sourcePort !== 80 && sourcePort !== 443) {
            port = `:${this.sourcePort()}`;
        }
        return (this.secure() ? 'https://' : 'http://') + this.domain() + port + this.path();
    }
    setSize(size) {
        this.#size = size;
    }
    expiresDate(requestDate) {
        if (this.maxAge()) {
            return new Date(requestDate.getTime() + 1000 * this.maxAge());
        }
        if (this.expires()) {
            return new Date(this.expires());
        }
        return null;
    }
    addAttribute(key, value) {
        if (!key) {
            return;
        }
        switch (key) {
            case "priority" :
                this.#priority = value;
                break;
            default:
                this.#attributes.set(key, value);
        }
    }
    hasAttribute(key) {
        return this.#attributes.has(key);
    }
    getAttribute(key) {
        return this.#attributes.get(key);
    }
    setCookieLine(cookieLine) {
        this.#cookieLine = cookieLine;
    }
    getCookieLine() {
        return this.#cookieLine;
    }
    matchesSecurityOrigin(securityOrigin) {
        const hostname = new URL(securityOrigin).hostname;
        return Cookie.isDomainMatch(this.domain(), hostname);
    }
    static isDomainMatch(domain, hostname) {
        if (hostname === domain) {
            return true;
        }
        if (domain?.[0] !== '.') {
            return false;
        }
        if (domain.substr(1) === hostname) {
            return true;
        }
        return hostname.length > domain.length && hostname.endsWith(domain);
    }
}

// Copyright 2017 The Chromium Authors
class CookieModel extends SDKModel {
    #blockedCookies = new Map();
    #cookieToBlockedReasons = new Map();
    #refreshThrottler = new Throttler(300);
    #cookies = new Map();
    constructor(target) {
        super(target);
        target.model(ResourceTreeModel)
            ?.addEventListener(Events$6.PrimaryPageChanged, this.#onPrimaryPageChanged, this);
        target.model(NetworkManager)
            ?.addEventListener(Events$c.ResponseReceived, this.#onResponseReceived, this);
        target.model(NetworkManager)?.addEventListener(Events$c.LoadingFinished, this.#onLoadingFinished, this);
    }
    addBlockedCookie(cookie, blockedReasons) {
        const key = cookie.key();
        const previousCookie = this.#blockedCookies.get(key);
        this.#blockedCookies.set(key, cookie);
        if (blockedReasons) {
            this.#cookieToBlockedReasons.set(cookie, blockedReasons);
        }
        else {
            this.#cookieToBlockedReasons.delete(cookie);
        }
        if (previousCookie) {
            this.#cookieToBlockedReasons.delete(previousCookie);
        }
    }
    removeBlockedCookie(cookie) {
        this.#blockedCookies.delete(cookie.key());
    }
    async #onPrimaryPageChanged() {
        this.#blockedCookies.clear();
        this.#cookieToBlockedReasons.clear();
        await this.#refresh();
    }
    getCookieToBlockedReasonsMap() {
        return this.#cookieToBlockedReasons;
    }
    async #getCookies(urls) {
        const networkAgent = this.target().networkAgent();
        const newCookies = new Map(await Promise.all(urls.keysArray().map(domain => networkAgent.invoke_getCookies({ urls: [...urls.get(domain).values()] })
            .then(({ cookies }) => [domain, cookies.map(Cookie.fromProtocolCookie)]))));
        const updated = this.#isUpdated(newCookies);
        this.#cookies = newCookies;
        if (updated) {
            this.dispatchEventToListeners("CookieListUpdated" );
        }
    }
    async deleteCookie(cookie) {
        await this.deleteCookies([cookie]);
    }
    async clear(domain, securityOrigin) {
        if (!this.#isRefreshing()) {
            await this.#refreshThrottled();
        }
        const cookies = domain ? (this.#cookies.get(domain) || []) : [...this.#cookies.values()].flat();
        cookies.push(...this.#blockedCookies.values());
        if (securityOrigin) {
            const cookiesToDelete = cookies.filter(cookie => {
                return cookie.matchesSecurityOrigin(securityOrigin);
            });
            await this.deleteCookies(cookiesToDelete);
        }
        else {
            await this.deleteCookies(cookies);
        }
    }
    async saveCookie(cookie) {
        let domain = cookie.domain();
        if (!domain.startsWith('.')) {
            domain = '';
        }
        let expires = undefined;
        if (cookie.expires()) {
            expires = Math.floor(Date.parse(`${cookie.expires()}`) / 1000);
        }
        const enabled = experiments.isEnabled(ExperimentName.EXPERIMENTAL_COOKIE_FEATURES);
        const preserveUnset = (scheme) => scheme === "Unset"  ? scheme : undefined;
        const protocolCookie = {
            name: cookie.name(),
            value: cookie.value(),
            url: cookie.url() || undefined,
            domain,
            path: cookie.path(),
            secure: cookie.secure(),
            httpOnly: cookie.httpOnly(),
            sameSite: cookie.sameSite(),
            expires,
            priority: cookie.priority(),
            partitionKey: cookie.partitionKey(),
            sourceScheme: enabled ? cookie.sourceScheme() : preserveUnset(cookie.sourceScheme()),
            sourcePort: enabled ? cookie.sourcePort() : undefined,
        };
        const response = await this.target().networkAgent().invoke_setCookie(protocolCookie);
        const error = response.getError();
        if (error || !response.success) {
            return false;
        }
        await this.#refreshThrottled();
        return response.success;
    }
    async getCookiesForDomain(domain, forceUpdate) {
        if (!this.#isRefreshing() || forceUpdate) {
            await this.#refreshThrottled();
        }
        const normalCookies = this.#cookies.get(domain) || [];
        return normalCookies.concat(Array.from(this.#blockedCookies.values()));
    }
    async deleteCookies(cookies) {
        const networkAgent = this.target().networkAgent();
        this.#blockedCookies.clear();
        this.#cookieToBlockedReasons.clear();
        await Promise.all(cookies.map(cookie => networkAgent.invoke_deleteCookies({
            name: cookie.name(),
            domain: cookie.domain(),
            path: cookie.path(),
            partitionKey: cookie.partitionKey(),
        })));
        await this.#refreshThrottled();
    }
    #isRefreshing() {
        return Boolean(this.listeners?.size);
    }
    #isUpdated(newCookies) {
        if (newCookies.size !== this.#cookies.size) {
            return true;
        }
        for (const [domain, newDomainCookies] of newCookies) {
            if (!this.#cookies.has(domain)) {
                return true;
            }
            const oldDomainCookies = this.#cookies.get(domain) || [];
            if (newDomainCookies.length !== oldDomainCookies.length) {
                return true;
            }
            const comparisonKey = (c) => c.key() + ' ' + c.value();
            const oldDomainCookieKeys = new Set(oldDomainCookies.map(comparisonKey));
            for (const newCookie of newDomainCookies) {
                if (!oldDomainCookieKeys.has(comparisonKey(newCookie))) {
                    return true;
                }
            }
        }
        return false;
    }
    #refreshThrottled() {
        return this.#refreshThrottler.schedule(() => this.#refresh());
    }
    #refresh() {
        const resourceURLs = new Multimap();
        function populateResourceURLs(resource) {
            const documentURL = ParsedURL.fromString(resource.documentURL);
            if (documentURL) {
                resourceURLs.set(documentURL.securityOrigin(), resource.url);
            }
            return false;
        }
        const resourceTreeModel = this.target().model(ResourceTreeModel);
        if (resourceTreeModel) {
            const unreachableUrl = resourceTreeModel.mainFrame?.unreachableUrl();
            if (unreachableUrl) {
                const documentURL = ParsedURL.fromString(unreachableUrl);
                if (documentURL) {
                    resourceURLs.set(documentURL.securityOrigin(), unreachableUrl);
                }
            }
            resourceTreeModel.forAllResources(populateResourceURLs);
        }
        return this.#getCookies(resourceURLs);
    }
    #onResponseReceived() {
        if (this.#isRefreshing()) {
            void this.#refreshThrottled();
        }
    }
    #onLoadingFinished() {
        if (this.#isRefreshing()) {
            void this.#refreshThrottled();
        }
    }
}
SDKModel.register(CookieModel, { capabilities: 16 , autostart: false });

// Copyright 2010 The Chromium Authors
class CookieParser {
    #domain;
    #cookies;
    #input;
    #originalInputLength;
    #lastCookie;
    #lastCookieLine;
    #lastCookiePosition;
    constructor(domain) {
        if (domain) {
            this.#domain = domain.toLowerCase().replace(/^\./, '');
        }
        this.#cookies = [];
        this.#originalInputLength = 0;
    }
    static parseSetCookie(header, domain) {
        return (new CookieParser(domain)).parseSetCookie(header);
    }
    getCookieAttribute(header) {
        if (!header) {
            return null;
        }
        switch (header.toLowerCase()) {
            case 'domain':
                return "domain" ;
            case 'expires':
                return "expires" ;
            case 'max-age':
                return "max-age" ;
            case 'httponly':
                return "http-only" ;
            case 'name':
                return "name" ;
            case 'path':
                return "path" ;
            case 'samesite':
                return "same-site" ;
            case 'secure':
                return "secure" ;
            case 'value':
                return "value" ;
            case 'priority':
                return "priority" ;
            case 'sourceport':
                return "source-port" ;
            case 'sourcescheme':
                return "source-scheme" ;
            case 'partitioned':
                return "partitioned" ;
            default:
                console.error('Failed getting cookie attribute: ' + header);
                return null;
        }
    }
    cookies() {
        return this.#cookies;
    }
    parseSetCookie(setCookieHeader) {
        if (!this.initialize(setCookieHeader)) {
            return null;
        }
        for (let kv = this.extractKeyValue(); kv; kv = this.extractKeyValue()) {
            if (this.#lastCookie) {
                this.#lastCookie.addAttribute(this.getCookieAttribute(kv.key), kv.value);
            }
            else {
                this.addCookie(kv, 1 );
            }
            if (this.advanceAndCheckCookieDelimiter()) {
                this.flushCookie();
            }
        }
        this.flushCookie();
        return this.#cookies;
    }
    initialize(headerValue) {
        this.#input = headerValue;
        if (typeof headerValue !== 'string') {
            return false;
        }
        this.#cookies = [];
        this.#lastCookie = null;
        this.#lastCookieLine = '';
        this.#originalInputLength = this.#input.length;
        return true;
    }
    flushCookie() {
        if (this.#lastCookie) {
            this.#lastCookie.setSize(this.#originalInputLength - this.#input.length - this.#lastCookiePosition);
            this.#lastCookie.setCookieLine(this.#lastCookieLine.replace('\n', ''));
        }
        this.#lastCookie = null;
        this.#lastCookieLine = '';
    }
    extractKeyValue() {
        if (!this.#input || !this.#input.length) {
            return null;
        }
        const keyValueMatch = /^[ \t]*([^=;\n]+)[ \t]*(?:=[ \t]*([^;\n]*))?/.exec(this.#input);
        if (!keyValueMatch) {
            console.error('Failed parsing cookie header before: ' + this.#input);
            return null;
        }
        const result = new KeyValue(keyValueMatch[1]?.trim(), keyValueMatch[2]?.trim(), (this.#originalInputLength) - this.#input.length);
        this.#lastCookieLine += keyValueMatch[0];
        this.#input = this.#input.slice(keyValueMatch[0].length);
        return result;
    }
    advanceAndCheckCookieDelimiter() {
        if (!this.#input) {
            return false;
        }
        const match = /^\s*[\n;]\s*/.exec(this.#input);
        if (!match) {
            return false;
        }
        this.#lastCookieLine += match[0];
        this.#input = this.#input.slice(match[0].length);
        return match[0].match('\n') !== null;
    }
    addCookie(keyValue, type) {
        if (this.#lastCookie) {
            this.#lastCookie.setSize(keyValue.position - this.#lastCookiePosition);
        }
        this.#lastCookie = typeof keyValue.value === 'string' ? new Cookie(keyValue.key, keyValue.value, type) :
            new Cookie('', keyValue.key, type);
        if (this.#domain) {
            this.#lastCookie.addAttribute("domain" , this.#domain);
        }
        this.#lastCookiePosition = keyValue.position;
        this.#cookies.push(this.#lastCookie);
    }
}
class KeyValue {
    key;
    value;
    position;
    constructor(key, value, position) {
        this.key = key;
        this.value = value;
        this.position = position;
    }
}

// Copyright 2023 The Chromium Authors
function getStatusText(statusCode) {
    const statusTextLookup = {
        100: 'Continue',
        101: 'Switching Protocols',
        102: 'Processing',
        103: 'Early Hints',
        200: 'OK',
        201: 'Created',
        202: 'Accepted',
        203: 'Non-Authoritative Information',
        204: 'No Content',
        205: 'Reset Content',
        206: 'Partial Content',
        207: 'Multi-Status',
        208: 'Already Reported',
        226: 'IM Used',
        300: 'Multiple Choices',
        301: 'Moved Permanently',
        302: 'Found',
        303: 'See Other',
        304: 'Not Modified',
        305: 'Use Proxy',
        307: 'Temporary Redirect',
        308: 'Permanent Redirect',
        400: 'Bad Request',
        401: 'Unauthorized',
        402: 'Payment Required',
        403: 'Forbidden',
        404: 'Not Found',
        405: 'Method Not Allowed',
        406: 'Not Acceptable',
        407: 'Proxy Authentication Required',
        408: 'Request Timeout',
        409: 'Conflict',
        410: 'Gone',
        411: 'Length Required',
        412: 'Precondition Failed',
        413: 'Content Too Large',
        414: 'URI Too Long',
        415: 'Unsupported Media Type',
        416: 'Range Not Satisfiable',
        417: 'Expectation Failed',
        418: 'I\'m a teapot',
        421: 'Misdirected Request',
        422: 'Unprocessable Content',
        423: 'Locked',
        424: 'Failed Dependency',
        425: 'Too Early',
        426: 'Upgrade Required',
        428: 'Precondition Required',
        429: 'Too Many Requests',
        431: 'Request Header Fields Too Large',
        451: 'Unavailable For Legal Reasons',
        500: 'Internal Server Error',
        501: 'Not Implemented',
        502: 'Bad Gateway',
        503: 'Service Unavailable',
        504: 'Gateway Timeout',
        505: 'HTTP Version Not Supported',
        506: 'Variant Also Negotiates',
        507: 'Insufficient Storage',
        508: 'Loop Detected',
        510: 'Not Extended',
        511: 'Network Authentication Required',
    };
    return lockedString(statusTextLookup[statusCode] ?? '');
}

// Copyright 2023 The Chromium Authors
class ServerSentEventsParser {
    #onEventCallback;
    #decoder;
    #isRecognizingCrLf = false;
    #line = '';
    #id = '';
    #data = '';
    #eventType = '';
    constructor(callback, encodingLabel) {
        this.#onEventCallback = callback;
        this.#decoder = new Base64TextDecoder(this.#onTextChunk.bind(this), encodingLabel);
    }
    async addBase64Chunk(raw) {
        await this.#decoder.addBase64Chunk(raw);
    }
    addTextChunk(chunk) {
        this.#onTextChunk(chunk);
    }
    #onTextChunk(chunk) {
        let start = 0;
        for (let i = 0; i < chunk.length; ++i) {
            if (this.#isRecognizingCrLf && chunk[i] === '\n') {
                this.#isRecognizingCrLf = false;
                ++start;
                continue;
            }
            this.#isRecognizingCrLf = false;
            if (chunk[i] === '\r' || chunk[i] === '\n') {
                this.#line += chunk.substring(start, i);
                this.#parseLine();
                this.#line = '';
                start = i + 1;
                this.#isRecognizingCrLf = chunk[i] === '\r';
            }
        }
        this.#line += chunk.substring(start);
    }
    #parseLine() {
        if (this.#line.length === 0) {
            if (this.#data.length > 0) {
                const data = this.#data.slice(0, -1);
                this.#onEventCallback(this.#eventType || 'message', data, this.#id);
                this.#data = '';
            }
            this.#eventType = '';
            return;
        }
        let fieldNameEnd = this.#line.indexOf(':');
        let fieldValueStart;
        if (fieldNameEnd < 0) {
            fieldNameEnd = this.#line.length;
            fieldValueStart = fieldNameEnd;
        }
        else {
            fieldValueStart = fieldNameEnd + 1;
            if (fieldValueStart < this.#line.length && this.#line[fieldValueStart] === ' ') {
                ++fieldValueStart;
            }
        }
        const fieldName = this.#line.substring(0, fieldNameEnd);
        if (fieldName === 'event') {
            this.#eventType = this.#line.substring(fieldValueStart);
            return;
        }
        if (fieldName === 'data') {
            this.#data += this.#line.substring(fieldValueStart);
            this.#data += '\n';
        }
        if (fieldName === 'id') {
            this.#id = this.#line.substring(fieldValueStart);
        }
    }
}
class Base64TextDecoder {
    #decoder;
    #writer;
    constructor(onTextChunk, encodingLabel) {
        this.#decoder = new TextDecoderStream(encodingLabel);
        this.#writer = this.#decoder.writable.getWriter();
        void this.#decoder.readable.pipeTo(new WritableStream({ write: onTextChunk }));
    }
    async addBase64Chunk(chunk) {
        const binString = window.atob(chunk);
        const bytes = Uint8Array.from(binString, m => m.codePointAt(0));
        await this.#writer.ready;
        await this.#writer.write(bytes);
    }
}

// Copyright 2024 The Chromium Authors
class ServerSentEvents {
    #request;
    #parser;
    #lastDataReceivedTime = 0;
    #eventSourceMessages = [];
    constructor(request, parseFromStreamedData) {
        this.#request = request;
        if (parseFromStreamedData) {
            this.#lastDataReceivedTime = request.pseudoWallTime(request.startTime);
            this.#parser = new ServerSentEventsParser(this.#onParserEvent.bind(this), request.charset() ?? undefined);
            void this.#request.requestStreamingContent().then(streamingContentData => {
                if (!isError(streamingContentData)) {
                    void this.#parser?.addBase64Chunk(streamingContentData.content().base64);
                    streamingContentData.addEventListener("ChunkAdded" , ({ data: { chunk } }) => {
                        this.#lastDataReceivedTime = request.pseudoWallTime(request.endTime);
                        void this.#parser?.addBase64Chunk(chunk);
                    });
                }
            });
        }
    }
    get eventSourceMessages() {
        return this.#eventSourceMessages;
    }
    onProtocolEventSourceMessageReceived(eventName, data, eventId, time) {
        this.#recordMessageAndDispatchEvent({
            eventName,
            eventId,
            data,
            time,
        });
    }
    #onParserEvent(eventName, data, eventId) {
        this.#recordMessageAndDispatchEvent({
            eventName,
            eventId,
            data,
            time: this.#lastDataReceivedTime,
        });
    }
    #recordMessageAndDispatchEvent(message) {
        this.#eventSourceMessages.push(message);
        this.#request.dispatchEventToListeners(Events$d.EVENT_SOURCE_MESSAGE_ADDED, message);
    }
}

// Copyright 2016 The Chromium Authors
const UIStrings$14 = {
    deprecatedSyntaxFoundPleaseUse: 'Deprecated syntax found for metric "{PH1}". Please use: <name>;dur=<duration>;desc=<description>',
    duplicateParameterSIgnored: 'Duplicate parameter "{PH1}" ignored.',
    noValueFoundForParameterS: 'No value found for parameter "{PH1}".',
    unrecognizedParameterS: 'Unrecognized parameter "{PH1}".',
    extraneousTrailingCharacters: 'Extraneous trailing characters.',
    unableToParseSValueS: 'Unable to parse "{PH1}" value "{PH2}".',
};
const str_$13 = registerUIStrings('core/sdk/ServerTiming.ts', UIStrings$14);
const i18nString$N = getLocalizedString.bind(undefined, str_$13);
const cloudflarePrefix = '(cf) ';
const cloudinaryPrefix = '(cld) ';
class ServerTiming {
    metric;
    value;
    description;
    constructor(metric, value, description) {
        this.metric = metric;
        this.value = value;
        this.description = description;
    }
    static parseHeaders(headers) {
        const rawServerTimingHeaders = headers.filter(item => item.name.toLowerCase() === 'server-timing');
        if (!rawServerTimingHeaders.length) {
            return null;
        }
        const serverTimings = rawServerTimingHeaders.reduce((timings, header) => {
            const timing = this.createFromHeaderValue(header.value);
            timings.push(...timing.map(function (entry) {
                return new ServerTiming(entry.name, entry.dur ?? null, entry.desc ?? '');
            }));
            return timings;
        }, []);
        return serverTimings;
    }
    static createFromHeaderValue(valueString) {
        function trimLeadingWhiteSpace() {
            valueString = valueString.replace(/^\s*/, '');
        }
        function consumeDelimiter(char) {
            console.assert(char.length === 1);
            trimLeadingWhiteSpace();
            if (valueString.charAt(0) !== char) {
                return false;
            }
            valueString = valueString.substring(1);
            return true;
        }
        function consumeToken() {
            const result = /^(?:\s*)([\w!#$%&'*+\-.^`|~]+)(?:\s*)(.*)/.exec(valueString);
            if (!result) {
                return null;
            }
            valueString = result[2];
            return result[1];
        }
        function consumeTokenOrQuotedString() {
            trimLeadingWhiteSpace();
            if (valueString.charAt(0) === '"') {
                return consumeQuotedString();
            }
            return consumeToken();
        }
        function consumeQuotedString() {
            console.assert(valueString.charAt(0) === '"');
            valueString = valueString.substring(1);
            let value = '';
            while (valueString.length) {
                const result = /^([^"\\]*)(.*)/.exec(valueString);
                if (!result) {
                    return null;
                }
                value += result[1];
                if (result[2].charAt(0) === '"') {
                    valueString = result[2].substring(1);
                    return value;
                }
                console.assert(result[2].charAt(0) === '\\');
                value += result[2].charAt(1);
                valueString = result[2].substring(2);
            }
            return null;
        }
        function consumeExtraneous() {
            const result = /([,;].*)/.exec(valueString);
            if (result) {
                valueString = result[1];
            }
        }
        const result = [];
        let name;
        while ((name = consumeToken()) !== null) {
            const entry = { name };
            if (valueString.charAt(0) === '=') {
                this.showWarning(i18nString$N(UIStrings$14.deprecatedSyntaxFoundPleaseUse, { PH1: name }));
            }
            while (consumeDelimiter(';')) {
                let paramName;
                if ((paramName = consumeToken()) === null) {
                    continue;
                }
                paramName = paramName.toLowerCase();
                const parseParameter = this.getParserForParameter(paramName);
                let paramValue = null;
                if (consumeDelimiter('=')) {
                    paramValue = consumeTokenOrQuotedString();
                    consumeExtraneous();
                }
                if (parseParameter) {
                    if (entry.hasOwnProperty(paramName)) {
                        this.showWarning(i18nString$N(UIStrings$14.duplicateParameterSIgnored, { PH1: paramName }));
                        continue;
                    }
                    if (paramValue === null) {
                        this.showWarning(i18nString$N(UIStrings$14.noValueFoundForParameterS, { PH1: paramName }));
                    }
                    parseParameter.call(this, entry, paramValue);
                }
                else {
                    this.showWarning(i18nString$N(UIStrings$14.unrecognizedParameterS, { PH1: paramName }));
                }
            }
            result.push(entry);
            if (entry.name === 'cfL4' && entry.desc) {
                new URLSearchParams(entry.desc).entries().forEach(([key, val]) => {
                    result.push({ name: `${cloudflarePrefix}${key}`, desc: val });
                });
            }
            if (entry.name === 'content-info' && entry.desc) {
                new URLSearchParams(entry.desc.replace(/,/g, '&')).entries().forEach(([key, val]) => {
                    result.push({ name: `${cloudinaryPrefix}${key}`, desc: val });
                });
            }
            if (!consumeDelimiter(',')) {
                break;
            }
        }
        if (valueString.length) {
            this.showWarning(i18nString$N(UIStrings$14.extraneousTrailingCharacters));
        }
        return result;
    }
    static getParserForParameter(paramName) {
        switch (paramName) {
            case 'dur': {
                function durParser(entry, paramValue) {
                    entry.dur = 0;
                    if (paramValue !== null) {
                        const duration = parseFloat(paramValue);
                        if (isNaN(duration)) {
                            ServerTiming.showWarning(i18nString$N(UIStrings$14.unableToParseSValueS, { PH1: paramName, PH2: paramValue }));
                            return;
                        }
                        entry.dur = duration;
                    }
                }
                return durParser;
            }
            case 'desc': {
                function descParser(entry, paramValue) {
                    entry.desc = paramValue || '';
                }
                return descParser;
            }
            default: {
                return null;
            }
        }
    }
    static showWarning(msg) {
        Console.instance().warn(`ServerTiming: ${msg}`);
    }
}

// Copyright 2021 The Chromium Authors
class Target extends TargetBase {
    #targetManager;
    #name;
    #inspectedURL = EmptyUrlString;
    #inspectedURLName = '';
    #capabilitiesMask;
    #type;
    #parentTarget;
    #id;
    #modelByConstructor = new Map();
    #isSuspended;
    #hasCrashed = false;
    #targetInfo;
    #creatingModels;
    constructor(targetManager, id, name, type, parentTarget, sessionId, suspended, connection, targetInfo) {
        super(parentTarget, sessionId, connection);
        this.#targetManager = targetManager;
        this.#name = name;
        this.#capabilitiesMask = 0;
        switch (type) {
            case Type$2.FRAME:
                this.#capabilitiesMask = 1  | 8192  | 2  | 4  |
                    8  | 16  | 32  | 128  | 256  |
                    1024  | 2048  | 32768  | 65536  | 131072  |
                    262144  | 524288  | 1048576 ;
                if (parentTarget?.type() !== Type$2.FRAME) {
                    this.#capabilitiesMask |=
                        4096  | 64  | 512  | 16384 ;
                    if (schemeIs(targetInfo?.url, 'chrome-extension:')) {
                        this.#capabilitiesMask &= -513 ;
                    }
                }
                break;
            case Type$2.ServiceWorker:
                this.#capabilitiesMask = 4  | 8  | 16  | 32  |
                    2048  | 131072  | 524288 ;
                if (parentTarget?.type() !== Type$2.FRAME) {
                    this.#capabilitiesMask |= 1 ;
                }
                break;
            case Type$2.SHARED_WORKER:
                this.#capabilitiesMask = 4  | 8  | 16  | 32  |
                    131072  | 262144  | 2048  | 524288 ;
                if (parentTarget?.type() !== Type$2.FRAME) {
                    this.#capabilitiesMask |= 8192 ;
                }
                break;
            case Type$2.SHARED_STORAGE_WORKLET:
                this.#capabilitiesMask = 4  | 8  | 2048  | 524288 ;
                break;
            case Type$2.Worker:
                this.#capabilitiesMask = 4  | 8  | 16  | 32  |
                    131072  | 262144  | 256  | 524288 ;
                if (parentTarget?.type() !== Type$2.FRAME) {
                    this.#capabilitiesMask |= 8192 ;
                }
                break;
            case Type$2.WORKLET:
                this.#capabilitiesMask = 4  | 8  | 524288  | 16 ;
                break;
            case Type$2.NODE:
                this.#capabilitiesMask =
                    4  | 16  | 32  | 131072  | 1048576 ;
                break;
            case Type$2.AUCTION_WORKLET:
                this.#capabilitiesMask = 4  | 524288 ;
                break;
            case Type$2.BROWSER:
                this.#capabilitiesMask = 32  | 131072 ;
                break;
            case Type$2.TAB:
                this.#capabilitiesMask = 32  | 128 ;
                break;
            case Type$2.NODE_WORKER:
                this.#capabilitiesMask = 4  | 16  | 32  | 131072 ;
        }
        this.#type = type;
        this.#parentTarget = parentTarget;
        this.#id = id;
        this.#isSuspended = suspended;
        this.#targetInfo = targetInfo;
    }
    createModels(models) {
        this.#creatingModels = true;
        for (const model of models) {
            this.model(model);
        }
        this.#creatingModels = false;
    }
    id() {
        return this.#id;
    }
    name() {
        return this.#name || this.#inspectedURLName;
    }
    setName(name) {
        if (this.#name === name) {
            return;
        }
        this.#name = name;
        this.#targetManager.onNameChange(this);
    }
    type() {
        return this.#type;
    }
    markAsNodeJSForTest() {
        this.#type = Type$2.NODE;
    }
    targetManager() {
        return this.#targetManager;
    }
    hasAllCapabilities(capabilitiesMask) {
        return (this.#capabilitiesMask & capabilitiesMask) === capabilitiesMask;
    }
    decorateLabel(label) {
        return (this.#type === Type$2.Worker || this.#type === Type$2.ServiceWorker) ? '\u2699 ' + label : label;
    }
    parentTarget() {
        return this.#parentTarget;
    }
    outermostTarget() {
        let lastTarget = null;
        let currentTarget = this;
        do {
            if (currentTarget.type() !== Type$2.TAB && currentTarget.type() !== Type$2.BROWSER) {
                lastTarget = currentTarget;
            }
            currentTarget = currentTarget.parentTarget();
        } while (currentTarget);
        return lastTarget;
    }
    dispose(reason) {
        super.dispose(reason);
        this.#targetManager.removeTarget(this);
        for (const model of this.#modelByConstructor.values()) {
            model.dispose();
        }
    }
    model(modelClass) {
        if (!this.#modelByConstructor.get(modelClass)) {
            const info = SDKModel.registeredModels.get(modelClass);
            if (info === undefined) {
                throw new Error('Model class is not registered');
            }
            if ((this.#capabilitiesMask & info.capabilities) === info.capabilities) {
                const model = new modelClass(this);
                this.#modelByConstructor.set(modelClass, model);
                if (!this.#creatingModels) {
                    this.#targetManager.modelAdded(modelClass, model, this.#targetManager.isInScope(this));
                }
            }
        }
        return this.#modelByConstructor.get(modelClass) || null;
    }
    models() {
        return this.#modelByConstructor;
    }
    inspectedURL() {
        return this.#inspectedURL;
    }
    setInspectedURL(inspectedURL) {
        this.#inspectedURL = inspectedURL;
        const parsedURL = ParsedURL.fromString(inspectedURL);
        this.#inspectedURLName = parsedURL ? parsedURL.lastPathComponentWithFragment() : '#' + this.#id;
        this.#targetManager.onInspectedURLChange(this);
        if (!this.#name) {
            this.#targetManager.onNameChange(this);
        }
    }
    hasCrashed() {
        return this.#hasCrashed;
    }
    setHasCrashed(isCrashed) {
        const wasCrashed = this.#hasCrashed;
        this.#hasCrashed = isCrashed;
        if (wasCrashed && !isCrashed) {
            void this.resume();
        }
    }
    async suspend(reason) {
        if (this.#isSuspended) {
            return;
        }
        this.#isSuspended = true;
        if (this.#hasCrashed) {
            return;
        }
        await Promise.all(Array.from(this.models().values(), m => m.preSuspendModel(reason)));
        await Promise.all(Array.from(this.models().values(), m => m.suspendModel(reason)));
    }
    async resume() {
        if (!this.#isSuspended) {
            return;
        }
        this.#isSuspended = false;
        if (this.#hasCrashed) {
            return;
        }
        await Promise.all(Array.from(this.models().values(), m => m.resumeModel()));
        await Promise.all(Array.from(this.models().values(), m => m.postResumeModel()));
    }
    suspended() {
        return this.#isSuspended;
    }
    updateTargetInfo(targetInfo) {
        this.#targetInfo = targetInfo;
    }
    targetInfo() {
        return this.#targetInfo;
    }
}
var Type$2;
(function (Type) {
    Type["FRAME"] = "frame";
    Type["ServiceWorker"] = "service-worker";
    Type["Worker"] = "worker";
    Type["SHARED_WORKER"] = "shared-worker";
    Type["SHARED_STORAGE_WORKLET"] = "shared-storage-worklet";
    Type["NODE"] = "node";
    Type["BROWSER"] = "browser";
    Type["AUCTION_WORKLET"] = "auction-worklet";
    Type["WORKLET"] = "worklet";
    Type["TAB"] = "tab";
    Type["NODE_WORKER"] = "node-worker";
})(Type$2 || (Type$2 = {}));

// Copyright 2012 The Chromium Authors
const UIStrings$13 = {
    binary: '(binary)',
    secureOnly: 'This cookie was blocked because it had the "`Secure`" attribute and the connection was not secure.',
    notOnPath: 'This cookie was blocked because its path was not an exact match for or a superdirectory of the request url\'s path.',
    domainMismatch: 'This cookie was blocked because neither did the request URL\'s domain exactly match the cookie\'s domain, nor was the request URL\'s domain a subdomain of the cookie\'s Domain attribute value.',
    sameSiteStrict: 'This cookie was blocked because it had the "`SameSite=Strict`" attribute and the request was made from a different site. This includes top-level navigation requests initiated by other sites.',
    sameSiteLax: 'This cookie was blocked because it had the "`SameSite=Lax`" attribute and the request was made from a different site and was not initiated by a top-level navigation.',
    sameSiteUnspecifiedTreatedAsLax: 'This cookie didn\'t specify a "`SameSite`" attribute when it was stored and was defaulted to "SameSite=Lax," and was blocked because the request was made from a different site and was not initiated by a top-level navigation. The cookie had to have been set with "`SameSite=None`" to enable cross-site usage.',
    sameSiteNoneInsecure: 'This cookie was blocked because it had the "`SameSite=None`" attribute but was not marked "Secure". Cookies without SameSite restrictions must be marked "Secure" and sent over a secure connection.',
    userPreferences: 'This cookie was blocked due to user preferences.',
    thirdPartyPhaseout: 'This cookie was blocked either because of Chrome flags or browser configuration. Learn more in the Issues panel.',
    unknownError: 'An unknown error was encountered when trying to send this cookie.',
    schemefulSameSiteStrict: 'This cookie was blocked because it had the "`SameSite=Strict`" attribute but the request was cross-site. This includes top-level navigation requests initiated by other sites. This request is considered cross-site because the URL has a different scheme than the current site.',
    schemefulSameSiteLax: 'This cookie was blocked because it had the "`SameSite=Lax`" attribute but the request was cross-site and was not initiated by a top-level navigation. This request is considered cross-site because the URL has a different scheme than the current site.',
    schemefulSameSiteUnspecifiedTreatedAsLax: 'This cookie didn\'t specify a "`SameSite`" attribute when it was stored, was defaulted to "`SameSite=Lax"`, and was blocked because the request was cross-site and was not initiated by a top-level navigation. This request is considered cross-site because the URL has a different scheme than the current site.',
    nameValuePairExceedsMaxSize: 'This cookie was blocked because it was too large. The combined size of the name and value must be less than or equal to 4096 characters.',
    thisSetcookieWasBlockedDueToUser: 'This attempt to set a cookie via a `Set-Cookie` header was blocked due to user preferences.',
    thisSetcookieWasBlockedDueThirdPartyPhaseout: 'Setting this cookie was blocked either because of Chrome flags or browser configuration. Learn more in the Issues panel.',
    thisSetcookieHadInvalidSyntax: 'This `Set-Cookie` header had invalid syntax.',
    thisSetcookieHadADisallowedCharacter: 'This `Set-Cookie` header contained a disallowed character (a forbidden ASCII control character, or the tab character if it appears in the middle of the cookie name, value, an attribute name, or an attribute value).',
    theSchemeOfThisConnectionIsNot: 'The scheme of this connection is not allowed to store cookies.',
    anUnknownErrorWasEncounteredWhenTrying: 'An unknown error was encountered when trying to store this cookie.',
    thisSetcookieWasBlockedBecauseItHadTheSamesiteStrictLax: 'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "{PH1}" attribute but came from a cross-site response which was not the response to a top-level navigation. This response is considered cross-site because the URL has a different scheme than the current site.',
    thisSetcookieDidntSpecifyASamesite: 'This `Set-Cookie` header didn\'t specify a "`SameSite`" attribute, was defaulted to "`SameSite=Lax"`, and was blocked because it came from a cross-site response which was not the response to a top-level navigation. This response is considered cross-site because the URL has a different scheme than the current site.',
    blockedReasonSecureOnly: 'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "Secure" attribute but was not received over a secure connection.',
    blockedReasonSameSiteStrictLax: 'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "{PH1}" attribute but came from a cross-site response which was not the response to a top-level navigation.',
    blockedReasonSameSiteUnspecifiedTreatedAsLax: 'This `Set-Cookie` header didn\'t specify a "`SameSite`" attribute and was defaulted to "`SameSite=Lax,`" and was blocked because it came from a cross-site response which was not the response to a top-level navigation. The `Set-Cookie` had to have been set with "`SameSite=None`" to enable cross-site usage.',
    blockedReasonSameSiteNoneInsecure: 'This attempt to set a cookie via a `Set-Cookie` header was blocked because it had the "`SameSite=None`" attribute but did not have the "Secure" attribute, which is required in order to use "`SameSite=None`".',
    blockedReasonOverwriteSecure: 'This attempt to set a cookie via a `Set-Cookie` header was blocked because it was not sent over a secure connection and would have overwritten a cookie with the Secure attribute.',
    blockedReasonInvalidDomain: 'This attempt to set a cookie via a `Set-Cookie` header was blocked because its Domain attribute was invalid with regards to the current host url.',
    blockedReasonInvalidPrefix: 'This attempt to set a cookie via a `Set-Cookie` header was blocked because it used the "`__Secure-`" or "`__Host-`" prefix in its name and broke the additional rules applied to cookies with these prefixes as defined in `https://tools.ietf.org/html/draft-west-cookie-prefixes-05`.',
    thisSetcookieWasBlockedBecauseTheNameValuePairExceedsMaxSize: 'This attempt to set a cookie via a `Set-Cookie` header was blocked because the cookie was too large. The combined size of the name and value must be less than or equal to 4096 characters.',
    setcookieHeaderIsIgnoredIn: 'Set-Cookie header is ignored in response from url: {PH1}. The combined size of the name and value must be less than or equal to 4096 characters.',
    exemptionReasonUserSetting: 'This cookie is allowed by user preference.',
    exemptionReasonTPCDMetadata: 'This cookie is allowed by a third-party cookie deprecation trial grace period. Learn more: goo.gle/dt-grace.',
    exemptionReasonTPCDDeprecationTrial: 'This cookie is allowed by third-party cookie deprecation trial. Learn more: goo.gle/ps-dt.',
    exemptionReasonTopLevelTPCDDeprecationTrial: 'This cookie is allowed by top-level third-party cookie deprecation trial. Learn more: goo.gle/ps-dt.',
    exemptionReasonTPCDHeuristics: 'This cookie is allowed by third-party cookie heuristics. Learn more: goo.gle/hbe',
    exemptionReasonEnterprisePolicy: 'This cookie is allowed by Chrome Enterprise policy. Learn more: goo.gle/ce-3pc',
    exemptionReasonStorageAccessAPI: 'This cookie is allowed by the Storage Access API. Learn more: goo.gle/saa',
    exemptionReasonTopLevelStorageAccessAPI: 'This cookie is allowed by the top-level Storage Access API. Learn more: goo.gle/saa-top',
    exemptionReasonScheme: 'This cookie is allowed by the top-level url scheme',
};
const str_$12 = registerUIStrings('core/sdk/NetworkRequest.ts', UIStrings$13);
const i18nString$M = getLocalizedString.bind(undefined, str_$12);
class NetworkRequest extends ObjectWrapper {
    #requestId;
    #backendRequestId;
    #documentURL;
    #frameId;
    #loaderId;
    #hasUserGesture;
    #initiator;
    #redirectSource = null;
    #preflightRequest = null;
    #preflightInitiatorRequest = null;
    #isRedirect = false;
    #redirectDestination = null;
    #issueTime = -1;
    #startTime = -1;
    #endTime = -1;
    #blockedReason = undefined;
    #renderBlockingBehavior;
    #corsErrorStatus = undefined;
    statusCode = 0;
    statusText = '';
    requestMethod = '';
    requestTime = 0;
    protocol = '';
    alternateProtocolUsage = undefined;
    mixedContentType = "none" ;
    #initialPriority = null;
    #currentPriority = null;
    #signedExchangeInfo = null;
    #resourceType = resourceTypes.Other;
    #contentData = null;
    #streamingContentData = null;
    #frames = [];
    #responseHeaderValues = {};
    #responseHeadersText = '';
    #originalResponseHeaders = [];
    #sortedOriginalResponseHeaders;
    #setCookieHeaders = [];
    #requestHeaders = [];
    #requestHeaderValues = {};
    #remoteAddress = '';
    #remoteAddressSpace = "Unknown" ;
    #referrerPolicy = null;
    #securityState = "unknown" ;
    #securityDetails = null;
    connectionId = '0';
    connectionReused = false;
    hasNetworkData = false;
    #formParametersPromise = null;
    #requestFormDataPromise = Promise.resolve(null);
    #hasExtraRequestInfo = false;
    #hasExtraResponseInfo = false;
    #blockedRequestCookies = [];
    #includedRequestCookies = [];
    #blockedResponseCookies = [];
    #exemptedResponseCookies = [];
    #responseCookiesPartitionKey = null;
    #responseCookiesPartitionKeyOpaque = null;
    #deviceBoundSessionUsages = [];
    #siteHasCookieInOtherPartition = false;
    localizedFailDescription = null;
    #url;
    #responseReceivedTime;
    #transferSize;
    #finished;
    #failed;
    #canceled;
    #preserved;
    #mimeType;
    #charset;
    #parsedURL;
    #name;
    #path;
    #clientSecurityState;
    #trustTokenParams;
    #trustTokenOperationDoneEvent;
    #responseCacheStorageCacheName;
    #serviceWorkerResponseSource;
    #wallIssueTime;
    #responseRetrievalTime;
    #resourceSize;
    #fromMemoryCache;
    #fromDiskCache;
    #fromPrefetchCache;
    #fromEarlyHints;
    #fetchedViaServiceWorker;
    #serviceWorkerRouterInfo;
    #timing;
    #requestHeadersText;
    #responseHeaders;
    #earlyHintsHeaders;
    #sortedResponseHeaders;
    #responseCookies;
    #serverTimings;
    #queryString;
    #parsedQueryParameters;
    #contentDataProvider;
    #isSameSite = null;
    #wasIntercepted = false;
    #associatedData = new Map();
    #hasOverriddenContent = false;
    #hasThirdPartyCookiePhaseoutIssue = false;
    #serverSentEvents;
    responseReceivedPromise;
    responseReceivedPromiseResolve;
    directSocketInfo;
    #directSocketChunks = [];
    #isAdRelated;
    #appliedNetworkConditionsId;
    constructor(requestId, backendRequestId, url, documentURL, frameId, loaderId, initiator, hasUserGesture) {
        super();
        this.#requestId = requestId;
        this.#backendRequestId = backendRequestId;
        this.setUrl(url);
        this.#documentURL = documentURL;
        this.#frameId = frameId;
        this.#loaderId = loaderId;
        this.#initiator = initiator;
        this.#hasUserGesture = hasUserGesture;
        this.#isAdRelated = false;
    }
    static create(backendRequestId, url, documentURL, frameId, loaderId, initiator, hasUserGesture) {
        return new NetworkRequest(backendRequestId, backendRequestId, url, documentURL, frameId, loaderId, initiator, hasUserGesture);
    }
    static createForSocket(backendRequestId, requestURL, initiator) {
        return new NetworkRequest(backendRequestId, backendRequestId, requestURL, EmptyUrlString, null, null, initiator || null);
    }
    static createWithoutBackendRequest(requestId, url, documentURL, initiator) {
        return new NetworkRequest(requestId, undefined, url, documentURL, null, null, initiator);
    }
    identityCompare(other) {
        const thisId = this.requestId();
        const thatId = other.requestId();
        if (thisId > thatId) {
            return 1;
        }
        if (thisId < thatId) {
            return -1;
        }
        return 0;
    }
    requestId() {
        return this.#requestId;
    }
    backendRequestId() {
        return this.#backendRequestId;
    }
    url() {
        return this.#url;
    }
    isBlobRequest() {
        return schemeIs(this.#url, 'blob:');
    }
    setUrl(x) {
        if (this.#url === x) {
            return;
        }
        this.#url = x;
        this.#parsedURL = new ParsedURL(x);
        this.#queryString = undefined;
        this.#parsedQueryParameters = undefined;
        this.#name = undefined;
        this.#path = undefined;
    }
    get documentURL() {
        return this.#documentURL;
    }
    get parsedURL() {
        return this.#parsedURL;
    }
    get frameId() {
        return this.#frameId;
    }
    get loaderId() {
        return this.#loaderId;
    }
    get appliedNetworkConditionsId() {
        return this.#appliedNetworkConditionsId;
    }
    setRemoteAddress(ip, port) {
        this.#remoteAddress = ip + ':' + port;
        this.dispatchEventToListeners(Events$d.REMOTE_ADDRESS_CHANGED, this);
    }
    remoteAddress() {
        return this.#remoteAddress;
    }
    remoteAddressSpace() {
        return this.#remoteAddressSpace;
    }
    getResponseCacheStorageCacheName() {
        return this.#responseCacheStorageCacheName;
    }
    setResponseCacheStorageCacheName(x) {
        this.#responseCacheStorageCacheName = x;
    }
    serviceWorkerResponseSource() {
        return this.#serviceWorkerResponseSource;
    }
    setServiceWorkerResponseSource(serviceWorkerResponseSource) {
        this.#serviceWorkerResponseSource = serviceWorkerResponseSource;
    }
    setReferrerPolicy(referrerPolicy) {
        this.#referrerPolicy = referrerPolicy;
    }
    referrerPolicy() {
        return this.#referrerPolicy;
    }
    securityState() {
        return this.#securityState;
    }
    setSecurityState(securityState) {
        this.#securityState = securityState;
    }
    securityDetails() {
        return this.#securityDetails;
    }
    securityOrigin() {
        return this.#parsedURL.securityOrigin();
    }
    setSecurityDetails(securityDetails) {
        this.#securityDetails = securityDetails;
    }
    get startTime() {
        return this.#startTime || -1;
    }
    setIssueTime(monotonicTime, wallTime) {
        this.#issueTime = monotonicTime;
        this.#wallIssueTime = wallTime;
        this.#startTime = monotonicTime;
    }
    issueTime() {
        return this.#issueTime;
    }
    pseudoWallTime(monotonicTime) {
        return this.#wallIssueTime ? this.#wallIssueTime - this.#issueTime + monotonicTime : monotonicTime;
    }
    get responseReceivedTime() {
        return this.#responseReceivedTime || -1;
    }
    set responseReceivedTime(x) {
        this.#responseReceivedTime = x;
    }
    getResponseRetrievalTime() {
        return this.#responseRetrievalTime;
    }
    setResponseRetrievalTime(x) {
        this.#responseRetrievalTime = x;
    }
    get endTime() {
        return this.#endTime || -1;
    }
    set endTime(x) {
        if (this.timing?.requestTime) {
            this.#endTime = Math.max(x, this.responseReceivedTime);
        }
        else {
            this.#endTime = x;
            if (this.#responseReceivedTime > x) {
                this.#responseReceivedTime = x;
            }
        }
        this.dispatchEventToListeners(Events$d.TIMING_CHANGED, this);
    }
    get duration() {
        if (this.#endTime === -1 || this.#startTime === -1) {
            return -1;
        }
        return this.#endTime - this.#startTime;
    }
    get latency() {
        if (this.#responseReceivedTime === -1 || this.#startTime === -1) {
            return -1;
        }
        return this.#responseReceivedTime - this.#startTime;
    }
    get resourceSize() {
        return this.#resourceSize || 0;
    }
    set resourceSize(x) {
        this.#resourceSize = x;
    }
    get transferSize() {
        return this.#transferSize || 0;
    }
    increaseTransferSize(x) {
        this.#transferSize = (this.#transferSize || 0) + x;
    }
    setTransferSize(x) {
        this.#transferSize = x;
    }
    get finished() {
        return this.#finished;
    }
    set finished(x) {
        if (this.#finished === x) {
            return;
        }
        this.#finished = x;
        if (x) {
            this.dispatchEventToListeners(Events$d.FINISHED_LOADING, this);
        }
    }
    get failed() {
        return this.#failed;
    }
    set failed(x) {
        this.#failed = x;
    }
    get canceled() {
        return this.#canceled;
    }
    set canceled(x) {
        this.#canceled = x;
    }
    get preserved() {
        return this.#preserved;
    }
    set preserved(x) {
        this.#preserved = x;
    }
    blockedReason() {
        return this.#blockedReason;
    }
    setBlockedReason(reason) {
        this.#blockedReason = reason;
    }
    setRenderBlockingBehavior(renderBlocking) {
        this.#renderBlockingBehavior = renderBlocking;
    }
    renderBlockingBehavior() {
        return this.#renderBlockingBehavior;
    }
    corsErrorStatus() {
        return this.#corsErrorStatus;
    }
    setCorsErrorStatus(corsErrorStatus) {
        this.#corsErrorStatus = corsErrorStatus;
    }
    wasBlocked() {
        return Boolean(this.#blockedReason);
    }
    cached() {
        return ((Boolean(this.#fromMemoryCache) || Boolean(this.#fromDiskCache)) && !this.#transferSize);
    }
    cachedInMemory() {
        return Boolean(this.#fromMemoryCache) && !this.#transferSize;
    }
    fromPrefetchCache() {
        return Boolean(this.#fromPrefetchCache);
    }
    setFromMemoryCache() {
        this.#fromMemoryCache = true;
        this.#timing = undefined;
    }
    get fromDiskCache() {
        return this.#fromDiskCache;
    }
    setFromDiskCache() {
        this.#fromDiskCache = true;
    }
    setFromPrefetchCache() {
        this.#fromPrefetchCache = true;
    }
    fromEarlyHints() {
        return Boolean(this.#fromEarlyHints);
    }
    setFromEarlyHints() {
        this.#fromEarlyHints = true;
    }
    get fetchedViaServiceWorker() {
        return Boolean(this.#fetchedViaServiceWorker);
    }
    set fetchedViaServiceWorker(x) {
        this.#fetchedViaServiceWorker = x;
    }
    get serviceWorkerRouterInfo() {
        return this.#serviceWorkerRouterInfo;
    }
    set serviceWorkerRouterInfo(x) {
        this.#serviceWorkerRouterInfo = x;
    }
    hasMatchingServiceWorkerRouter() {
        return (this.#serviceWorkerRouterInfo !== undefined && this.serviceWorkerRouterInfo?.matchedSourceType !== undefined);
    }
    initiatedByServiceWorker() {
        const networkManager = NetworkManager.forRequest(this);
        if (!networkManager) {
            return false;
        }
        return networkManager.target().type() === Type$2.ServiceWorker;
    }
    get timing() {
        return this.#timing;
    }
    set timing(timingInfo) {
        if (!timingInfo || this.#fromMemoryCache) {
            return;
        }
        this.#startTime = timingInfo.requestTime;
        const headersReceivedTime = timingInfo.requestTime + timingInfo.receiveHeadersEnd / 1000.0;
        if ((this.#responseReceivedTime || -1) < 0 || this.#responseReceivedTime > headersReceivedTime) {
            this.#responseReceivedTime = headersReceivedTime;
        }
        if (this.#startTime > this.#responseReceivedTime) {
            this.#responseReceivedTime = this.#startTime;
        }
        this.#timing = timingInfo;
        this.dispatchEventToListeners(Events$d.TIMING_CHANGED, this);
    }
    setConnectTimingFromExtraInfo(connectTiming) {
        this.#startTime = connectTiming.requestTime;
        this.dispatchEventToListeners(Events$d.TIMING_CHANGED, this);
    }
    get mimeType() {
        return this.#mimeType;
    }
    set mimeType(x) {
        this.#mimeType = x;
        if (x === "text/event-stream"  && !this.#serverSentEvents) {
            const parseFromStreamedData = this.resourceType() !== resourceTypes.EventSource;
            this.#serverSentEvents = new ServerSentEvents(this, parseFromStreamedData);
        }
    }
    get displayName() {
        return this.#parsedURL.displayName;
    }
    name() {
        if (this.#name) {
            return this.#name;
        }
        this.parseNameAndPathFromURL();
        return this.#name;
    }
    path() {
        if (this.#path) {
            return this.#path;
        }
        this.parseNameAndPathFromURL();
        return this.#path;
    }
    parseNameAndPathFromURL() {
        if (this.#parsedURL.isDataURL()) {
            this.#name = this.#parsedURL.dataURLDisplayName();
            this.#path = '';
        }
        else if (this.#parsedURL.isBlobURL()) {
            this.#name = this.#parsedURL.url;
            this.#path = '';
        }
        else if (this.#parsedURL.isAboutBlank()) {
            this.#name = this.#parsedURL.url;
            this.#path = '';
        }
        else {
            this.#path = this.#parsedURL.host + this.#parsedURL.folderPathComponents;
            const networkManager = NetworkManager.forRequest(this);
            const inspectedURL = networkManager ? ParsedURL.fromString(networkManager.target().inspectedURL()) :
                null;
            this.#path = trimURL(this.#path, inspectedURL ? inspectedURL.host : '');
            if (this.#parsedURL.lastPathComponent || this.#parsedURL.queryParams) {
                this.#name =
                    this.#parsedURL.lastPathComponent + (this.#parsedURL.queryParams ? '?' + this.#parsedURL.queryParams : '');
            }
            else if (this.#parsedURL.folderPathComponents) {
                this.#name = this.#parsedURL.folderPathComponents.substring(this.#parsedURL.folderPathComponents.lastIndexOf('/') + 1) +
                    '/';
                this.#path = this.#path.substring(0, this.#path.lastIndexOf('/'));
            }
            else {
                this.#name = this.#parsedURL.host;
                this.#path = '';
            }
        }
    }
    get folder() {
        let path = this.#parsedURL.path;
        const indexOfQuery = path.indexOf('?');
        if (indexOfQuery !== -1) {
            path = path.substring(0, indexOfQuery);
        }
        const lastSlashIndex = path.lastIndexOf('/');
        return lastSlashIndex !== -1 ? path.substring(0, lastSlashIndex) : '';
    }
    get pathname() {
        return this.#parsedURL.path;
    }
    resourceType() {
        return this.#resourceType;
    }
    setResourceType(resourceType) {
        this.#resourceType = resourceType;
    }
    get domain() {
        return this.#parsedURL.host;
    }
    get scheme() {
        return this.#parsedURL.scheme;
    }
    getInferredStatusText() {
        return (this.statusText || getStatusText(this.statusCode));
    }
    redirectSource() {
        return this.#redirectSource;
    }
    setRedirectSource(originatingRequest) {
        this.#redirectSource = originatingRequest;
    }
    preflightRequest() {
        return this.#preflightRequest;
    }
    setPreflightRequest(preflightRequest) {
        this.#preflightRequest = preflightRequest;
    }
    preflightInitiatorRequest() {
        return this.#preflightInitiatorRequest;
    }
    setPreflightInitiatorRequest(preflightInitiatorRequest) {
        this.#preflightInitiatorRequest = preflightInitiatorRequest;
    }
    isPreflightRequest() {
        return (this.#initiator !== null && this.#initiator !== undefined &&
            this.#initiator.type === "preflight" );
    }
    redirectDestination() {
        return this.#redirectDestination;
    }
    setRedirectDestination(redirectDestination) {
        this.#redirectDestination = redirectDestination;
    }
    requestHeaders() {
        return this.#requestHeaders;
    }
    setRequestHeaders(headers) {
        this.#requestHeaders = headers;
        this.dispatchEventToListeners(Events$d.REQUEST_HEADERS_CHANGED);
    }
    requestHeadersText() {
        return this.#requestHeadersText;
    }
    setRequestHeadersText(text) {
        this.#requestHeadersText = text;
        this.dispatchEventToListeners(Events$d.REQUEST_HEADERS_CHANGED);
    }
    requestHeaderValue(headerName) {
        if (this.#requestHeaderValues[headerName]) {
            return this.#requestHeaderValues[headerName];
        }
        this.#requestHeaderValues[headerName] = this.computeHeaderValue(this.requestHeaders(), headerName);
        return this.#requestHeaderValues[headerName];
    }
    requestFormData() {
        if (!this.#requestFormDataPromise) {
            this.#requestFormDataPromise = NetworkManager.requestPostData(this);
        }
        return this.#requestFormDataPromise;
    }
    setRequestFormData(hasData, data) {
        this.#requestFormDataPromise = hasData && data === null ? null : Promise.resolve(data);
        this.#formParametersPromise = null;
    }
    filteredProtocolName() {
        const protocol = this.protocol.toLowerCase();
        if (protocol === 'h2') {
            return 'http/2.0';
        }
        return protocol.replace(/^http\/2(\.0)?\+/, 'http/2.0+');
    }
    requestHttpVersion() {
        const headersText = this.requestHeadersText();
        if (!headersText) {
            const version = this.requestHeaderValue('version') || this.requestHeaderValue(':version');
            if (version) {
                return version;
            }
            return this.filteredProtocolName();
        }
        const firstLine = headersText.split(/\r\n/)[0];
        const match = firstLine.match(/(HTTP\/\d+\.\d+)$/);
        return match ? match[1] : 'HTTP/0.9';
    }
    get responseHeaders() {
        return this.#responseHeaders || [];
    }
    set responseHeaders(x) {
        this.#responseHeaders = x;
        this.#sortedResponseHeaders = undefined;
        this.#serverTimings = undefined;
        this.#responseCookies = undefined;
        this.#responseHeaderValues = {};
        this.dispatchEventToListeners(Events$d.RESPONSE_HEADERS_CHANGED);
    }
    get earlyHintsHeaders() {
        return this.#earlyHintsHeaders || [];
    }
    set earlyHintsHeaders(x) {
        this.#earlyHintsHeaders = x;
    }
    get originalResponseHeaders() {
        return this.#originalResponseHeaders;
    }
    set originalResponseHeaders(headers) {
        this.#originalResponseHeaders = headers;
        this.#sortedOriginalResponseHeaders = undefined;
    }
    get setCookieHeaders() {
        return this.#setCookieHeaders;
    }
    set setCookieHeaders(headers) {
        this.#setCookieHeaders = headers;
    }
    get responseHeadersText() {
        return this.#responseHeadersText;
    }
    set responseHeadersText(x) {
        this.#responseHeadersText = x;
        this.dispatchEventToListeners(Events$d.RESPONSE_HEADERS_CHANGED);
    }
    get sortedResponseHeaders() {
        if (this.#sortedResponseHeaders !== undefined) {
            return this.#sortedResponseHeaders;
        }
        this.#sortedResponseHeaders = this.responseHeaders.slice();
        return this.#sortedResponseHeaders.sort(function (a, b) {
            return compare(a.name.toLowerCase(), b.name.toLowerCase());
        });
    }
    get sortedOriginalResponseHeaders() {
        if (this.#sortedOriginalResponseHeaders !== undefined) {
            return this.#sortedOriginalResponseHeaders;
        }
        this.#sortedOriginalResponseHeaders = this.originalResponseHeaders.slice();
        return this.#sortedOriginalResponseHeaders.sort(function (a, b) {
            return compare(a.name.toLowerCase(), b.name.toLowerCase());
        });
    }
    get overrideTypes() {
        const types = [];
        if (this.hasOverriddenContent) {
            types.push('content');
        }
        if (this.hasOverriddenHeaders()) {
            types.push('headers');
        }
        return types;
    }
    get hasOverriddenContent() {
        return this.#hasOverriddenContent;
    }
    set hasOverriddenContent(value) {
        this.#hasOverriddenContent = value;
    }
    #deduplicateHeaders(sortedHeaders) {
        const dedupedHeaders = [];
        for (const header of sortedHeaders) {
            if (dedupedHeaders.length && dedupedHeaders[dedupedHeaders.length - 1].name === header.name) {
                dedupedHeaders[dedupedHeaders.length - 1].value += `, ${header.value}`;
            }
            else {
                dedupedHeaders.push({ name: header.name, value: header.value });
            }
        }
        return dedupedHeaders;
    }
    hasOverriddenHeaders() {
        if (!this.#originalResponseHeaders.length) {
            return false;
        }
        const responseHeaders = this.#deduplicateHeaders(this.sortedResponseHeaders);
        const originalResponseHeaders = this.#deduplicateHeaders(this.sortedOriginalResponseHeaders);
        if (responseHeaders.length !== originalResponseHeaders.length) {
            return true;
        }
        for (let i = 0; i < responseHeaders.length; i++) {
            if (responseHeaders[i].name.toLowerCase() !== originalResponseHeaders[i].name.toLowerCase()) {
                return true;
            }
            if (responseHeaders[i].value !== originalResponseHeaders[i].value) {
                return true;
            }
        }
        return false;
    }
    responseHeaderValue(headerName) {
        if (headerName in this.#responseHeaderValues) {
            return this.#responseHeaderValues[headerName];
        }
        this.#responseHeaderValues[headerName] = this.computeHeaderValue(this.responseHeaders, headerName);
        return this.#responseHeaderValues[headerName];
    }
    wasIntercepted() {
        return this.#wasIntercepted;
    }
    setWasIntercepted(wasIntercepted) {
        this.#wasIntercepted = wasIntercepted;
    }
    setEarlyHintsHeaders(headers) {
        this.earlyHintsHeaders = headers;
    }
    get responseCookies() {
        if (!this.#responseCookies) {
            this.#responseCookies = CookieParser.parseSetCookie(this.responseHeaderValue('Set-Cookie'), this.domain) ||
                [];
            if (this.#responseCookiesPartitionKey) {
                for (const cookie of this.#responseCookies) {
                    if (cookie.partitioned()) {
                        cookie.setPartitionKey(this.#responseCookiesPartitionKey.topLevelSite, this.#responseCookiesPartitionKey.hasCrossSiteAncestor);
                    }
                }
            }
            else if (this.#responseCookiesPartitionKeyOpaque) {
                for (const cookie of this.#responseCookies) {
                    cookie.setPartitionKeyOpaque();
                }
            }
        }
        return this.#responseCookies;
    }
    set responseCookies(responseCookies) {
        this.#responseCookies = responseCookies;
    }
    responseLastModified() {
        return this.responseHeaderValue('last-modified');
    }
    allCookiesIncludingBlockedOnes() {
        return [
            ...this.includedRequestCookies().map(includedRequestCookie => includedRequestCookie.cookie),
            ...this.responseCookies,
            ...this.blockedRequestCookies().map(blockedRequestCookie => blockedRequestCookie.cookie),
            ...this.blockedResponseCookies().map(blockedResponseCookie => blockedResponseCookie.cookie),
        ].filter(v => !!v);
    }
    get serverTimings() {
        if (typeof this.#serverTimings === 'undefined') {
            this.#serverTimings = ServerTiming.parseHeaders(this.responseHeaders);
        }
        return this.#serverTimings;
    }
    queryString() {
        if (this.#queryString !== undefined) {
            return this.#queryString;
        }
        let queryString = null;
        const url = this.url();
        const questionMarkPosition = url.indexOf('?');
        if (questionMarkPosition !== -1) {
            queryString = url.substring(questionMarkPosition + 1);
            const hashSignPosition = queryString.indexOf('#');
            if (hashSignPosition !== -1) {
                queryString = queryString.substring(0, hashSignPosition);
            }
        }
        this.#queryString = queryString;
        return this.#queryString;
    }
    get queryParameters() {
        if (this.#parsedQueryParameters) {
            return this.#parsedQueryParameters;
        }
        const queryString = this.queryString();
        if (!queryString) {
            return null;
        }
        this.#parsedQueryParameters = this.parseParameters(queryString);
        return this.#parsedQueryParameters;
    }
    async parseFormParameters() {
        const requestContentType = this.requestContentType();
        if (!requestContentType) {
            return null;
        }
        if (requestContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)) {
            const formData = await this.requestFormData();
            if (!formData) {
                return null;
            }
            return this.parseParameters(formData);
        }
        const multipartDetails = requestContentType.match(/^multipart\/form-data\s*;\s*boundary\s*=\s*(\S+)\s*$/);
        if (!multipartDetails) {
            return null;
        }
        const boundary = multipartDetails[1];
        if (!boundary) {
            return null;
        }
        const formData = await this.requestFormData();
        if (!formData) {
            return null;
        }
        return this.parseMultipartFormDataParameters(formData, boundary);
    }
    formParameters() {
        if (!this.#formParametersPromise) {
            this.#formParametersPromise = this.parseFormParameters();
        }
        return this.#formParametersPromise;
    }
    responseHttpVersion() {
        const headersText = this.#responseHeadersText;
        if (!headersText) {
            const version = this.responseHeaderValue('version') || this.responseHeaderValue(':version');
            if (version) {
                return version;
            }
            return this.filteredProtocolName();
        }
        const firstLine = headersText.split(/\r\n/)[0];
        const match = firstLine.match(/^(HTTP\/\d+\.\d+)/);
        return match ? match[1] : 'HTTP/0.9';
    }
    parseParameters(queryString) {
        function parseNameValue(pair) {
            const position = pair.indexOf('=');
            if (position === -1) {
                return { name: pair, value: '' };
            }
            return {
                name: pair.substring(0, position),
                value: pair.substring(position + 1),
            };
        }
        return queryString.split('&').map(parseNameValue);
    }
    parseMultipartFormDataParameters(data, boundary) {
        const sanitizedBoundary = escapeForRegExp(boundary);
        const keyValuePattern = new RegExp(
        '^\\r\\ncontent-disposition\\s*:\\s*form-data\\s*;\\s*name="([^"]*)"(?:\\s*;\\s*filename="([^"]*)")?' +
            '(?:\\r\\ncontent-type\\s*:\\s*([^\\r\\n]*))?' +
            '\\r\\n\\r\\n' +
            '(.*)' +
            '\\r\\n$', 'is');
        const fields = data.split(new RegExp(`--${sanitizedBoundary}(?:--\s*$)?`, 'g'));
        return fields.reduce(parseMultipartField, []);
        function parseMultipartField(result, field) {
            const [match, name, filename, contentType, value] = field.match(keyValuePattern) || [];
            if (!match) {
                return result;
            }
            const processedValue = filename || contentType ? i18nString$M(UIStrings$13.binary) : value;
            result.push({ name, value: processedValue });
            return result;
        }
    }
    computeHeaderValue(headers, headerName) {
        headerName = headerName.toLowerCase();
        const values = [];
        for (let i = 0; i < headers.length; ++i) {
            if (headers[i].name.toLowerCase() === headerName) {
                values.push(headers[i].value);
            }
        }
        if (!values.length) {
            return undefined;
        }
        if (headerName === 'set-cookie') {
            return values.join('\n');
        }
        return values.join(', ');
    }
    requestContentData() {
        if (this.#contentData) {
            return this.#contentData;
        }
        if (this.#contentDataProvider) {
            this.#contentData = this.#contentDataProvider();
        }
        else {
            this.#contentData = NetworkManager.requestContentData(this);
        }
        return this.#contentData;
    }
    setContentDataProvider(dataProvider) {
        console.assert(!this.#contentData, 'contentData can only be set once.');
        this.#contentDataProvider = dataProvider;
    }
    requestStreamingContent() {
        if (this.#streamingContentData) {
            return this.#streamingContentData;
        }
        const contentPromise = this.finished ? this.requestContentData() : NetworkManager.streamResponseBody(this);
        this.#streamingContentData = contentPromise.then(contentData => {
            if (ContentData.isError(contentData)) {
                return contentData;
            }
            return StreamingContentData.from(contentData);
        });
        return this.#streamingContentData;
    }
    contentURL() {
        return this.#url;
    }
    contentType() {
        return this.#resourceType;
    }
    async searchInContent(query, caseSensitive, isRegex) {
        if (!this.#contentDataProvider) {
            return await NetworkManager.searchInRequest(this, query, caseSensitive, isRegex);
        }
        const contentData = await this.requestContentData();
        if (ContentData.isError(contentData) || !contentData.isTextContent) {
            return [];
        }
        return performSearchInContentData(contentData, query, caseSensitive, isRegex);
    }
    requestContentType() {
        return this.requestHeaderValue('Content-Type');
    }
    requestContentEncoding() {
        return this.requestHeaderValue('Content-Encoding');
    }
    hasErrorStatusCode() {
        return this.statusCode >= 400;
    }
    setInitialPriority(priority) {
        this.#initialPriority = priority;
    }
    initialPriority() {
        return this.#initialPriority;
    }
    setPriority(priority) {
        this.#currentPriority = priority;
    }
    priority() {
        return this.#currentPriority || this.#initialPriority || null;
    }
    setSignedExchangeInfo(info) {
        this.#signedExchangeInfo = info;
    }
    signedExchangeInfo() {
        return this.#signedExchangeInfo;
    }
    async populateImageSource(image) {
        const contentData = await this.requestContentData();
        if (ContentData.isError(contentData)) {
            return;
        }
        let imageSrc = contentData.asDataUrl();
        if (imageSrc === null && !this.#failed) {
            const cacheControl = this.responseHeaderValue('cache-control') || '';
            if (!cacheControl.includes('no-cache')) {
                imageSrc = this.#url;
            }
        }
        if (imageSrc !== null) {
            image.src = imageSrc;
        }
    }
    initiator() {
        return this.#initiator || null;
    }
    hasUserGesture() {
        return this.#hasUserGesture ?? null;
    }
    frames() {
        return this.#frames;
    }
    addProtocolFrameError(errorMessage, time) {
        this.addFrame({
            type: WebSocketFrameType.Error,
            text: errorMessage,
            time: this.pseudoWallTime(time),
            opCode: -1,
            mask: false,
        });
    }
    addProtocolFrame(response, time, sent) {
        const type = sent ? WebSocketFrameType.Send : WebSocketFrameType.Receive;
        this.addFrame({
            type,
            text: response.payloadData,
            time: this.pseudoWallTime(time),
            opCode: response.opcode,
            mask: response.mask,
        });
    }
    addFrame(frame) {
        this.#frames.push(frame);
        this.dispatchEventToListeners(Events$d.WEBSOCKET_FRAME_ADDED, frame);
    }
    directSocketChunks() {
        return this.#directSocketChunks;
    }
    addDirectSocketChunk(chunk) {
        this.#directSocketChunks.push(chunk);
        this.dispatchEventToListeners(Events$d.DIRECTSOCKET_CHUNK_ADDED, chunk);
    }
    eventSourceMessages() {
        return this.#serverSentEvents?.eventSourceMessages ?? [];
    }
    addEventSourceMessage(time, eventName, eventId, data) {
        this.#serverSentEvents?.onProtocolEventSourceMessageReceived(eventName, data, eventId, this.pseudoWallTime(time));
    }
    markAsRedirect(redirectCount) {
        this.#isRedirect = true;
        this.#requestId = `${this.#backendRequestId}:redirected.${redirectCount}`;
    }
    isRedirect() {
        return this.#isRedirect;
    }
    setRequestIdForTest(requestId) {
        this.#backendRequestId = requestId;
        this.#requestId = requestId;
    }
    charset() {
        return this.#charset ?? null;
    }
    setCharset(charset) {
        this.#charset = charset;
    }
    addExtraRequestInfo(extraRequestInfo) {
        this.#blockedRequestCookies = extraRequestInfo.blockedRequestCookies;
        this.setIncludedRequestCookies(extraRequestInfo.includedRequestCookies);
        this.setRequestHeaders(extraRequestInfo.requestHeaders);
        this.#hasExtraRequestInfo = true;
        this.setRequestHeadersText('');
        this.#deviceBoundSessionUsages = extraRequestInfo.deviceBoundSessionUsages || [];
        this.#clientSecurityState = extraRequestInfo.clientSecurityState;
        this.#appliedNetworkConditionsId = extraRequestInfo.appliedNetworkConditionsId;
        if (extraRequestInfo.connectTiming) {
            this.setConnectTimingFromExtraInfo(extraRequestInfo.connectTiming);
        }
        this.#siteHasCookieInOtherPartition = extraRequestInfo.siteHasCookieInOtherPartition ?? false;
        this.#hasThirdPartyCookiePhaseoutIssue = this.#blockedRequestCookies.some(item => item.blockedReasons.includes("ThirdPartyPhaseout" ));
    }
    setAppliedNetworkConditions(appliedNetworkConditionsId) {
        this.#appliedNetworkConditionsId = appliedNetworkConditionsId;
    }
    getDeviceBoundSessionUsages() {
        return this.#deviceBoundSessionUsages;
    }
    hasExtraRequestInfo() {
        return this.#hasExtraRequestInfo;
    }
    blockedRequestCookies() {
        return this.#blockedRequestCookies;
    }
    setIncludedRequestCookies(includedRequestCookies) {
        this.#includedRequestCookies = includedRequestCookies;
    }
    includedRequestCookies() {
        return this.#includedRequestCookies;
    }
    hasRequestCookies() {
        return (this.#includedRequestCookies.length > 0 || this.#blockedRequestCookies.length > 0);
    }
    siteHasCookieInOtherPartition() {
        return this.#siteHasCookieInOtherPartition;
    }
    static parseStatusTextFromResponseHeadersText(responseHeadersText) {
        const firstLineParts = responseHeadersText.split('\r')[0].split(' ');
        return firstLineParts.slice(2).join(' ');
    }
    addExtraResponseInfo(extraResponseInfo) {
        this.#blockedResponseCookies = extraResponseInfo.blockedResponseCookies;
        if (extraResponseInfo.exemptedResponseCookies) {
            this.#exemptedResponseCookies = extraResponseInfo.exemptedResponseCookies;
        }
        this.#responseCookiesPartitionKey =
            extraResponseInfo.cookiePartitionKey ? extraResponseInfo.cookiePartitionKey : null;
        this.#responseCookiesPartitionKeyOpaque = extraResponseInfo.cookiePartitionKeyOpaque || null;
        this.responseHeaders = extraResponseInfo.responseHeaders;
        this.originalResponseHeaders = extraResponseInfo.responseHeaders.map(headerEntry => ({ ...headerEntry }));
        if (extraResponseInfo.responseHeadersText) {
            this.responseHeadersText = extraResponseInfo.responseHeadersText;
            if (!this.requestHeadersText()) {
                let requestHeadersText = `${this.requestMethod} ${this.parsedURL.path}`;
                if (this.parsedURL.queryParams) {
                    requestHeadersText += `?${this.parsedURL.queryParams}`;
                }
                requestHeadersText += ' HTTP/1.1\r\n';
                for (const { name, value } of this.requestHeaders()) {
                    requestHeadersText += `${name}: ${value}\r\n`;
                }
                this.setRequestHeadersText(requestHeadersText);
            }
            this.statusText = NetworkRequest.parseStatusTextFromResponseHeadersText(extraResponseInfo.responseHeadersText);
        }
        this.#remoteAddressSpace = extraResponseInfo.resourceIPAddressSpace;
        if (extraResponseInfo.statusCode) {
            this.statusCode = extraResponseInfo.statusCode;
        }
        this.#hasExtraResponseInfo = true;
        const networkManager = NetworkManager.forRequest(this);
        if (!networkManager) {
            return;
        }
        for (const blockedCookie of this.#blockedResponseCookies) {
            if (blockedCookie.blockedReasons.includes("NameValuePairExceedsMaxSize" )) {
                const message = i18nString$M(UIStrings$13.setcookieHeaderIsIgnoredIn, {
                    PH1: this.url(),
                });
                networkManager.dispatchEventToListeners(Events$c.MessageGenerated, { message, requestId: this.#requestId, warning: true });
            }
        }
        const cookieModel = networkManager.target().model(CookieModel);
        if (!cookieModel) {
            return;
        }
        for (const exemptedCookie of this.#exemptedResponseCookies) {
            cookieModel.removeBlockedCookie(exemptedCookie.cookie);
        }
        for (const blockedCookie of this.#blockedResponseCookies) {
            const cookie = blockedCookie.cookie;
            if (!cookie) {
                continue;
            }
            if (blockedCookie.blockedReasons.includes("ThirdPartyPhaseout" )) {
                this.#hasThirdPartyCookiePhaseoutIssue = true;
            }
            cookieModel.addBlockedCookie(cookie, blockedCookie.blockedReasons.map(blockedReason => ({
                attribute: setCookieBlockedReasonToAttribute(blockedReason),
                uiString: setCookieBlockedReasonToUiString(blockedReason),
            })));
        }
    }
    hasExtraResponseInfo() {
        return this.#hasExtraResponseInfo;
    }
    blockedResponseCookies() {
        return this.#blockedResponseCookies;
    }
    exemptedResponseCookies() {
        return this.#exemptedResponseCookies;
    }
    nonBlockedResponseCookies() {
        const blockedCookieLines = this.blockedResponseCookies().map(blockedCookie => blockedCookie.cookieLine);
        const responseCookies = this.responseCookies.filter(cookie => {
            const index = blockedCookieLines.indexOf(cookie.getCookieLine());
            if (index !== -1) {
                blockedCookieLines[index] = null;
                return false;
            }
            return true;
        });
        return responseCookies;
    }
    responseCookiesPartitionKey() {
        return this.#responseCookiesPartitionKey;
    }
    responseCookiesPartitionKeyOpaque() {
        return this.#responseCookiesPartitionKeyOpaque;
    }
    redirectSourceSignedExchangeInfoHasNoErrors() {
        return (this.#redirectSource !== null && this.#redirectSource.#signedExchangeInfo !== null &&
            !this.#redirectSource.#signedExchangeInfo.errors);
    }
    clientSecurityState() {
        return this.#clientSecurityState;
    }
    setTrustTokenParams(trustTokenParams) {
        this.#trustTokenParams = trustTokenParams;
    }
    trustTokenParams() {
        return this.#trustTokenParams;
    }
    setTrustTokenOperationDoneEvent(doneEvent) {
        this.#trustTokenOperationDoneEvent = doneEvent;
        this.dispatchEventToListeners(Events$d.TRUST_TOKEN_RESULT_ADDED);
    }
    trustTokenOperationDoneEvent() {
        return this.#trustTokenOperationDoneEvent;
    }
    setIsSameSite(isSameSite) {
        this.#isSameSite = isSameSite;
    }
    isSameSite() {
        return this.#isSameSite;
    }
    setIsAdRelated(isAdRelated) {
        this.#isAdRelated = isAdRelated;
    }
    isAdRelated() {
        return this.#isAdRelated;
    }
    getAssociatedData(key) {
        return this.#associatedData.get(key) || null;
    }
    setAssociatedData(key, data) {
        this.#associatedData.set(key, data);
    }
    deleteAssociatedData(key) {
        this.#associatedData.delete(key);
    }
    hasThirdPartyCookiePhaseoutIssue() {
        return this.#hasThirdPartyCookiePhaseoutIssue;
    }
    addDataReceivedEvent({ timestamp, dataLength, encodedDataLength, data, }) {
        this.resourceSize += dataLength;
        if (encodedDataLength !== -1) {
            this.increaseTransferSize(encodedDataLength);
        }
        this.endTime = timestamp;
        if (data) {
            void this.#streamingContentData?.then(contentData => {
                if (!isError(contentData)) {
                    contentData.addChunk(data);
                }
            });
        }
    }
    waitForResponseReceived() {
        if (this.responseReceivedPromise) {
            return this.responseReceivedPromise;
        }
        const { promise, resolve } = Promise.withResolvers();
        this.responseReceivedPromise = promise;
        this.responseReceivedPromiseResolve = resolve;
        return this.responseReceivedPromise;
    }
}
var Events$d;
(function (Events) {
    Events["FINISHED_LOADING"] = "FinishedLoading";
    Events["TIMING_CHANGED"] = "TimingChanged";
    Events["REMOTE_ADDRESS_CHANGED"] = "RemoteAddressChanged";
    Events["REQUEST_HEADERS_CHANGED"] = "RequestHeadersChanged";
    Events["RESPONSE_HEADERS_CHANGED"] = "ResponseHeadersChanged";
    Events["WEBSOCKET_FRAME_ADDED"] = "WebsocketFrameAdded";
    Events["DIRECTSOCKET_CHUNK_ADDED"] = "DirectsocketChunkAdded";
    Events["EVENT_SOURCE_MESSAGE_ADDED"] = "EventSourceMessageAdded";
    Events["TRUST_TOKEN_RESULT_ADDED"] = "TrustTokenResultAdded";
})(Events$d || (Events$d = {}));
var WebSocketFrameType;
(function (WebSocketFrameType) {
    WebSocketFrameType["Send"] = "send";
    WebSocketFrameType["Receive"] = "receive";
    WebSocketFrameType["Error"] = "error";
})(WebSocketFrameType || (WebSocketFrameType = {}));
const setCookieBlockedReasonToUiString = function (blockedReason) {
    switch (blockedReason) {
        case "SecureOnly" :
            return i18nString$M(UIStrings$13.blockedReasonSecureOnly);
        case "SameSiteStrict" :
            return i18nString$M(UIStrings$13.blockedReasonSameSiteStrictLax, {
                PH1: 'SameSite=Strict',
            });
        case "SameSiteLax" :
            return i18nString$M(UIStrings$13.blockedReasonSameSiteStrictLax, {
                PH1: 'SameSite=Lax',
            });
        case "SameSiteUnspecifiedTreatedAsLax" :
            return i18nString$M(UIStrings$13.blockedReasonSameSiteUnspecifiedTreatedAsLax);
        case "SameSiteNoneInsecure" :
            return i18nString$M(UIStrings$13.blockedReasonSameSiteNoneInsecure);
        case "UserPreferences" :
            return i18nString$M(UIStrings$13.thisSetcookieWasBlockedDueToUser);
        case "SyntaxError" :
            return i18nString$M(UIStrings$13.thisSetcookieHadInvalidSyntax);
        case "SchemeNotSupported" :
            return i18nString$M(UIStrings$13.theSchemeOfThisConnectionIsNot);
        case "OverwriteSecure" :
            return i18nString$M(UIStrings$13.blockedReasonOverwriteSecure);
        case "InvalidDomain" :
            return i18nString$M(UIStrings$13.blockedReasonInvalidDomain);
        case "InvalidPrefix" :
            return i18nString$M(UIStrings$13.blockedReasonInvalidPrefix);
        case "UnknownError" :
            return i18nString$M(UIStrings$13.anUnknownErrorWasEncounteredWhenTrying);
        case "SchemefulSameSiteStrict" :
            return i18nString$M(UIStrings$13.thisSetcookieWasBlockedBecauseItHadTheSamesiteStrictLax, { PH1: 'SameSite=Strict' });
        case "SchemefulSameSiteLax" :
            return i18nString$M(UIStrings$13.thisSetcookieWasBlockedBecauseItHadTheSamesiteStrictLax, { PH1: 'SameSite=Lax' });
        case "SchemefulSameSiteUnspecifiedTreatedAsLax" :
            return i18nString$M(UIStrings$13.thisSetcookieDidntSpecifyASamesite);
        case "NameValuePairExceedsMaxSize" :
            return i18nString$M(UIStrings$13.thisSetcookieWasBlockedBecauseTheNameValuePairExceedsMaxSize);
        case "DisallowedCharacter" :
            return i18nString$M(UIStrings$13.thisSetcookieHadADisallowedCharacter);
        case "ThirdPartyPhaseout" :
            return i18nString$M(UIStrings$13.thisSetcookieWasBlockedDueThirdPartyPhaseout);
    }
    return '';
};
const setCookieBlockedReasonToAttribute = function (blockedReason) {
    switch (blockedReason) {
        case "SecureOnly" :
        case "OverwriteSecure" :
            return "secure" ;
        case "SameSiteStrict" :
        case "SameSiteLax" :
        case "SameSiteUnspecifiedTreatedAsLax" :
        case "SameSiteNoneInsecure" :
        case "SchemefulSameSiteStrict" :
        case "SchemefulSameSiteLax" :
        case "SchemefulSameSiteUnspecifiedTreatedAsLax" :
            return "same-site" ;
        case "InvalidDomain" :
            return "domain" ;
        case "InvalidPrefix" :
            return "name" ;
        case "NameValuePairExceedsMaxSize" :
        case "UserPreferences" :
        case "ThirdPartyPhaseout" :
        case "SyntaxError" :
        case "SchemeNotSupported" :
        case "UnknownError" :
        case "DisallowedCharacter" :
            return null;
    }
    return null;
};
var DirectSocketType;
(function (DirectSocketType) {
    DirectSocketType[DirectSocketType["TCP"] = 1] = "TCP";
    DirectSocketType[DirectSocketType["UDP_BOUND"] = 2] = "UDP_BOUND";
    DirectSocketType[DirectSocketType["UDP_CONNECTED"] = 3] = "UDP_CONNECTED";
})(DirectSocketType || (DirectSocketType = {}));
var DirectSocketStatus;
(function (DirectSocketStatus) {
    DirectSocketStatus[DirectSocketStatus["OPENING"] = 1] = "OPENING";
    DirectSocketStatus[DirectSocketStatus["OPEN"] = 2] = "OPEN";
    DirectSocketStatus[DirectSocketStatus["CLOSED"] = 3] = "CLOSED";
    DirectSocketStatus[DirectSocketStatus["ABORTED"] = 4] = "ABORTED";
})(DirectSocketStatus || (DirectSocketStatus = {}));
var DirectSocketChunkType;
(function (DirectSocketChunkType) {
    DirectSocketChunkType["SEND"] = "send";
    DirectSocketChunkType["RECEIVE"] = "receive";
})(DirectSocketChunkType || (DirectSocketChunkType = {}));

// Copyright 2021 The Chromium Authors
class TargetManager extends ObjectWrapper {
    context;
    #targets;
    #observers;
    #modelListeners;
    #modelObservers;
    #scopedObservers;
    #isSuspended;
    #browserTarget;
    #scopeTarget;
    #defaultScopeSet;
    #scopeChangeListeners;
    #overrideAutoStartModels;
    constructor(context, overrideAutoStartModels) {
        super();
        this.context = context;
        this.#targets = new Set();
        this.#observers = new Set();
        this.#modelListeners = new Multimap();
        this.#modelObservers = new Multimap();
        this.#isSuspended = false;
        this.#browserTarget = null;
        this.#scopeTarget = null;
        this.#scopedObservers = new WeakSet();
        this.#defaultScopeSet = false;
        this.#scopeChangeListeners = new Set();
        this.#overrideAutoStartModels = overrideAutoStartModels;
    }
    static instance({ forceNew } = { forceNew: false }) {
        if (!globalInstance().has(TargetManager) || forceNew) {
            globalInstance().set(TargetManager, new TargetManager(globalInstance()));
        }
        return globalInstance().get(TargetManager);
    }
    static removeInstance() {
        globalInstance().delete(TargetManager);
    }
    onInspectedURLChange(target) {
        if (target !== this.#scopeTarget) {
            return;
        }
        InspectorFrontendHostInstance.inspectedURLChanged(target.inspectedURL() || EmptyUrlString);
        this.dispatchEventToListeners("InspectedURLChanged" , target);
    }
    onNameChange(target) {
        this.dispatchEventToListeners("NameChanged" , target);
    }
    async suspendAllTargets(reason) {
        if (this.#isSuspended) {
            return;
        }
        this.#isSuspended = true;
        this.dispatchEventToListeners("SuspendStateChanged" );
        const suspendPromises = Array.from(this.#targets.values(), target => target.suspend(reason));
        await Promise.all(suspendPromises);
    }
    async resumeAllTargets() {
        if (!this.#isSuspended) {
            return;
        }
        this.#isSuspended = false;
        this.dispatchEventToListeners("SuspendStateChanged" );
        const resumePromises = Array.from(this.#targets.values(), target => target.resume());
        await Promise.all(resumePromises);
    }
    allTargetsSuspended() {
        return this.#isSuspended;
    }
    models(modelClass, opts) {
        const result = [];
        for (const target of this.#targets) {
            if (opts?.scoped && !this.isInScope(target)) {
                continue;
            }
            const model = target.model(modelClass);
            if (!model) {
                continue;
            }
            result.push(model);
        }
        return result;
    }
    inspectedURL() {
        const mainTarget = this.primaryPageTarget();
        return mainTarget ? mainTarget.inspectedURL() : '';
    }
    observeModels(modelClass, observer, opts) {
        const models = this.models(modelClass, opts);
        this.#modelObservers.set(modelClass, observer);
        if (opts?.scoped) {
            this.#scopedObservers.add(observer);
        }
        for (const model of models) {
            observer.modelAdded(model);
        }
    }
    unobserveModels(modelClass, observer) {
        this.#modelObservers.delete(modelClass, observer);
        this.#scopedObservers.delete(observer);
    }
    modelAdded(modelClass, model, inScope) {
        for (const observer of this.#modelObservers.get(modelClass).values()) {
            if (!this.#scopedObservers.has(observer) || inScope) {
                observer.modelAdded(model);
            }
        }
    }
    modelRemoved(modelClass, model, inScope) {
        for (const observer of this.#modelObservers.get(modelClass).values()) {
            if (!this.#scopedObservers.has(observer) || inScope) {
                observer.modelRemoved(model);
            }
        }
    }
    addModelListener(modelClass, eventType, listener, thisObject, opts) {
        const wrappedListener = (event) => {
            if (!opts?.scoped || this.isInScope(event)) {
                listener.call(thisObject, event);
            }
        };
        for (const model of this.models(modelClass)) {
            model.addEventListener(eventType, wrappedListener);
        }
        this.#modelListeners.set(eventType, { modelClass, thisObject, listener, wrappedListener });
    }
    removeModelListener(modelClass, eventType, listener, thisObject) {
        if (!this.#modelListeners.has(eventType)) {
            return;
        }
        let wrappedListener = null;
        for (const info of this.#modelListeners.get(eventType)) {
            if (info.modelClass === modelClass && info.listener === listener && info.thisObject === thisObject) {
                wrappedListener = info.wrappedListener;
                this.#modelListeners.delete(eventType, info);
            }
        }
        if (wrappedListener) {
            for (const model of this.models(modelClass)) {
                model.removeEventListener(eventType, wrappedListener);
            }
        }
    }
    observeTargets(targetObserver, opts) {
        if (this.#observers.has(targetObserver)) {
            throw new Error('Observer can only be registered once');
        }
        if (opts?.scoped) {
            this.#scopedObservers.add(targetObserver);
        }
        for (const target of this.#targets) {
            if (!opts?.scoped || this.isInScope(target)) {
                targetObserver.targetAdded(target);
            }
        }
        this.#observers.add(targetObserver);
    }
    unobserveTargets(targetObserver) {
        this.#observers.delete(targetObserver);
        this.#scopedObservers.delete(targetObserver);
    }
    #autoStartModels() {
        const earlyModels = new Set();
        const models = new Set();
        const shouldAutostart = (model, info) => this.#overrideAutoStartModels ? this.#overrideAutoStartModels.has(model) : info.autostart;
        for (const [model, info] of SDKModel.registeredModels) {
            if (info.early) {
                earlyModels.add(model);
            }
            else if (shouldAutostart(model, info) || this.#modelObservers.has(model)) {
                models.add(model);
            }
        }
        return [...earlyModels, ...models];
    }
    createTarget(id, name, type, parentTarget, sessionId, waitForDebuggerInPage, connection, targetInfo) {
        const target = new Target(this, id, name, type, parentTarget, sessionId || '', this.#isSuspended, connection || null, targetInfo);
        if (waitForDebuggerInPage) {
            void target.pageAgent().invoke_waitForDebugger();
        }
        target.createModels(this.#autoStartModels());
        this.#targets.add(target);
        const inScope = this.isInScope(target);
        for (const observer of [...this.#observers]) {
            if (!this.#scopedObservers.has(observer) || inScope) {
                observer.targetAdded(target);
            }
        }
        for (const [modelClass, model] of target.models().entries()) {
            this.modelAdded(modelClass, model, inScope);
        }
        for (const key of this.#modelListeners.keysArray()) {
            for (const info of this.#modelListeners.get(key)) {
                const model = target.model(info.modelClass);
                if (model) {
                    model.addEventListener(key, info.wrappedListener);
                }
            }
        }
        if ((target === target.outermostTarget() &&
            (target.type() !== Type$2.FRAME || target === this.primaryPageTarget())) &&
            !this.#defaultScopeSet) {
            this.setScopeTarget(target);
        }
        return target;
    }
    removeTarget(target) {
        if (!this.#targets.has(target)) {
            return;
        }
        const inScope = this.isInScope(target);
        this.#targets.delete(target);
        for (const modelClass of target.models().keys()) {
            const model = target.models().get(modelClass);
            assertNotNullOrUndefined(model);
            this.modelRemoved(modelClass, model, inScope);
        }
        for (const observer of [...this.#observers]) {
            if (!this.#scopedObservers.has(observer) || inScope) {
                observer.targetRemoved(target);
            }
        }
        for (const key of this.#modelListeners.keysArray()) {
            for (const info of this.#modelListeners.get(key)) {
                const model = target.model(info.modelClass);
                if (model) {
                    model.removeEventListener(key, info.wrappedListener);
                }
            }
        }
    }
    targets() {
        return [...this.#targets];
    }
    targetById(id) {
        return this.targets().find(target => target.id() === id) || null;
    }
    rootTarget() {
        if (this.#targets.size === 0) {
            return null;
        }
        return this.#targets.values().next().value ?? null;
    }
    primaryPageTarget() {
        let target = this.rootTarget();
        if (target?.type() === Type$2.TAB) {
            target =
                this.targets().find(t => t.parentTarget() === target && t.type() === Type$2.FRAME && !t.targetInfo()?.subtype?.length) ||
                    null;
        }
        return target;
    }
    browserTarget() {
        return this.#browserTarget;
    }
    async maybeAttachInitialTarget() {
        if (!Boolean(Runtime.queryParam('browserConnection'))) {
            return false;
        }
        if (!this.#browserTarget) {
            this.#browserTarget = new Target(this,  'main',  'browser', Type$2.BROWSER,  null,
             '',  false,  null,  undefined);
            this.#browserTarget.createModels(this.#autoStartModels());
        }
        const targetId = await InspectorFrontendHostInstance.initialTargetId();
        void this.#browserTarget.targetAgent().invoke_autoAttachRelated({
            targetId,
            waitForDebuggerOnStart: true,
        });
        return true;
    }
    clearAllTargetsForTest() {
        this.#targets.clear();
    }
    isInScope(arg) {
        if (!arg) {
            return false;
        }
        if (isSDKModelEvent(arg)) {
            arg = arg.source;
        }
        if (arg instanceof SDKModel) {
            arg = arg.target();
        }
        while (arg && arg !== this.#scopeTarget) {
            arg = arg.parentTarget();
        }
        return Boolean(arg) && arg === this.#scopeTarget;
    }
    setScopeTarget(scopeTarget) {
        if (scopeTarget === this.#scopeTarget) {
            return;
        }
        for (const target of this.targets()) {
            if (!this.isInScope(target)) {
                continue;
            }
            for (const modelClass of this.#modelObservers.keysArray()) {
                const model = target.models().get(modelClass);
                if (!model) {
                    continue;
                }
                for (const observer of [...this.#modelObservers.get(modelClass)].filter(o => this.#scopedObservers.has(o))) {
                    observer.modelRemoved(model);
                }
            }
            for (const observer of [...this.#observers].filter(o => this.#scopedObservers.has(o))) {
                observer.targetRemoved(target);
            }
        }
        this.#scopeTarget = scopeTarget;
        for (const target of this.targets()) {
            if (!this.isInScope(target)) {
                continue;
            }
            for (const observer of [...this.#observers].filter(o => this.#scopedObservers.has(o))) {
                observer.targetAdded(target);
            }
            for (const [modelClass, model] of target.models().entries()) {
                for (const observer of [...this.#modelObservers.get(modelClass)].filter(o => this.#scopedObservers.has(o))) {
                    observer.modelAdded(model);
                }
            }
        }
        for (const scopeChangeListener of this.#scopeChangeListeners) {
            scopeChangeListener();
        }
        if (scopeTarget?.inspectedURL()) {
            this.onInspectedURLChange(scopeTarget);
        }
    }
    addScopeChangeListener(listener) {
        this.#scopeChangeListeners.add(listener);
    }
    scopeTarget() {
        return this.#scopeTarget;
    }
}
function isSDKModelEvent(arg) {
    return 'source' in arg && arg.source instanceof SDKModel;
}

// Copyright 2011 The Chromium Authors
const UIStrings$12 = {
    noContentForWebSocket: 'Content for WebSockets is currently not supported',
    noContentForRedirect: 'No content available because this request was redirected',
    noContentForPreflight: 'No content available for preflight request',
    noThrottling: 'No throttling',
    offline: 'Offline',
    slowG: '3G',
    fastG: 'Slow 4G',
    fast4G: 'Fast 4G',
    block: 'Block',
    requestWasBlockedByDevtoolsS: 'Request was blocked by DevTools: "{PH1}"',
    sFailedLoadingSS: '{PH1} failed loading: {PH2} "{PH3}".',
    sFinishedLoadingSS: '{PH1} finished loading: {PH2} "{PH3}".',
    directSocketStatusOpening: 'Opening',
    directSocketStatusOpen: 'Open',
    directSocketStatusClosed: 'Closed',
    directSocketStatusAborted: 'Aborted',
};
const str_$11 = registerUIStrings('core/sdk/NetworkManager.ts', UIStrings$12);
const i18nString$L = getLocalizedString.bind(undefined, str_$11);
const i18nLazyString$e = getLazilyComputedLocalizedString.bind(undefined, str_$11);
const requestToManagerMap = new WeakMap();
const CONNECTION_TYPES = new Map([
    ['2g', "cellular2g" ],
    ['3g', "cellular3g" ],
    ['4g', "cellular4g" ],
    ['bluetooth', "bluetooth" ],
    ['wifi', "wifi" ],
    ['wimax', "wimax" ],
]);
function customUserNetworkConditionsSetting() {
    return Settings.instance().moduleSetting('custom-network-conditions');
}
function activeNetworkThrottlingKeySetting() {
    return Settings.instance().createSetting('active-network-condition-key', "NO_THROTTLING" );
}
class NetworkManager extends SDKModel {
    dispatcher;
    fetchDispatcher;
    #networkAgent;
    #bypassServiceWorkerSetting;
    activeNetworkThrottlingKey = activeNetworkThrottlingKeySetting();
    constructor(target) {
        super(target);
        this.dispatcher = new NetworkDispatcher(this);
        this.fetchDispatcher = new FetchDispatcher(target.fetchAgent(), this);
        this.#networkAgent = target.networkAgent();
        target.registerNetworkDispatcher(this.dispatcher);
        target.registerFetchDispatcher(this.fetchDispatcher);
        if (Settings.instance().moduleSetting('cache-disabled').get()) {
            void this.#networkAgent.invoke_setCacheDisabled({ cacheDisabled: true });
        }
        void this.#networkAgent.invoke_enable({
            maxPostDataSize: MAX_EAGER_POST_REQUEST_BODY_LENGTH,
            enableDurableMessages: hostConfig.devToolsEnableDurableMessages?.enabled,
            maxTotalBufferSize: MAX_RESPONSE_BODY_TOTAL_BUFFER_LENGTH,
            reportDirectSocketTraffic: true,
        });
        void this.#networkAgent.invoke_setAttachDebugStack({ enabled: true });
        this.#bypassServiceWorkerSetting =
            Settings.instance().createSetting('bypass-service-worker', false);
        if (this.#bypassServiceWorkerSetting.get()) {
            this.bypassServiceWorkerChanged();
        }
        this.#bypassServiceWorkerSetting.addChangeListener(this.bypassServiceWorkerChanged, this);
        Settings.instance()
            .moduleSetting('cache-disabled')
            .addChangeListener(this.cacheDisabledSettingChanged, this);
    }
    static forRequest(request) {
        return requestToManagerMap.get(request) || null;
    }
    static canReplayRequest(request) {
        return Boolean(requestToManagerMap.get(request)) && Boolean(request.backendRequestId()) && !request.isRedirect() &&
            request.resourceType() === resourceTypes.XHR;
    }
    static replayRequest(request) {
        const manager = requestToManagerMap.get(request);
        const requestId = request.backendRequestId();
        if (!manager || !requestId || request.isRedirect()) {
            return;
        }
        void manager.#networkAgent.invoke_replayXHR({ requestId });
    }
    static async searchInRequest(request, query, caseSensitive, isRegex) {
        const manager = NetworkManager.forRequest(request);
        const requestId = request.backendRequestId();
        if (!manager || !requestId || request.isRedirect()) {
            return [];
        }
        const response = await manager.#networkAgent.invoke_searchInResponseBody({ requestId, query, caseSensitive, isRegex });
        return performSearchInSearchMatches(response.result || [], query, caseSensitive, isRegex);
    }
    static async requestContentData(request) {
        if (request.resourceType() === resourceTypes.WebSocket) {
            return { error: i18nString$L(UIStrings$12.noContentForWebSocket) };
        }
        if (!request.finished) {
            await request.once(Events$d.FINISHED_LOADING);
        }
        if (request.isRedirect()) {
            return { error: i18nString$L(UIStrings$12.noContentForRedirect) };
        }
        if (request.isPreflightRequest()) {
            return { error: i18nString$L(UIStrings$12.noContentForPreflight) };
        }
        const manager = NetworkManager.forRequest(request);
        if (!manager) {
            return { error: 'No network manager for request' };
        }
        const requestId = request.backendRequestId();
        if (!requestId) {
            return { error: 'No backend request id for request' };
        }
        const response = await manager.#networkAgent.invoke_getResponseBody({ requestId });
        const error = response.getError();
        if (error) {
            return { error };
        }
        return new ContentData(response.body, response.base64Encoded, request.mimeType, request.charset() ?? undefined);
    }
    static async streamResponseBody(request) {
        if (request.finished) {
            return { error: 'Streaming the response body is only available for in-flight requests.' };
        }
        const manager = NetworkManager.forRequest(request);
        if (!manager) {
            return { error: 'No network manager for request' };
        }
        const requestId = request.backendRequestId();
        if (!requestId) {
            return { error: 'No backend request id for request' };
        }
        const response = await manager.#networkAgent.invoke_streamResourceContent({ requestId });
        const error = response.getError();
        if (error) {
            return { error };
        }
        await request.waitForResponseReceived();
        return new ContentData(response.bufferedData,  true, request.mimeType, request.charset() ?? undefined);
    }
    static async requestPostData(request) {
        const manager = NetworkManager.forRequest(request);
        if (!manager) {
            console.error('No network manager for request');
            return null;
        }
        const requestId = request.backendRequestId();
        if (!requestId) {
            console.error('No backend request id for request');
            return null;
        }
        try {
            const { postData, base64Encoded } = await manager.#networkAgent.invoke_getRequestPostData({ requestId });
            if (base64Encoded && postData) {
                const binaryString = window.atob(postData);
                const bytes = new Uint8Array(binaryString.length);
                for (let i = 0; i < binaryString.length; i++) {
                    bytes[i] = binaryString.charCodeAt(i);
                }
                const requestContentType = request.requestContentType();
                const charset = requestContentType ? parseContentType(requestContentType).charset ?? 'utf-8' : 'utf-8';
                const contentEncoding = request.requestContentEncoding()?.toLowerCase();
                if (contentEncoding) {
                    const decompressed = await NetworkManager.#tryDecompressBody(bytes.buffer, contentEncoding, charset);
                    if (decompressed !== null) {
                        return decompressed;
                    }
                }
                return new TextDecoder(charset).decode(bytes);
            }
            return postData;
        }
        catch (e) {
            return e.message;
        }
    }
    static async #tryDecompressBody(buffer, encoding, charset) {
        try {
            if (encoding.includes('gzip') && isGzip(buffer)) {
                return await decompress(buffer, charset);
            }
            if (encoding.includes('deflate')) {
                return await decompressDeflate(buffer, charset);
            }
        }
        catch (e) {
            console.warn('Failed to decompress request body:', e);
        }
        return null;
    }
    static connectionType(conditions) {
        if (!conditions.download && !conditions.upload) {
            return "none" ;
        }
        try {
            const title = typeof conditions.title === 'function' ? conditions.title().toLowerCase() : conditions.title.toLowerCase();
            for (const [name, protocolType] of CONNECTION_TYPES) {
                if (title.includes(name)) {
                    return protocolType;
                }
            }
        }
        catch {
            return "none" ;
        }
        return "other" ;
    }
    static lowercaseHeaders(headers) {
        const newHeaders = {};
        for (const headerName in headers) {
            newHeaders[headerName.toLowerCase()] = headers[headerName];
        }
        return newHeaders;
    }
    requestForURL(url) {
        return this.dispatcher.requestForURL(url);
    }
    requestForId(id) {
        return this.dispatcher.requestForId(id);
    }
    requestForLoaderId(loaderId) {
        return this.dispatcher.requestForLoaderId(loaderId);
    }
    cacheDisabledSettingChanged({ data: enabled }) {
        void this.#networkAgent.invoke_setCacheDisabled({ cacheDisabled: enabled });
    }
    dispose() {
        Settings.instance()
            .moduleSetting('cache-disabled')
            .removeChangeListener(this.cacheDisabledSettingChanged, this);
    }
    bypassServiceWorkerChanged() {
        void this.#networkAgent.invoke_setBypassServiceWorker({ bypass: this.#bypassServiceWorkerSetting.get() });
    }
    async getSecurityIsolationStatus(frameId) {
        const result = await this.#networkAgent.invoke_getSecurityIsolationStatus({ frameId: frameId ?? undefined });
        if (result.getError()) {
            return null;
        }
        return result.status;
    }
    async enableReportingApi(enable = true) {
        return await this.#networkAgent.invoke_enableReportingApi({ enable });
    }
    async enableDeviceBoundSessions(enable = true) {
        return await this.#networkAgent.invoke_enableDeviceBoundSessions({ enable });
    }
    async loadNetworkResource(frameId, url, options) {
        const result = await this.#networkAgent.invoke_loadNetworkResource({ frameId: frameId ?? undefined, url, options });
        if (result.getError()) {
            throw new Error(result.getError());
        }
        return result.resource;
    }
    clearRequests() {
        this.dispatcher.clearRequests();
    }
}
var Events$c;
(function (Events) {
    Events["RequestStarted"] = "RequestStarted";
    Events["RequestUpdated"] = "RequestUpdated";
    Events["RequestFinished"] = "RequestFinished";
    Events["RequestUpdateDropped"] = "RequestUpdateDropped";
    Events["ResponseReceived"] = "ResponseReceived";
    Events["MessageGenerated"] = "MessageGenerated";
    Events["RequestRedirected"] = "RequestRedirected";
    Events["LoadingFinished"] = "LoadingFinished";
    Events["ReportingApiReportAdded"] = "ReportingApiReportAdded";
    Events["ReportingApiReportUpdated"] = "ReportingApiReportUpdated";
    Events["ReportingApiEndpointsChangedForOrigin"] = "ReportingApiEndpointsChangedForOrigin";
    Events["DeviceBoundSessionsAdded"] = "DeviceBoundSessionsAdded";
    Events["DeviceBoundSessionEventOccurred"] = "DeviceBoundSessionEventOccurred";
})(Events$c || (Events$c = {}));
const BlockingConditions = {
    key: "BLOCKING" ,
    block: true,
    title: i18nLazyString$e(UIStrings$12.block),
};
const NoThrottlingConditions = {
    key: "NO_THROTTLING" ,
    title: i18nLazyString$e(UIStrings$12.noThrottling),
    i18nTitleKey: UIStrings$12.noThrottling,
    download: -1,
    upload: -1,
    latency: 0,
};
const OfflineConditions = {
    key: "OFFLINE" ,
    title: i18nLazyString$e(UIStrings$12.offline),
    i18nTitleKey: UIStrings$12.offline,
    download: 0,
    upload: 0,
    latency: 0,
};
const slow3GTargetLatency = 400;
const Slow3GConditions = {
    key: "SPEED_3G" ,
    title: i18nLazyString$e(UIStrings$12.slowG),
    i18nTitleKey: UIStrings$12.slowG,
    download: 500 * 1000 / 8 * .8,
    upload: 500 * 1000 / 8 * .8,
    latency: slow3GTargetLatency * 5,
    targetLatency: slow3GTargetLatency,
};
const slow4GTargetLatency = 150;
const Slow4GConditions = {
    key: "SPEED_SLOW_4G" ,
    title: i18nLazyString$e(UIStrings$12.fastG),
    i18nTitleKey: UIStrings$12.fastG,
    download: 1.6 * 1000 * 1000 / 8 * .9,
    upload: 750 * 1000 / 8 * .9,
    latency: slow4GTargetLatency * 3.75,
    targetLatency: slow4GTargetLatency,
};
const fast4GTargetLatency = 60;
const Fast4GConditions = {
    key: "SPEED_FAST_4G" ,
    title: i18nLazyString$e(UIStrings$12.fast4G),
    i18nTitleKey: UIStrings$12.fast4G,
    download: 9 * 1000 * 1000 / 8 * .9,
    upload: 1.5 * 1000 * 1000 / 8 * .9,
    latency: fast4GTargetLatency * 2.75,
    targetLatency: fast4GTargetLatency,
};
const MAX_EAGER_POST_REQUEST_BODY_LENGTH = 64 * 1024;
const MAX_RESPONSE_BODY_TOTAL_BUFFER_LENGTH = 250 * 1024 * 1024;
class FetchDispatcher {
    #fetchAgent;
    #manager;
    constructor(agent, manager) {
        this.#fetchAgent = agent;
        this.#manager = manager;
    }
    requestPaused({ requestId, request, resourceType, responseStatusCode, responseHeaders, networkId }) {
        const networkRequest = networkId ? this.#manager.requestForId(networkId) : null;
        if (networkRequest?.originalResponseHeaders.length === 0 && responseHeaders) {
            networkRequest.originalResponseHeaders = responseHeaders;
        }
        void MultitargetNetworkManager.instance().requestIntercepted(new InterceptedRequest(this.#fetchAgent, request, resourceType, requestId, networkRequest, responseStatusCode, responseHeaders));
    }
    authRequired({}) {
    }
}
class NetworkDispatcher {
    #manager;
    #requestsById = new Map();
    #requestsByURL = new Map();
    #requestsByLoaderId = new Map();
    #requestIdToExtraInfoBuilder = new Map();
    #requestIdToTrustTokenEvent = new Map();
    constructor(manager) {
        this.#manager = manager;
        MultitargetNetworkManager.instance().addEventListener("RequestIntercepted" , this.#markAsIntercepted.bind(this));
    }
    #markAsIntercepted(event) {
        const request = this.requestForId(event.data);
        if (request) {
            request.setWasIntercepted(true);
        }
    }
    headersMapToHeadersArray(headersMap) {
        const result = [];
        for (const name in headersMap) {
            const values = headersMap[name].split('\n');
            for (let i = 0; i < values.length; ++i) {
                result.push({ name, value: values[i] });
            }
        }
        return result;
    }
    updateNetworkRequestWithRequest(networkRequest, request) {
        networkRequest.requestMethod = request.method;
        networkRequest.setRequestHeaders(this.headersMapToHeadersArray(request.headers));
        const isCompressed = Boolean(networkRequest.requestContentEncoding());
        networkRequest.setRequestFormData(Boolean(request.hasPostData), isCompressed ? null : (request.postData || null));
        networkRequest.setInitialPriority(request.initialPriority);
        networkRequest.mixedContentType = request.mixedContentType || "none" ;
        networkRequest.setReferrerPolicy(request.referrerPolicy);
        networkRequest.setIsSameSite(request.isSameSite || false);
        networkRequest.setIsAdRelated(request.isAdRelated || false);
    }
    updateNetworkRequestWithResponse(networkRequest, response) {
        if (response.url && networkRequest.url() !== response.url) {
            networkRequest.setUrl(response.url);
        }
        networkRequest.mimeType = response.mimeType;
        networkRequest.setCharset(response.charset);
        if (!networkRequest.statusCode || networkRequest.wasIntercepted()) {
            networkRequest.statusCode = response.status;
        }
        if (!networkRequest.statusText || networkRequest.wasIntercepted()) {
            networkRequest.statusText = response.statusText;
        }
        if (!networkRequest.hasExtraResponseInfo() || networkRequest.wasIntercepted()) {
            networkRequest.responseHeaders = this.headersMapToHeadersArray(response.headers);
        }
        if (response.encodedDataLength >= 0) {
            networkRequest.setTransferSize(response.encodedDataLength);
        }
        if (response.requestHeaders && !networkRequest.hasExtraRequestInfo()) {
            networkRequest.setRequestHeaders(this.headersMapToHeadersArray(response.requestHeaders));
            networkRequest.setRequestHeadersText(response.requestHeadersText || '');
        }
        networkRequest.connectionReused = response.connectionReused;
        networkRequest.connectionId = String(response.connectionId);
        if (response.remoteIPAddress) {
            networkRequest.setRemoteAddress(response.remoteIPAddress, response.remotePort || -1);
        }
        if (response.fromServiceWorker) {
            networkRequest.fetchedViaServiceWorker = true;
        }
        if (response.fromDiskCache) {
            networkRequest.setFromDiskCache();
        }
        if (response.fromPrefetchCache) {
            networkRequest.setFromPrefetchCache();
        }
        if (response.fromEarlyHints) {
            networkRequest.setFromEarlyHints();
        }
        if (response.cacheStorageCacheName) {
            networkRequest.setResponseCacheStorageCacheName(response.cacheStorageCacheName);
        }
        if (response.serviceWorkerRouterInfo) {
            networkRequest.serviceWorkerRouterInfo = response.serviceWorkerRouterInfo;
        }
        if (response.responseTime) {
            networkRequest.setResponseRetrievalTime(new Date(response.responseTime));
        }
        networkRequest.timing = response.timing;
        networkRequest.protocol = response.protocol || '';
        networkRequest.alternateProtocolUsage = response.alternateProtocolUsage;
        if (response.serviceWorkerResponseSource) {
            networkRequest.setServiceWorkerResponseSource(response.serviceWorkerResponseSource);
        }
        networkRequest.setSecurityState(response.securityState);
        if (response.securityDetails) {
            networkRequest.setSecurityDetails(response.securityDetails);
        }
        const newResourceType = ResourceType.fromMimeTypeOverride(networkRequest.mimeType);
        if (newResourceType) {
            networkRequest.setResourceType(newResourceType);
        }
        if (networkRequest.responseReceivedPromiseResolve) {
            networkRequest.responseReceivedPromiseResolve();
        }
        else {
            networkRequest.responseReceivedPromise = Promise.resolve();
        }
    }
    requestForId(id) {
        return this.#requestsById.get(id) || null;
    }
    requestForURL(url) {
        return this.#requestsByURL.get(url) || null;
    }
    requestForLoaderId(loaderId) {
        return this.#requestsByLoaderId.get(loaderId) || null;
    }
    resourceChangedPriority({ requestId, newPriority }) {
        const networkRequest = this.#requestsById.get(requestId);
        if (networkRequest) {
            networkRequest.setPriority(newPriority);
        }
    }
    signedExchangeReceived({ requestId, info }) {
        let networkRequest = this.#requestsById.get(requestId);
        if (!networkRequest) {
            networkRequest = this.#requestsByURL.get(info.outerResponse.url);
            if (!networkRequest) {
                return;
            }
            const backendRequestId = networkRequest.backendRequestId() || requestId;
            requestId = backendRequestId;
        }
        networkRequest.setSignedExchangeInfo(info);
        networkRequest.setResourceType(resourceTypes.SignedExchange);
        this.updateNetworkRequestWithResponse(networkRequest, info.outerResponse);
        this.updateNetworkRequest(networkRequest);
        this.getExtraInfoBuilder(requestId).addHasExtraInfo(info.hasExtraInfo);
        this.#manager.dispatchEventToListeners(Events$c.ResponseReceived, { request: networkRequest, response: info.outerResponse });
    }
    requestWillBeSent({ requestId, loaderId, documentURL, request, timestamp, wallTime, initiator, redirectHasExtraInfo, redirectResponse, type, frameId, hasUserGesture, renderBlockingBehavior, }) {
        let networkRequest = this.#requestsById.get(requestId);
        if (networkRequest) {
            if (!redirectResponse) {
                return;
            }
            if (!networkRequest.signedExchangeInfo()) {
                this.responseReceived({
                    requestId,
                    loaderId,
                    timestamp,
                    type: type || "Other" ,
                    response: redirectResponse,
                    hasExtraInfo: redirectHasExtraInfo,
                    frameId,
                });
            }
            networkRequest = this.appendRedirect(requestId, timestamp, request.url);
            this.#manager.dispatchEventToListeners(Events$c.RequestRedirected, networkRequest);
        }
        else {
            networkRequest = NetworkRequest.create(requestId, request.url, documentURL, frameId ?? null, loaderId, initiator, hasUserGesture);
            if (renderBlockingBehavior) {
                networkRequest.setRenderBlockingBehavior(renderBlockingBehavior);
            }
            requestToManagerMap.set(networkRequest, this.#manager);
        }
        networkRequest.hasNetworkData = true;
        this.updateNetworkRequestWithRequest(networkRequest, request);
        networkRequest.setIssueTime(timestamp, wallTime);
        networkRequest.setResourceType(type ? resourceTypes[type] : resourceTypes.Other);
        if (request.trustTokenParams) {
            networkRequest.setTrustTokenParams(request.trustTokenParams);
        }
        const maybeTrustTokenEvent = this.#requestIdToTrustTokenEvent.get(requestId);
        if (maybeTrustTokenEvent) {
            networkRequest.setTrustTokenOperationDoneEvent(maybeTrustTokenEvent);
            this.#requestIdToTrustTokenEvent.delete(requestId);
        }
        this.getExtraInfoBuilder(requestId).addRequest(networkRequest);
        this.startNetworkRequest(networkRequest, request);
    }
    requestServedFromCache({ requestId }) {
        const networkRequest = this.#requestsById.get(requestId);
        if (!networkRequest) {
            return;
        }
        networkRequest.setFromMemoryCache();
    }
    responseReceived({ requestId, loaderId, timestamp, type, response, hasExtraInfo, frameId }) {
        const networkRequest = this.#requestsById.get(requestId);
        const lowercaseHeaders = NetworkManager.lowercaseHeaders(response.headers);
        if (!networkRequest) {
            const lastModifiedHeader = lowercaseHeaders['last-modified'];
            const eventData = {
                url: response.url,
                frameId: frameId ?? null,
                loaderId,
                resourceType: type,
                mimeType: response.mimeType,
                lastModified: lastModifiedHeader ? new Date(lastModifiedHeader) : null,
            };
            this.#manager.dispatchEventToListeners(Events$c.RequestUpdateDropped, eventData);
            return;
        }
        networkRequest.responseReceivedTime = timestamp;
        networkRequest.setResourceType(resourceTypes[type]);
        this.updateNetworkRequestWithResponse(networkRequest, response);
        this.updateNetworkRequest(networkRequest);
        this.getExtraInfoBuilder(requestId).addHasExtraInfo(hasExtraInfo);
        this.#manager.dispatchEventToListeners(Events$c.ResponseReceived, { request: networkRequest, response });
    }
    dataReceived(event) {
        let networkRequest = this.#requestsById.get(event.requestId);
        if (!networkRequest) {
            networkRequest = this.maybeAdoptMainResourceRequest(event.requestId);
        }
        if (!networkRequest) {
            return;
        }
        networkRequest.addDataReceivedEvent(event);
        this.updateNetworkRequest(networkRequest);
    }
    loadingFinished({ requestId, timestamp: finishTime, encodedDataLength }) {
        let networkRequest = this.#requestsById.get(requestId);
        if (!networkRequest) {
            networkRequest = this.maybeAdoptMainResourceRequest(requestId);
        }
        if (!networkRequest) {
            return;
        }
        this.getExtraInfoBuilder(requestId).finished();
        this.finishNetworkRequest(networkRequest, finishTime, encodedDataLength);
        this.#manager.dispatchEventToListeners(Events$c.LoadingFinished, networkRequest);
    }
    loadingFailed({ requestId, timestamp: time, type: resourceType, errorText: localizedDescription, canceled, blockedReason, corsErrorStatus, }) {
        const networkRequest = this.#requestsById.get(requestId);
        if (!networkRequest) {
            return;
        }
        networkRequest.failed = true;
        networkRequest.setResourceType(resourceTypes[resourceType]);
        networkRequest.canceled = Boolean(canceled);
        if (blockedReason) {
            networkRequest.setBlockedReason(blockedReason);
            if (blockedReason === "inspector" ) {
                const message = i18nString$L(UIStrings$12.requestWasBlockedByDevtoolsS, { PH1: networkRequest.url() });
                this.#manager.dispatchEventToListeners(Events$c.MessageGenerated, { message, requestId, warning: true });
            }
        }
        if (corsErrorStatus) {
            networkRequest.setCorsErrorStatus(corsErrorStatus);
        }
        networkRequest.localizedFailDescription = localizedDescription;
        this.getExtraInfoBuilder(requestId).finished();
        this.finishNetworkRequest(networkRequest, time, -1);
    }
    webSocketCreated({ requestId, url: requestURL, initiator }) {
        const networkRequest = NetworkRequest.createForSocket(requestId, requestURL, initiator);
        requestToManagerMap.set(networkRequest, this.#manager);
        networkRequest.setResourceType(resourceTypes.WebSocket);
        this.startNetworkRequest(networkRequest, null);
    }
    webSocketWillSendHandshakeRequest({ requestId, timestamp: time, wallTime, request }) {
        const networkRequest = this.#requestsById.get(requestId);
        if (!networkRequest) {
            return;
        }
        networkRequest.requestMethod = 'GET';
        networkRequest.setRequestHeaders(this.headersMapToHeadersArray(request.headers));
        networkRequest.setIssueTime(time, wallTime);
        this.updateNetworkRequest(networkRequest);
    }
    webSocketHandshakeResponseReceived({ requestId, timestamp: time, response }) {
        const networkRequest = this.#requestsById.get(requestId);
        if (!networkRequest) {
            return;
        }
        networkRequest.statusCode = response.status;
        networkRequest.statusText = response.statusText;
        networkRequest.responseHeaders = this.headersMapToHeadersArray(response.headers);
        networkRequest.responseHeadersText = response.headersText || '';
        if (response.requestHeaders) {
            networkRequest.setRequestHeaders(this.headersMapToHeadersArray(response.requestHeaders));
        }
        if (response.requestHeadersText) {
            networkRequest.setRequestHeadersText(response.requestHeadersText);
        }
        networkRequest.responseReceivedTime = time;
        networkRequest.protocol = 'websocket';
        this.updateNetworkRequest(networkRequest);
    }
    webSocketFrameReceived({ requestId, timestamp: time, response }) {
        const networkRequest = this.#requestsById.get(requestId);
        if (!networkRequest) {
            return;
        }
        networkRequest.addProtocolFrame(response, time, false);
        networkRequest.responseReceivedTime = time;
        this.updateNetworkRequest(networkRequest);
    }
    webSocketFrameSent({ requestId, timestamp: time, response }) {
        const networkRequest = this.#requestsById.get(requestId);
        if (!networkRequest) {
            return;
        }
        networkRequest.addProtocolFrame(response, time, true);
        networkRequest.responseReceivedTime = time;
        this.updateNetworkRequest(networkRequest);
    }
    webSocketFrameError({ requestId, timestamp: time, errorMessage }) {
        const networkRequest = this.#requestsById.get(requestId);
        if (!networkRequest) {
            return;
        }
        networkRequest.addProtocolFrameError(errorMessage, time);
        networkRequest.responseReceivedTime = time;
        this.updateNetworkRequest(networkRequest);
    }
    webSocketClosed({ requestId, timestamp: time }) {
        const networkRequest = this.#requestsById.get(requestId);
        if (!networkRequest) {
            return;
        }
        this.finishNetworkRequest(networkRequest, time, -1);
    }
    eventSourceMessageReceived({ requestId, timestamp: time, eventName, eventId, data }) {
        const networkRequest = this.#requestsById.get(requestId);
        if (!networkRequest) {
            return;
        }
        networkRequest.addEventSourceMessage(time, eventName, eventId, data);
    }
    requestIntercepted({}) {
    }
    requestWillBeSentExtraInfo({ requestId, associatedCookies, headers, deviceBoundSessionUsages, clientSecurityState, connectTiming, siteHasCookieInOtherPartition, appliedNetworkConditionsId }) {
        const blockedRequestCookies = [];
        const includedRequestCookies = [];
        for (const { blockedReasons, exemptionReason, cookie } of associatedCookies) {
            if (blockedReasons.length === 0) {
                includedRequestCookies.push({ exemptionReason, cookie: Cookie.fromProtocolCookie(cookie) });
            }
            else {
                blockedRequestCookies.push({ blockedReasons, cookie: Cookie.fromProtocolCookie(cookie) });
            }
        }
        const extraRequestInfo = {
            blockedRequestCookies,
            includedRequestCookies,
            requestHeaders: this.headersMapToHeadersArray(headers),
            deviceBoundSessionUsages,
            clientSecurityState,
            connectTiming,
            siteHasCookieInOtherPartition,
            appliedNetworkConditionsId,
        };
        this.getExtraInfoBuilder(requestId).addRequestExtraInfo(extraRequestInfo);
        const networkRequest = this.#requestsById.get(requestId);
        if (appliedNetworkConditionsId && networkRequest) {
            networkRequest.setAppliedNetworkConditions(appliedNetworkConditionsId);
            this.updateNetworkRequest(networkRequest);
        }
    }
    responseReceivedEarlyHints({ requestId, headers, }) {
        this.getExtraInfoBuilder(requestId).setEarlyHintsHeaders(this.headersMapToHeadersArray(headers));
    }
    responseReceivedExtraInfo({ requestId, blockedCookies, headers, headersText, resourceIPAddressSpace, statusCode, cookiePartitionKey, cookiePartitionKeyOpaque, exemptedCookies, }) {
        const extraResponseInfo = {
            blockedResponseCookies: blockedCookies.map(blockedCookie => ({
                blockedReasons: blockedCookie.blockedReasons,
                cookieLine: blockedCookie.cookieLine,
                cookie: blockedCookie.cookie ? Cookie.fromProtocolCookie(blockedCookie.cookie) : null,
            })),
            responseHeaders: this.headersMapToHeadersArray(headers),
            responseHeadersText: headersText,
            resourceIPAddressSpace,
            statusCode,
            cookiePartitionKey,
            cookiePartitionKeyOpaque,
            exemptedResponseCookies: exemptedCookies?.map(exemptedCookie => ({
                cookie: Cookie.fromProtocolCookie(exemptedCookie.cookie),
                cookieLine: exemptedCookie.cookieLine,
                exemptionReason: exemptedCookie.exemptionReason,
            })),
        };
        this.getExtraInfoBuilder(requestId).addResponseExtraInfo(extraResponseInfo);
    }
    getExtraInfoBuilder(requestId) {
        let builder;
        if (!this.#requestIdToExtraInfoBuilder.has(requestId)) {
            builder = new ExtraInfoBuilder();
            this.#requestIdToExtraInfoBuilder.set(requestId, builder);
        }
        else {
            builder = this.#requestIdToExtraInfoBuilder.get(requestId);
        }
        return builder;
    }
    appendRedirect(requestId, time, redirectURL) {
        const originalNetworkRequest = this.#requestsById.get(requestId);
        if (!originalNetworkRequest) {
            throw new Error(`Could not find original network request for ${requestId}`);
        }
        let redirectCount = 0;
        for (let redirect = originalNetworkRequest.redirectSource(); redirect; redirect = redirect.redirectSource()) {
            redirectCount++;
        }
        originalNetworkRequest.markAsRedirect(redirectCount);
        this.finishNetworkRequest(originalNetworkRequest, time, -1);
        const newNetworkRequest = NetworkRequest.create(requestId, redirectURL, originalNetworkRequest.documentURL, originalNetworkRequest.frameId, originalNetworkRequest.loaderId, originalNetworkRequest.initiator(), originalNetworkRequest.hasUserGesture() ?? undefined);
        requestToManagerMap.set(newNetworkRequest, this.#manager);
        newNetworkRequest.setRedirectSource(originalNetworkRequest);
        originalNetworkRequest.setRedirectDestination(newNetworkRequest);
        return newNetworkRequest;
    }
    maybeAdoptMainResourceRequest(requestId) {
        const request = MultitargetNetworkManager.instance().inflightMainResourceRequests.get(requestId);
        if (!request) {
            return null;
        }
        const oldDispatcher = NetworkManager.forRequest(request).dispatcher;
        oldDispatcher.#requestsById.delete(requestId);
        oldDispatcher.#requestsByURL.delete(request.url());
        const loaderId = request.loaderId;
        if (loaderId) {
            oldDispatcher.#requestsByLoaderId.delete(loaderId);
        }
        const builder = oldDispatcher.#requestIdToExtraInfoBuilder.get(requestId);
        oldDispatcher.#requestIdToExtraInfoBuilder.delete(requestId);
        this.#requestsById.set(requestId, request);
        this.#requestsByURL.set(request.url(), request);
        if (loaderId) {
            this.#requestsByLoaderId.set(loaderId, request);
        }
        if (builder) {
            this.#requestIdToExtraInfoBuilder.set(requestId, builder);
        }
        requestToManagerMap.set(request, this.#manager);
        return request;
    }
    startNetworkRequest(networkRequest, originalRequest) {
        this.#requestsById.set(networkRequest.requestId(), networkRequest);
        this.#requestsByURL.set(networkRequest.url(), networkRequest);
        const loaderId = networkRequest.loaderId;
        if (loaderId) {
            this.#requestsByLoaderId.set(loaderId, networkRequest);
        }
        if (networkRequest.loaderId === networkRequest.requestId() || networkRequest.loaderId === '') {
            MultitargetNetworkManager.instance().inflightMainResourceRequests.set(networkRequest.requestId(), networkRequest);
        }
        this.#manager.dispatchEventToListeners(Events$c.RequestStarted, { request: networkRequest, originalRequest });
    }
    updateNetworkRequest(networkRequest) {
        this.#manager.dispatchEventToListeners(Events$c.RequestUpdated, networkRequest);
    }
    finishNetworkRequest(networkRequest, finishTime, encodedDataLength) {
        networkRequest.endTime = finishTime;
        networkRequest.finished = true;
        if (encodedDataLength >= 0) {
            const redirectSource = networkRequest.redirectSource();
            if (redirectSource?.signedExchangeInfo()) {
                networkRequest.setTransferSize(0);
                redirectSource.setTransferSize(encodedDataLength);
                this.updateNetworkRequest(redirectSource);
            }
            else {
                networkRequest.setTransferSize(encodedDataLength);
            }
        }
        this.#manager.dispatchEventToListeners(Events$c.RequestFinished, networkRequest);
        MultitargetNetworkManager.instance().inflightMainResourceRequests.delete(networkRequest.requestId());
        if (Settings.instance().moduleSetting('monitoring-xhr-enabled').get() &&
            networkRequest.resourceType().category() === resourceCategories.XHR) {
            let message;
            const failedToLoad = networkRequest.failed || networkRequest.hasErrorStatusCode();
            if (failedToLoad) {
                message = i18nString$L(UIStrings$12.sFailedLoadingSS, { PH1: networkRequest.resourceType().title(), PH2: networkRequest.requestMethod, PH3: networkRequest.url() });
            }
            else {
                message = i18nString$L(UIStrings$12.sFinishedLoadingSS, { PH1: networkRequest.resourceType().title(), PH2: networkRequest.requestMethod, PH3: networkRequest.url() });
            }
            this.#manager.dispatchEventToListeners(Events$c.MessageGenerated, { message, requestId: networkRequest.requestId(), warning: false });
        }
    }
    clearRequests() {
        for (const [requestId, request] of this.#requestsById) {
            if (request.finished) {
                this.#requestsById.delete(requestId);
            }
        }
        for (const [requestURL, request] of this.#requestsByURL) {
            if (request.finished) {
                this.#requestsByURL.delete(requestURL);
            }
        }
        for (const [requestLoaderId, request] of this.#requestsByLoaderId) {
            if (request.finished) {
                this.#requestsByLoaderId.delete(requestLoaderId);
            }
        }
        for (const [requestId, builder] of this.#requestIdToExtraInfoBuilder) {
            if (builder.isFinished()) {
                this.#requestIdToExtraInfoBuilder.delete(requestId);
            }
        }
    }
    webTransportCreated({ transportId, url: requestURL, timestamp: time, initiator }) {
        const networkRequest = NetworkRequest.createForSocket(transportId, requestURL, initiator);
        networkRequest.hasNetworkData = true;
        requestToManagerMap.set(networkRequest, this.#manager);
        networkRequest.setResourceType(resourceTypes.WebTransport);
        networkRequest.setIssueTime(time, 0);
        this.startNetworkRequest(networkRequest, null);
    }
    webTransportConnectionEstablished({ transportId, timestamp: time }) {
        const networkRequest = this.#requestsById.get(transportId);
        if (!networkRequest) {
            return;
        }
        networkRequest.responseReceivedTime = time;
        networkRequest.endTime = time + 0.001;
        this.updateNetworkRequest(networkRequest);
    }
    webTransportClosed({ transportId, timestamp: time }) {
        const networkRequest = this.#requestsById.get(transportId);
        if (!networkRequest) {
            return;
        }
        networkRequest.endTime = time;
        this.finishNetworkRequest(networkRequest, time, 0);
    }
    directTCPSocketCreated(event) {
        const requestURL = this.concatHostPort(event.remoteAddr, event.remotePort);
        const networkRequest = NetworkRequest.createForSocket(event.identifier, requestURL, event.initiator);
        networkRequest.hasNetworkData = true;
        networkRequest.setRemoteAddress(event.remoteAddr, event.remotePort);
        networkRequest.protocol = lockedString('tcp');
        networkRequest.statusText = i18nString$L(UIStrings$12.directSocketStatusOpening);
        networkRequest.directSocketInfo = {
            type: DirectSocketType.TCP,
            status: DirectSocketStatus.OPENING,
            createOptions: {
                remoteAddr: event.remoteAddr,
                remotePort: event.remotePort,
                noDelay: event.options.noDelay,
                keepAliveDelay: event.options.keepAliveDelay,
                sendBufferSize: event.options.sendBufferSize,
                receiveBufferSize: event.options.receiveBufferSize,
                dnsQueryType: event.options.dnsQueryType,
            }
        };
        networkRequest.setResourceType(resourceTypes.DirectSocket);
        networkRequest.setIssueTime(event.timestamp, event.timestamp);
        requestToManagerMap.set(networkRequest, this.#manager);
        this.startNetworkRequest(networkRequest, null);
    }
    directTCPSocketOpened(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest?.directSocketInfo) {
            return;
        }
        networkRequest.responseReceivedTime = event.timestamp;
        networkRequest.directSocketInfo.status = DirectSocketStatus.OPEN;
        networkRequest.statusText = i18nString$L(UIStrings$12.directSocketStatusOpen);
        networkRequest.directSocketInfo.openInfo = {
            remoteAddr: event.remoteAddr,
            remotePort: event.remotePort,
            localAddr: event.localAddr,
            localPort: event.localPort,
        };
        networkRequest.setRemoteAddress(event.remoteAddr, event.remotePort);
        const requestURL = this.concatHostPort(event.remoteAddr, event.remotePort);
        networkRequest.setUrl(requestURL);
        this.updateNetworkRequest(networkRequest);
    }
    directTCPSocketAborted(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest?.directSocketInfo) {
            return;
        }
        networkRequest.failed = true;
        networkRequest.directSocketInfo.status = DirectSocketStatus.ABORTED;
        networkRequest.statusText = i18nString$L(UIStrings$12.directSocketStatusAborted);
        networkRequest.directSocketInfo.errorMessage = event.errorMessage;
        this.finishNetworkRequest(networkRequest, event.timestamp, 0);
    }
    directTCPSocketClosed(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest?.directSocketInfo) {
            return;
        }
        networkRequest.statusText = i18nString$L(UIStrings$12.directSocketStatusClosed);
        networkRequest.directSocketInfo.status = DirectSocketStatus.CLOSED;
        this.finishNetworkRequest(networkRequest, event.timestamp, 0);
    }
    directTCPSocketChunkSent(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest) {
            return;
        }
        networkRequest.addDirectSocketChunk({
            data: event.data,
            type: DirectSocketChunkType.SEND,
            timestamp: event.timestamp,
        });
        networkRequest.responseReceivedTime = event.timestamp;
        this.updateNetworkRequest(networkRequest);
    }
    directTCPSocketChunkReceived(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest) {
            return;
        }
        networkRequest.addDirectSocketChunk({
            data: event.data,
            type: DirectSocketChunkType.RECEIVE,
            timestamp: event.timestamp,
        });
        networkRequest.responseReceivedTime = event.timestamp;
        this.updateNetworkRequest(networkRequest);
    }
    directUDPSocketCreated(event) {
        let requestURL = '';
        let type;
        if (event.options.remoteAddr && event.options.remotePort) {
            requestURL = this.concatHostPort(event.options.remoteAddr, event.options.remotePort);
            type = DirectSocketType.UDP_CONNECTED;
        }
        else if (event.options.localAddr) {
            requestURL = this.concatHostPort(event.options.localAddr, event.options.localPort);
            type = DirectSocketType.UDP_BOUND;
        }
        else {
            return;
        }
        const networkRequest = NetworkRequest.createForSocket(event.identifier, requestURL, event.initiator);
        networkRequest.hasNetworkData = true;
        if (event.options.remoteAddr && event.options.remotePort) {
            networkRequest.setRemoteAddress(event.options.remoteAddr, event.options.remotePort);
        }
        networkRequest.protocol = lockedString('udp');
        networkRequest.statusText = i18nString$L(UIStrings$12.directSocketStatusOpening);
        networkRequest.directSocketInfo = {
            type,
            status: DirectSocketStatus.OPENING,
            createOptions: {
                remoteAddr: event.options.remoteAddr,
                remotePort: event.options.remotePort,
                localAddr: event.options.localAddr,
                localPort: event.options.localPort,
                sendBufferSize: event.options.sendBufferSize,
                receiveBufferSize: event.options.receiveBufferSize,
                dnsQueryType: event.options.dnsQueryType,
                multicastLoopback: event.options.multicastLoopback,
                multicastTimeToLive: event.options.multicastTimeToLive,
                multicastAllowAddressSharing: event.options.multicastAllowAddressSharing,
            },
            joinedMulticastGroups: new Set(),
        };
        networkRequest.setResourceType(resourceTypes.DirectSocket);
        networkRequest.setIssueTime(event.timestamp, event.timestamp);
        requestToManagerMap.set(networkRequest, this.#manager);
        this.startNetworkRequest(networkRequest, null);
    }
    directUDPSocketOpened(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest?.directSocketInfo) {
            return;
        }
        let requestURL;
        if (networkRequest.directSocketInfo.type === DirectSocketType.UDP_CONNECTED) {
            if (!event.remoteAddr || !event.remotePort) {
                return;
            }
            networkRequest.setRemoteAddress(event.remoteAddr, event.remotePort);
            requestURL = this.concatHostPort(event.remoteAddr, event.remotePort);
        }
        else {
            requestURL = this.concatHostPort(event.localAddr, event.localPort);
        }
        networkRequest.setUrl(requestURL);
        networkRequest.responseReceivedTime = event.timestamp;
        networkRequest.directSocketInfo.status = DirectSocketStatus.OPEN;
        networkRequest.statusText = i18nString$L(UIStrings$12.directSocketStatusOpen);
        networkRequest.directSocketInfo.openInfo = {
            remoteAddr: event.remoteAddr,
            remotePort: event.remotePort,
            localAddr: event.localAddr,
            localPort: event.localPort,
        };
        this.updateNetworkRequest(networkRequest);
    }
    directUDPSocketAborted(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest?.directSocketInfo) {
            return;
        }
        networkRequest.failed = true;
        networkRequest.directSocketInfo.status = DirectSocketStatus.ABORTED;
        networkRequest.statusText = i18nString$L(UIStrings$12.directSocketStatusAborted);
        networkRequest.directSocketInfo.errorMessage = event.errorMessage;
        this.finishNetworkRequest(networkRequest, event.timestamp, 0);
    }
    directUDPSocketClosed(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest?.directSocketInfo) {
            return;
        }
        networkRequest.statusText = i18nString$L(UIStrings$12.directSocketStatusClosed);
        networkRequest.directSocketInfo.status = DirectSocketStatus.CLOSED;
        this.finishNetworkRequest(networkRequest, event.timestamp, 0);
    }
    directUDPSocketChunkSent(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest) {
            return;
        }
        networkRequest.addDirectSocketChunk({
            data: event.message.data,
            type: DirectSocketChunkType.SEND,
            timestamp: event.timestamp,
            remoteAddress: event.message.remoteAddr,
            remotePort: event.message.remotePort
        });
        networkRequest.responseReceivedTime = event.timestamp;
        this.updateNetworkRequest(networkRequest);
    }
    directUDPSocketChunkReceived(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest) {
            return;
        }
        networkRequest.addDirectSocketChunk({
            data: event.message.data,
            type: DirectSocketChunkType.RECEIVE,
            timestamp: event.timestamp,
            remoteAddress: event.message.remoteAddr,
            remotePort: event.message.remotePort
        });
        networkRequest.responseReceivedTime = event.timestamp;
        this.updateNetworkRequest(networkRequest);
    }
    directUDPSocketJoinedMulticastGroup(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest?.directSocketInfo) {
            return;
        }
        if (!networkRequest.directSocketInfo.joinedMulticastGroups) {
            networkRequest.directSocketInfo.joinedMulticastGroups = new Set();
        }
        if (!networkRequest.directSocketInfo.joinedMulticastGroups.has(event.IPAddress)) {
            networkRequest.directSocketInfo.joinedMulticastGroups.add(event.IPAddress);
            this.updateNetworkRequest(networkRequest);
        }
    }
    directUDPSocketLeftMulticastGroup(event) {
        const networkRequest = this.#requestsById.get(event.identifier);
        if (!networkRequest?.directSocketInfo?.joinedMulticastGroups) {
            return;
        }
        if (networkRequest.directSocketInfo.joinedMulticastGroups.delete(event.IPAddress)) {
            this.updateNetworkRequest(networkRequest);
        }
    }
    trustTokenOperationDone(event) {
        const request = this.#requestsById.get(event.requestId);
        if (!request) {
            this.#requestIdToTrustTokenEvent.set(event.requestId, event);
            return;
        }
        request.setTrustTokenOperationDoneEvent(event);
    }
    reportingApiReportAdded(data) {
        this.#manager.dispatchEventToListeners(Events$c.ReportingApiReportAdded, data.report);
    }
    reportingApiReportUpdated(data) {
        this.#manager.dispatchEventToListeners(Events$c.ReportingApiReportUpdated, data.report);
    }
    reportingApiEndpointsChangedForOrigin(data) {
        this.#manager.dispatchEventToListeners(Events$c.ReportingApiEndpointsChangedForOrigin, data);
    }
    deviceBoundSessionsAdded(_params) {
        this.#manager.dispatchEventToListeners(Events$c.DeviceBoundSessionsAdded, _params.sessions);
    }
    deviceBoundSessionEventOccurred(_params) {
        this.#manager.dispatchEventToListeners(Events$c.DeviceBoundSessionEventOccurred, _params);
    }
    policyUpdated() {
    }
    createNetworkRequest(requestId, frameId, loaderId, url, documentURL, initiator) {
        const request = NetworkRequest.create(requestId, url, documentURL, frameId, loaderId, initiator);
        requestToManagerMap.set(request, this.#manager);
        return request;
    }
    concatHostPort(host, port) {
        if (!port || port === 0) {
            return host;
        }
        return `${host}:${port}`;
    }
}
class RequestURLPattern {
    constructorString;
    pattern;
    constructor(constructorString, pattern) {
        this.constructorString = constructorString;
        this.pattern = pattern;
        if (pattern.hasRegExpGroups) {
            throw new Error('RegExp groups are not allowed');
        }
    }
    static isValidPattern(pattern) {
        try {
            const urlPattern = new URLPattern(pattern);
            return urlPattern.hasRegExpGroups ? "has-regexp-groups"  : "valid" ;
        }
        catch {
            return "failed-to-parse" ;
        }
    }
    static create(constructorString) {
        try {
            const urlPattern = new URLPattern(constructorString);
            return urlPattern.hasRegExpGroups ? null : new RequestURLPattern(constructorString, urlPattern);
        }
        catch {
            return null;
        }
    }
    static upgradeFromWildcard(pattern) {
        const tryCreate = (constructorString) => {
            const result = this.create(constructorString);
            if (result?.pattern.protocol === 'localhost' && result?.pattern.hostname === '') {
                return tryCreate(`*://${constructorString}`);
            }
            return result;
        };
        return tryCreate(pattern)
            ??
                tryCreate(`*://${pattern}*`);
    }
}
class RequestCondition extends ObjectWrapper {
    #pattern;
    #enabled;
    #conditions;
    #ruleIds = new Set();
    static createFromSetting(setting) {
        if ('urlPattern' in setting) {
            const pattern = RequestURLPattern.create(setting.urlPattern) ?? {
                wildcardURL: setting.urlPattern,
                upgradedPattern: RequestURLPattern.upgradeFromWildcard(setting.urlPattern) ?? undefined,
            };
            const conditions = getPredefinedOrBlockingCondition(setting.conditions) ??
                customUserNetworkConditionsSetting().get().find(condition => condition.key === setting.conditions) ??
                NoThrottlingConditions;
            return new this(pattern, setting.enabled, conditions);
        }
        const pattern = {
            wildcardURL: setting.url,
            upgradedPattern: RequestURLPattern.upgradeFromWildcard(setting.url) ?? undefined
        };
        return new this(pattern, setting.enabled, BlockingConditions);
    }
    static create(pattern, conditions) {
        return new this(pattern,  true, conditions);
    }
    constructor(pattern, enabled, conditions) {
        super();
        this.#pattern = pattern;
        this.#enabled = enabled;
        this.#conditions = conditions;
    }
    get isBlocking() {
        return this.conditions === BlockingConditions;
    }
    get ruleIds() {
        return this.#ruleIds;
    }
    get constructorString() {
        return this.#pattern instanceof RequestURLPattern ? this.#pattern.constructorString :
            this.#pattern.upgradedPattern?.constructorString;
    }
    get wildcardURL() {
        return 'wildcardURL' in this.#pattern ? this.#pattern.wildcardURL : undefined;
    }
    get constructorStringOrWildcardURL() {
        return this.#pattern instanceof RequestURLPattern ?
            this.#pattern.constructorString :
            (this.#pattern.upgradedPattern?.constructorString ?? this.#pattern.wildcardURL);
    }
    set pattern(pattern) {
        this.#pattern = pattern;
        this.dispatchEventToListeners("request-condition-changed" );
    }
    get enabled() {
        return this.#enabled;
    }
    set enabled(enabled) {
        this.#enabled = enabled;
        this.dispatchEventToListeners("request-condition-changed" );
    }
    get conditions() {
        return this.#conditions;
    }
    set conditions(conditions) {
        this.#conditions = conditions;
        this.#ruleIds = new Set();
        this.dispatchEventToListeners("request-condition-changed" );
    }
    toSetting() {
        const enabled = this.enabled;
        if (this.#pattern instanceof RequestURLPattern) {
            return { enabled, urlPattern: this.#pattern.constructorString, conditions: this.#conditions.key };
        }
        if (this.#conditions !== BlockingConditions && this.#pattern.upgradedPattern) {
            return { enabled, urlPattern: this.#pattern.upgradedPattern.constructorString, conditions: this.#conditions.key };
        }
        return { enabled, url: this.#pattern.wildcardURL };
    }
    get originalOrUpgradedURLPattern() {
        return this.#pattern instanceof RequestURLPattern ? this.#pattern.pattern : this.#pattern.upgradedPattern?.pattern;
    }
}
class RequestConditions extends ObjectWrapper {
    #setting = Settings.instance().createSetting('network-blocked-patterns', []);
    #conditionsEnabledSetting = Settings.instance().moduleSetting('request-blocking-enabled');
    #conditions = [];
    #requestConditionsById = new Map();
    #conditionsAppliedForTestPromise = Promise.resolve();
    constructor() {
        super();
        for (const condition of this.#setting.get()) {
            try {
                this.#conditions.push(RequestCondition.createFromSetting(condition));
            }
            catch (e) {
                console.error('Error loading throttling settings: ', e);
            }
        }
        for (const condition of this.#conditions) {
            condition.addEventListener("request-condition-changed" , this.#conditionsChanged, this);
        }
        this.#conditionsEnabledSetting.addChangeListener(() => this.dispatchEventToListeners("request-conditions-changed" ));
    }
    get count() {
        return this.#conditions.length;
    }
    get conditionsEnabled() {
        return this.#conditionsEnabledSetting.get();
    }
    set conditionsEnabled(enabled) {
        if (this.#conditionsEnabledSetting.get() === enabled) {
            return;
        }
        this.#conditionsEnabledSetting.set(enabled);
    }
    findCondition(pattern) {
        return this.#conditions.find(condition => condition.constructorString === pattern);
    }
    has(url) {
        return Boolean(this.findCondition(url));
    }
    add(...conditions) {
        this.#conditions.push(...conditions);
        for (const condition of conditions) {
            condition.addEventListener("request-condition-changed" , this.#conditionsChanged, this);
        }
        this.#conditionsChanged();
    }
    decreasePriority(condition) {
        const index = this.#conditions.indexOf(condition);
        if (index < 0 || index >= this.#conditions.length - 1) {
            return;
        }
        swap(this.#conditions, index, index + 1);
        this.#conditionsChanged();
    }
    increasePriority(condition) {
        const index = this.#conditions.indexOf(condition);
        if (index <= 0) {
            return;
        }
        swap(this.#conditions, index - 1, index);
        this.#conditionsChanged();
    }
    delete(condition) {
        const index = this.#conditions.indexOf(condition);
        if (index < 0) {
            return;
        }
        condition.removeEventListener("request-condition-changed" , this.#conditionsChanged, this);
        this.#conditions.splice(index, 1);
        this.#conditionsChanged();
    }
    clear() {
        this.#conditions.splice(0);
        this.#conditionsChanged();
        for (const condition of this.#conditions) {
            condition.removeEventListener("request-condition-changed" , this.#conditionsChanged, this);
        }
    }
    #conditionsChanged() {
        this.#setting.set(this.#conditions.map(condition => condition.toSetting()));
        this.dispatchEventToListeners("request-conditions-changed" );
    }
    get conditions() {
        return this.#conditions.values();
    }
    applyConditions(offline, globalConditions, ...agents) {
        function isNonBlockingCondition(condition) {
            return !('block' in condition);
        }
        const urlPatterns = [];
        const matchedNetworkConditions = [];
        if (this.conditionsEnabled) {
            for (const condition of this.#conditions) {
                const urlPattern = condition.constructorString;
                const conditions = condition.conditions;
                if (!condition.enabled || !urlPattern || conditions === NoThrottlingConditions) {
                    continue;
                }
                const block = !isNonBlockingCondition(conditions);
                urlPatterns.push({ urlPattern, block });
                if (!block) {
                    const { ruleIds } = condition;
                    matchedNetworkConditions.push({ ruleIds, urlPattern, conditions });
                }
            }
        }
        if (globalConditions) {
            matchedNetworkConditions.push({ conditions: globalConditions });
        }
        const promises = [];
        for (const agent of agents) {
            promises.push(agent.invoke_setBlockedURLs({ urlPatterns }));
            promises.push(agent
                .invoke_emulateNetworkConditionsByRule({
                offline,
                matchedNetworkConditions: matchedNetworkConditions.map(({ urlPattern, conditions }) => ({
                    urlPattern: urlPattern ?? '',
                    latency: conditions.latency,
                    downloadThroughput: conditions.download < 0 ? 0 : conditions.download,
                    uploadThroughput: conditions.upload < 0 ? 0 : conditions.upload,
                    packetLoss: (conditions.packetLoss ?? 0) < 0 ? 0 : conditions.packetLoss,
                    packetQueueLength: conditions.packetQueueLength,
                    packetReordering: conditions.packetReordering,
                    connectionType: NetworkManager.connectionType(conditions),
                }))
            })
                .then(response => {
                if (!response.getError()) {
                    for (let i = 0; i < response.ruleIds.length; ++i) {
                        const ruleId = response.ruleIds[i];
                        const { ruleIds, conditions, urlPattern } = matchedNetworkConditions[i];
                        if (ruleIds) {
                            this.#requestConditionsById.set(ruleId, { urlPattern, conditions });
                            matchedNetworkConditions[i].ruleIds?.add(ruleId);
                        }
                    }
                }
            }));
            promises.push(agent.invoke_overrideNetworkState({
                offline,
                latency: globalConditions?.latency ?? 0,
                downloadThroughput: globalConditions?.download ?? -1,
                uploadThroughput: globalConditions?.upload ?? -1,
                connectionType: globalConditions ? NetworkManager.connectionType(globalConditions) :
                    "none" ,
            }));
        }
        this.#conditionsAppliedForTestPromise = this.#conditionsAppliedForTestPromise.then(() => Promise.all(promises));
        return urlPatterns.length > 0;
    }
    conditionsAppliedForTest() {
        return this.#conditionsAppliedForTestPromise;
    }
    conditionsForId(appliedNetworkConditionsId) {
        const requestConditions = this.#requestConditionsById.get(appliedNetworkConditionsId);
        if (!requestConditions) {
            return undefined;
        }
        const { conditions, urlPattern } = requestConditions;
        return new AppliedNetworkConditions(conditions, appliedNetworkConditionsId, urlPattern);
    }
}
class AppliedNetworkConditions {
    conditions;
    appliedNetworkConditionsId;
    urlPattern;
    constructor(conditions, appliedNetworkConditionsId, urlPattern) {
        this.conditions = conditions;
        this.appliedNetworkConditionsId = appliedNetworkConditionsId;
        this.urlPattern = urlPattern;
    }
}
class MultitargetNetworkManager extends ObjectWrapper {
    #targetManager;
    #userAgentOverride = '';
    #userAgentMetadataOverride = null;
    #customAcceptedEncodings = null;
    #networkAgents = new Set();
    #fetchAgents = new Set();
    inflightMainResourceRequests = new Map();
    #networkConditions = NoThrottlingConditions;
    #updatingInterceptionPatternsPromise = null;
    #requestConditions = new RequestConditions();
    #urlsForRequestInterceptor = new Multimap();
    #extraHeaders;
    #customUserAgent;
    #isBlocking = false;
    constructor(targetManager) {
        super();
        this.#targetManager = targetManager;
        const blockedPatternChanged = () => {
            this.updateBlockedPatterns();
            this.dispatchEventToListeners("BlockedPatternsChanged" );
        };
        this.#requestConditions.addEventListener("request-conditions-changed" , blockedPatternChanged);
        this.updateBlockedPatterns();
        this.#targetManager.observeModels(NetworkManager, this);
    }
    static instance(opts = { forceNew: null }) {
        const { forceNew, targetManager } = opts;
        if (!globalInstance().has(MultitargetNetworkManager) || forceNew) {
            globalInstance().set(MultitargetNetworkManager, new MultitargetNetworkManager(targetManager ?? TargetManager.instance()));
        }
        return globalInstance().get(MultitargetNetworkManager);
    }
    static dispose() {
        globalInstance().delete(MultitargetNetworkManager);
    }
    static patchUserAgentWithChromeVersion(uaString) {
        const chromeVersion = getChromeVersion();
        if (chromeVersion.length > 0) {
            const additionalAppVersion = chromeVersion.split('.', 1)[0] + '.0.100.0';
            return sprintf(uaString, chromeVersion, additionalAppVersion);
        }
        return uaString;
    }
    static patchUserAgentMetadataWithChromeVersion(userAgentMetadata) {
        if (!userAgentMetadata.brands) {
            return;
        }
        const chromeVersion = getChromeVersion();
        if (chromeVersion.length === 0) {
            return;
        }
        const majorVersion = chromeVersion.split('.', 1)[0];
        for (const brand of userAgentMetadata.brands) {
            if (brand.version.includes('%s')) {
                brand.version = sprintf(brand.version, majorVersion);
            }
        }
        if (userAgentMetadata.fullVersion) {
            if (userAgentMetadata.fullVersion.includes('%s')) {
                userAgentMetadata.fullVersion = sprintf(userAgentMetadata.fullVersion, chromeVersion);
            }
        }
    }
    modelAdded(networkManager) {
        const networkAgent = networkManager.target().networkAgent();
        const fetchAgent = networkManager.target().fetchAgent();
        if (this.#extraHeaders) {
            void networkAgent.invoke_setExtraHTTPHeaders({ headers: this.#extraHeaders });
        }
        if (this.currentUserAgent()) {
            void networkAgent.invoke_setUserAgentOverride({ userAgent: this.currentUserAgent(), userAgentMetadata: this.#userAgentMetadataOverride || undefined });
        }
        this.#requestConditions.applyConditions(this.isOffline(), this.isThrottling() ? this.#networkConditions : null, networkAgent);
        if (this.isIntercepting()) {
            void fetchAgent.invoke_enable({ patterns: this.#urlsForRequestInterceptor.valuesArray() });
        }
        if (this.#customAcceptedEncodings === null) {
            void networkAgent.invoke_clearAcceptedEncodingsOverride();
        }
        else {
            void networkAgent.invoke_setAcceptedEncodings({ encodings: this.#customAcceptedEncodings });
        }
        this.#networkAgents.add(networkAgent);
        this.#fetchAgents.add(fetchAgent);
    }
    modelRemoved(networkManager) {
        for (const entry of this.inflightMainResourceRequests) {
            const manager = NetworkManager.forRequest((entry[1]));
            if (manager !== networkManager) {
                continue;
            }
            this.inflightMainResourceRequests.delete((entry[0]));
        }
        this.#networkAgents.delete(networkManager.target().networkAgent());
        this.#fetchAgents.delete(networkManager.target().fetchAgent());
    }
    isThrottling() {
        return this.#networkConditions.download >= 0 || this.#networkConditions.upload >= 0 ||
            this.#networkConditions.latency > 0;
    }
    isOffline() {
        return !this.#networkConditions.download && !this.#networkConditions.upload;
    }
    setNetworkConditions(conditions) {
        this.#networkConditions = conditions;
        this.#requestConditions.applyConditions(this.isOffline(), this.isThrottling() ? this.#networkConditions : null, ...this.#networkAgents);
        this.dispatchEventToListeners("ConditionsChanged" );
    }
    networkConditions() {
        return this.#networkConditions;
    }
    updateNetworkConditions(networkAgent) {
        const conditions = this.#networkConditions;
        if (!this.isThrottling()) {
            void networkAgent.invoke_emulateNetworkConditions({
                offline: false,
                latency: 0,
                downloadThroughput: 0,
                uploadThroughput: 0,
            });
        }
        else {
            void networkAgent.invoke_emulateNetworkConditions({
                offline: this.isOffline(),
                latency: conditions.latency,
                downloadThroughput: conditions.download < 0 ? 0 : conditions.download,
                uploadThroughput: conditions.upload < 0 ? 0 : conditions.upload,
                packetLoss: (conditions.packetLoss ?? 0) < 0 ? 0 : conditions.packetLoss,
                packetQueueLength: conditions.packetQueueLength,
                packetReordering: conditions.packetReordering,
                connectionType: NetworkManager.connectionType(conditions),
            });
        }
    }
    setExtraHTTPHeaders(headers) {
        this.#extraHeaders = headers;
        for (const agent of this.#networkAgents) {
            void agent.invoke_setExtraHTTPHeaders({ headers: this.#extraHeaders });
        }
    }
    currentUserAgent() {
        return this.#customUserAgent ? this.#customUserAgent : this.#userAgentOverride;
    }
    updateUserAgentOverride() {
        const userAgent = this.currentUserAgent();
        for (const agent of this.#networkAgents) {
            void agent.invoke_setUserAgentOverride({ userAgent, userAgentMetadata: this.#userAgentMetadataOverride || undefined });
        }
    }
    setUserAgentOverride(userAgent, userAgentMetadataOverride) {
        const uaChanged = (this.#userAgentOverride !== userAgent);
        this.#userAgentOverride = userAgent;
        if (!this.#customUserAgent) {
            this.#userAgentMetadataOverride = userAgentMetadataOverride;
            this.updateUserAgentOverride();
        }
        else {
            this.#userAgentMetadataOverride = null;
        }
        if (uaChanged) {
            this.dispatchEventToListeners("UserAgentChanged" );
        }
    }
    setCustomUserAgentOverride(userAgent, userAgentMetadataOverride = null) {
        this.#customUserAgent = userAgent;
        this.#userAgentMetadataOverride = userAgentMetadataOverride;
        this.updateUserAgentOverride();
    }
    setCustomAcceptedEncodingsOverride(acceptedEncodings) {
        this.#customAcceptedEncodings = acceptedEncodings;
        this.updateAcceptedEncodingsOverride();
        this.dispatchEventToListeners("AcceptedEncodingsChanged" );
    }
    clearCustomAcceptedEncodingsOverride() {
        this.#customAcceptedEncodings = null;
        this.updateAcceptedEncodingsOverride();
        this.dispatchEventToListeners("AcceptedEncodingsChanged" );
    }
    isAcceptedEncodingOverrideSet() {
        return this.#customAcceptedEncodings !== null;
    }
    updateAcceptedEncodingsOverride() {
        const customAcceptedEncodings = this.#customAcceptedEncodings;
        for (const agent of this.#networkAgents) {
            if (customAcceptedEncodings === null) {
                void agent.invoke_clearAcceptedEncodingsOverride();
            }
            else {
                void agent.invoke_setAcceptedEncodings({ encodings: customAcceptedEncodings });
            }
        }
    }
    get requestConditions() {
        return this.#requestConditions;
    }
    isBlocking() {
        return this.#isBlocking && this.requestConditions.conditionsEnabled;
    }
    updateBlockedPatterns() {
        this.#isBlocking = this.#requestConditions.applyConditions(this.isOffline(), this.isThrottling() ? this.#networkConditions : null, ...this.#networkAgents);
    }
    isIntercepting() {
        return Boolean(this.#urlsForRequestInterceptor.size);
    }
    setInterceptionHandlerForPatterns(patterns, requestInterceptor) {
        this.#urlsForRequestInterceptor.deleteAll(requestInterceptor);
        for (const newPattern of patterns) {
            this.#urlsForRequestInterceptor.set(requestInterceptor, newPattern);
        }
        return this.updateInterceptionPatternsOnNextTick();
    }
    updateInterceptionPatternsOnNextTick() {
        if (!this.#updatingInterceptionPatternsPromise) {
            this.#updatingInterceptionPatternsPromise = Promise.resolve().then(this.updateInterceptionPatterns.bind(this));
        }
        return this.#updatingInterceptionPatternsPromise;
    }
    async updateInterceptionPatterns() {
        if (!Settings.instance().moduleSetting('cache-disabled').get()) {
            Settings.instance().moduleSetting('cache-disabled').set(true);
        }
        this.#updatingInterceptionPatternsPromise = null;
        const promises = [];
        for (const agent of this.#fetchAgents) {
            promises.push(agent.invoke_enable({ patterns: this.#urlsForRequestInterceptor.valuesArray() }));
        }
        this.dispatchEventToListeners("InterceptorsChanged" );
        await Promise.all(promises);
    }
    async requestIntercepted(interceptedRequest) {
        for (const requestInterceptor of this.#urlsForRequestInterceptor.keysArray()) {
            await requestInterceptor(interceptedRequest);
            if (interceptedRequest.hasResponded() && interceptedRequest.networkRequest) {
                this.dispatchEventToListeners("RequestIntercepted" , interceptedRequest.networkRequest.requestId());
                return;
            }
        }
        if (!interceptedRequest.hasResponded()) {
            interceptedRequest.continueRequestWithoutChange();
        }
    }
    clearBrowserCache() {
        for (const agent of this.#networkAgents) {
            void agent.invoke_clearBrowserCache();
        }
    }
    clearBrowserCookies() {
        for (const agent of this.#networkAgents) {
            void agent.invoke_clearBrowserCookies();
        }
    }
    async getCertificate(origin) {
        const target = this.#targetManager.primaryPageTarget();
        if (!target) {
            return [];
        }
        const certificate = await target.networkAgent().invoke_getCertificate({ origin });
        if (!certificate) {
            return [];
        }
        return certificate.tableNames;
    }
    appliedRequestConditions(requestInternal) {
        if (!requestInternal.appliedNetworkConditionsId) {
            return undefined;
        }
        return this.requestConditions.conditionsForId(requestInternal.appliedNetworkConditionsId);
    }
}
class InterceptedRequest {
    #fetchAgent;
    #hasResponded = false;
    request;
    resourceType;
    responseStatusCode;
    responseHeaders;
    requestId;
    networkRequest;
    constructor(fetchAgent, request, resourceType, requestId, networkRequest, responseStatusCode, responseHeaders) {
        this.#fetchAgent = fetchAgent;
        this.request = request;
        this.resourceType = resourceType;
        this.responseStatusCode = responseStatusCode;
        this.responseHeaders = responseHeaders;
        this.requestId = requestId;
        this.networkRequest = networkRequest;
    }
    hasResponded() {
        return this.#hasResponded;
    }
    static mergeSetCookieHeaders(originalSetCookieHeaders, setCookieHeadersFromOverrides) {
        const generateHeaderMap = (headers) => {
            const result = new Map();
            for (const header of headers) {
                const match = header.value.match(/^([a-zA-Z0-9!#$%&'*+.^_`|~-]+=)(.*)$/);
                if (match) {
                    if (result.has(match[1])) {
                        result.get(match[1])?.push(header.value);
                    }
                    else {
                        result.set(match[1], [header.value]);
                    }
                }
                else if (result.has(header.value)) {
                    result.get(header.value)?.push(header.value);
                }
                else {
                    result.set(header.value, [header.value]);
                }
            }
            return result;
        };
        const originalHeadersMap = generateHeaderMap(originalSetCookieHeaders);
        const overridesHeaderMap = generateHeaderMap(setCookieHeadersFromOverrides);
        const mergedHeaders = [];
        for (const [key, headerValues] of originalHeadersMap) {
            if (overridesHeaderMap.has(key)) {
                for (const headerValue of overridesHeaderMap.get(key) || []) {
                    mergedHeaders.push({ name: 'set-cookie', value: headerValue });
                }
            }
            else {
                for (const headerValue of headerValues) {
                    mergedHeaders.push({ name: 'set-cookie', value: headerValue });
                }
            }
        }
        for (const [key, headerValues] of overridesHeaderMap) {
            if (originalHeadersMap.has(key)) {
                continue;
            }
            for (const headerValue of headerValues) {
                mergedHeaders.push({ name: 'set-cookie', value: headerValue });
            }
        }
        return mergedHeaders;
    }
    async continueRequestWithContent(contentBlob, encoded, responseHeaders, isBodyOverridden) {
        this.#hasResponded = true;
        const body = encoded ? await contentBlob.text() : await encode(contentBlob).catch(err => {
            console.error(err);
            return '';
        });
        const responseCode = isBodyOverridden ? 200 : (this.responseStatusCode || 200);
        if (this.networkRequest) {
            const originalSetCookieHeaders = this.networkRequest?.originalResponseHeaders.filter(header => header.name === 'set-cookie') || [];
            const setCookieHeadersFromOverrides = responseHeaders.filter(header => header.name === 'set-cookie');
            this.networkRequest.setCookieHeaders =
                InterceptedRequest.mergeSetCookieHeaders(originalSetCookieHeaders, setCookieHeadersFromOverrides);
            this.networkRequest.hasOverriddenContent = isBodyOverridden;
        }
        void this.#fetchAgent.invoke_fulfillRequest({ requestId: this.requestId, responseCode, body, responseHeaders });
        MultitargetNetworkManager.instance().dispatchEventToListeners("RequestFulfilled" , this.request.url);
    }
    continueRequestWithoutChange() {
        console.assert(!this.#hasResponded);
        this.#hasResponded = true;
        void this.#fetchAgent.invoke_continueRequest({ requestId: this.requestId });
    }
    async responseBody() {
        const response = await this.#fetchAgent.invoke_getResponseBody({ requestId: this.requestId });
        const error = response.getError();
        if (error) {
            return { error };
        }
        const { mimeType, charset } = this.getMimeTypeAndCharset();
        return new ContentData(response.body, response.base64Encoded, mimeType ?? 'application/octet-stream', charset ?? undefined);
    }
    isRedirect() {
        return this.responseStatusCode !== undefined && this.responseStatusCode >= 300 && this.responseStatusCode < 400;
    }
    getMimeTypeAndCharset() {
        for (const header of this.responseHeaders ?? []) {
            if (header.name.toLowerCase() === 'content-type') {
                return parseContentType(header.value);
            }
        }
        const mimeType = this.networkRequest?.mimeType ?? null;
        const charset = this.networkRequest?.charset() ?? null;
        return { mimeType, charset };
    }
}
class ExtraInfoBuilder {
    #requests = [];
    #responseExtraInfoFlag = [];
    #requestExtraInfos = [];
    #responseExtraInfos = [];
    #responseEarlyHintsHeaders = [];
    #finished = false;
    addRequest(req) {
        this.#requests.push(req);
        this.sync(this.#requests.length - 1);
    }
    addHasExtraInfo(hasExtraInfo) {
        this.#responseExtraInfoFlag.push(hasExtraInfo);
        console.assert(this.#requests.length === this.#responseExtraInfoFlag.length, 'request/response count mismatch');
        if (!hasExtraInfo) {
            this.#requestExtraInfos.splice(this.#requests.length - 1, 0, null);
            this.#responseExtraInfos.splice(this.#requests.length - 1, 0, null);
        }
        this.sync(this.#requests.length - 1);
    }
    addRequestExtraInfo(info) {
        this.#requestExtraInfos.push(info);
        this.sync(this.#requestExtraInfos.length - 1);
    }
    addResponseExtraInfo(info) {
        this.#responseExtraInfos.push(info);
        this.sync(this.#responseExtraInfos.length - 1);
    }
    setEarlyHintsHeaders(earlyHintsHeaders) {
        this.#responseEarlyHintsHeaders = earlyHintsHeaders;
        this.updateFinalRequest();
    }
    finished() {
        this.#finished = true;
        if (this.#responseExtraInfoFlag.length < this.#requests.length) {
            this.#responseExtraInfoFlag.push(true);
            this.sync(this.#responseExtraInfoFlag.length - 1);
        }
        console.assert(this.#requests.length === this.#responseExtraInfoFlag.length, 'request/response count mismatch when request finished');
        this.updateFinalRequest();
    }
    isFinished() {
        return this.#finished;
    }
    sync(index) {
        const req = this.#requests[index];
        if (!req) {
            return;
        }
        if (index >= this.#responseExtraInfoFlag.length) {
            return;
        }
        if (!this.#responseExtraInfoFlag[index]) {
            return;
        }
        const requestExtraInfo = this.#requestExtraInfos[index];
        if (requestExtraInfo) {
            req.addExtraRequestInfo(requestExtraInfo);
            this.#requestExtraInfos[index] = null;
        }
        const responseExtraInfo = this.#responseExtraInfos[index];
        if (responseExtraInfo) {
            req.addExtraResponseInfo(responseExtraInfo);
            this.#responseExtraInfos[index] = null;
        }
    }
    finalRequest() {
        if (!this.#finished) {
            return null;
        }
        return this.#requests[this.#requests.length - 1] || null;
    }
    updateFinalRequest() {
        if (!this.#finished) {
            return;
        }
        const finalRequest = this.finalRequest();
        finalRequest?.setEarlyHintsHeaders(this.#responseEarlyHintsHeaders);
    }
}
SDKModel.register(NetworkManager, { capabilities: 16 , autostart: true });
const THROTTLING_CONDITIONS_LOOKUP = new Map([
    ["NO_THROTTLING" , NoThrottlingConditions],
    ["OFFLINE" , OfflineConditions],
    ["SPEED_3G" , Slow3GConditions],
    ["SPEED_SLOW_4G" , Slow4GConditions],
    ["SPEED_FAST_4G" , Fast4GConditions]
]);
function keyIsPredefined(key) {
    return !key.startsWith('USER_CUSTOM_SETTING_');
}
function getPredefinedCondition(key) {
    if (!keyIsPredefined(key)) {
        return null;
    }
    return THROTTLING_CONDITIONS_LOOKUP.get(key) ?? null;
}
function getPredefinedOrBlockingCondition(key) {
    return key === "BLOCKING"  ? BlockingConditions : getPredefinedCondition(key);
}

// Copyright 2020 The Chromium Authors
const UIStrings$11 = {
    loadCanceledDueToReloadOf: 'Load canceled due to reload of inspected page',
};
const str_$10 = registerUIStrings('core/sdk/PageResourceLoader.ts', UIStrings$11);
const i18nString$K = getLocalizedString.bind(undefined, str_$10);
function isExtensionInitiator(initiator) {
    return 'extensionId' in initiator;
}
class PageResourceLoader extends ObjectWrapper {
    #targetManager;
    #settings;
    #userAgentProvider;
    #currentlyLoading = 0;
    #currentlyLoadingPerTarget = new Map();
    #maxConcurrentLoads;
    #pageResources = new Map();
    #queuedLoads = [];
    #loadOverride;
    constructor(targetManager, settings, userAgentProvider, loadOverride, maxConcurrentLoads = 500) {
        super();
        this.#targetManager = targetManager;
        this.#settings = settings;
        this.#userAgentProvider = userAgentProvider;
        this.#maxConcurrentLoads = maxConcurrentLoads;
        this.#targetManager.addModelListener(ResourceTreeModel, Events$6.PrimaryPageChanged, this.onPrimaryPageChanged, this);
        this.#loadOverride = loadOverride;
    }
    static instance({ forceNew, targetManager, settings, userAgentProvider, loadOverride, maxConcurrentLoads } = {
        forceNew: false,
        loadOverride: null,
    }) {
        if (forceNew) {
            globalInstance().set(PageResourceLoader, new PageResourceLoader(targetManager ?? TargetManager.instance(), settings ?? Settings.instance(), userAgentProvider ?? MultitargetNetworkManager.instance(), loadOverride, maxConcurrentLoads));
        }
        return globalInstance().get(PageResourceLoader);
    }
    static removeInstance() {
        globalInstance().delete(PageResourceLoader);
    }
    onPrimaryPageChanged(event) {
        const { frame: mainFrame, type } = event.data;
        if (!mainFrame.isOutermostFrame()) {
            return;
        }
        for (const { reject } of this.#queuedLoads) {
            reject(new Error(i18nString$K(UIStrings$11.loadCanceledDueToReloadOf)));
        }
        this.#queuedLoads = [];
        const mainFrameTarget = mainFrame.resourceTreeModel().target();
        const keptResources = new Map();
        for (const [key, pageResource] of this.#pageResources.entries()) {
            if ((type === "Activation" ) && mainFrameTarget === pageResource.initiator.target) {
                keptResources.set(key, pageResource);
            }
        }
        this.#pageResources = keptResources;
        this.dispatchEventToListeners("Update" );
    }
    getResourcesLoaded() {
        return this.#pageResources;
    }
    getScopedResourcesLoaded() {
        return new Map([...this.#pageResources].filter(([_, pageResource]) => this.#targetManager.isInScope(pageResource.initiator.target) ||
            isExtensionInitiator(pageResource.initiator)));
    }
    getNumberOfResources() {
        return { loading: this.#currentlyLoading, queued: this.#queuedLoads.length, resources: this.#pageResources.size };
    }
    getScopedNumberOfResources() {
        let loadingCount = 0;
        for (const [targetId, count] of this.#currentlyLoadingPerTarget) {
            const target = this.#targetManager.targetById(targetId);
            if (this.#targetManager.isInScope(target)) {
                loadingCount += count;
            }
        }
        return { loading: loadingCount, resources: this.getScopedResourcesLoaded().size };
    }
    async acquireLoadSlot(target) {
        this.#currentlyLoading++;
        if (target) {
            const currentCount = this.#currentlyLoadingPerTarget.get(target.id()) || 0;
            this.#currentlyLoadingPerTarget.set(target.id(), currentCount + 1);
        }
        if (this.#currentlyLoading > this.#maxConcurrentLoads) {
            const { promise: waitForCapacity, resolve, reject, } = Promise.withResolvers();
            this.#queuedLoads.push({ resolve, reject });
            await waitForCapacity;
        }
    }
    releaseLoadSlot(target) {
        this.#currentlyLoading--;
        if (target) {
            const currentCount = this.#currentlyLoadingPerTarget.get(target.id());
            if (currentCount) {
                this.#currentlyLoadingPerTarget.set(target.id(), currentCount - 1);
            }
        }
        const entry = this.#queuedLoads.shift();
        if (entry) {
            entry.resolve();
        }
    }
    static makeExtensionKey(url, initiator) {
        if (isExtensionInitiator(initiator) && initiator.extensionId) {
            return `${url}-${initiator.extensionId}`;
        }
        throw new Error('Invalid initiator');
    }
    static makeKey(url, initiator) {
        if (initiator.frameId) {
            return `${url}-${initiator.frameId}`;
        }
        if (initiator.target) {
            return `${url}-${initiator.target.id()}`;
        }
        throw new Error('Invalid initiator');
    }
    resourceLoadedThroughExtension(pageResource) {
        const key = PageResourceLoader.makeExtensionKey(pageResource.url, pageResource.initiator);
        this.#pageResources.set(key, pageResource);
        this.dispatchEventToListeners("Update" );
    }
    async loadResource(url, initiator, isBinary = false) {
        if (isExtensionInitiator(initiator)) {
            throw new Error('Invalid initiator');
        }
        const key = PageResourceLoader.makeKey(url, initiator);
        const pageResource = {
            success: null,
            size: null,
            duration: null,
            url,
            initiator,
        };
        this.#pageResources.set(key, pageResource);
        this.dispatchEventToListeners("Update" );
        const startTime = performance.now();
        try {
            await this.acquireLoadSlot(initiator.target);
            const resultPromise = this.dispatchLoad(url, initiator, isBinary);
            const result = await resultPromise;
            pageResource.errorMessage = result.errorDescription.message;
            pageResource.success = result.success;
            if (result.success) {
                pageResource.size = result.content.length;
                return { content: result.content };
            }
            throw new Error(result.errorDescription.message);
        }
        catch (e) {
            if (pageResource.errorMessage === undefined) {
                pageResource.errorMessage = e.message;
            }
            if (pageResource.success === null) {
                pageResource.success = false;
            }
            throw e;
        }
        finally {
            pageResource.duration = performance.now() - startTime;
            this.releaseLoadSlot(initiator.target);
            this.dispatchEventToListeners("Update" );
        }
    }
    async dispatchLoad(url, initiator, isBinary) {
        if (isExtensionInitiator(initiator)) {
            throw new Error('Invalid initiator');
        }
        if (this.#loadOverride) {
            return await this.#loadOverride(url);
        }
        const parsedURL = new ParsedURL(url);
        const eligibleForLoadFromTarget = this.getLoadThroughTargetSetting().get() && parsedURL &&
            parsedURL.scheme !== 'file' && parsedURL.scheme !== 'data' && parsedURL.scheme !== 'devtools' &&
            initiator.target;
        userMetrics.developerResourceScheme(this.getDeveloperResourceScheme(parsedURL));
        if (eligibleForLoadFromTarget) {
            try {
                userMetrics.developerResourceLoaded(0 );
                const result = await this.loadFromTarget(initiator.target, initiator.frameId, url, isBinary);
                return result;
            }
            catch (e) {
                if (e instanceof Error) {
                    userMetrics.developerResourceLoaded(2 );
                    if (e.message.includes('CSP violation')) {
                        return {
                            success: false,
                            content: '',
                            errorDescription: {
                                statusCode: 0,
                                message: e.message,
                            }
                        };
                    }
                }
            }
            userMetrics.developerResourceLoaded(3 );
        }
        else {
            const code = this.getLoadThroughTargetSetting().get() ?
                6  :
                5 ;
            userMetrics.developerResourceLoaded(code);
        }
        const result = await this.loadFromHostBindings(url);
        if (eligibleForLoadFromTarget && !result.success) {
            userMetrics.developerResourceLoaded(7 );
        }
        return result;
    }
    getDeveloperResourceScheme(parsedURL) {
        if (!parsedURL || parsedURL.scheme === '') {
            return 1 ;
        }
        const isLocalhost = parsedURL.host === 'localhost' || parsedURL.host.endsWith('.localhost');
        switch (parsedURL.scheme) {
            case 'file':
                return 7 ;
            case 'data':
                return 6 ;
            case 'blob':
                return 8 ;
            case 'http':
                return isLocalhost ? 4  :
                    2 ;
            case 'https':
                return isLocalhost ? 5  :
                    3 ;
        }
        return 0 ;
    }
    async loadFromTarget(target, frameId, url, isBinary) {
        const networkManager = target.model(NetworkManager);
        const ioModel = target.model(IOModel);
        const disableCache = this.#settings.moduleSetting('cache-disabled').get();
        const resource = await networkManager.loadNetworkResource(frameId, url, { disableCache, includeCredentials: true });
        try {
            const content = resource.stream ?
                (isBinary ? await ioModel.readToBuffer(resource.stream) : await ioModel.readToString(resource.stream)) :
                '';
            return {
                success: resource.success,
                content,
                errorDescription: {
                    statusCode: resource.httpStatusCode || 0,
                    netError: resource.netError,
                    netErrorName: resource.netErrorName,
                    message: netErrorToMessage(resource.netError, resource.httpStatusCode, resource.netErrorName) ||
                        '',
                },
            };
        }
        finally {
            if (resource.stream) {
                void ioModel.close(resource.stream);
            }
        }
    }
    async loadFromHostBindings(url) {
        const headers = {};
        const currentUserAgent = this.#userAgentProvider.currentUserAgent();
        if (currentUserAgent) {
            headers['User-Agent'] = currentUserAgent;
        }
        if (this.#settings.moduleSetting('cache-disabled').get()) {
            headers['Cache-Control'] = 'no-cache';
        }
        const allowRemoteFilePaths = this.#settings.moduleSetting('network.enable-remote-file-loading').get();
        return await new Promise(resolve => load(url, headers, (success, _responseHeaders, content, errorDescription) => {
            resolve({ success, content, errorDescription });
        }, allowRemoteFilePaths));
    }
    getLoadThroughTargetSetting() {
        return this.#settings.createSetting('load-through-target', true);
    }
}

// Copyright 2025 The Chromium Authors. All rights reserved.
const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const BASE64_CODES = new Uint8Array(123);
for (let index = 0; index < BASE64_CHARS.length; ++index) {
    BASE64_CODES[BASE64_CHARS.charCodeAt(index)] = index;
}
const VLQ_BASE_SHIFT$1 = 5;
const VLQ_BASE_MASK$1 = (1 << 5) - 1;
const VLQ_CONTINUATION_MASK$1 = 1 << 5;
let TokenIterator$1 = class TokenIterator {
    #string;
    #position;
    constructor(string) {
        this.#string = string;
        this.#position = 0;
    }
    nextChar() {
        return this.#string.charAt(this.#position++);
    }
    nextCharCode() {
        return this.#string.charCodeAt(this.#position++);
    }
    peek() {
        return this.#string.charAt(this.#position);
    }
    hasNext() {
        return this.#position < this.#string.length;
    }
    nextSignedVLQ() {
        let result = this.nextUnsignedVLQ();
        const negative = result & 1;
        result >>>= 1;
        return negative ? -result : result;
    }
    nextUnsignedVLQ() {
        let result = 0;
        let shift = 0;
        let digit = 0;
        do {
            const charCode = this.nextCharCode();
            digit = BASE64_CODES[charCode];
            result += (digit & VLQ_BASE_MASK$1) << shift;
            shift += VLQ_BASE_SHIFT$1;
        } while (digit & VLQ_CONTINUATION_MASK$1);
        return result;
    }
    currentChar() {
        return this.#string.charAt(this.#position - 1);
    }
};

// Copyright 2025 The Chromium Authors. All rights reserved.
const DEFAULT_DECODE_OPTIONS = {
    mode: 2 ,
    generatedOffset: { line: 0, column: 0 },
};
function decode(sourceMap, options = DEFAULT_DECODE_OPTIONS) {
    const opts = { ...DEFAULT_DECODE_OPTIONS, ...options };
    if ("sections" in sourceMap) {
        return decodeIndexMap(sourceMap, {
            ...opts,
            generatedOffset: { line: 0, column: 0 },
        });
    }
    return decodeMap(sourceMap, opts);
}
function decodeMap(sourceMap, options) {
    if (!sourceMap.scopes || !sourceMap.names) {
        return { scopes: [], ranges: [], hasVariableAndBindingInfo: false };
    }
    return new Decoder(sourceMap.scopes, sourceMap.names, options).decode();
}
function decodeIndexMap(sourceMap, options) {
    const scopeInfo = {
        scopes: [],
        ranges: [],
        hasVariableAndBindingInfo: false,
    };
    for (const section of sourceMap.sections) {
        const { scopes, ranges, hasVariableAndBindingInfo } = decode(section.map, {
            ...options,
            generatedOffset: section.offset,
        });
        for (const scope of scopes)
            scopeInfo.scopes.push(scope);
        for (const range of ranges)
            scopeInfo.ranges.push(range);
        scopeInfo.hasVariableAndBindingInfo ||= hasVariableAndBindingInfo;
    }
    return scopeInfo;
}
const DEFAULT_SCOPE_STATE = {
    line: 0,
    column: 0,
    name: 0,
    kind: 0,
    variable: 0,
};
const DEFAULT_RANGE_STATE = {
    line: 0,
    column: 0,
    defScopeIdx: 0,
};
class Decoder {
    #encodedScopes;
    #names;
    #mode;
    #scopes = [];
    #ranges = [];
    #scopeState = { ...DEFAULT_SCOPE_STATE };
    #rangeState = { ...DEFAULT_RANGE_STATE };
    #scopeStack = [];
    #rangeStack = [];
    #flatOriginalScopes = [];
    #subRangeBindingsForRange = new Map();
    #seenOriginalScopeVariables = false;
    #seenGeneratedRangeBindings = false;
    constructor(scopes, names, options) {
        this.#encodedScopes = scopes;
        this.#names = names;
        this.#mode = options.mode;
        this.#rangeState.line = options.generatedOffset.line;
        this.#rangeState.column = options.generatedOffset.column;
    }
    decode() {
        const iter = new TokenIterator$1(this.#encodedScopes);
        while (iter.hasNext()) {
            const tag = iter.nextUnsignedVLQ();
            switch (tag) {
                case 0 : {
                    this.#scopes.push(null);
                    break;
                }
                case 1 : {
                    const item = {
                        flags: iter.nextUnsignedVLQ(),
                        line: iter.nextUnsignedVLQ(),
                        column: iter.nextUnsignedVLQ(),
                    };
                    if (item.flags & 1 ) {
                        item.nameIdx = iter.nextSignedVLQ();
                    }
                    if (item.flags & 2 ) {
                        item.kindIdx = iter.nextSignedVLQ();
                    }
                    this.#handleOriginalScopeStartItem(item);
                    break;
                }
                case 3 : {
                    const variableIdxs = [];
                    while (iter.hasNext() && iter.peek() !== ",") {
                        variableIdxs.push(iter.nextSignedVLQ());
                    }
                    this.#handleOriginalScopeVariablesItem(variableIdxs);
                    this.#seenOriginalScopeVariables = true;
                    break;
                }
                case 2 : {
                    this.#handleOriginalScopeEndItem(iter.nextUnsignedVLQ(), iter.nextUnsignedVLQ());
                    break;
                }
                case 4 : {
                    const flags = iter.nextUnsignedVLQ();
                    const line = flags & 1
                        ? iter.nextUnsignedVLQ()
                        : undefined;
                    const column = iter.nextUnsignedVLQ();
                    const definitionIdx = flags & 2
                        ? iter.nextSignedVLQ()
                        : undefined;
                    this.#handleGeneratedRangeStartItem({
                        flags,
                        line,
                        column,
                        definitionIdx,
                    });
                    break;
                }
                case 5 : {
                    const lineOrColumn = iter.nextUnsignedVLQ();
                    const maybeColumn = iter.hasNext() && iter.peek() !== ","
                        ? iter.nextUnsignedVLQ()
                        : undefined;
                    if (maybeColumn !== undefined) {
                        this.#handleGeneratedRangeEndItem(lineOrColumn, maybeColumn);
                    }
                    else {
                        this.#handleGeneratedRangeEndItem(0, lineOrColumn);
                    }
                    break;
                }
                case 6 : {
                    const valueIdxs = [];
                    while (iter.hasNext() && iter.peek() !== ",") {
                        valueIdxs.push(iter.nextUnsignedVLQ());
                    }
                    this.#handleGeneratedRangeBindingsItem(valueIdxs);
                    this.#seenGeneratedRangeBindings = true;
                    break;
                }
                case 7 : {
                    const variableIndex = iter.nextUnsignedVLQ();
                    const bindings = [];
                    while (iter.hasNext() && iter.peek() !== ",") {
                        bindings.push([
                            iter.nextUnsignedVLQ(),
                            iter.nextUnsignedVLQ(),
                            iter.nextUnsignedVLQ(),
                        ]);
                    }
                    this.#recordGeneratedSubRangeBindingItem(variableIndex, bindings);
                    this.#seenGeneratedRangeBindings = true;
                    break;
                }
                case 8 : {
                    this.#handleGeneratedRangeCallSite(iter.nextUnsignedVLQ(), iter.nextUnsignedVLQ(), iter.nextUnsignedVLQ());
                    break;
                }
                case 99 : {
                    iter.nextUnsignedVLQ();
                    break;
                }
                default: {
                    this.#throwInStrictMode(`Encountered illegal item tag ${tag}`);
                    break;
                }
            }
            while (iter.hasNext() && iter.peek() !== ",")
                iter.nextUnsignedVLQ();
            if (iter.hasNext())
                iter.nextChar();
        }
        if (this.#scopeStack.length > 0) {
            this.#throwInStrictMode("Encountered ORIGINAL_SCOPE_START without matching END!");
        }
        if (this.#rangeStack.length > 0) {
            this.#throwInStrictMode("Encountered GENERATED_RANGE_START without matching END!");
        }
        const info = {
            scopes: this.#scopes,
            ranges: this.#ranges,
            hasVariableAndBindingInfo: this.#seenOriginalScopeVariables &&
                this.#seenGeneratedRangeBindings,
        };
        this.#scopes = [];
        this.#ranges = [];
        this.#flatOriginalScopes = [];
        this.#seenOriginalScopeVariables = false;
        this.#seenGeneratedRangeBindings = false;
        return info;
    }
    #throwInStrictMode(message) {
        if (this.#mode === 1 )
            throw new Error(message);
    }
    #handleOriginalScopeStartItem(item) {
        this.#scopeState.line += item.line;
        if (item.line === 0) {
            this.#scopeState.column += item.column;
        }
        else {
            this.#scopeState.column = item.column;
        }
        const scope = {
            start: { line: this.#scopeState.line, column: this.#scopeState.column },
            end: { line: this.#scopeState.line, column: this.#scopeState.column },
            isStackFrame: false,
            variables: [],
            children: [],
        };
        if (item.nameIdx !== undefined) {
            this.#scopeState.name += item.nameIdx;
            scope.name = this.#resolveName(this.#scopeState.name);
        }
        if (item.kindIdx !== undefined) {
            this.#scopeState.kind += item.kindIdx;
            scope.kind = this.#resolveName(this.#scopeState.kind);
        }
        scope.isStackFrame = Boolean(item.flags & 4 );
        this.#scopeStack.push(scope);
        this.#flatOriginalScopes.push(scope);
    }
    #handleOriginalScopeVariablesItem(variableIdxs) {
        const scope = this.#scopeStack.at(-1);
        if (!scope) {
            this.#throwInStrictMode("Encountered ORIGINAL_SCOPE_VARIABLES without surrounding ORIGINAL_SCOPE_START");
            return;
        }
        for (const variableIdx of variableIdxs) {
            this.#scopeState.variable += variableIdx;
            scope.variables.push(this.#resolveName(this.#scopeState.variable));
        }
    }
    #handleOriginalScopeEndItem(line, column) {
        this.#scopeState.line += line;
        if (line === 0) {
            this.#scopeState.column += column;
        }
        else {
            this.#scopeState.column = column;
        }
        const scope = this.#scopeStack.pop();
        if (!scope) {
            this.#throwInStrictMode("Encountered ORIGINAL_SCOPE_END without matching ORIGINAL_SCOPE_START!");
            return;
        }
        scope.end = {
            line: this.#scopeState.line,
            column: this.#scopeState.column,
        };
        if (this.#scopeStack.length > 0) {
            const parent = this.#scopeStack.at(-1);
            scope.parent = parent;
            parent.children.push(scope);
        }
        else {
            this.#scopes.push(scope);
            this.#scopeState.line = 0;
            this.#scopeState.column = 0;
        }
    }
    #handleGeneratedRangeStartItem(item) {
        if (item.line !== undefined) {
            this.#rangeState.line += item.line;
            this.#rangeState.column = item.column;
        }
        else {
            this.#rangeState.column += item.column;
        }
        const range = {
            start: {
                line: this.#rangeState.line,
                column: this.#rangeState.column,
            },
            end: {
                line: this.#rangeState.line,
                column: this.#rangeState.column,
            },
            isStackFrame: Boolean(item.flags & 4 ),
            isHidden: Boolean(item.flags & 8 ),
            values: [],
            children: [],
        };
        if (item.definitionIdx !== undefined) {
            this.#rangeState.defScopeIdx += item.definitionIdx;
            if (this.#rangeState.defScopeIdx < 0 ||
                this.#rangeState.defScopeIdx >= this.#flatOriginalScopes.length) {
                this.#throwInStrictMode("Invalid definition scope index");
            }
            else {
                range.originalScope =
                    this.#flatOriginalScopes[this.#rangeState.defScopeIdx];
            }
        }
        this.#rangeStack.push(range);
    }
    #handleGeneratedRangeBindingsItem(valueIdxs) {
        const range = this.#rangeStack.at(-1);
        if (!range) {
            this.#throwInStrictMode("Encountered GENERATED_RANGE_BINDINGS without surrounding GENERATED_RANGE_START");
            return;
        }
        for (const valueIdx of valueIdxs) {
            if (valueIdx === 0) {
                range.values.push(null);
            }
            else {
                range.values.push(this.#resolveName(valueIdx - 1));
            }
        }
    }
    #recordGeneratedSubRangeBindingItem(variableIndex, bindings) {
        const range = this.#rangeStack.at(-1);
        if (!range) {
            this.#throwInStrictMode("Encountered GENERATED_RANGE_SUBRANGE_BINDING without surrounding GENERATED_RANGE_START");
            return;
        }
        let subRangeBindings = this.#subRangeBindingsForRange.get(range);
        if (!subRangeBindings) {
            subRangeBindings = new Map();
            this.#subRangeBindingsForRange.set(range, subRangeBindings);
        }
        if (subRangeBindings.has(variableIndex)) {
            this.#throwInStrictMode("Encountered multiple GENERATED_RANGE_SUBRANGE_BINDING items for the same variable");
            return;
        }
        subRangeBindings.set(variableIndex, bindings);
    }
    #handleGeneratedRangeCallSite(sourceIndex, line, column) {
        const range = this.#rangeStack.at(-1);
        if (!range) {
            this.#throwInStrictMode("Encountered GENERATED_RANGE_CALL_SITE without surrounding GENERATED_RANGE_START");
            return;
        }
        range.callSite = {
            sourceIndex,
            line,
            column,
        };
    }
    #handleGeneratedRangeEndItem(line, column) {
        if (line !== 0) {
            this.#rangeState.line += line;
            this.#rangeState.column = column;
        }
        else {
            this.#rangeState.column += column;
        }
        const range = this.#rangeStack.pop();
        if (!range) {
            this.#throwInStrictMode("Encountered GENERATED_RANGE_END without matching GENERATED_RANGE_START!");
            return;
        }
        range.end = {
            line: this.#rangeState.line,
            column: this.#rangeState.column,
        };
        this.#handleGeneratedRangeSubRangeBindings(range);
        if (this.#rangeStack.length > 0) {
            const parent = this.#rangeStack.at(-1);
            range.parent = parent;
            parent.children.push(range);
        }
        else {
            this.#ranges.push(range);
        }
    }
    #handleGeneratedRangeSubRangeBindings(range) {
        const subRangeBindings = this.#subRangeBindingsForRange.get(range);
        if (!subRangeBindings)
            return;
        for (const [variableIndex, bindings] of subRangeBindings) {
            const value = range.values[variableIndex];
            const subRanges = [];
            range.values[variableIndex] = subRanges;
            let lastLine = range.start.line;
            let lastColumn = range.start.column;
            subRanges.push({
                from: { line: lastLine, column: lastColumn },
                to: { line: 0, column: 0 },
                value: value,
            });
            for (const [binding, line, column] of bindings) {
                lastLine += line;
                if (line === 0) {
                    lastColumn += column;
                }
                else {
                    lastColumn = column;
                }
                subRanges.push({
                    from: { line: lastLine, column: lastColumn },
                    to: { line: 0, column: 0 },
                    value: binding === 0 ? undefined : this.#resolveName(binding - 1),
                });
            }
        }
        for (const value of range.values) {
            if (Array.isArray(value)) {
                const subRanges = value;
                for (let i = 0; i < subRanges.length - 1; ++i) {
                    subRanges[i].to = subRanges[i + 1].from;
                }
                subRanges[subRanges.length - 1].to = range.end;
            }
        }
    }
    #resolveName(index) {
        if (index < 0 || index >= this.#names.length) {
            this.#throwInStrictMode("Illegal index into the 'names' array");
        }
        return this.#names[index] ?? "";
    }
}

// Copyright 2016 The Chromium Authors
let formatterWorkerPoolInstance;
class FormatterWorkerPool {
    taskQueue;
    workerTasks;
    entrypointURL;
    constructor(entrypointURL) {
        this.taskQueue = [];
        this.workerTasks = new Map();
        this.entrypointURL =
            entrypointURL ?? import.meta.resolve('../../entrypoints/formatter_worker/formatter_worker-entrypoint.js');
    }
    static instance(opts) {
        if (!formatterWorkerPoolInstance || opts?.forceNew) {
            formatterWorkerPoolInstance = new FormatterWorkerPool(opts?.entrypointURL);
        }
        return formatterWorkerPoolInstance;
    }
    dispose() {
        for (const task of this.taskQueue) {
            console.error('rejecting task');
            task.errorCallback(new Event('Worker terminated'));
        }
        for (const [worker, task] of this.workerTasks.entries()) {
            task?.errorCallback(new Event('Worker terminated'));
            worker.terminate( true);
        }
    }
    static removeInstance() {
        formatterWorkerPoolInstance?.dispose();
        formatterWorkerPoolInstance = undefined;
    }
    createWorker() {
        const worker = HOST_RUNTIME.createWorker(this.entrypointURL);
        worker.onmessage = this.onWorkerMessage.bind(this, worker);
        worker.onerror = this.onWorkerError.bind(this, worker);
        return worker;
    }
    processNextTask() {
        const maxWorkers = Math.max(2, navigator.hardwareConcurrency - 1);
        if (!this.taskQueue.length) {
            return;
        }
        let freeWorker = [...this.workerTasks.keys()].find(worker => !this.workerTasks.get(worker));
        if (!freeWorker && this.workerTasks.size < maxWorkers) {
            freeWorker = this.createWorker();
        }
        if (!freeWorker) {
            return;
        }
        const task = this.taskQueue.shift();
        if (task) {
            this.workerTasks.set(freeWorker, task);
            freeWorker.postMessage({ method: task.method, params: task.params });
        }
    }
    onWorkerMessage(worker, event) {
        const task = this.workerTasks.get(worker);
        if (!task) {
            return;
        }
        if (task.isChunked && event.data && !event.data['isLastChunk']) {
            task.callback(event.data);
            return;
        }
        this.workerTasks.set(worker, null);
        this.processNextTask();
        task.callback(event.data ? event.data : null);
    }
    onWorkerError(worker, event) {
        console.error(event);
        const task = this.workerTasks.get(worker);
        worker.terminate();
        this.workerTasks.delete(worker);
        const newWorker = this.createWorker();
        this.workerTasks.set(newWorker, null);
        this.processNextTask();
        if (task) {
            task.errorCallback(event);
        }
    }
    runChunkedTask(methodName, params, callback) {
        const task = new Task(methodName, params, onData, () => onData(null), true);
        this.taskQueue.push(task);
        this.processNextTask();
        function onData(data) {
            if (!data) {
                callback(true, null);
                return;
            }
            const isLastChunk = 'isLastChunk' in data && Boolean(data['isLastChunk']);
            const chunk = 'chunk' in data && data['chunk'];
            callback(isLastChunk, chunk);
        }
    }
    runTask(methodName, params) {
        return new Promise((resolve, reject) => {
            const task = new Task(methodName, params, resolve, reject, false);
            this.taskQueue.push(task);
            this.processNextTask();
        });
    }
    format(mimeType, content, indentString) {
        const parameters = { mimeType, content, indentString };
        return this.runTask("format" , parameters);
    }
    javaScriptSubstitute(expression, mapping) {
        if (mapping.size === 0) {
            return Promise.resolve(expression);
        }
        return this.runTask("javaScriptSubstitute" , { content: expression, mapping })
            .then(result => result || '');
    }
    javaScriptScopeTree(expression, sourceType = 'script') {
        return this.runTask("javaScriptScopeTree" , { content: expression, sourceType })
            .then(result => result || null);
    }
    parseCSS(content, callback) {
        this.runChunkedTask("parseCSS" , { content }, onDataChunk);
        function onDataChunk(isLastChunk, data) {
            const rules = (data || []);
            callback(isLastChunk, rules);
        }
    }
}
class Task {
    method;
    params;
    callback;
    errorCallback;
    isChunked;
    constructor(method, params, callback, errorCallback, isChunked) {
        this.method = method;
        this.params = params;
        this.callback = callback;
        this.errorCallback = errorCallback;
        this.isChunked = isChunked;
    }
}
function formatterWorkerPool() {
    return FormatterWorkerPool.instance();
}

var FormatterWorkerPool$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	FormatterWorkerPool: FormatterWorkerPool,
	formatterWorkerPool: formatterWorkerPool
});

// Copyright 2011 The Chromium Authors
function locationToPosition(lineEndings, lineNumber, columnNumber) {
    const position = lineNumber ? lineEndings[lineNumber - 1] + 1 : 0;
    return position + columnNumber;
}
function positionToLocation(lineEndings, position) {
    const lineNumber = upperBound(lineEndings, position - 1, DEFAULT_COMPARATOR);
    let columnNumber;
    if (!lineNumber) {
        columnNumber = position;
    }
    else {
        columnNumber = position - lineEndings[lineNumber - 1] - 1;
    }
    return [lineNumber, columnNumber];
}
async function format(contentType, mimeType, content, indent = Settings.instance().moduleSetting('text-editor-indent').get()) {
    if (contentType.isDocumentOrScriptOrStyleSheet()) {
        return await formatScriptContent(mimeType, content, indent);
    }
    return { formattedContent: content, formattedMapping: new IdentityFormatterSourceMapping() };
}
async function formatScriptContent(mimeType, content, indent = Settings.instance().moduleSetting('text-editor-indent').get()) {
    const originalContent = content.replace(/\r\n?|[\n\u2028\u2029]/g, '\n').replace(/^\uFEFF/, '');
    const pool = formatterWorkerPool();
    let formatResult = { content: originalContent, mapping: { original: [], formatted: [] } };
    try {
        formatResult = await pool.format(mimeType, originalContent, indent);
    }
    catch {
    }
    const originalContentLineEndings = findLineEndingIndexes(originalContent);
    const formattedContentLineEndings = findLineEndingIndexes(formatResult.content);
    const sourceMapping = new FormatterSourceMappingImpl(originalContentLineEndings, formattedContentLineEndings, formatResult.mapping);
    return { formattedContent: formatResult.content, formattedMapping: sourceMapping };
}
class IdentityFormatterSourceMapping {
    originalToFormatted(lineNumber, columnNumber = 0) {
        return [lineNumber, columnNumber];
    }
    formattedToOriginal(lineNumber, columnNumber = 0) {
        return [lineNumber, columnNumber];
    }
}
class FormatterSourceMappingImpl {
    originalLineEndings;
    formattedLineEndings;
    mapping;
    constructor(originalLineEndings, formattedLineEndings, mapping) {
        this.originalLineEndings = originalLineEndings;
        this.formattedLineEndings = formattedLineEndings;
        this.mapping = mapping;
    }
    originalToFormatted(lineNumber, columnNumber) {
        const originalPosition = locationToPosition(this.originalLineEndings, lineNumber, columnNumber || 0);
        const formattedPosition = this.convertPosition(this.mapping.original, this.mapping.formatted, originalPosition);
        return positionToLocation(this.formattedLineEndings, formattedPosition);
    }
    formattedToOriginal(lineNumber, columnNumber) {
        const formattedPosition = locationToPosition(this.formattedLineEndings, lineNumber, columnNumber || 0);
        const originalPosition = this.convertPosition(this.mapping.formatted, this.mapping.original, formattedPosition);
        return positionToLocation(this.originalLineEndings, originalPosition);
    }
    convertPosition(positions1, positions2, position) {
        const index = upperBound(positions1, position, DEFAULT_COMPARATOR) - 1;
        let convertedPosition = positions2[index] + position - positions1[index];
        if (index < positions2.length - 1 && convertedPosition > positions2[index + 1]) {
            convertedPosition = positions2[index + 1];
        }
        return convertedPosition;
    }
}

var ScriptFormatter = /*#__PURE__*/Object.freeze({
	__proto__: null,
	format: format,
	formatScriptContent: formatScriptContent
});

// Copyright 2019 The Chromium Authors

var formatter = /*#__PURE__*/Object.freeze({
	__proto__: null,
	FormatterWorkerPool: FormatterWorkerPool$1,
	ScriptFormatter: ScriptFormatter
});

// Copyright 2023 The Chromium Authors
const scopeTrees = new WeakMap();
function scopeTreeForScript(script) {
    if (script.isWasm()) {
        return Promise.resolve(null);
    }
    let promise = scopeTrees.get(script);
    if (promise === undefined) {
        promise = script.requestContentData().then(content => {
            if (ContentData.isError(content)) {
                return null;
            }
            const sourceType = script.isModule ? 'module' : 'script';
            return formatterWorkerPool()
                .javaScriptScopeTree(content.text, sourceType)
                .then(scopeTree => scopeTree ? ({ scopeTree, text: content.textObj }) : null)
                .catch(() => null);
        });
        scopeTrees.set(script, promise);
    }
    return promise;
}

// Copyright 2025 The Chromium Authors
function buildOriginalScopes(ranges) {
    validateStartBeforeEnd(ranges);
    ranges.sort((a, b) => comparePositions(a.start, b.start) || comparePositions(b.end, a.end));
    const root = {
        start: { line: 0, column: 0 },
        end: { line: Number.POSITIVE_INFINITY, column: Number.POSITIVE_INFINITY },
        kind: 'Global',
        isStackFrame: false,
        children: [],
        variables: [],
    };
    const stack = [root];
    for (const range of ranges) {
        let stackTop = stack.at(-1);
        while (true) {
            if (comparePositions(stackTop.end, range.start) <= 0) {
                stack.pop();
                stackTop = stack.at(-1);
            }
            else {
                break;
            }
        }
        if (comparePositions(range.start, stackTop.end) < 0 && comparePositions(stackTop.end, range.end) < 0) {
            throw new Error(`Range ${JSON.stringify(range)} and ${JSON.stringify(stackTop)} partially overlap.`);
        }
        const scope = createScopeFrom(range);
        stackTop.children.push(scope);
        stack.push(scope);
    }
    const lastChild = root.children.at(-1);
    if (lastChild) {
        root.end = lastChild.end;
    }
    return root;
}
function validateStartBeforeEnd(ranges) {
    for (const range of ranges) {
        if (comparePositions(range.start, range.end) >= 0) {
            throw new Error(`Invalid range. End before start: ${JSON.stringify(range)}`);
        }
    }
}
function createScopeFrom(range) {
    return {
        ...range,
        kind: 'Function',
        isStackFrame: true,
        children: [],
        variables: [],
    };
}
function decodePastaRanges(encodedRanges, names) {
    const result = [];
    let nameIndex = 0;
    let startLineNumber = 0;
    let startColumnNumber = 0;
    let endLineNumber = 0;
    let endColumnNumber = 0;
    const tokenIter = new TokenIterator(encodedRanges);
    let atStart = true;
    while (tokenIter.hasNext()) {
        if (atStart) {
            atStart = false;
        }
        else if (tokenIter.peek() === ',') {
            tokenIter.next();
        }
        else {
            break;
        }
        nameIndex += tokenIter.nextVLQ();
        startLineNumber = endLineNumber + tokenIter.nextVLQ();
        startColumnNumber += tokenIter.nextVLQ();
        endLineNumber = startLineNumber + tokenIter.nextVLQ();
        endColumnNumber += tokenIter.nextVLQ();
        const name = names[nameIndex];
        if (name === undefined) {
            continue;
        }
        result.push({
            start: { line: startLineNumber, column: startColumnNumber },
            end: { line: endLineNumber, column: endColumnNumber },
            name,
        });
    }
    return result;
}
function comparePositions(a, b) {
    return a.line - b.line || a.column - b.column;
}

// Copyright 2024 The Chromium Authors
const UIStrings$10 = {
    local: 'Local',
    closure: 'Closure',
    block: 'Block',
    global: 'Global',
    returnValue: 'Return value',
};
const str_$$ = registerUIStrings('core/sdk/SourceMapScopeChainEntry.ts', UIStrings$10);
const i18nString$J = getLocalizedString.bind(undefined, str_$$);
class SourceMapScopeChainEntry {
    #callFrame;
    #scope;
    #range;
    #isInnerMostFunction;
    #returnValue;
    constructor(callFrame, scope, range, isInnerMostFunction, returnValue) {
        this.#callFrame = callFrame;
        this.#scope = scope;
        this.#range = range;
        this.#isInnerMostFunction = isInnerMostFunction;
        this.#returnValue = returnValue;
    }
    extraProperties() {
        if (this.#returnValue) {
            return [new RemoteObjectProperty(i18nString$J(UIStrings$10.returnValue), this.#returnValue, undefined, undefined, undefined, undefined, undefined,
                 true)];
        }
        return [];
    }
    callFrame() {
        return this.#callFrame;
    }
    type() {
        switch (this.#scope.kind) {
            case 'global':
                return "global" ;
            case 'function':
                return this.#isInnerMostFunction ? "local"  : "closure" ;
            case 'block':
                return "block" ;
        }
        return this.#scope.kind ?? '';
    }
    typeName() {
        switch (this.#scope.kind) {
            case 'global':
                return i18nString$J(UIStrings$10.global);
            case 'function':
                return this.#isInnerMostFunction ? i18nString$J(UIStrings$10.local) : i18nString$J(UIStrings$10.closure);
            case 'block':
                return i18nString$J(UIStrings$10.block);
        }
        return this.#scope.kind ?? '';
    }
    name() {
        return this.#scope.name;
    }
    range() {
        return null;
    }
    object() {
        return new SourceMapScopeRemoteObject(this.#callFrame, this.#scope, this.#range);
    }
    description() {
        return '';
    }
    icon() {
        return undefined;
    }
}
class SourceMapScopeRemoteObject extends RemoteObjectImpl {
    #callFrame;
    #scope;
    #range;
    constructor(callFrame, scope, range) {
        super(callFrame.debuggerModel.runtimeModel(),  undefined, 'object',  undefined,
         null);
        this.#callFrame = callFrame;
        this.#scope = scope;
        this.#range = range;
    }
    async doGetProperties(_ownProperties, accessorPropertiesOnly, generatePreview) {
        if (accessorPropertiesOnly) {
            return { properties: [], internalProperties: [] };
        }
        const properties = [];
        for (const [index, variable] of this.#scope.variables.entries()) {
            const expression = this.#findExpression(index);
            if (expression === null) {
                properties.push(SourceMapScopeRemoteObject.#unavailableProperty(variable));
                continue;
            }
            const result = await this.#callFrame.evaluate({ expression, generatePreview });
            if ('error' in result || result.exceptionDetails) {
                properties.push(SourceMapScopeRemoteObject.#unavailableProperty(variable));
            }
            else {
                properties.push(new RemoteObjectProperty(variable, result.object,  false,  false,  true,
                 false));
            }
        }
        return { properties, internalProperties: [] };
    }
    #findExpression(index) {
        if (!this.#range) {
            return null;
        }
        const expressionOrSubRanges = this.#range.values[index];
        if (typeof expressionOrSubRanges === 'string') {
            return expressionOrSubRanges;
        }
        if (expressionOrSubRanges === null) {
            return null;
        }
        const pausedPosition = this.#callFrame.location();
        for (const range of expressionOrSubRanges) {
            if (contains({ start: range.from, end: range.to }, pausedPosition.lineNumber, pausedPosition.columnNumber)) {
                return range.value ?? null;
            }
        }
        return null;
    }
    static #unavailableProperty(name) {
        return new RemoteObjectProperty(name, null,  false,  false,  true,  false);
    }
}

// Copyright 2024 The Chromium Authors
class SourceMapScopesInfo {
    #sourceMap;
    #originalScopes;
    #generatedRanges;
    #cachedVariablesAndBindingsPresent = null;
    constructor(sourceMap, scopeInfo) {
        this.#sourceMap = sourceMap;
        this.#originalScopes = scopeInfo.scopes;
        this.#generatedRanges = scopeInfo.ranges;
    }
    static createFromAst(sourceMap, scopeTree, text) {
        const numSourceUrls = sourceMap.sourceURLs().length;
        const scopeBySourceUrl = [];
        for (let i = 0; i < numSourceUrls; i++) {
            const scope = {
                start: { line: 0, column: 0 },
                end: { line: Number.POSITIVE_INFINITY, column: Number.POSITIVE_INFINITY },
                isStackFrame: false,
                variables: [],
                children: [],
            };
            scopeBySourceUrl.push(scope);
        }
        const { range } = convertScope(scopeTree, undefined);
        return new SourceMapScopesInfo(sourceMap, { scopes: scopeBySourceUrl, ranges: [range] });
        function insertInScope(parent, newScope) {
            for (const child of parent.children) {
                if (contains(child, newScope)) {
                    insertInScope(child, newScope);
                    return;
                }
            }
            const childrenToKeep = [];
            for (const child of parent.children) {
                if (contains(newScope, child)) {
                    newScope.children.push(child);
                    child.parent = newScope;
                }
                else {
                    childrenToKeep.push(child);
                }
            }
            const insertIndex = childrenToKeep.findIndex(child => compareScopes(newScope, child) < 0);
            if (insertIndex === -1) {
                childrenToKeep.push(newScope);
            }
            else {
                childrenToKeep.splice(insertIndex, 0, newScope);
            }
            parent.children = childrenToKeep;
            newScope.parent = parent;
        }
        function contains(outer, inner) {
            return comparePositions(outer.start, inner.start) <= 0 && comparePositions(outer.end, inner.end) >= 0;
        }
        function compareScopes(a, b) {
            return comparePositions(a.start, b.start);
        }
        function comparePositions(a, b) {
            if (a.line !== b.line) {
                return a.line - b.line;
            }
            return a.column - b.column;
        }
        function convertScope(node, parentRange) {
            const start = positionFromOffset(node.start);
            const end = positionFromOffset(node.end);
            const startEntry = sourceMap.findEntry(start.line, start.column);
            const endEntry = sourceMap.findEntry(end.line, end.column);
            const sourceIndex = startEntry?.sourceIndex;
            const canMapOriginalPosition = startEntry && endEntry && sourceIndex !== undefined &&
                startEntry.sourceIndex === endEntry.sourceIndex && startEntry.sourceIndex !== undefined && sourceIndex >= 0 &&
                sourceIndex < numSourceUrls;
            const isStackFrame = node.kind === 2  ||
                node.kind === 4 ;
            let name = undefined;
            for (const offset of node.nameMappingLocations ?? []) {
                const position = positionFromOffset(offset);
                const entry = sourceMap.findEntryExact(position.line, position.column);
                if (entry?.name !== undefined) {
                    name = entry.name;
                    break;
                }
            }
            let scope;
            if (canMapOriginalPosition) {
                scope = {
                    start: { line: startEntry.sourceLineNumber, column: startEntry.sourceColumnNumber },
                    end: { line: endEntry.sourceLineNumber, column: endEntry.sourceColumnNumber },
                    name: name ?? node.name,
                    isStackFrame,
                    variables: [],
                    children: [],
                };
            }
            const range = {
                start,
                end,
                originalScope: scope,
                isStackFrame,
                isHidden: false,
                values: [],
                children: [],
            };
            parentRange?.children.push(range);
            if (canMapOriginalPosition && scope) {
                const rootScope = scopeBySourceUrl[sourceIndex];
                insertInScope(rootScope, scope);
            }
            node.children.forEach(child => convertScope(child, range));
            return { range };
        }
        function positionFromOffset(offset) {
            const location = text.positionFromOffset(offset);
            return { line: location.lineNumber, column: location.columnNumber };
        }
    }
    addOriginalScopes(scopes) {
        for (const scope of scopes) {
            this.#originalScopes.push(scope);
        }
    }
    addGeneratedRanges(ranges) {
        for (const range of ranges) {
            this.#generatedRanges.push(range);
        }
    }
    hasOriginalScopes(sourceIdx) {
        return Boolean(this.#originalScopes[sourceIdx]);
    }
    isEmpty() {
        const noScopes = this.#originalScopes.every(scope => scope === null);
        return noScopes && !this.#generatedRanges.length;
    }
    addOriginalScopesAtIndex(sourceIdx, scope) {
        if (!this.#originalScopes[sourceIdx]) {
            this.#originalScopes[sourceIdx] = scope;
        }
        else {
            throw new Error(`Trying to re-augment existing scopes for source at index: ${sourceIdx}`);
        }
    }
    isOutlinedFrame(generatedLine, generatedColumn) {
        const rangeChain = this.#findGeneratedRangeChain(generatedLine, generatedColumn);
        return this.#isOutlinedFrame(rangeChain);
    }
    #isOutlinedFrame(rangeChain) {
        for (let i = rangeChain.length - 1; i >= 0; --i) {
            if (rangeChain[i].isStackFrame) {
                return rangeChain[i].isHidden;
            }
        }
        return false;
    }
    hasInlinedFrames(generatedLine, generatedColumn) {
        const rangeChain = this.#findGeneratedRangeChain(generatedLine, generatedColumn);
        for (let i = rangeChain.length - 1; i >= 0; --i) {
            if (rangeChain[i].isStackFrame) {
                return false;
            }
            if (rangeChain[i].callSite) {
                return true;
            }
        }
        return false;
    }
    findInlinedFunctions(generatedLine, generatedColumn) {
        const rangeChain = this.#findGeneratedRangeChain(generatedLine, generatedColumn);
        const result = {
            inlinedFunctions: [],
            originalFunctionName: '',
        };
        for (let i = rangeChain.length - 1; i >= 0; --i) {
            const range = rangeChain[i];
            if (range.callSite) {
                result.inlinedFunctions.push({
                    name: range.originalScope?.name ?? '',
                    callsite: { ...range.callSite, sourceURL: this.#sourceMap.sourceURLForSourceIndex(range.callSite.sourceIndex) }
                });
            }
            if (range.isStackFrame) {
                result.originalFunctionName = range.originalScope?.name ?? '';
                break;
            }
        }
        return result;
    }
    #findGeneratedRangeChain(line, column) {
        const result = [];
        (function walkRanges(ranges) {
            for (const range of ranges) {
                if (!contains(range, line, column)) {
                    continue;
                }
                result.push(range);
                walkRanges(range.children);
            }
        })(this.#generatedRanges);
        return result;
    }
    hasVariablesAndBindings() {
        if (this.#cachedVariablesAndBindingsPresent === null) {
            this.#cachedVariablesAndBindingsPresent = this.#areVariablesAndBindingsPresent();
        }
        return this.#cachedVariablesAndBindingsPresent;
    }
    #areVariablesAndBindingsPresent() {
        function walkTree(nodes) {
            for (const node of nodes) {
                if (!node) {
                    continue;
                }
                if ('variables' in node && node.variables.length > 0) {
                    return true;
                }
                if ('values' in node && node.values.some(v => v !== null)) {
                    return true;
                }
                if (walkTree(node.children)) {
                    return true;
                }
            }
            return false;
        }
        return walkTree(this.#originalScopes) && walkTree(this.#generatedRanges);
    }
    resolveMappedScopeChain(callFrame) {
        const rangeChain = this.#findGeneratedRangeChainForFrame(callFrame);
        const innerMostOriginalScope = rangeChain.at(-1)?.originalScope;
        if (innerMostOriginalScope === undefined) {
            return null;
        }
        let seenFunctionScope = false;
        const result = [];
        for (let originalScope = rangeChain.at(-1)?.originalScope; originalScope; originalScope = originalScope.parent) {
            const range = rangeChain.findLast(r => r.originalScope === originalScope);
            const isFunctionScope = originalScope.kind === 'function';
            const isInnerMostFunction = isFunctionScope && !seenFunctionScope;
            const returnValue = isInnerMostFunction ? callFrame.returnValue() : null;
            result.push(new SourceMapScopeChainEntry(callFrame, originalScope, range, isInnerMostFunction, returnValue ?? undefined));
            seenFunctionScope ||= isFunctionScope;
        }
        if (callFrame.returnValue() !== null) {
            while (result.length && result[0].type() !== "local" ) {
                result.shift();
            }
        }
        return result;
    }
    #findGeneratedRangeChainForFrame(callFrame) {
        const rangeChain = this.#findGeneratedRangeChain(callFrame.location().lineNumber, callFrame.location().columnNumber);
        if (callFrame.inlineFrameIndex === 0) {
            return rangeChain;
        }
        for (let inlineIndex = 0; inlineIndex < callFrame.inlineFrameIndex;) {
            const range = rangeChain.pop();
            if (range?.callSite) {
                ++inlineIndex;
            }
        }
        return rangeChain;
    }
    findOriginalFunctionName(position) {
        const originalInnerMostScope = this.findOriginalFunctionScope(position)?.scope ?? undefined;
        return this.#findFunctionNameInOriginalScopeChain(originalInnerMostScope);
    }
    findOriginalFunctionScope({ line, column }) {
        let originalInnerMostScope;
        if (this.#generatedRanges.length > 0) {
            const rangeChain = this.#findGeneratedRangeChain(line, column);
            originalInnerMostScope = rangeChain.at(-1)?.originalScope;
        }
        else {
            const entry = this.#sourceMap.findEntry(line, column);
            if (entry?.sourceIndex === undefined) {
                return null;
            }
            originalInnerMostScope =
                this.#findOriginalScopeChain({ sourceIndex: entry.sourceIndex, line: entry.sourceLineNumber, column: entry.sourceColumnNumber })
                    .at(-1);
        }
        if (!originalInnerMostScope) {
            return null;
        }
        const functionScope = this.#findFunctionScopeInOriginalScopeChain(originalInnerMostScope);
        if (!functionScope) {
            return null;
        }
        let rootScope = functionScope;
        while (rootScope.parent) {
            rootScope = rootScope.parent;
        }
        const sourceIndex = this.#originalScopes.indexOf(rootScope);
        const url = sourceIndex !== -1 ? this.#sourceMap.sourceURLForSourceIndex(sourceIndex) : undefined;
        return functionScope ? { scope: functionScope, url } : null;
    }
    #findOriginalScopeChain({ sourceIndex, line, column }) {
        const scope = this.#originalScopes[sourceIndex];
        if (!scope) {
            return [];
        }
        const result = [];
        (function walkScopes(scopes) {
            for (const scope of scopes) {
                if (!contains(scope, line, column)) {
                    continue;
                }
                result.push(scope);
                walkScopes(scope.children);
            }
        })([scope]);
        return result;
    }
    #findFunctionScopeInOriginalScopeChain(innerOriginalScope) {
        for (let originalScope = innerOriginalScope; originalScope; originalScope = originalScope.parent) {
            if (originalScope.isStackFrame) {
                return originalScope;
            }
        }
        return null;
    }
    #findFunctionNameInOriginalScopeChain(innerOriginalScope) {
        const functionScope = this.#findFunctionScopeInOriginalScopeChain(innerOriginalScope);
        if (!functionScope) {
            return null;
        }
        return functionScope.name ?? '';
    }
    translateCallSite(generatedLine, generatedColumn) {
        const rangeChain = this.#findGeneratedRangeChain(generatedLine, generatedColumn);
        if (this.#isOutlinedFrame(rangeChain)) {
            throw new Error('SourceMapScopesInfo is unable to translate an outlined function by itself');
        }
        const mapping = this.#sourceMap.findEntry(generatedLine, generatedColumn);
        if (mapping?.sourceIndex === undefined) {
            return [];
        }
        const result = [{
                line: mapping.sourceLineNumber,
                column: mapping.sourceColumnNumber,
                name: this.findOriginalFunctionName({ line: generatedLine, column: generatedColumn }) ?? undefined,
                url: mapping.sourceURL,
            }];
        for (let i = rangeChain.length - 1; i >= 0 && !rangeChain[i].isStackFrame; --i) {
            const range = rangeChain[i];
            if (!range.callSite) {
                continue;
            }
            const originalScopeChain = this.#findOriginalScopeChain(range.callSite);
            result.push({
                line: range.callSite.line,
                column: range.callSite.column,
                name: this.#findFunctionNameInOriginalScopeChain(originalScopeChain.at(-1)) ?? undefined,
                url: this.#sourceMap.sourceURLForSourceIndex(range.callSite.sourceIndex),
            });
        }
        return result;
    }
}
function contains(range, line, column) {
    if (range.start.line > line || (range.start.line === line && range.start.column > column)) {
        return false;
    }
    if (range.end.line < line || (range.end.line === line && range.end.column <= column)) {
        return false;
    }
    return true;
}

// Copyright 2012 The Chromium Authors
var _a$5;
function parseSourceMap(content) {
    if (content.startsWith(')]}')) {
        content = content.substring(content.indexOf('\n'));
    }
    if (content.charCodeAt(0) === 0xFEFF) {
        content = content.slice(1);
    }
    return JSON.parse(content);
}
class SourceMapEntry {
    lineNumber;
    columnNumber;
    sourceIndex;
    sourceURL;
    sourceLineNumber;
    sourceColumnNumber;
    name;
    constructor(lineNumber, columnNumber, sourceIndex, sourceURL, sourceLineNumber, sourceColumnNumber, name) {
        this.lineNumber = lineNumber;
        this.columnNumber = columnNumber;
        this.sourceIndex = sourceIndex;
        this.sourceURL = sourceURL;
        this.sourceLineNumber = sourceLineNumber;
        this.sourceColumnNumber = sourceColumnNumber;
        this.name = name;
    }
    static compare(entry1, entry2) {
        if (entry1.lineNumber !== entry2.lineNumber) {
            return entry1.lineNumber - entry2.lineNumber;
        }
        return entry1.columnNumber - entry2.columnNumber;
    }
}
class SourceMap {
    static retainRawSourceMaps = false;
    #json;
    #compiledURL;
    #sourceMappingURL;
    #baseURL;
    #mappings = null;
    #sourceInfos = [];
    #sourceInfoByURL = new Map();
    #script;
    #scopesInfo = null;
    #debugId;
    #scopesFallbackPromise;
    constructor(compiledURL, sourceMappingURL, payload, script) {
        this.#json = payload;
        this.#script = script;
        this.#compiledURL = compiledURL;
        this.#sourceMappingURL = sourceMappingURL;
        this.#baseURL = (schemeIs(sourceMappingURL, 'data:')) ? compiledURL : sourceMappingURL;
        this.#debugId = 'debugId' in payload ? payload.debugId : undefined;
        if ('sections' in this.#json) {
            if (this.#json.sections.find(section => 'url' in section)) {
                Console.instance().warn(`SourceMap "${sourceMappingURL}" contains unsupported "URL" field in one of its sections.`);
            }
        }
        this.eachSection(this.parseSources.bind(this));
    }
    json() {
        return this.#json;
    }
    augmentWithScopes(scriptUrl, ranges) {
        this.#ensureSourceMapProcessed();
        if (this.#json && this.#json.version > 3) {
            throw new Error('Only support augmenting source maps up to version 3.');
        }
        const sourceIdx = this.#sourceIndex(scriptUrl);
        if (sourceIdx >= 0) {
            if (!this.#scopesInfo) {
                this.#scopesInfo = new SourceMapScopesInfo(this, { scopes: [], ranges: [] });
            }
            if (!this.#scopesInfo.hasOriginalScopes(sourceIdx)) {
                const originalScopes = buildOriginalScopes(ranges);
                this.#scopesInfo.addOriginalScopesAtIndex(sourceIdx, originalScopes);
            }
        }
        else {
            throw new Error(`Could not find sourceURL ${scriptUrl} in sourceMap`);
        }
    }
    #sourceIndex(sourceURL) {
        return this.#sourceInfos.findIndex(info => info.sourceURL === sourceURL);
    }
    compiledURL() {
        return this.#compiledURL;
    }
    url() {
        return this.#sourceMappingURL;
    }
    debugId() {
        return this.#debugId ?? null;
    }
    sourceURLForSourceIndex(index) {
        return this.#sourceInfos[index]?.sourceURL;
    }
    sourceURLs() {
        return [...this.#sourceInfoByURL.keys()];
    }
    embeddedContentByURL(sourceURL) {
        const entry = this.#sourceInfoByURL.get(sourceURL);
        if (!entry) {
            return null;
        }
        return entry.content;
    }
    hasScopeInfo() {
        this.#ensureSourceMapProcessed();
        return this.#scopesInfo !== null && !this.#scopesInfo.isEmpty();
    }
    waitForScopeInfo() {
        this.#ensureSourceMapProcessed();
        return this.#scopesFallbackPromise ?? Promise.resolve();
    }
    findEntry(lineNumber, columnNumber, inlineFrameIndex) {
        this.#ensureSourceMapProcessed();
        if (inlineFrameIndex && this.#scopesInfo !== null) {
            const { inlinedFunctions } = this.#scopesInfo.findInlinedFunctions(lineNumber, columnNumber);
            const { callsite } = inlinedFunctions[inlineFrameIndex - 1];
            if (!callsite) {
                console.error('Malformed source map. Expected to have a callsite info for index', inlineFrameIndex);
                return null;
            }
            return {
                lineNumber,
                columnNumber,
                sourceIndex: callsite.sourceIndex,
                sourceURL: this.sourceURLs()[callsite.sourceIndex],
                sourceLineNumber: callsite.line,
                sourceColumnNumber: callsite.column,
            };
        }
        const mappings = this.mappings();
        const index = upperBound(mappings, undefined, (_, entry) => lineNumber - entry.lineNumber || columnNumber - entry.columnNumber);
        return index ? mappings[index - 1] : null;
    }
    findEntryExact(lineNumber, columnNumber) {
        const entry = this.findEntry(lineNumber, columnNumber);
        if (entry?.lineNumber === lineNumber && entry.columnNumber === columnNumber) {
            return entry;
        }
        return null;
    }
    findEntryRanges(lineNumber, columnNumber) {
        const mappings = this.mappings();
        const endIndex = upperBound(mappings, undefined, (_, entry) => lineNumber - entry.lineNumber || columnNumber - entry.columnNumber);
        if (!endIndex) {
            return null;
        }
        const startIndex = endIndex - 1;
        const sourceURL = mappings[startIndex].sourceURL;
        if (!sourceURL) {
            return null;
        }
        const endLine = endIndex < mappings.length ? mappings[endIndex].lineNumber : 2 ** 31 - 1;
        const endColumn = endIndex < mappings.length ? mappings[endIndex].columnNumber : 2 ** 31 - 1;
        const range = new TextRange(mappings[startIndex].lineNumber, mappings[startIndex].columnNumber, endLine, endColumn);
        const reverseMappings = this.reversedMappings(sourceURL);
        const startSourceLine = mappings[startIndex].sourceLineNumber;
        const startSourceColumn = mappings[startIndex].sourceColumnNumber;
        const endReverseIndex = upperBound(reverseMappings, undefined, (_, i) => startSourceLine - mappings[i].sourceLineNumber || startSourceColumn - mappings[i].sourceColumnNumber);
        if (!endReverseIndex) {
            return null;
        }
        const endSourceLine = endReverseIndex < reverseMappings.length ?
            mappings[reverseMappings[endReverseIndex]].sourceLineNumber :
            2 ** 31 - 1;
        const endSourceColumn = endReverseIndex < reverseMappings.length ?
            mappings[reverseMappings[endReverseIndex]].sourceColumnNumber :
            2 ** 31 - 1;
        const sourceRange = new TextRange(startSourceLine, startSourceColumn, endSourceLine, endSourceColumn);
        return { range, sourceRange, sourceURL };
    }
    sourceLineMapping(sourceURL, lineNumber, columnNumber) {
        const mappings = this.mappings();
        const reverseMappings = this.reversedMappings(sourceURL);
        const first = lowerBound(reverseMappings, lineNumber, lineComparator);
        const last = upperBound(reverseMappings, lineNumber, lineComparator);
        if (first >= reverseMappings.length || mappings[reverseMappings[first]].sourceLineNumber !== lineNumber) {
            return null;
        }
        const columnMappings = reverseMappings.slice(first, last);
        if (!columnMappings.length) {
            return null;
        }
        const index = lowerBound(columnMappings, columnNumber, (columnNumber, i) => columnNumber - mappings[i].sourceColumnNumber);
        return index >= columnMappings.length ? mappings[columnMappings[columnMappings.length - 1]] :
            mappings[columnMappings[index]];
        function lineComparator(lineNumber, i) {
            return lineNumber - mappings[i].sourceLineNumber;
        }
    }
    findReverseIndices(sourceURL, lineNumber, columnNumber) {
        const mappings = this.mappings();
        const reverseMappings = this.reversedMappings(sourceURL);
        const endIndex = upperBound(reverseMappings, undefined, (_, i) => lineNumber - mappings[i].sourceLineNumber || columnNumber - mappings[i].sourceColumnNumber);
        let startIndex = endIndex;
        while (startIndex > 0 &&
            mappings[reverseMappings[startIndex - 1]].sourceLineNumber ===
                mappings[reverseMappings[endIndex - 1]].sourceLineNumber &&
            mappings[reverseMappings[startIndex - 1]].sourceColumnNumber ===
                mappings[reverseMappings[endIndex - 1]].sourceColumnNumber) {
            --startIndex;
        }
        return reverseMappings.slice(startIndex, endIndex);
    }
    findReverseEntries(sourceURL, lineNumber, columnNumber) {
        const mappings = this.mappings();
        return this.findReverseIndices(sourceURL, lineNumber, columnNumber).map(i => mappings[i]);
    }
    findReverseRanges(sourceURL, lineNumber, columnNumber) {
        const mappings = this.mappings();
        const indices = this.findReverseIndices(sourceURL, lineNumber, columnNumber);
        const ranges = [];
        for (let i = 0; i < indices.length; ++i) {
            const startIndex = indices[i];
            let endIndex = startIndex + 1;
            while (i + 1 < indices.length && endIndex === indices[i + 1]) {
                ++endIndex;
                ++i;
            }
            const startLine = mappings[startIndex].lineNumber;
            const startColumn = mappings[startIndex].columnNumber;
            const endLine = endIndex < mappings.length ? mappings[endIndex].lineNumber : 2 ** 31 - 1;
            const endColumn = endIndex < mappings.length ? mappings[endIndex].columnNumber : 2 ** 31 - 1;
            ranges.push(new TextRange(startLine, startColumn, endLine, endColumn));
        }
        return ranges;
    }
    mappings() {
        this.#ensureSourceMapProcessed();
        return this.#mappings ?? [];
    }
    async #buildScopesFallback() {
        const scopeTreeAndText = this.#script ? await scopeTreeForScript(this.#script) : null;
        if (!scopeTreeAndText) {
            return null;
        }
        const { scopeTree, text } = scopeTreeAndText;
        return SourceMapScopesInfo.createFromAst(this, scopeTree, text);
    }
    reversedMappings(sourceURL) {
        this.#ensureSourceMapProcessed();
        return this.#sourceInfoByURL.get(sourceURL)?.reverseMappings ?? [];
    }
    #ensureSourceMapProcessed() {
        if (this.#mappings === null) {
            this.#mappings = [];
            try {
                this.eachSection(this.parseMap.bind(this));
                if (!this.hasScopeInfo()) {
                    this.#scopesFallbackPromise = this.#buildScopesFallback().then(info => {
                        this.#scopesInfo = info;
                    });
                }
            }
            catch (e) {
                console.error('Failed to parse source map', e);
                this.#mappings = [];
            }
            this.mappings().sort(SourceMapEntry.compare);
            this.#computeReverseMappings(this.#mappings);
        }
        if (!_a$5.retainRawSourceMaps) {
            this.#json = null;
        }
    }
    #computeReverseMappings(mappings) {
        const reverseMappingsPerUrl = new Map();
        for (let i = 0; i < mappings.length; i++) {
            const entryUrl = mappings[i]?.sourceURL;
            if (!entryUrl) {
                continue;
            }
            let reverseMap = reverseMappingsPerUrl.get(entryUrl);
            if (!reverseMap) {
                reverseMap = [];
                reverseMappingsPerUrl.set(entryUrl, reverseMap);
            }
            reverseMap.push(i);
        }
        for (const [url, reverseMap] of reverseMappingsPerUrl.entries()) {
            const info = this.#sourceInfoByURL.get(url);
            if (!info) {
                continue;
            }
            reverseMap.sort(sourceMappingComparator);
            info.reverseMappings = reverseMap;
        }
        function sourceMappingComparator(indexA, indexB) {
            const a = mappings[indexA];
            const b = mappings[indexB];
            return a.sourceLineNumber - b.sourceLineNumber || a.sourceColumnNumber - b.sourceColumnNumber ||
                a.lineNumber - b.lineNumber || a.columnNumber - b.columnNumber;
        }
    }
    eachSection(callback) {
        if (!this.#json) {
            return;
        }
        if ('sections' in this.#json) {
            let sourcesIndex = 0;
            for (const section of this.#json.sections) {
                if ('map' in section) {
                    callback(section.map, sourcesIndex, section.offset.line, section.offset.column);
                    sourcesIndex += section.map.sources.length;
                }
            }
        }
        else {
            callback(this.#json, 0, 0, 0);
        }
    }
    parseSources(sourceMap) {
        const sourceRoot = sourceMap.sourceRoot ?? '';
        const ignoreList = new Set(sourceMap.ignoreList ?? sourceMap.x_google_ignoreList);
        for (let i = 0; i < sourceMap.sources.length; ++i) {
            let href = sourceMap.sources[i];
            if (ParsedURL.isRelativeURL(href)) {
                if (sourceRoot && !sourceRoot.endsWith('/') && href && !href.startsWith('/')) {
                    href = sourceRoot.concat('/', href);
                }
                else {
                    href = sourceRoot.concat(href);
                }
            }
            const url = ParsedURL.completeURL(this.#baseURL, href) || href;
            const source = sourceMap.sourcesContent?.[i];
            const sourceInfo = {
                sourceURL: url,
                content: source ?? null,
                ignoreListHint: ignoreList.has(i),
                reverseMappings: null,
            };
            this.#sourceInfos.push(sourceInfo);
            if (!this.#sourceInfoByURL.has(url)) {
                this.#sourceInfoByURL.set(url, sourceInfo);
            }
        }
    }
    parseMap(map, baseSourceIndex, baseLineNumber, baseColumnNumber) {
        let sourceIndex = baseSourceIndex;
        let lineNumber = baseLineNumber;
        let columnNumber = baseColumnNumber;
        let sourceLineNumber = 0;
        let sourceColumnNumber = 0;
        let nameIndex = 0;
        const names = map.names ?? [];
        const tokenIter = new TokenIterator(map.mappings);
        let sourceURL = this.#sourceInfos[sourceIndex]?.sourceURL;
        while (true) {
            if (tokenIter.peek() === ',') {
                tokenIter.next();
            }
            else {
                while (tokenIter.peek() === ';') {
                    lineNumber += 1;
                    columnNumber = 0;
                    tokenIter.next();
                }
                if (!tokenIter.hasNext()) {
                    break;
                }
            }
            columnNumber += tokenIter.nextVLQ();
            if (!tokenIter.hasNext() || this.isSeparator(tokenIter.peek())) {
                this.mappings().push(new SourceMapEntry(lineNumber, columnNumber));
                continue;
            }
            const sourceIndexDelta = tokenIter.nextVLQ();
            if (sourceIndexDelta) {
                sourceIndex += sourceIndexDelta;
                sourceURL = this.#sourceInfos[sourceIndex]?.sourceURL;
            }
            sourceLineNumber += tokenIter.nextVLQ();
            sourceColumnNumber += tokenIter.nextVLQ();
            if (!tokenIter.hasNext() || this.isSeparator(tokenIter.peek())) {
                this.mappings().push(new SourceMapEntry(lineNumber, columnNumber, sourceIndex, sourceURL, sourceLineNumber, sourceColumnNumber));
                continue;
            }
            nameIndex += tokenIter.nextVLQ();
            this.mappings().push(new SourceMapEntry(lineNumber, columnNumber, sourceIndex, sourceURL, sourceLineNumber, sourceColumnNumber, names[nameIndex]));
        }
        if (experiments.isEnabled(ExperimentName.USE_SOURCE_MAP_SCOPES)) {
            if (!this.#scopesInfo) {
                this.#scopesInfo = new SourceMapScopesInfo(this, { scopes: [], ranges: [] });
            }
            if (map.scopes) {
                const { scopes, ranges } = decode(map, { mode: 2 , generatedOffset: { line: baseLineNumber, column: baseColumnNumber } });
                this.#scopesInfo.addOriginalScopes(scopes);
                this.#scopesInfo.addGeneratedRanges(ranges);
            }
            else if (map.x_com_bloomberg_sourcesFunctionMappings) {
                const originalScopes = this.parseBloombergScopes(map);
                this.#scopesInfo.addOriginalScopes(originalScopes);
            }
            else {
                this.#scopesInfo.addOriginalScopes(new Array(map.sources.length).fill(null));
            }
        }
    }
    parseBloombergScopes(map) {
        const scopeList = map.x_com_bloomberg_sourcesFunctionMappings;
        if (!scopeList) {
            throw new Error('Cant decode pasta scopes without x_com_bloomberg_sourcesFunctionMappings field');
        }
        else if (scopeList.length !== map.sources.length) {
            throw new Error(`x_com_bloomberg_sourcesFunctionMappings must have ${map.sources.length} scope trees`);
        }
        const names = map.names ?? [];
        return scopeList.map(rawScopes => {
            if (!rawScopes) {
                return null;
            }
            const ranges = decodePastaRanges(rawScopes, names);
            return buildOriginalScopes(ranges);
        });
    }
    isSeparator(char) {
        return char === ',' || char === ';';
    }
    reverseMapTextRanges(url, textRange) {
        const reverseMappings = this.reversedMappings(url);
        const mappings = this.mappings();
        if (reverseMappings.length === 0) {
            return [];
        }
        let startReverseIndex = lowerBound(reverseMappings, textRange, ({ startLine, startColumn }, index) => {
            const { sourceLineNumber, sourceColumnNumber } = mappings[index];
            return startLine - sourceLineNumber || startColumn - sourceColumnNumber;
        });
        while (startReverseIndex === reverseMappings.length ||
            startReverseIndex > 0 &&
                (mappings[reverseMappings[startReverseIndex]].sourceLineNumber > textRange.startLine ||
                    mappings[reverseMappings[startReverseIndex]].sourceColumnNumber > textRange.startColumn)) {
            startReverseIndex--;
        }
        let endReverseIndex = startReverseIndex + 1;
        for (; endReverseIndex < reverseMappings.length; ++endReverseIndex) {
            const { sourceLineNumber, sourceColumnNumber } = mappings[reverseMappings[endReverseIndex]];
            if (sourceLineNumber < textRange.endLine ||
                (sourceLineNumber === textRange.endLine && sourceColumnNumber < textRange.endColumn)) {
                continue;
            }
            break;
        }
        const ranges = [];
        for (let reverseIndex = startReverseIndex; reverseIndex < endReverseIndex; ++reverseIndex) {
            const startIndex = reverseMappings[reverseIndex], endIndex = startIndex + 1;
            const range = TextRange.createUnboundedFromLocation(mappings[startIndex].lineNumber, mappings[startIndex].columnNumber);
            if (endIndex < mappings.length) {
                range.endLine = mappings[endIndex].lineNumber;
                range.endColumn = mappings[endIndex].columnNumber;
            }
            ranges.push(range);
        }
        ranges.sort(TextRange.comparator);
        let j = 0;
        for (let i = 1; i < ranges.length; ++i) {
            if (ranges[j].immediatelyPrecedes(ranges[i])) {
                ranges[j].endLine = ranges[i].endLine;
                ranges[j].endColumn = ranges[i].endColumn;
            }
            else {
                ranges[++j] = ranges[i];
            }
        }
        ranges.length = j + 1;
        return ranges;
    }
    mapsOrigin() {
        const mappings = this.mappings();
        if (mappings.length > 0) {
            const firstEntry = mappings[0];
            return firstEntry?.lineNumber === 0 || firstEntry.columnNumber === 0;
        }
        return false;
    }
    hasIgnoreListHint(sourceURL) {
        return this.#sourceInfoByURL.get(sourceURL)?.ignoreListHint ?? false;
    }
    findRanges(predicate, options) {
        const mappings = this.mappings();
        const ranges = [];
        if (!mappings.length) {
            return [];
        }
        let current = null;
        if ((mappings[0].lineNumber !== 0 || mappings[0].columnNumber !== 0) && options?.isStartMatching) {
            current = TextRange.createUnboundedFromLocation(0, 0);
            ranges.push(current);
        }
        for (const { sourceURL, lineNumber, columnNumber } of mappings) {
            const ignoreListHint = sourceURL && predicate(sourceURL);
            if (!current && ignoreListHint) {
                current = TextRange.createUnboundedFromLocation(lineNumber, columnNumber);
                ranges.push(current);
                continue;
            }
            if (current && !ignoreListHint) {
                current.endLine = lineNumber;
                current.endColumn = columnNumber;
                current = null;
            }
        }
        return ranges;
    }
    compatibleForURL(sourceURL, other) {
        return this.embeddedContentByURL(sourceURL) === other.embeddedContentByURL(sourceURL) &&
            this.hasIgnoreListHint(sourceURL) === other.hasIgnoreListHint(sourceURL);
    }
    resolveScopeChain(frame) {
        this.#ensureSourceMapProcessed();
        if (this.#scopesInfo === null) {
            return null;
        }
        return this.#scopesInfo.resolveMappedScopeChain(frame);
    }
    findOriginalFunctionName(position) {
        this.#ensureSourceMapProcessed();
        return this.#scopesInfo?.findOriginalFunctionName(position) ?? null;
    }
    findOriginalFunctionScope(position) {
        this.#ensureSourceMapProcessed();
        return this.#scopesInfo?.findOriginalFunctionScope(position) ?? null;
    }
    isOutlinedFrame(generatedLine, generatedColumn) {
        this.#ensureSourceMapProcessed();
        return this.#scopesInfo?.isOutlinedFrame(generatedLine, generatedColumn) ?? false;
    }
    hasInlinedFrames(generatedLine, generatedColumn) {
        this.#ensureSourceMapProcessed();
        return this.#scopesInfo?.hasInlinedFrames(generatedLine, generatedColumn) ?? false;
    }
    translateCallSite(generatedLine, generatedColumn) {
        this.#ensureSourceMapProcessed();
        return this.#scopesInfo?.translateCallSite(generatedLine, generatedColumn) ?? [];
    }
}
_a$5 = SourceMap;
const VLQ_BASE_SHIFT = 5;
const VLQ_BASE_MASK = (1 << 5) - 1;
const VLQ_CONTINUATION_MASK = 1 << 5;
class TokenIterator {
    #string;
    #position;
    constructor(string) {
        this.#string = string;
        this.#position = 0;
    }
    next() {
        return this.#string.charAt(this.#position++);
    }
    nextCharCode() {
        return this.#string.charCodeAt(this.#position++);
    }
    peek() {
        return this.#string.charAt(this.#position);
    }
    hasNext() {
        return this.#position < this.#string.length;
    }
    nextVLQ() {
        let result = 0;
        let shift = 0;
        let digit = VLQ_CONTINUATION_MASK;
        while (digit & VLQ_CONTINUATION_MASK) {
            if (!this.hasNext()) {
                throw new Error('Unexpected end of input while decodling VLQ number!');
            }
            const charCode = this.nextCharCode();
            digit = BASE64_CODES$1[charCode];
            if (charCode !== 65  && digit === 0) {
                throw new Error(`Unexpected char '${String.fromCharCode(charCode)}' encountered while decoding`);
            }
            result += (digit & VLQ_BASE_MASK) << shift;
            shift += VLQ_BASE_SHIFT;
        }
        const negative = result & 1;
        result >>= 1;
        return negative ? -result : result;
    }
    peekVLQ() {
        const pos = this.#position;
        try {
            return this.nextVLQ();
        }
        catch {
            return null;
        }
        finally {
            this.#position = pos;
        }
    }
}

// Copyright 2025 The Chromium Authors
class SourceMapCache {
    static #INSTANCE = new SourceMapCache('devtools-source-map-cache');
    static instance() {
        if (typeof window === 'undefined') {
            return IN_MEMORY_INSTANCE;
        }
        return this.#INSTANCE;
    }
    static createForTest(name) {
        return new SourceMapCache(name);
    }
    #name;
    #cachePromise;
    constructor(name) {
        this.#name = name;
    }
    async set(debugId, sourceMap) {
        const cache = await this.#cache();
        await cache.put(SourceMapCache.#urlForDebugId(debugId), new Response(JSON.stringify(sourceMap)));
    }
    async get(debugId) {
        const cache = await this.#cache();
        const response = await cache.match(SourceMapCache.#urlForDebugId(debugId));
        return await response?.json() ?? null;
    }
    async #cache() {
        if (this.#cachePromise) {
            return await this.#cachePromise;
        }
        this.#cachePromise = window.caches.open(this.#name);
        return await this.#cachePromise;
    }
    static #urlForDebugId(debugId) {
        return 'http://debug.id/' + encodeURIComponent(debugId);
    }
    async disposeForTest() {
        await window.caches.delete(this.#name);
    }
}
const IN_MEMORY_INSTANCE = new (class {
    #cache = new Map();
    async set(debugId, sourceMap) {
        this.#cache.set(debugId, sourceMap);
    }
    async get(debugId) {
        return this.#cache.get(debugId) ?? null;
    }
    async disposeForTest() {
    }
})();

// Copyright 2017 The Chromium Authors
class SourceMapManager extends ObjectWrapper {
    #target;
    #factory;
    #isEnabled = true;
    #clientData = new Map();
    #sourceMaps = new Map();
    #attachingClient = null;
    constructor(target, factory) {
        super();
        this.#target = target;
        this.#factory =
            factory ?? ((compiledURL, sourceMappingURL, payload) => new SourceMap(compiledURL, sourceMappingURL, payload));
    }
    setEnabled(isEnabled) {
        if (isEnabled === this.#isEnabled) {
            return;
        }
        const clientData = [...this.#clientData.entries()];
        for (const [client] of clientData) {
            this.detachSourceMap(client);
        }
        this.#isEnabled = isEnabled;
        for (const [client, { relativeSourceURL, relativeSourceMapURL }] of clientData) {
            this.attachSourceMap(client, relativeSourceURL, relativeSourceMapURL);
        }
    }
    static getBaseUrl(target) {
        while (target && target.type() !== Type$2.FRAME) {
            target = target.parentTarget();
        }
        return target?.inspectedURL() ?? EmptyUrlString;
    }
    static resolveRelativeSourceURL(target, url) {
        url = ParsedURL.completeURL(SourceMapManager.getBaseUrl(target), url) ?? url;
        return url;
    }
    sourceMapForClient(client) {
        return this.#clientData.get(client)?.sourceMap;
    }
    sourceMapForClientPromise(client) {
        const clientData = this.#clientData.get(client);
        if (!clientData) {
            return Promise.resolve(undefined);
        }
        return clientData.sourceMapPromise;
    }
    clientForSourceMap(sourceMap) {
        return this.#sourceMaps.get(sourceMap);
    }
    attachSourceMap(client, relativeSourceURL, relativeSourceMapURL) {
        if (this.#clientData.has(client)) {
            throw new Error('SourceMap is already attached or being attached to client');
        }
        if (!relativeSourceMapURL) {
            return;
        }
        let clientData = {
            relativeSourceURL,
            relativeSourceMapURL,
            sourceMapPromise: Promise.resolve(undefined),
        };
        if (this.#isEnabled) {
            const sourceURL = SourceMapManager.resolveRelativeSourceURL(this.#target, relativeSourceURL);
            const sourceMapURL = ParsedURL.completeURL(sourceURL, relativeSourceMapURL);
            if (sourceMapURL) {
                if (this.#attachingClient) {
                    console.error('Attaching source map may cancel previously attaching source map');
                }
                this.#attachingClient = client;
                this.dispatchEventToListeners(Events$b.SourceMapWillAttach, { client });
                if (this.#attachingClient === client) {
                    this.#attachingClient = null;
                    const initiator = client.createPageResourceLoadInitiator();
                    const resourceLoader = this.#target.targetManager().context.get(PageResourceLoader);
                    clientData.sourceMapPromise =
                        loadSourceMap(resourceLoader, sourceMapURL, client.debugId(), initiator)
                            .then(payload => {
                            const sourceMap = this.#factory(sourceURL, sourceMapURL, payload, client);
                            if (this.#clientData.get(client) === clientData) {
                                clientData.sourceMap = sourceMap;
                                this.#sourceMaps.set(sourceMap, client);
                                this.dispatchEventToListeners(Events$b.SourceMapAttached, { client, sourceMap });
                            }
                            return sourceMap;
                        }, () => {
                            if (this.#clientData.get(client) === clientData) {
                                this.dispatchEventToListeners(Events$b.SourceMapFailedToAttach, { client });
                            }
                            return undefined;
                        });
                }
                else {
                    if (this.#attachingClient) {
                        console.error('Cancelling source map attach because another source map is attaching');
                    }
                    clientData = null;
                    this.dispatchEventToListeners(Events$b.SourceMapFailedToAttach, { client });
                }
            }
        }
        if (clientData) {
            this.#clientData.set(client, clientData);
        }
    }
    cancelAttachSourceMap(client) {
        if (client === this.#attachingClient) {
            this.#attachingClient = null;
        }
        else if (this.#attachingClient) {
            console.error('cancel attach source map requested but a different source map was being attached');
        }
        else {
            console.error('cancel attach source map requested but no source map was being attached');
        }
    }
    detachSourceMap(client) {
        const clientData = this.#clientData.get(client);
        if (!clientData) {
            return;
        }
        this.#clientData.delete(client);
        if (!this.#isEnabled) {
            return;
        }
        const { sourceMap } = clientData;
        if (sourceMap) {
            this.#sourceMaps.delete(sourceMap);
            this.dispatchEventToListeners(Events$b.SourceMapDetached, { client, sourceMap });
        }
        else {
            this.dispatchEventToListeners(Events$b.SourceMapFailedToAttach, { client });
        }
    }
    waitForSourceMapsProcessedForTest() {
        return Promise.all(this.#sourceMaps.keys().map(sourceMap => sourceMap.waitForScopeInfo()));
    }
}
async function loadSourceMap(resourceLoader, url, debugId, initiator) {
    try {
        if (debugId) {
            const cachedSourceMap = await SourceMapCache.instance().get(debugId);
            if (cachedSourceMap) {
                return cachedSourceMap;
            }
        }
        const { content } = await resourceLoader.loadResource(url, initiator);
        const sourceMap = parseSourceMap(content);
        if ('debugId' in sourceMap && sourceMap.debugId) {
            await SourceMapCache.instance().set(sourceMap.debugId, sourceMap).catch();
        }
        return sourceMap;
    }
    catch (cause) {
        throw new Error(`Could not load content for ${url}: ${cause.message}`, { cause });
    }
}
var Events$b;
(function (Events) {
    Events["SourceMapWillAttach"] = "SourceMapWillAttach";
    Events["SourceMapFailedToAttach"] = "SourceMapFailedToAttach";
    Events["SourceMapAttached"] = "SourceMapAttached";
    Events["SourceMapDetached"] = "SourceMapDetached";
})(Events$b || (Events$b = {}));

// Copyright 2010 The Chromium Authors
class CSSModel extends SDKModel {
    agent;
    #domModel;
    #fontFaces = new Map();
    #originalStyleSheetText = new Map();
    #resourceTreeModel;
    #sourceMapManager;
    #styleLoader;
    #stylePollingThrottler = new Throttler(StylePollingInterval);
    #styleSheetIdsForURL = new Map();
    #styleSheetIdToHeader = new Map();
    #cachedMatchedCascadeNode = null;
    #cachedMatchedCascadePromise = null;
    #cssPropertyTracker = null;
    #isCSSPropertyTrackingEnabled = false;
    #isEnabled = false;
    #isRuleUsageTrackingEnabled = false;
    #isTrackingRequestPending = false;
    #colorScheme;
    constructor(target) {
        super(target);
        this.#domModel = target.model(DOMModel);
        this.#sourceMapManager = new SourceMapManager(target);
        this.agent = target.cssAgent();
        this.#styleLoader = new ComputedStyleLoader(this);
        this.#resourceTreeModel = target.model(ResourceTreeModel);
        if (this.#resourceTreeModel) {
            this.#resourceTreeModel.addEventListener(Events$6.PrimaryPageChanged, this.onPrimaryPageChanged, this);
        }
        target.registerCSSDispatcher(new CSSDispatcher(this));
        if (!target.suspended()) {
            void this.enable();
        }
        this.#sourceMapManager.setEnabled(Settings.instance().moduleSetting('css-source-maps-enabled').get());
        Settings.instance()
            .moduleSetting('css-source-maps-enabled')
            .addChangeListener(event => this.#sourceMapManager.setEnabled(event.data));
    }
    async colorScheme() {
        if (!this.#colorScheme) {
            const colorSchemeResponse = await this.domModel()?.target().runtimeAgent().invoke_evaluate({ expression: 'window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches' });
            if (colorSchemeResponse && !colorSchemeResponse.exceptionDetails && !colorSchemeResponse.getError()) {
                this.#colorScheme = colorSchemeResponse.result.value ? "dark"  : "light" ;
            }
        }
        return this.#colorScheme;
    }
    async resolveValues(propertyName, nodeId, ...values) {
        if (propertyName && cssMetadata().getLonghands(propertyName)?.length) {
            return null;
        }
        const response = await this.agent.invoke_resolveValues({ values, nodeId, propertyName });
        if (response.getError()) {
            return null;
        }
        return response.results;
    }
    headersForSourceURL(sourceURL) {
        const headers = [];
        for (const headerId of this.getStyleSheetIdsForURL(sourceURL)) {
            const header = this.styleSheetHeaderForId(headerId);
            if (header) {
                headers.push(header);
            }
        }
        return headers;
    }
    createRawLocationsByURL(sourceURL, lineNumber, columnNumber = 0) {
        const headers = this.headersForSourceURL(sourceURL);
        headers.sort(stylesheetComparator);
        const endIndex = upperBound(headers, undefined, (_, header) => lineNumber - header.startLine || columnNumber - header.startColumn);
        if (!endIndex) {
            return [];
        }
        const locations = [];
        const last = headers[endIndex - 1];
        for (let index = endIndex - 1; index >= 0 && headers[index].startLine === last.startLine && headers[index].startColumn === last.startColumn; --index) {
            if (headers[index].containsLocation(lineNumber, columnNumber)) {
                locations.push(new CSSLocation(headers[index], lineNumber, columnNumber));
            }
        }
        return locations;
        function stylesheetComparator(a, b) {
            return a.startLine - b.startLine || a.startColumn - b.startColumn || a.id.localeCompare(b.id);
        }
    }
    sourceMapManager() {
        return this.#sourceMapManager;
    }
    static readableLayerName(text) {
        return text || '<anonymous>';
    }
    static trimSourceURL(text) {
        let sourceURLIndex = text.lastIndexOf('/*# sourceURL=');
        if (sourceURLIndex === -1) {
            sourceURLIndex = text.lastIndexOf('/*@ sourceURL=');
            if (sourceURLIndex === -1) {
                return text;
            }
        }
        const sourceURLLineIndex = text.lastIndexOf('\n', sourceURLIndex);
        if (sourceURLLineIndex === -1) {
            return text;
        }
        const sourceURLLine = text.substr(sourceURLLineIndex + 1).split('\n', 1)[0];
        const sourceURLRegex = /[\x20\t]*\/\*[#@] sourceURL=[\x20\t]*([^\s]*)[\x20\t]*\*\/[\x20\t]*$/;
        if (sourceURLLine.search(sourceURLRegex) === -1) {
            return text;
        }
        return text.substr(0, sourceURLLineIndex) + text.substr(sourceURLLineIndex + sourceURLLine.length + 1);
    }
    domModel() {
        return this.#domModel;
    }
    async trackComputedStyleUpdatesForNode(nodeId) {
        await this.agent.invoke_trackComputedStyleUpdatesForNode({ nodeId });
    }
    async setStyleText(styleSheetId, range, text, majorChange) {
        try {
            await this.ensureOriginalStyleSheetText(styleSheetId);
            const { styles } = await this.agent.invoke_setStyleTexts({ edits: [{ styleSheetId, range: range.serializeToObject(), text }] });
            if (styles?.length !== 1) {
                return false;
            }
            this.#domModel.markUndoableState(!majorChange);
            const edit = new Edit(styleSheetId, range, text, styles[0]);
            this.fireStyleSheetChanged(styleSheetId, edit);
            return true;
        }
        catch (e) {
            console.error(e);
            return false;
        }
    }
    async setSelectorText(styleSheetId, range, text) {
        userMetrics.actionTaken(Action.StyleRuleEdited);
        try {
            await this.ensureOriginalStyleSheetText(styleSheetId);
            const { selectorList } = await this.agent.invoke_setRuleSelector({ styleSheetId, range, selector: text });
            if (!selectorList) {
                return false;
            }
            this.#domModel.markUndoableState();
            const edit = new Edit(styleSheetId, range, text, selectorList);
            this.fireStyleSheetChanged(styleSheetId, edit);
            return true;
        }
        catch (e) {
            console.error(e);
            return false;
        }
    }
    async setPropertyRulePropertyName(styleSheetId, range, text) {
        userMetrics.actionTaken(Action.StyleRuleEdited);
        try {
            await this.ensureOriginalStyleSheetText(styleSheetId);
            const { propertyName } = await this.agent.invoke_setPropertyRulePropertyName({ styleSheetId, range, propertyName: text });
            if (!propertyName) {
                return false;
            }
            this.#domModel.markUndoableState();
            const edit = new Edit(styleSheetId, range, text, propertyName);
            this.fireStyleSheetChanged(styleSheetId, edit);
            return true;
        }
        catch (e) {
            console.error(e);
            return false;
        }
    }
    async setKeyframeKey(styleSheetId, range, text) {
        userMetrics.actionTaken(Action.StyleRuleEdited);
        try {
            await this.ensureOriginalStyleSheetText(styleSheetId);
            const { keyText } = await this.agent.invoke_setKeyframeKey({ styleSheetId, range, keyText: text });
            if (!keyText) {
                return false;
            }
            this.#domModel.markUndoableState();
            const edit = new Edit(styleSheetId, range, text, keyText);
            this.fireStyleSheetChanged(styleSheetId, edit);
            return true;
        }
        catch (e) {
            console.error(e);
            return false;
        }
    }
    startCoverage() {
        this.#isRuleUsageTrackingEnabled = true;
        return this.agent.invoke_startRuleUsageTracking();
    }
    async takeCoverageDelta() {
        const r = await this.agent.invoke_takeCoverageDelta();
        const timestamp = (r?.timestamp) || 0;
        const coverage = (r?.coverage) || [];
        return { timestamp, coverage };
    }
    setLocalFontsEnabled(enabled) {
        return this.agent.invoke_setLocalFontsEnabled({
            enabled,
        });
    }
    async stopCoverage() {
        this.#isRuleUsageTrackingEnabled = false;
        await this.agent.invoke_stopRuleUsageTracking();
    }
    async getMediaQueries() {
        const { medias } = await this.agent.invoke_getMediaQueries();
        return medias ? CSSMedia.parseMediaArrayPayload(this, medias) : [];
    }
    async getRootLayer(nodeId) {
        const { rootLayer } = await this.agent.invoke_getLayersForNode({ nodeId });
        return rootLayer;
    }
    isEnabled() {
        return this.#isEnabled;
    }
    async enable() {
        await this.agent.invoke_enable();
        this.#isEnabled = true;
        if (this.#isRuleUsageTrackingEnabled) {
            await this.startCoverage();
        }
        this.dispatchEventToListeners(Events$a.ModelWasEnabled);
    }
    async getAnimatedStylesForNode(nodeId) {
        const response = await this.agent.invoke_getAnimatedStylesForNode({ nodeId });
        if (response.getError()) {
            return null;
        }
        return response;
    }
    async getMatchedStyles(nodeId) {
        const node = this.#domModel.nodeForId(nodeId);
        if (!node) {
            return null;
        }
        const shouldGetAnimatedStyles = hostConfig.devToolsAnimationStylesInStylesTab?.enabled;
        const [matchedStylesResponse, animatedStylesResponse] = await Promise.all([
            this.agent.invoke_getMatchedStylesForNode({ nodeId }),
            shouldGetAnimatedStyles ? this.agent.invoke_getAnimatedStylesForNode({ nodeId }) : undefined,
        ]);
        if (matchedStylesResponse.getError()) {
            return null;
        }
        const payload = {
            cssModel: this,
            node,
            inlinePayload: matchedStylesResponse.inlineStyle || null,
            attributesPayload: matchedStylesResponse.attributesStyle || null,
            matchedPayload: matchedStylesResponse.matchedCSSRules || [],
            pseudoPayload: matchedStylesResponse.pseudoElements || [],
            inheritedPayload: matchedStylesResponse.inherited || [],
            inheritedPseudoPayload: matchedStylesResponse.inheritedPseudoElements || [],
            animationsPayload: matchedStylesResponse.cssKeyframesRules || [],
            parentLayoutNodeId: matchedStylesResponse.parentLayoutNodeId,
            positionTryRules: matchedStylesResponse.cssPositionTryRules || [],
            propertyRules: matchedStylesResponse.cssPropertyRules ?? [],
            functionRules: matchedStylesResponse.cssFunctionRules ?? [],
            cssPropertyRegistrations: matchedStylesResponse.cssPropertyRegistrations ?? [],
            atRules: matchedStylesResponse.cssAtRules ?? [],
            activePositionFallbackIndex: matchedStylesResponse.activePositionFallbackIndex ?? -1,
            animationStylesPayload: animatedStylesResponse?.animationStyles || [],
            inheritedAnimatedPayload: animatedStylesResponse?.inherited || [],
            transitionsStylePayload: animatedStylesResponse?.transitionsStyle || null,
        };
        return await CSSMatchedStyles.create(payload);
    }
    async getClassNames(styleSheetId) {
        const { classNames } = await this.agent.invoke_collectClassNames({ styleSheetId });
        return classNames || [];
    }
    async getComputedStyle(nodeId) {
        if (!this.isEnabled()) {
            await this.enable();
        }
        return await this.#styleLoader.computedStylePromise(nodeId);
    }
    async getComputedStyleExtraFields(nodeId) {
        if (!this.isEnabled()) {
            await this.enable();
        }
        return await this.#styleLoader.extraFieldsPromise(nodeId);
    }
    async getLayoutPropertiesFromComputedStyle(nodeId) {
        const styles = await this.getComputedStyle(nodeId);
        if (!styles) {
            return null;
        }
        const display = styles.get('display');
        const isFlex = display === 'flex' || display === 'inline-flex';
        const isGrid = display === 'grid' || display === 'inline-grid';
        const isSubgrid = (isGrid &&
            (styles.get('grid-template-columns')?.startsWith('subgrid') ||
                styles.get('grid-template-rows')?.startsWith('subgrid'))) ??
            false;
        const isGridLanes = display === 'grid-lanes' || display === 'inline-grid-lanes';
        const containerType = styles.get('container-type');
        const isContainer = Boolean(containerType) && containerType !== '' && containerType !== 'normal';
        const hasScroll = Boolean(styles.get('scroll-snap-type')) && styles.get('scroll-snap-type') !== 'none';
        return {
            isFlex,
            isGrid,
            isSubgrid,
            isGridLanes,
            containerType: isContainer ? containerType : undefined,
            hasScroll,
        };
    }
    async getEnvironmentVariables() {
        const response = await this.agent.invoke_getEnvironmentVariables();
        if (response.getError()) {
            return {};
        }
        return response.environmentVariables;
    }
    async getBackgroundColors(nodeId) {
        const response = await this.agent.invoke_getBackgroundColors({ nodeId });
        if (response.getError()) {
            return null;
        }
        return {
            backgroundColors: response.backgroundColors || null,
            computedFontSize: response.computedFontSize || '',
            computedFontWeight: response.computedFontWeight || '',
        };
    }
    async getPlatformFonts(nodeId) {
        const { fonts } = await this.agent.invoke_getPlatformFontsForNode({ nodeId });
        return fonts;
    }
    allStyleSheets() {
        const values = [...this.#styleSheetIdToHeader.values()];
        function styleSheetComparator(a, b) {
            if (a.sourceURL < b.sourceURL) {
                return -1;
            }
            if (a.sourceURL > b.sourceURL) {
                return 1;
            }
            return a.startLine - b.startLine || a.startColumn - b.startColumn;
        }
        values.sort(styleSheetComparator);
        return values;
    }
    async getInlineStyles(nodeId) {
        const response = await this.agent.invoke_getInlineStylesForNode({ nodeId });
        if (response.getError() || !response.inlineStyle) {
            return null;
        }
        const inlineStyle = new CSSStyleDeclaration(this, null, response.inlineStyle, Type$3.Inline);
        const attributesStyle = response.attributesStyle ?
            new CSSStyleDeclaration(this, null, response.attributesStyle, Type$3.Attributes) :
            null;
        return new InlineStyleResult(inlineStyle, attributesStyle);
    }
    forceStartingStyle(node, forced) {
        void this.agent.invoke_forceStartingStyle({ nodeId: node.id, forced });
        this.dispatchEventToListeners(Events$a.StartingStylesStateForced, node);
        return true;
    }
    forcePseudoState(node, pseudoClass, enable) {
        const forcedPseudoClasses = node.marker(PseudoStateMarker) || [];
        const hasPseudoClass = forcedPseudoClasses.includes(pseudoClass);
        if (enable) {
            if (hasPseudoClass) {
                return false;
            }
            forcedPseudoClasses.push(pseudoClass);
            node.setMarker(PseudoStateMarker, forcedPseudoClasses);
        }
        else {
            if (!hasPseudoClass) {
                return false;
            }
            removeElement(forcedPseudoClasses, pseudoClass);
            if (forcedPseudoClasses.length) {
                node.setMarker(PseudoStateMarker, forcedPseudoClasses);
            }
            else {
                node.setMarker(PseudoStateMarker, null);
            }
        }
        if (node.id === undefined) {
            return false;
        }
        void this.agent.invoke_forcePseudoState({ nodeId: node.id, forcedPseudoClasses });
        this.dispatchEventToListeners(Events$a.PseudoStateForced, { node, pseudoClass, enable });
        return true;
    }
    pseudoState(node) {
        return node.marker(PseudoStateMarker) || [];
    }
    async setMediaText(styleSheetId, range, newMediaText) {
        userMetrics.actionTaken(Action.StyleRuleEdited);
        try {
            await this.ensureOriginalStyleSheetText(styleSheetId);
            const { media } = await this.agent.invoke_setMediaText({ styleSheetId, range, text: newMediaText });
            if (!media) {
                return false;
            }
            this.#domModel.markUndoableState();
            const edit = new Edit(styleSheetId, range, newMediaText, media);
            this.fireStyleSheetChanged(styleSheetId, edit);
            return true;
        }
        catch (e) {
            console.error(e);
            return false;
        }
    }
    async setContainerQueryText(styleSheetId, range, newContainerQueryText) {
        userMetrics.actionTaken(Action.StyleRuleEdited);
        try {
            await this.ensureOriginalStyleSheetText(styleSheetId);
            const { containerQuery } = await this.agent.invoke_setContainerQueryText({ styleSheetId, range, text: newContainerQueryText });
            if (!containerQuery) {
                return false;
            }
            this.#domModel.markUndoableState();
            const edit = new Edit(styleSheetId, range, newContainerQueryText, containerQuery);
            this.fireStyleSheetChanged(styleSheetId, edit);
            return true;
        }
        catch (e) {
            console.error(e);
            return false;
        }
    }
    async setSupportsText(styleSheetId, range, newSupportsText) {
        userMetrics.actionTaken(Action.StyleRuleEdited);
        try {
            await this.ensureOriginalStyleSheetText(styleSheetId);
            const { supports } = await this.agent.invoke_setSupportsText({ styleSheetId, range, text: newSupportsText });
            if (!supports) {
                return false;
            }
            this.#domModel.markUndoableState();
            const edit = new Edit(styleSheetId, range, newSupportsText, supports);
            this.fireStyleSheetChanged(styleSheetId, edit);
            return true;
        }
        catch (e) {
            console.error(e);
            return false;
        }
    }
    async setScopeText(styleSheetId, range, newScopeText) {
        userMetrics.actionTaken(Action.StyleRuleEdited);
        try {
            await this.ensureOriginalStyleSheetText(styleSheetId);
            const { scope } = await this.agent.invoke_setScopeText({ styleSheetId, range, text: newScopeText });
            if (!scope) {
                return false;
            }
            this.#domModel.markUndoableState();
            const edit = new Edit(styleSheetId, range, newScopeText, scope);
            this.fireStyleSheetChanged(styleSheetId, edit);
            return true;
        }
        catch (e) {
            console.error(e);
            return false;
        }
    }
    async addRule(styleSheetId, ruleText, ruleLocation) {
        try {
            await this.ensureOriginalStyleSheetText(styleSheetId);
            const { rule } = await this.agent.invoke_addRule({ styleSheetId, ruleText, location: ruleLocation });
            if (!rule) {
                return null;
            }
            this.#domModel.markUndoableState();
            const edit = new Edit(styleSheetId, ruleLocation, ruleText, rule);
            this.fireStyleSheetChanged(styleSheetId, edit);
            return new CSSStyleRule(this, rule);
        }
        catch (e) {
            console.error(e);
            return null;
        }
    }
    async requestViaInspectorStylesheet(maybeFrameId) {
        const frameId = maybeFrameId ||
            (this.#resourceTreeModel && this.#resourceTreeModel.mainFrame ? this.#resourceTreeModel.mainFrame.id : null);
        const headers = [...this.#styleSheetIdToHeader.values()];
        const styleSheetHeader = headers.find(header => header.frameId === frameId && header.isViaInspector());
        if (styleSheetHeader) {
            return styleSheetHeader;
        }
        if (!frameId) {
            return null;
        }
        try {
            return await this.createInspectorStylesheet(frameId);
        }
        catch (e) {
            console.error(e);
            return null;
        }
    }
    async createInspectorStylesheet(frameId, force = false) {
        const result = await this.agent.invoke_createStyleSheet({ frameId, force });
        if (result.getError()) {
            throw new Error(result.getError());
        }
        return this.#styleSheetIdToHeader.get(result.styleSheetId) || null;
    }
    mediaQueryResultChanged() {
        this.#colorScheme = undefined;
        this.dispatchEventToListeners(Events$a.MediaQueryResultChanged);
    }
    fontsUpdated(fontFace) {
        if (fontFace) {
            this.#fontFaces.set(fontFace.src, new CSSFontFace(fontFace));
        }
        this.dispatchEventToListeners(Events$a.FontsUpdated);
    }
    fontFaces() {
        return [...this.#fontFaces.values()];
    }
    fontFaceForSource(src) {
        return this.#fontFaces.get(src);
    }
    styleSheetHeaderForId(id) {
        return this.#styleSheetIdToHeader.get(id) || null;
    }
    styleSheetHeaders() {
        return [...this.#styleSheetIdToHeader.values()];
    }
    fireStyleSheetChanged(styleSheetId, edit) {
        this.dispatchEventToListeners(Events$a.StyleSheetChanged, { styleSheetId, edit });
    }
    ensureOriginalStyleSheetText(styleSheetId) {
        const header = this.styleSheetHeaderForId(styleSheetId);
        if (!header) {
            return Promise.resolve(null);
        }
        let promise = this.#originalStyleSheetText.get(header);
        if (!promise) {
            promise = this.getStyleSheetText(header.id);
            this.#originalStyleSheetText.set(header, promise);
            this.originalContentRequestedForTest(header);
        }
        return promise;
    }
    originalContentRequestedForTest(_header) {
    }
    originalStyleSheetText(header) {
        return this.ensureOriginalStyleSheetText(header.id);
    }
    getAllStyleSheetHeaders() {
        return this.#styleSheetIdToHeader.values();
    }
    computedStyleUpdated(nodeId) {
        this.dispatchEventToListeners(Events$a.ComputedStyleUpdated, { nodeId });
    }
    styleSheetAdded(header) {
        console.assert(!this.#styleSheetIdToHeader.get(header.styleSheetId));
        if (header.loadingFailed) {
            header.hasSourceURL = false;
            header.isConstructed = true;
            header.isInline = false;
            header.isMutable = false;
            header.sourceURL = '';
            header.sourceMapURL = undefined;
        }
        const styleSheetHeader = new CSSStyleSheetHeader(this, header);
        this.#styleSheetIdToHeader.set(header.styleSheetId, styleSheetHeader);
        const url = styleSheetHeader.resourceURL();
        let frameIdToStyleSheetIds = this.#styleSheetIdsForURL.get(url);
        if (!frameIdToStyleSheetIds) {
            frameIdToStyleSheetIds = new Map();
            this.#styleSheetIdsForURL.set(url, frameIdToStyleSheetIds);
        }
        if (frameIdToStyleSheetIds) {
            let styleSheetIds = frameIdToStyleSheetIds.get(styleSheetHeader.frameId);
            if (!styleSheetIds) {
                styleSheetIds = new Set();
                frameIdToStyleSheetIds.set(styleSheetHeader.frameId, styleSheetIds);
            }
            styleSheetIds.add(styleSheetHeader.id);
        }
        this.#sourceMapManager.attachSourceMap(styleSheetHeader, styleSheetHeader.sourceURL, styleSheetHeader.sourceMapURL);
        this.dispatchEventToListeners(Events$a.StyleSheetAdded, styleSheetHeader);
    }
    styleSheetRemoved(id) {
        const header = this.#styleSheetIdToHeader.get(id);
        console.assert(Boolean(header));
        if (!header) {
            return;
        }
        this.#styleSheetIdToHeader.delete(id);
        const url = header.resourceURL();
        const frameIdToStyleSheetIds = this.#styleSheetIdsForURL.get(url);
        console.assert(Boolean(frameIdToStyleSheetIds), 'No frameId to styleSheetId map is available for given style sheet URL.');
        if (frameIdToStyleSheetIds) {
            const stylesheetIds = frameIdToStyleSheetIds.get(header.frameId);
            if (stylesheetIds) {
                stylesheetIds.delete(id);
                if (!stylesheetIds.size) {
                    frameIdToStyleSheetIds.delete(header.frameId);
                    if (!frameIdToStyleSheetIds.size) {
                        this.#styleSheetIdsForURL.delete(url);
                    }
                }
            }
        }
        this.#originalStyleSheetText.delete(header);
        this.#sourceMapManager.detachSourceMap(header);
        this.dispatchEventToListeners(Events$a.StyleSheetRemoved, header);
    }
    getStyleSheetIdsForURL(url) {
        const frameIdToStyleSheetIds = this.#styleSheetIdsForURL.get(url);
        if (!frameIdToStyleSheetIds) {
            return [];
        }
        const result = [];
        for (const styleSheetIds of frameIdToStyleSheetIds.values()) {
            result.push(...styleSheetIds);
        }
        return result;
    }
    async setStyleSheetText(styleSheetId, newText, majorChange) {
        const header = this.#styleSheetIdToHeader.get(styleSheetId);
        if (!header) {
            return 'Unknown stylesheet in CSS.setStyleSheetText';
        }
        newText = CSSModel.trimSourceURL(newText);
        if (header.hasSourceURL) {
            newText += '\n/*# sourceURL=' + header.sourceURL + ' */';
        }
        await this.ensureOriginalStyleSheetText(styleSheetId);
        const response = await this.agent.invoke_setStyleSheetText({ styleSheetId: header.id, text: newText });
        const sourceMapURL = response.sourceMapURL;
        this.#sourceMapManager.detachSourceMap(header);
        header.setSourceMapURL(sourceMapURL);
        this.#sourceMapManager.attachSourceMap(header, header.sourceURL, header.sourceMapURL);
        if (sourceMapURL === null) {
            return 'Error in CSS.setStyleSheetText';
        }
        this.#domModel.markUndoableState(!majorChange);
        this.fireStyleSheetChanged(styleSheetId);
        return null;
    }
    async getStyleSheetText(styleSheetId) {
        const response = await this.agent.invoke_getStyleSheetText({ styleSheetId });
        if (response.getError()) {
            return null;
        }
        const { text } = response;
        return text && CSSModel.trimSourceURL(text);
    }
    async onPrimaryPageChanged(event) {
        if (event.data.frame.backForwardCacheDetails.restoredFromCache) {
            await this.suspendModel();
            await this.resumeModel();
        }
        else if (event.data.type !== "Activation" ) {
            this.resetStyleSheets();
            this.resetFontFaces();
        }
    }
    resetStyleSheets() {
        const headers = [...this.#styleSheetIdToHeader.values()];
        this.#styleSheetIdsForURL.clear();
        this.#styleSheetIdToHeader.clear();
        for (const header of headers) {
            this.#sourceMapManager.detachSourceMap(header);
            this.dispatchEventToListeners(Events$a.StyleSheetRemoved, header);
        }
    }
    resetFontFaces() {
        this.#fontFaces.clear();
    }
    async suspendModel() {
        this.#isEnabled = false;
        await this.agent.invoke_disable();
        this.resetStyleSheets();
        this.resetFontFaces();
    }
    async resumeModel() {
        return await this.enable();
    }
    setEffectivePropertyValueForNode(nodeId, propertyName, value) {
        void this.agent.invoke_setEffectivePropertyValueForNode({ nodeId, propertyName, value });
    }
    cachedMatchedCascadeForNode(node) {
        if (this.#cachedMatchedCascadeNode !== node) {
            this.discardCachedMatchedCascade();
        }
        this.#cachedMatchedCascadeNode = node;
        if (!this.#cachedMatchedCascadePromise) {
            if (node.id) {
                this.#cachedMatchedCascadePromise = this.getMatchedStyles(node.id);
            }
            else {
                return Promise.resolve(null);
            }
        }
        return this.#cachedMatchedCascadePromise;
    }
    discardCachedMatchedCascade() {
        this.#cachedMatchedCascadeNode = null;
        this.#cachedMatchedCascadePromise = null;
    }
    createCSSPropertyTracker(propertiesToTrack) {
        const cssPropertyTracker = new CSSPropertyTracker(this, propertiesToTrack);
        return cssPropertyTracker;
    }
    enableCSSPropertyTracker(cssPropertyTracker) {
        const propertiesToTrack = cssPropertyTracker.getTrackedProperties();
        if (propertiesToTrack.length === 0) {
            return;
        }
        void this.agent.invoke_trackComputedStyleUpdates({ propertiesToTrack });
        this.#isCSSPropertyTrackingEnabled = true;
        this.#cssPropertyTracker = cssPropertyTracker;
        void this.pollComputedStyleUpdates();
    }
    disableCSSPropertyTracker() {
        this.#isCSSPropertyTrackingEnabled = false;
        this.#cssPropertyTracker = null;
        void this.agent.invoke_trackComputedStyleUpdates({ propertiesToTrack: [] });
    }
    async pollComputedStyleUpdates() {
        if (this.#isTrackingRequestPending) {
            return;
        }
        if (this.#isCSSPropertyTrackingEnabled) {
            this.#isTrackingRequestPending = true;
            const result = await this.agent.invoke_takeComputedStyleUpdates();
            this.#isTrackingRequestPending = false;
            if (result.getError() || !result.nodeIds || !this.#isCSSPropertyTrackingEnabled) {
                return;
            }
            if (this.#cssPropertyTracker) {
                this.#cssPropertyTracker.dispatchEventToListeners("TrackedCSSPropertiesUpdated" , result.nodeIds.map(nodeId => this.#domModel.nodeForId(nodeId)));
            }
        }
        if (this.#isCSSPropertyTrackingEnabled) {
            void this.#stylePollingThrottler.schedule(this.pollComputedStyleUpdates.bind(this));
        }
    }
    dispose() {
        this.disableCSSPropertyTracker();
        super.dispose();
        this.dispatchEventToListeners(Events$a.ModelDisposed, this);
    }
    getAgent() {
        return this.agent;
    }
}
var Events$a;
(function (Events) {
    Events["FontsUpdated"] = "FontsUpdated";
    Events["MediaQueryResultChanged"] = "MediaQueryResultChanged";
    Events["ModelWasEnabled"] = "ModelWasEnabled";
    Events["ModelDisposed"] = "ModelDisposed";
    Events["PseudoStateForced"] = "PseudoStateForced";
    Events["StartingStylesStateForced"] = "StartingStylesStateForced";
    Events["StyleSheetAdded"] = "StyleSheetAdded";
    Events["StyleSheetChanged"] = "StyleSheetChanged";
    Events["StyleSheetRemoved"] = "StyleSheetRemoved";
    Events["ComputedStyleUpdated"] = "ComputedStyleUpdated";
})(Events$a || (Events$a = {}));
const PseudoStateMarker = 'pseudo-state-marker';
class Edit {
    styleSheetId;
    oldRange;
    newRange;
    newText;
    payload;
    constructor(styleSheetId, oldRange, newText, payload) {
        this.styleSheetId = styleSheetId;
        this.oldRange = oldRange;
        this.newRange = TextRange.fromEdit(oldRange, newText);
        this.newText = newText;
        this.payload = payload;
    }
}
class CSSLocation {
    #cssModel;
    styleSheetId;
    url;
    lineNumber;
    columnNumber;
    constructor(header, lineNumber, columnNumber) {
        this.#cssModel = header.cssModel();
        this.styleSheetId = header.id;
        this.url = header.resourceURL();
        this.lineNumber = lineNumber;
        this.columnNumber = columnNumber || 0;
    }
    cssModel() {
        return this.#cssModel;
    }
    header() {
        return this.#cssModel.styleSheetHeaderForId(this.styleSheetId);
    }
}
class CSSDispatcher {
    #cssModel;
    constructor(cssModel) {
        this.#cssModel = cssModel;
    }
    mediaQueryResultChanged() {
        this.#cssModel.mediaQueryResultChanged();
    }
    fontsUpdated({ font }) {
        this.#cssModel.fontsUpdated(font);
    }
    styleSheetChanged({ styleSheetId }) {
        this.#cssModel.fireStyleSheetChanged(styleSheetId);
    }
    styleSheetAdded({ header }) {
        this.#cssModel.styleSheetAdded(header);
    }
    styleSheetRemoved({ styleSheetId }) {
        this.#cssModel.styleSheetRemoved(styleSheetId);
    }
    computedStyleUpdated({ nodeId }) {
        this.#cssModel.computedStyleUpdated(nodeId);
    }
}
class ComputedStyleLoader {
    #cssModel;
    #nodeIdToPromise = new Map();
    constructor(cssModel) {
        this.#cssModel = cssModel;
    }
    #getResponsePromise(nodeId) {
        let promise = this.#nodeIdToPromise.get(nodeId);
        if (promise) {
            return promise;
        }
        promise =
            this.#cssModel.getAgent().invoke_getComputedStyleForNode({ nodeId }).then(({ computedStyle, extraFields }) => {
                this.#nodeIdToPromise.delete(nodeId);
                if (!computedStyle?.length) {
                    return { style: null, extraFields };
                }
                const result = new Map();
                for (const property of computedStyle) {
                    result.set(property.name, property.value);
                }
                return { style: result, extraFields };
            });
        this.#nodeIdToPromise.set(nodeId, promise);
        return promise;
    }
    async computedStylePromise(nodeId) {
        const computedStyleWithExtraFields = await this.#getResponsePromise(nodeId);
        return computedStyleWithExtraFields.style;
    }
    async extraFieldsPromise(nodeId) {
        const computedStyleWithExtraFields = await this.#getResponsePromise(nodeId);
        return computedStyleWithExtraFields.extraFields;
    }
}
class InlineStyleResult {
    inlineStyle;
    attributesStyle;
    constructor(inlineStyle, attributesStyle) {
        this.inlineStyle = inlineStyle;
        this.attributesStyle = attributesStyle;
    }
}
class CSSPropertyTracker extends ObjectWrapper {
    #cssModel;
    #properties;
    constructor(cssModel, propertiesToTrack) {
        super();
        this.#cssModel = cssModel;
        this.#properties = propertiesToTrack;
    }
    start() {
        this.#cssModel.enableCSSPropertyTracker(this);
    }
    stop() {
        this.#cssModel.disableCSSPropertyTracker();
    }
    getTrackedProperties() {
        return this.#properties;
    }
}
const StylePollingInterval = 1000;
SDKModel.register(CSSModel, { capabilities: 2 , autostart: true });

// Copyright 2020 The Chromium Authors
let frameManagerInstance = null;
class FrameManager extends ObjectWrapper {
    #eventListeners = new WeakMap();
    #frames = new Map();
    #framesForTarget = new Map();
    #outermostFrame = null;
    #transferringFramesDataCache = new Map();
    #awaitedFrames = new Map();
    constructor() {
        super();
        TargetManager.instance().observeModels(ResourceTreeModel, this);
    }
    static instance({ forceNew } = { forceNew: false }) {
        if (!frameManagerInstance || forceNew) {
            frameManagerInstance = new FrameManager();
        }
        return frameManagerInstance;
    }
    static removeInstance() {
        frameManagerInstance = null;
    }
    modelAdded(resourceTreeModel) {
        const addListener = resourceTreeModel.addEventListener(Events$6.FrameAdded, this.frameAdded, this);
        const detachListener = resourceTreeModel.addEventListener(Events$6.FrameDetached, this.frameDetached, this);
        const navigatedListener = resourceTreeModel.addEventListener(Events$6.FrameNavigated, this.frameNavigated, this);
        const resourceAddedListener = resourceTreeModel.addEventListener(Events$6.ResourceAdded, this.resourceAdded, this);
        this.#eventListeners.set(resourceTreeModel, [addListener, detachListener, navigatedListener, resourceAddedListener]);
        this.#framesForTarget.set(resourceTreeModel.target().id(), new Set());
    }
    modelRemoved(resourceTreeModel) {
        const listeners = this.#eventListeners.get(resourceTreeModel);
        if (listeners) {
            removeEventListeners(listeners);
        }
        const frameSet = this.#framesForTarget.get(resourceTreeModel.target().id());
        if (frameSet) {
            for (const frameId of frameSet) {
                this.decreaseOrRemoveFrame(frameId);
            }
        }
        this.#framesForTarget.delete(resourceTreeModel.target().id());
    }
    frameAdded(event) {
        const frame = event.data;
        const frameData = this.#frames.get(frame.id);
        if (frameData) {
            frame.setCreationStackTrace(frameData.frame.getCreationStackTraceData());
            this.#frames.set(frame.id, { frame, count: frameData.count + 1 });
        }
        else {
            const cachedFrameAttributes = this.#transferringFramesDataCache.get(frame.id);
            if (cachedFrameAttributes?.creationStackTrace && cachedFrameAttributes?.creationStackTraceTarget) {
                frame.setCreationStackTrace({
                    creationStackTrace: cachedFrameAttributes.creationStackTrace,
                    creationStackTraceTarget: cachedFrameAttributes.creationStackTraceTarget,
                });
            }
            this.#frames.set(frame.id, { frame, count: 1 });
            this.#transferringFramesDataCache.delete(frame.id);
        }
        this.resetOutermostFrame();
        const frameSet = this.#framesForTarget.get(frame.resourceTreeModel().target().id());
        if (frameSet) {
            frameSet.add(frame.id);
        }
        this.dispatchEventToListeners("FrameAddedToTarget" , { frame });
        this.resolveAwaitedFrame(frame);
    }
    frameDetached(event) {
        const { frame, isSwap } = event.data;
        this.decreaseOrRemoveFrame(frame.id);
        if (isSwap && !this.#frames.get(frame.id)) {
            const traceData = frame.getCreationStackTraceData();
            const cachedFrameAttributes = {
                ...(traceData.creationStackTrace && { creationStackTrace: traceData.creationStackTrace }),
                ...(traceData.creationStackTrace && { creationStackTraceTarget: traceData.creationStackTraceTarget }),
            };
            this.#transferringFramesDataCache.set(frame.id, cachedFrameAttributes);
        }
        const frameSet = this.#framesForTarget.get(frame.resourceTreeModel().target().id());
        if (frameSet) {
            frameSet.delete(frame.id);
        }
    }
    frameNavigated(event) {
        const frame = event.data;
        this.dispatchEventToListeners("FrameNavigated" , { frame });
        if (frame.isOutermostFrame()) {
            this.dispatchEventToListeners("OutermostFrameNavigated" , { frame });
        }
    }
    resourceAdded(event) {
        this.dispatchEventToListeners("ResourceAdded" , { resource: event.data });
    }
    decreaseOrRemoveFrame(frameId) {
        const frameData = this.#frames.get(frameId);
        if (frameData) {
            if (frameData.count === 1) {
                this.#frames.delete(frameId);
                this.resetOutermostFrame();
                this.dispatchEventToListeners("FrameRemoved" , { frameId });
            }
            else {
                frameData.count--;
            }
        }
    }
    resetOutermostFrame() {
        const outermostFrames = this.getAllFrames().filter(frame => frame.isOutermostFrame());
        this.#outermostFrame = outermostFrames.length > 0 ? outermostFrames[0] : null;
    }
    getFrame(frameId) {
        const frameData = this.#frames.get(frameId);
        if (frameData) {
            return frameData.frame;
        }
        return null;
    }
    getAllFrames() {
        return Array.from(this.#frames.values(), frameData => frameData.frame);
    }
    getOutermostFrame() {
        return this.#outermostFrame;
    }
    async getOrWaitForFrame(frameId, notInTarget) {
        const frame = this.getFrame(frameId);
        if (frame && (!notInTarget || notInTarget !== frame.resourceTreeModel().target())) {
            return frame;
        }
        return await new Promise(resolve => {
            const waiting = this.#awaitedFrames.get(frameId);
            if (waiting) {
                waiting.push({ notInTarget, resolve });
            }
            else {
                this.#awaitedFrames.set(frameId, [{ notInTarget, resolve }]);
            }
        });
    }
    resolveAwaitedFrame(frame) {
        const waiting = this.#awaitedFrames.get(frame.id);
        if (!waiting) {
            return;
        }
        const newWaiting = waiting.filter(({ notInTarget, resolve }) => {
            if (!notInTarget || notInTarget !== frame.resourceTreeModel().target()) {
                resolve(frame);
                return false;
            }
            return true;
        });
        if (newWaiting.length > 0) {
            this.#awaitedFrames.set(frame.id, newWaiting);
        }
        else {
            this.#awaitedFrames.delete(frame.id);
        }
    }
}

// Copyright 2020 The Chromium Authors
class OverlayColorGenerator {
    #colors;
    #index;
    constructor() {
        const format = "rgba" ;
        this.#colors = [
            new Legacy([0.9607843137254902, 0.592156862745098, 0.5803921568627451, 1], format),
            new Legacy([0.9411764705882353, 0.7490196078431373, 0.2980392156862745, 1], format),
            new Legacy([0.8313725490196079, 0.9294117647058824, 0.19215686274509805, 1], format),
            new Legacy([0.6196078431372549, 0.9215686274509803, 0.2784313725490196, 1], format),
            new Legacy([0.3568627450980392, 0.8196078431372549, 0.8431372549019608, 1], format),
            new Legacy([0.7372549019607844, 0.807843137254902, 0.984313725490196, 1], format),
            new Legacy([0.7764705882352941, 0.7450980392156863, 0.9333333333333333, 1], format),
            new Legacy([0.8156862745098039, 0.5803921568627451, 0.9176470588235294, 1], format),
            new Legacy([0.9215686274509803, 0.5803921568627451, 0.8117647058823529, 1], format),
        ];
        this.#index = 0;
    }
    next() {
        const color = this.#colors[this.#index];
        this.#index++;
        if (this.#index >= this.#colors.length) {
            this.#index = 0;
        }
        return color;
    }
}

// Copyright 2020 The Chromium Authors
class OverlayPersistentHighlighter {
    #model;
    #colors = new Map();
    #persistentHighlightSetting = Settings.instance().createLocalSetting('persistent-highlight-setting', []);
    #gridHighlights = new Map();
    #scrollSnapHighlights = new Map();
    #flexHighlights = new Map();
    #containerQueryHighlights = new Map();
    #isolatedElementHighlights = new Map();
    #gridColorGenerator = new OverlayColorGenerator();
    #flexColorGenerator = new OverlayColorGenerator();
    #showGridLineLabelsSetting = Settings.instance().moduleSetting('show-grid-line-labels');
    #extendGridLinesSetting = Settings.instance().moduleSetting('extend-grid-lines');
    #showGridAreasSetting = Settings.instance().moduleSetting('show-grid-areas');
    #showGridTrackSizesSetting = Settings.instance().moduleSetting('show-grid-track-sizes');
    #callbacks;
    constructor(model, callbacks) {
        this.#model = model;
        this.#callbacks = callbacks;
        this.#showGridLineLabelsSetting.addChangeListener(this.onSettingChange, this);
        this.#extendGridLinesSetting.addChangeListener(this.onSettingChange, this);
        this.#showGridAreasSetting.addChangeListener(this.onSettingChange, this);
        this.#showGridTrackSizesSetting.addChangeListener(this.onSettingChange, this);
    }
    onSettingChange() {
        this.resetOverlay();
    }
    buildGridHighlightConfig(nodeId) {
        const mainColor = this.colorOfGrid(nodeId).asLegacyColor();
        const background = mainColor.setAlpha(0.1).asLegacyColor();
        const gapBackground = mainColor.setAlpha(0.3).asLegacyColor();
        const gapHatch = mainColor.setAlpha(0.8).asLegacyColor();
        const showGridExtensionLines = this.#extendGridLinesSetting.get();
        const showPositiveLineNumbers = this.#showGridLineLabelsSetting.get() === 'lineNumbers';
        const showNegativeLineNumbers = showPositiveLineNumbers;
        const showLineNames = this.#showGridLineLabelsSetting.get() === 'lineNames';
        return {
            rowGapColor: gapBackground.toProtocolRGBA(),
            rowHatchColor: gapHatch.toProtocolRGBA(),
            columnGapColor: gapBackground.toProtocolRGBA(),
            columnHatchColor: gapHatch.toProtocolRGBA(),
            gridBorderColor: mainColor.toProtocolRGBA(),
            gridBorderDash: false,
            rowLineColor: mainColor.toProtocolRGBA(),
            columnLineColor: mainColor.toProtocolRGBA(),
            rowLineDash: true,
            columnLineDash: true,
            showGridExtensionLines,
            showPositiveLineNumbers,
            showNegativeLineNumbers,
            showLineNames,
            showAreaNames: this.#showGridAreasSetting.get(),
            showTrackSizes: this.#showGridTrackSizesSetting.get(),
            areaBorderColor: mainColor.toProtocolRGBA(),
            gridBackgroundColor: background.toProtocolRGBA(),
        };
    }
    buildFlexContainerHighlightConfig(nodeId) {
        const mainColor = this.colorOfFlex(nodeId).asLegacyColor();
        return {
            containerBorder: { color: mainColor.toProtocolRGBA(), pattern: "dashed"  },
            itemSeparator: { color: mainColor.toProtocolRGBA(), pattern: "dotted"  },
            lineSeparator: { color: mainColor.toProtocolRGBA(), pattern: "dashed"  },
            mainDistributedSpace: { hatchColor: mainColor.toProtocolRGBA() },
            crossDistributedSpace: { hatchColor: mainColor.toProtocolRGBA() },
        };
    }
    buildScrollSnapContainerHighlightConfig(_nodeId) {
        return {
            snapAreaBorder: {
                color: PageHighlight.GridBorder.toProtocolRGBA(),
                pattern: "dashed" ,
            },
            snapportBorder: { color: PageHighlight.GridBorder.toProtocolRGBA() },
            scrollMarginColor: PageHighlight.Margin.toProtocolRGBA(),
            scrollPaddingColor: PageHighlight.Padding.toProtocolRGBA(),
        };
    }
    highlightGridInOverlay(nodeId) {
        this.#gridHighlights.set(nodeId, this.buildGridHighlightConfig(nodeId));
        this.updateHighlightsInOverlay();
        this.savePersistentHighlightSetting();
        this.#callbacks.onGridOverlayStateChanged({ nodeId, enabled: true });
    }
    isGridHighlighted(nodeId) {
        return this.#gridHighlights.has(nodeId);
    }
    colorOfGrid(nodeId) {
        let color = this.#colors.get(nodeId);
        if (!color) {
            color = this.#gridColorGenerator.next();
            this.#colors.set(nodeId, color);
        }
        return color;
    }
    setColorOfGrid(nodeId, color) {
        this.#colors.set(nodeId, color);
    }
    hideGridInOverlay(nodeId) {
        if (this.#gridHighlights.has(nodeId)) {
            this.#gridHighlights.delete(nodeId);
            this.updateHighlightsInOverlay();
            this.savePersistentHighlightSetting();
            this.#callbacks.onGridOverlayStateChanged({ nodeId, enabled: false });
        }
    }
    highlightScrollSnapInOverlay(nodeId) {
        this.#scrollSnapHighlights.set(nodeId, this.buildScrollSnapContainerHighlightConfig(nodeId));
        this.updateHighlightsInOverlay();
        this.#callbacks.onScrollSnapOverlayStateChanged({ nodeId, enabled: true });
        this.savePersistentHighlightSetting();
    }
    isScrollSnapHighlighted(nodeId) {
        return this.#scrollSnapHighlights.has(nodeId);
    }
    hideScrollSnapInOverlay(nodeId) {
        if (this.#scrollSnapHighlights.has(nodeId)) {
            this.#scrollSnapHighlights.delete(nodeId);
            this.updateHighlightsInOverlay();
            this.#callbacks.onScrollSnapOverlayStateChanged({ nodeId, enabled: false });
            this.savePersistentHighlightSetting();
        }
    }
    highlightFlexInOverlay(nodeId) {
        this.#flexHighlights.set(nodeId, this.buildFlexContainerHighlightConfig(nodeId));
        this.updateHighlightsInOverlay();
        this.savePersistentHighlightSetting();
        this.#callbacks.onFlexOverlayStateChanged({ nodeId, enabled: true });
    }
    isFlexHighlighted(nodeId) {
        return this.#flexHighlights.has(nodeId);
    }
    colorOfFlex(nodeId) {
        let color = this.#colors.get(nodeId);
        if (!color) {
            color = this.#flexColorGenerator.next();
            this.#colors.set(nodeId, color);
        }
        return color;
    }
    setColorOfFlex(nodeId, color) {
        this.#colors.set(nodeId, color);
    }
    hideFlexInOverlay(nodeId) {
        if (this.#flexHighlights.has(nodeId)) {
            this.#flexHighlights.delete(nodeId);
            this.updateHighlightsInOverlay();
            this.savePersistentHighlightSetting();
            this.#callbacks.onFlexOverlayStateChanged({ nodeId, enabled: false });
        }
    }
    highlightContainerQueryInOverlay(nodeId) {
        this.#containerQueryHighlights.set(nodeId, this.buildContainerQueryContainerHighlightConfig());
        this.updateHighlightsInOverlay();
        this.savePersistentHighlightSetting();
        this.#callbacks.onContainerQueryOverlayStateChanged({ nodeId, enabled: true });
    }
    hideContainerQueryInOverlay(nodeId) {
        if (this.#containerQueryHighlights.has(nodeId)) {
            this.#containerQueryHighlights.delete(nodeId);
            this.updateHighlightsInOverlay();
            this.savePersistentHighlightSetting();
            this.#callbacks.onContainerQueryOverlayStateChanged({ nodeId, enabled: false });
        }
    }
    isContainerQueryHighlighted(nodeId) {
        return this.#containerQueryHighlights.has(nodeId);
    }
    buildContainerQueryContainerHighlightConfig() {
        return {
            containerBorder: {
                color: PageHighlight.LayoutLine.toProtocolRGBA(),
                pattern: "dashed" ,
            },
            descendantBorder: {
                color: PageHighlight.LayoutLine.toProtocolRGBA(),
                pattern: "dashed" ,
            },
        };
    }
    highlightIsolatedElementInOverlay(nodeId) {
        this.#isolatedElementHighlights.set(nodeId, this.buildIsolationModeHighlightConfig());
        this.updateHighlightsInOverlay();
        this.savePersistentHighlightSetting();
    }
    hideIsolatedElementInOverlay(nodeId) {
        if (this.#isolatedElementHighlights.has(nodeId)) {
            this.#isolatedElementHighlights.delete(nodeId);
            this.updateHighlightsInOverlay();
            this.savePersistentHighlightSetting();
        }
    }
    isIsolatedElementHighlighted(nodeId) {
        return this.#isolatedElementHighlights.has(nodeId);
    }
    buildIsolationModeHighlightConfig() {
        return {
            resizerColor: IsolationModeHighlight.Resizer.toProtocolRGBA(),
            resizerHandleColor: IsolationModeHighlight.ResizerHandle.toProtocolRGBA(),
            maskColor: IsolationModeHighlight.Mask.toProtocolRGBA(),
        };
    }
    hideAllInOverlayWithoutSave() {
        this.#flexHighlights.clear();
        this.#gridHighlights.clear();
        this.#scrollSnapHighlights.clear();
        this.#containerQueryHighlights.clear();
        this.#isolatedElementHighlights.clear();
        this.updateHighlightsInOverlay();
    }
    refreshHighlights() {
        const gridsNeedUpdate = this.updateHighlightsForDeletedNodes(this.#gridHighlights);
        const flexboxesNeedUpdate = this.updateHighlightsForDeletedNodes(this.#flexHighlights);
        const scrollSnapsNeedUpdate = this.updateHighlightsForDeletedNodes(this.#scrollSnapHighlights);
        const containerQueriesNeedUpdate = this.updateHighlightsForDeletedNodes(this.#containerQueryHighlights);
        const isolatedElementsNeedUpdate = this.updateHighlightsForDeletedNodes(this.#isolatedElementHighlights);
        if (flexboxesNeedUpdate || gridsNeedUpdate || scrollSnapsNeedUpdate || containerQueriesNeedUpdate ||
            isolatedElementsNeedUpdate) {
            this.updateHighlightsInOverlay();
            this.savePersistentHighlightSetting();
        }
    }
    updateHighlightsForDeletedNodes(highlights) {
        let needsUpdate = false;
        for (const nodeId of highlights.keys()) {
            if (this.#model.getDOMModel().nodeForId(nodeId) === null) {
                highlights.delete(nodeId);
                needsUpdate = true;
            }
        }
        return needsUpdate;
    }
    resetOverlay() {
        for (const nodeId of this.#gridHighlights.keys()) {
            this.#gridHighlights.set(nodeId, this.buildGridHighlightConfig(nodeId));
        }
        for (const nodeId of this.#flexHighlights.keys()) {
            this.#flexHighlights.set(nodeId, this.buildFlexContainerHighlightConfig(nodeId));
        }
        for (const nodeId of this.#scrollSnapHighlights.keys()) {
            this.#scrollSnapHighlights.set(nodeId, this.buildScrollSnapContainerHighlightConfig(nodeId));
        }
        for (const nodeId of this.#containerQueryHighlights.keys()) {
            this.#containerQueryHighlights.set(nodeId, this.buildContainerQueryContainerHighlightConfig());
        }
        for (const nodeId of this.#isolatedElementHighlights.keys()) {
            this.#isolatedElementHighlights.set(nodeId, this.buildIsolationModeHighlightConfig());
        }
        this.updateHighlightsInOverlay();
    }
    updateHighlightsInOverlay() {
        const hasNodesToHighlight = this.#gridHighlights.size > 0 || this.#flexHighlights.size > 0 ||
            this.#containerQueryHighlights.size > 0 || this.#isolatedElementHighlights.size > 0;
        this.#model.setShowViewportSizeOnResize(!hasNodesToHighlight);
        this.updateGridHighlightsInOverlay();
        this.updateFlexHighlightsInOverlay();
        this.updateScrollSnapHighlightsInOverlay();
        this.updateContainerQueryHighlightsInOverlay();
        this.updateIsolatedElementHighlightsInOverlay();
    }
    updateGridHighlightsInOverlay() {
        const overlayModel = this.#model;
        const gridNodeHighlightConfigs = [];
        for (const [nodeId, gridHighlightConfig] of this.#gridHighlights.entries()) {
            gridNodeHighlightConfigs.push({ nodeId, gridHighlightConfig });
        }
        overlayModel.target().overlayAgent().invoke_setShowGridOverlays({ gridNodeHighlightConfigs });
    }
    updateFlexHighlightsInOverlay() {
        const overlayModel = this.#model;
        const flexNodeHighlightConfigs = [];
        for (const [nodeId, flexContainerHighlightConfig] of this.#flexHighlights.entries()) {
            flexNodeHighlightConfigs.push({ nodeId, flexContainerHighlightConfig });
        }
        overlayModel.target().overlayAgent().invoke_setShowFlexOverlays({ flexNodeHighlightConfigs });
    }
    updateScrollSnapHighlightsInOverlay() {
        const overlayModel = this.#model;
        const scrollSnapHighlightConfigs = [];
        for (const [nodeId, scrollSnapContainerHighlightConfig] of this.#scrollSnapHighlights.entries()) {
            scrollSnapHighlightConfigs.push({ nodeId, scrollSnapContainerHighlightConfig });
        }
        overlayModel.target().overlayAgent().invoke_setShowScrollSnapOverlays({ scrollSnapHighlightConfigs });
    }
    updateContainerQueryHighlightsInOverlay() {
        const overlayModel = this.#model;
        const containerQueryHighlightConfigs = [];
        for (const [nodeId, containerQueryContainerHighlightConfig] of this.#containerQueryHighlights.entries()) {
            containerQueryHighlightConfigs.push({ nodeId, containerQueryContainerHighlightConfig });
        }
        overlayModel.target().overlayAgent().invoke_setShowContainerQueryOverlays({ containerQueryHighlightConfigs });
    }
    updateIsolatedElementHighlightsInOverlay() {
        const overlayModel = this.#model;
        const isolatedElementHighlightConfigs = [];
        for (const [nodeId, isolationModeHighlightConfig] of this.#isolatedElementHighlights.entries()) {
            isolatedElementHighlightConfigs.push({ nodeId, isolationModeHighlightConfig });
        }
        overlayModel.target().overlayAgent().invoke_setShowIsolatedElements({ isolatedElementHighlightConfigs });
    }
    async restoreHighlightsForDocument() {
        this.#flexHighlights = new Map();
        this.#gridHighlights = new Map();
        this.#scrollSnapHighlights = new Map();
        this.#containerQueryHighlights = new Map();
        this.#isolatedElementHighlights = new Map();
        const document = await this.#model.getDOMModel().requestDocument();
        const currentURL = document ? document.documentURL : EmptyUrlString;
        await Promise.all(this.#persistentHighlightSetting.get().map(async (persistentHighlight) => {
            if (persistentHighlight.url === currentURL) {
                return await this.#model.getDOMModel().pushNodeByPathToFrontend(persistentHighlight.path).then(nodeId => {
                    const node = this.#model.getDOMModel().nodeForId(nodeId);
                    if (!node) {
                        return;
                    }
                    switch (persistentHighlight.type) {
                        case "GRID" :
                            this.#gridHighlights.set(node.id, this.buildGridHighlightConfig(node.id));
                            this.#callbacks.onGridOverlayStateChanged({ nodeId: node.id, enabled: true });
                            break;
                        case "FLEX" :
                            this.#flexHighlights.set(node.id, this.buildFlexContainerHighlightConfig(node.id));
                            this.#callbacks.onFlexOverlayStateChanged({ nodeId: node.id, enabled: true });
                            break;
                        case "CONTAINER_QUERY" :
                            this.#containerQueryHighlights.set(node.id, this.buildContainerQueryContainerHighlightConfig());
                            this.#callbacks.onContainerQueryOverlayStateChanged({ nodeId: node.id, enabled: true });
                            break;
                        case "SCROLL_SNAP" :
                            this.#scrollSnapHighlights.set(node.id, this.buildScrollSnapContainerHighlightConfig(node.id));
                            this.#callbacks.onScrollSnapOverlayStateChanged({ nodeId: node.id, enabled: true });
                            break;
                        case "ISOLATED_ELEMENT" :
                            this.#isolatedElementHighlights.set(node.id, this.buildIsolationModeHighlightConfig());
                            break;
                    }
                });
            }
        }));
        this.updateHighlightsInOverlay();
    }
    currentUrl() {
        const domDocument = this.#model.getDOMModel().existingDocument();
        return domDocument ? domDocument.documentURL : EmptyUrlString;
    }
    getPersistentHighlightSettingForOneType(highlights, type) {
        const persistentHighlights = [];
        for (const nodeId of highlights.keys()) {
            const node = this.#model.getDOMModel().nodeForId(nodeId);
            if (node) {
                persistentHighlights.push({ url: this.currentUrl(), path: node.path(), type });
            }
        }
        return persistentHighlights;
    }
    savePersistentHighlightSetting() {
        const currentURL = this.currentUrl();
        const highlightsInOtherDocuments = this.#persistentHighlightSetting.get().filter((persistentSetting) => persistentSetting.url !== currentURL);
        const persistentHighlights = [
            ...highlightsInOtherDocuments,
            ...this.getPersistentHighlightSettingForOneType(this.#gridHighlights, "GRID" ),
            ...this.getPersistentHighlightSettingForOneType(this.#flexHighlights, "FLEX" ),
            ...this.getPersistentHighlightSettingForOneType(this.#containerQueryHighlights, "CONTAINER_QUERY" ),
            ...this.getPersistentHighlightSettingForOneType(this.#scrollSnapHighlights, "SCROLL_SNAP" ),
            ...this.getPersistentHighlightSettingForOneType(this.#isolatedElementHighlights, "ISOLATED_ELEMENT" ),
        ];
        this.#persistentHighlightSetting.set(persistentHighlights);
    }
}

// Copyright 2017 The Chromium Authors
const UIStrings$$ = {
    pausedInDebugger: 'Paused in debugger',
};
const str_$_ = registerUIStrings('core/sdk/OverlayModel.ts', UIStrings$$);
const i18nString$I = getLocalizedString.bind(undefined, str_$_);
const platformOverlayDimensions = {
    mac: { x: 85, y: 0, width: 185, height: 40 },
    linux: { x: 0, y: 0, width: 196, height: 34 },
    windows: { x: 0, y: 0, width: 238, height: 33 },
};
class OverlayModel extends SDKModel {
    #domModel;
    overlayAgent;
    #debuggerModel;
    #inspectModeEnabled = false;
    #hideHighlightTimeout = null;
    #defaultHighlighter;
    #highlighter;
    #showPaintRectsSetting;
    #showLayoutShiftRegionsSetting;
    #showAdHighlightsSetting;
    #showDebugBordersSetting;
    #showFPSCounterSetting;
    #showScrollBottleneckRectsSetting;
    #registeredListeners = [];
    #showViewportSizeOnResize = true;
    #persistentHighlighter;
    #sourceOrderHighlighter;
    #sourceOrderModeActive = false;
    #windowControls;
    constructor(target) {
        super(target);
        this.#domModel = target.model(DOMModel);
        target.registerOverlayDispatcher(this);
        this.overlayAgent = target.overlayAgent();
        this.#debuggerModel = target.model(DebuggerModel);
        if (this.#debuggerModel) {
            Settings.instance()
                .moduleSetting('disable-paused-state-overlay')
                .addChangeListener(this.updatePausedInDebuggerMessage, this);
            this.#debuggerModel.addEventListener(Events$5.DebuggerPaused, this.updatePausedInDebuggerMessage, this);
            this.#debuggerModel.addEventListener(Events$5.DebuggerResumed, this.updatePausedInDebuggerMessage, this);
            this.#debuggerModel.addEventListener(Events$5.GlobalObjectCleared, this.updatePausedInDebuggerMessage, this);
        }
        this.#defaultHighlighter = new DefaultHighlighter(this);
        this.#highlighter = this.#defaultHighlighter;
        this.#showPaintRectsSetting = Settings.instance().moduleSetting('show-paint-rects');
        this.#showLayoutShiftRegionsSetting =
            Settings.instance().moduleSetting('show-layout-shift-regions');
        this.#showAdHighlightsSetting = Settings.instance().moduleSetting('show-ad-highlights');
        this.#showDebugBordersSetting = Settings.instance().moduleSetting('show-debug-borders');
        this.#showFPSCounterSetting = Settings.instance().moduleSetting('show-fps-counter');
        this.#showScrollBottleneckRectsSetting =
            Settings.instance().moduleSetting('show-scroll-bottleneck-rects');
        if (!target.suspended()) {
            void this.overlayAgent.invoke_enable();
            void this.wireAgentToSettings();
        }
        this.#persistentHighlighter = new OverlayPersistentHighlighter(this, {
            onGridOverlayStateChanged: ({ nodeId, enabled }) => {
                this.#domModel.nodeForId(nodeId)?.dispatchEventToListeners(DOMNodeEvents.GRID_OVERLAY_STATE_CHANGED, { enabled });
                this.dispatchEventToListeners("PersistentGridOverlayStateChanged" , { nodeId, enabled });
            },
            onFlexOverlayStateChanged: ({ nodeId, enabled }) => {
                this.#domModel.nodeForId(nodeId)?.dispatchEventToListeners(DOMNodeEvents.FLEX_CONTAINER_OVERLAY_STATE_CHANGED, { enabled });
                this.dispatchEventToListeners("PersistentFlexContainerOverlayStateChanged" , { nodeId, enabled });
            },
            onContainerQueryOverlayStateChanged: ({ nodeId, enabled }) => {
                this.#domModel.nodeForId(nodeId)?.dispatchEventToListeners(DOMNodeEvents.CONTAINER_QUERY_OVERLAY_STATE_CHANGED, { enabled });
                this.dispatchEventToListeners("PersistentContainerQueryOverlayStateChanged" , { nodeId, enabled });
            },
            onScrollSnapOverlayStateChanged: ({ nodeId, enabled }) => {
                this.#domModel.nodeForId(nodeId)?.dispatchEventToListeners(DOMNodeEvents.SCROLL_SNAP_OVERLAY_STATE_CHANGED, { enabled });
                this.dispatchEventToListeners("PersistentScrollSnapOverlayStateChanged" , { nodeId, enabled });
            },
        });
        this.#domModel.addEventListener(Events$8.NodeRemoved, () => {
            if (!this.#persistentHighlighter) {
                return;
            }
            this.#persistentHighlighter.refreshHighlights();
        });
        this.#domModel.addEventListener(Events$8.DocumentUpdated, () => {
            if (!this.#persistentHighlighter) {
                return;
            }
            this.#persistentHighlighter.hideAllInOverlayWithoutSave();
            if (!target.suspended()) {
                void this.#persistentHighlighter.restoreHighlightsForDocument();
            }
        });
        this.#sourceOrderHighlighter = new SourceOrderHighlighter(this);
        this.#windowControls = new WindowControls(this.#domModel.cssModel());
    }
    static highlightObjectAsDOMNode(object) {
        const domModel = object.runtimeModel().target().model(DOMModel);
        if (domModel) {
            domModel.overlayModel().highlightInOverlay({ object, selectorList: undefined });
        }
    }
    static hideDOMNodeHighlight() {
        for (const overlayModel of TargetManager.instance().models(OverlayModel)) {
            overlayModel.delayedHideHighlight(0);
        }
    }
    static async muteHighlight() {
        return await Promise.all(TargetManager.instance().models(OverlayModel).map(model => model.suspendModel()));
    }
    static async unmuteHighlight() {
        return await Promise.all(TargetManager.instance().models(OverlayModel).map(model => model.resumeModel()));
    }
    static highlightRect(rect) {
        for (const overlayModel of TargetManager.instance().models(OverlayModel)) {
            void overlayModel.highlightRect(rect);
        }
    }
    static clearHighlight() {
        for (const overlayModel of TargetManager.instance().models(OverlayModel)) {
            void overlayModel.clearHighlight();
        }
    }
    getDOMModel() {
        return this.#domModel;
    }
    highlightRect({ x, y, width, height, color, outlineColor }) {
        const highlightColor = color || { r: 255, g: 0, b: 255, a: 0.3 };
        const highlightOutlineColor = outlineColor || { r: 255, g: 0, b: 255, a: 0.5 };
        return this.overlayAgent.invoke_highlightRect({ x, y, width, height, color: highlightColor, outlineColor: highlightOutlineColor });
    }
    clearHighlight() {
        return this.overlayAgent.invoke_hideHighlight();
    }
    async wireAgentToSettings() {
        this.#registeredListeners = [
            this.#showPaintRectsSetting.addChangeListener(() => this.overlayAgent.invoke_setShowPaintRects({ result: this.#showPaintRectsSetting.get() })),
            this.#showLayoutShiftRegionsSetting.addChangeListener(() => this.overlayAgent.invoke_setShowLayoutShiftRegions({ result: this.#showLayoutShiftRegionsSetting.get() })),
            this.#showAdHighlightsSetting.addChangeListener(() => this.overlayAgent.invoke_setShowAdHighlights({ show: this.#showAdHighlightsSetting.get() })),
            this.#showDebugBordersSetting.addChangeListener(() => this.overlayAgent.invoke_setShowDebugBorders({ show: this.#showDebugBordersSetting.get() })),
            this.#showFPSCounterSetting.addChangeListener(() => this.overlayAgent.invoke_setShowFPSCounter({ show: this.#showFPSCounterSetting.get() })),
            this.#showScrollBottleneckRectsSetting.addChangeListener(() => this.overlayAgent.invoke_setShowScrollBottleneckRects({ show: this.#showScrollBottleneckRectsSetting.get() })),
        ];
        if (this.#showPaintRectsSetting.get()) {
            void this.overlayAgent.invoke_setShowPaintRects({ result: true });
        }
        if (this.#showLayoutShiftRegionsSetting.get()) {
            void this.overlayAgent.invoke_setShowLayoutShiftRegions({ result: true });
        }
        if (this.#showAdHighlightsSetting.get()) {
            void this.overlayAgent.invoke_setShowAdHighlights({ show: true });
        }
        if (this.#showDebugBordersSetting.get()) {
            void this.overlayAgent.invoke_setShowDebugBorders({ show: true });
        }
        if (this.#showFPSCounterSetting.get()) {
            void this.overlayAgent.invoke_setShowFPSCounter({ show: true });
        }
        if (this.#showScrollBottleneckRectsSetting.get()) {
            void this.overlayAgent.invoke_setShowScrollBottleneckRects({ show: true });
        }
        if (this.#debuggerModel && this.#debuggerModel.isPaused()) {
            this.updatePausedInDebuggerMessage();
        }
        await this.overlayAgent.invoke_setShowViewportSizeOnResize({ show: this.#showViewportSizeOnResize });
        this.#persistentHighlighter?.resetOverlay();
    }
    async suspendModel() {
        removeEventListeners(this.#registeredListeners);
        await this.overlayAgent.invoke_disable();
    }
    async resumeModel() {
        await Promise.all([this.overlayAgent.invoke_enable(), this.wireAgentToSettings()]);
    }
    setShowViewportSizeOnResize(show) {
        if (this.#showViewportSizeOnResize === show) {
            return;
        }
        this.#showViewportSizeOnResize = show;
        if (this.target().suspended()) {
            return;
        }
        void this.overlayAgent.invoke_setShowViewportSizeOnResize({ show });
    }
    updatePausedInDebuggerMessage() {
        if (this.target().suspended()) {
            return;
        }
        const message = this.#debuggerModel && this.#debuggerModel.isPaused() &&
            !Settings.instance().moduleSetting('disable-paused-state-overlay').get() ?
            i18nString$I(UIStrings$$.pausedInDebugger) :
            undefined;
        void this.overlayAgent.invoke_setPausedInDebuggerMessage({ message });
    }
    setHighlighter(highlighter) {
        this.#highlighter = highlighter || this.#defaultHighlighter;
    }
    async setInspectMode(mode, showDetailedTooltip = true) {
        await this.#domModel.requestDocument();
        this.#inspectModeEnabled = mode !== "none" ;
        this.dispatchEventToListeners("InspectModeWillBeToggled" , this);
        void this.#highlighter.setInspectMode(mode, this.buildHighlightConfig('all', showDetailedTooltip));
    }
    inspectModeEnabled() {
        return this.#inspectModeEnabled;
    }
    highlightInOverlay(data, mode, showInfo) {
        if (this.#sourceOrderModeActive) {
            return;
        }
        if (this.#hideHighlightTimeout) {
            clearTimeout(this.#hideHighlightTimeout);
            this.#hideHighlightTimeout = null;
        }
        const highlightConfig = this.buildHighlightConfig(mode);
        if (typeof showInfo !== 'undefined') {
            highlightConfig.showInfo = showInfo;
        }
        this.#highlighter.highlightInOverlay(data, highlightConfig);
    }
    highlightInOverlayForTwoSeconds(data) {
        this.highlightInOverlay(data);
        this.delayedHideHighlight(2000);
    }
    highlightGridInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return;
        }
        this.#persistentHighlighter.highlightGridInOverlay(nodeId);
    }
    isHighlightedGridInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return false;
        }
        return this.#persistentHighlighter.isGridHighlighted(nodeId);
    }
    hideGridInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return;
        }
        this.#persistentHighlighter.hideGridInOverlay(nodeId);
    }
    highlightScrollSnapInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return;
        }
        this.#persistentHighlighter.highlightScrollSnapInOverlay(nodeId);
    }
    isHighlightedScrollSnapInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return false;
        }
        return this.#persistentHighlighter.isScrollSnapHighlighted(nodeId);
    }
    hideScrollSnapInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return;
        }
        this.#persistentHighlighter.hideScrollSnapInOverlay(nodeId);
    }
    highlightFlexContainerInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return;
        }
        this.#persistentHighlighter.highlightFlexInOverlay(nodeId);
    }
    isHighlightedFlexContainerInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return false;
        }
        return this.#persistentHighlighter.isFlexHighlighted(nodeId);
    }
    hideFlexContainerInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return;
        }
        this.#persistentHighlighter.hideFlexInOverlay(nodeId);
    }
    highlightContainerQueryInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return;
        }
        this.#persistentHighlighter.highlightContainerQueryInOverlay(nodeId);
    }
    isHighlightedContainerQueryInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return false;
        }
        return this.#persistentHighlighter.isContainerQueryHighlighted(nodeId);
    }
    hideContainerQueryInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return;
        }
        this.#persistentHighlighter.hideContainerQueryInOverlay(nodeId);
    }
    highlightSourceOrderInOverlay(node) {
        const sourceOrderConfig = {
            parentOutlineColor: SourceOrderHighlight.ParentOutline.toProtocolRGBA(),
            childOutlineColor: SourceOrderHighlight.ChildOutline.toProtocolRGBA(),
        };
        this.#sourceOrderHighlighter.highlightSourceOrderInOverlay(node, sourceOrderConfig);
    }
    colorOfGridInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return null;
        }
        return this.#persistentHighlighter.colorOfGrid(nodeId).asString("hex" );
    }
    setColorOfGridInPersistentOverlay(nodeId, colorStr) {
        if (!this.#persistentHighlighter) {
            return;
        }
        const color = parse$2(colorStr);
        if (!color) {
            return;
        }
        this.#persistentHighlighter.setColorOfGrid(nodeId, color);
        this.#persistentHighlighter.resetOverlay();
    }
    colorOfFlexInPersistentOverlay(nodeId) {
        if (!this.#persistentHighlighter) {
            return null;
        }
        return this.#persistentHighlighter.colorOfFlex(nodeId).asString("hex" );
    }
    setColorOfFlexInPersistentOverlay(nodeId, colorStr) {
        if (!this.#persistentHighlighter) {
            return;
        }
        const color = parse$2(colorStr);
        if (!color) {
            return;
        }
        this.#persistentHighlighter.setColorOfFlex(nodeId, color);
        this.#persistentHighlighter.resetOverlay();
    }
    hideSourceOrderInOverlay() {
        this.#sourceOrderHighlighter.hideSourceOrderHighlight();
    }
    setSourceOrderActive(isActive) {
        this.#sourceOrderModeActive = isActive;
    }
    delayedHideHighlight(delay) {
        if (this.#hideHighlightTimeout === null) {
            this.#hideHighlightTimeout = window.setTimeout(() => this.highlightInOverlay({ clear: true }), delay);
        }
    }
    highlightFrame(frameId) {
        if (this.#hideHighlightTimeout) {
            clearTimeout(this.#hideHighlightTimeout);
            this.#hideHighlightTimeout = null;
        }
        this.#highlighter.highlightFrame(frameId);
    }
    showHingeForDualScreen(hinge) {
        if (hinge) {
            const { x, y, width, height, contentColor, outlineColor } = hinge;
            void this.overlayAgent.invoke_setShowHinge({
                hingeConfig: { rect: { x, y, width, height }, contentColor, outlineColor },
            });
        }
        else {
            void this.overlayAgent.invoke_setShowHinge({});
        }
    }
    setWindowControlsPlatform(selectedPlatform) {
        this.#windowControls.selectedPlatform = selectedPlatform;
    }
    setWindowControlsThemeColor(themeColor) {
        this.#windowControls.themeColor = themeColor;
    }
    getWindowControlsConfig() {
        return this.#windowControls.config;
    }
    async toggleWindowControlsToolbar(show) {
        const wcoConfigObj = show ? { windowControlsOverlayConfig: this.#windowControls.config } : {};
        const setWindowControlsOverlayOperation = this.overlayAgent.invoke_setShowWindowControlsOverlay(wcoConfigObj);
        const toggleStylesheetOperation = this.#windowControls.toggleEmulatedOverlay(show);
        await Promise.all([setWindowControlsOverlayOperation, toggleStylesheetOperation]);
        this.setShowViewportSizeOnResize(!show);
    }
    buildHighlightConfig(mode = 'all', showDetailedToolip = false) {
        const showRulers = Settings.instance().moduleSetting('show-metrics-rulers').get();
        const highlightConfig = {
            showInfo: mode === 'all' || mode === 'container-outline',
            showRulers,
            showStyles: showDetailedToolip,
            showAccessibilityInfo: showDetailedToolip,
            showExtensionLines: showRulers,
            gridHighlightConfig: {},
            flexContainerHighlightConfig: {},
            flexItemHighlightConfig: {},
            contrastAlgorithm: experiments.isEnabled(ExperimentName.APCA) ?
                "apca"  :
                "aa" ,
        };
        if (mode === 'all' || mode === 'content') {
            highlightConfig.contentColor = PageHighlight.Content.toProtocolRGBA();
        }
        if (mode === 'all' || mode === 'padding') {
            highlightConfig.paddingColor = PageHighlight.Padding.toProtocolRGBA();
        }
        if (mode === 'all' || mode === 'border') {
            highlightConfig.borderColor = PageHighlight.Border.toProtocolRGBA();
        }
        if (mode === 'all' || mode === 'margin') {
            highlightConfig.marginColor = PageHighlight.Margin.toProtocolRGBA();
        }
        if (mode === 'all') {
            highlightConfig.eventTargetColor = PageHighlight.EventTarget.toProtocolRGBA();
            highlightConfig.shapeColor = PageHighlight.Shape.toProtocolRGBA();
            highlightConfig.shapeMarginColor = PageHighlight.ShapeMargin.toProtocolRGBA();
            highlightConfig.gridHighlightConfig = {
                rowGapColor: PageHighlight.GapBackground.toProtocolRGBA(),
                rowHatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                columnGapColor: PageHighlight.GapBackground.toProtocolRGBA(),
                columnHatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                rowLineColor: PageHighlight.LayoutLine.toProtocolRGBA(),
                columnLineColor: PageHighlight.LayoutLine.toProtocolRGBA(),
                rowLineDash: true,
                columnLineDash: true,
            };
            highlightConfig.flexContainerHighlightConfig = {
                containerBorder: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                    pattern: "dashed" ,
                },
                itemSeparator: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                    pattern: "dotted" ,
                },
                lineSeparator: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                    pattern: "dashed" ,
                },
                mainDistributedSpace: {
                    hatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                    fillColor: PageHighlight.GapBackground.toProtocolRGBA(),
                },
                crossDistributedSpace: {
                    hatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                    fillColor: PageHighlight.GapBackground.toProtocolRGBA(),
                },
                rowGapSpace: {
                    hatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                    fillColor: PageHighlight.GapBackground.toProtocolRGBA(),
                },
                columnGapSpace: {
                    hatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                    fillColor: PageHighlight.GapBackground.toProtocolRGBA(),
                },
            };
            highlightConfig.flexItemHighlightConfig = {
                baseSizeBox: {
                    hatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                },
                baseSizeBorder: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                    pattern: "dotted" ,
                },
                flexibilityArrow: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                },
            };
        }
        if (mode.endsWith('gap')) {
            highlightConfig.gridHighlightConfig = {
                gridBorderColor: PageHighlight.GridBorder.toProtocolRGBA(),
                gridBorderDash: true,
            };
            if (mode === 'gap' || mode === 'row-gap') {
                highlightConfig.gridHighlightConfig.rowGapColor = PageHighlight.GapBackground.toProtocolRGBA();
                highlightConfig.gridHighlightConfig.rowHatchColor = PageHighlight.GapHatch.toProtocolRGBA();
            }
            if (mode === 'gap' || mode === 'column-gap') {
                highlightConfig.gridHighlightConfig.columnGapColor = PageHighlight.GapBackground.toProtocolRGBA();
                highlightConfig.gridHighlightConfig.columnHatchColor = PageHighlight.GapHatch.toProtocolRGBA();
            }
        }
        if (mode.endsWith('gap')) {
            highlightConfig.flexContainerHighlightConfig = {
                containerBorder: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                    pattern: "dashed" ,
                },
            };
            if (mode === 'gap' || mode === 'row-gap') {
                highlightConfig.flexContainerHighlightConfig.rowGapSpace = {
                    hatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                    fillColor: PageHighlight.GapBackground.toProtocolRGBA(),
                };
            }
            if (mode === 'gap' || mode === 'column-gap') {
                highlightConfig.flexContainerHighlightConfig.columnGapSpace = {
                    hatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                    fillColor: PageHighlight.GapBackground.toProtocolRGBA(),
                };
            }
        }
        if (mode === 'grid-areas') {
            highlightConfig.gridHighlightConfig = {
                rowLineColor: PageHighlight.LayoutLine.toProtocolRGBA(),
                columnLineColor: PageHighlight.LayoutLine.toProtocolRGBA(),
                rowLineDash: true,
                columnLineDash: true,
                showAreaNames: true,
                areaBorderColor: PageHighlight.GridAreaBorder.toProtocolRGBA(),
            };
        }
        if (mode === 'grid-template-columns') {
            highlightConfig.contentColor = PageHighlight.Content.toProtocolRGBA();
            highlightConfig.gridHighlightConfig = {
                columnLineColor: PageHighlight.LayoutLine.toProtocolRGBA(),
                columnLineDash: true,
            };
        }
        if (mode === 'grid-template-rows') {
            highlightConfig.contentColor = PageHighlight.Content.toProtocolRGBA();
            highlightConfig.gridHighlightConfig = {
                rowLineColor: PageHighlight.LayoutLine.toProtocolRGBA(),
                rowLineDash: true,
            };
        }
        if (mode === 'justify-content') {
            highlightConfig.flexContainerHighlightConfig = {
                containerBorder: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                    pattern: "dashed" ,
                },
                mainDistributedSpace: {
                    hatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                    fillColor: PageHighlight.GapBackground.toProtocolRGBA(),
                },
            };
        }
        if (mode === 'align-content') {
            highlightConfig.flexContainerHighlightConfig = {
                containerBorder: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                    pattern: "dashed" ,
                },
                crossDistributedSpace: {
                    hatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                    fillColor: PageHighlight.GapBackground.toProtocolRGBA(),
                },
            };
        }
        if (mode === 'align-items') {
            highlightConfig.flexContainerHighlightConfig = {
                containerBorder: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                    pattern: "dashed" ,
                },
                lineSeparator: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                    pattern: "dashed" ,
                },
                crossAlignment: { color: PageHighlight.LayoutLine.toProtocolRGBA() },
            };
        }
        if (mode === 'flexibility') {
            highlightConfig.flexItemHighlightConfig = {
                baseSizeBox: {
                    hatchColor: PageHighlight.GapHatch.toProtocolRGBA(),
                },
                baseSizeBorder: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                    pattern: "dotted" ,
                },
                flexibilityArrow: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                },
            };
        }
        if (mode === 'container-outline') {
            highlightConfig.containerQueryContainerHighlightConfig = {
                containerBorder: {
                    color: PageHighlight.LayoutLine.toProtocolRGBA(),
                    pattern: "dashed" ,
                },
            };
        }
        return highlightConfig;
    }
    nodeHighlightRequested({ nodeId }) {
        const node = this.#domModel.nodeForId(nodeId);
        if (node) {
            this.dispatchEventToListeners("HighlightNodeRequested" , node);
        }
    }
    static setInspectNodeHandler(handler) {
        OverlayModel.inspectNodeHandler = handler;
    }
    inspectNodeRequested({ backendNodeId }) {
        const deferredNode = new DeferredDOMNode(this.target(), backendNodeId);
        if (OverlayModel.inspectNodeHandler) {
            void deferredNode.resolvePromise().then(node => {
                if (node && OverlayModel.inspectNodeHandler) {
                    void OverlayModel.inspectNodeHandler(node);
                }
            });
        }
        else {
            void reveal(deferredNode);
        }
        this.dispatchEventToListeners("InspectModeExited" );
    }
    screenshotRequested({ viewport }) {
        this.dispatchEventToListeners("ScreenshotRequested" , viewport);
        this.dispatchEventToListeners("InspectModeExited" );
    }
    inspectModeCanceled() {
        this.dispatchEventToListeners("InspectModeExited" );
    }
    static inspectNodeHandler = null;
    getOverlayAgent() {
        return this.overlayAgent;
    }
    async hasStyleSheetText(url) {
        return await this.#windowControls.initializeStyleSheetText(url);
    }
    inspectPanelShowRequested({ backendNodeId }) {
        this.dispatchEventToListeners("InspectPanelShowRequested" , backendNodeId);
    }
    inspectedElementWindowRestored({ backendNodeId }) {
        this.dispatchEventToListeners("InspectedElementWindowRestored" , backendNodeId);
    }
}
class WindowControls {
    #cssModel;
    #originalStylesheetText;
    #stylesheetId;
    #currentUrl;
    #config = {
        showCSS: false,
        selectedPlatform: "Windows" ,
        themeColor: '#ffffff',
    };
    constructor(cssModel) {
        this.#cssModel = cssModel;
    }
    get selectedPlatform() {
        return this.#config.selectedPlatform;
    }
    set selectedPlatform(osType) {
        this.#config.selectedPlatform = osType;
    }
    get themeColor() {
        return this.#config.themeColor;
    }
    set themeColor(color) {
        this.#config.themeColor = color;
    }
    get config() {
        return this.#config;
    }
    async initializeStyleSheetText(url) {
        if (this.#originalStylesheetText && url === this.#currentUrl) {
            return true;
        }
        const cssSourceUrl = this.#fetchCssSourceUrl(url);
        if (!cssSourceUrl) {
            return false;
        }
        this.#stylesheetId = this.#fetchCurrentStyleSheet(cssSourceUrl);
        if (!this.#stylesheetId) {
            return false;
        }
        const stylesheetText = await this.#cssModel.getStyleSheetText(this.#stylesheetId);
        if (!stylesheetText) {
            return false;
        }
        this.#originalStylesheetText = stylesheetText;
        this.#currentUrl = url;
        return true;
    }
    async toggleEmulatedOverlay(showOverlay) {
        if (!this.#stylesheetId || !this.#originalStylesheetText) {
            return;
        }
        if (showOverlay) {
            const styleSheetText = WindowControls.#getStyleSheetForPlatform(this.#config.selectedPlatform.toLowerCase(), this.#originalStylesheetText);
            if (styleSheetText) {
                await this.#cssModel.setStyleSheetText(this.#stylesheetId, styleSheetText, false);
            }
        }
        else {
            await this.#cssModel.setStyleSheetText(this.#stylesheetId, this.#originalStylesheetText, false);
        }
    }
    static #getStyleSheetForPlatform(platform, originalStyleSheet) {
        const overlayDimensions = platformOverlayDimensions[platform];
        return WindowControls.#transformStyleSheet(overlayDimensions.x, overlayDimensions.y, overlayDimensions.width, overlayDimensions.height, originalStyleSheet);
    }
    #fetchCssSourceUrl(url) {
        const parentURL = ParsedURL.extractOrigin(url);
        const cssHeaders = this.#cssModel.styleSheetHeaders();
        const header = cssHeaders.find(header => header.sourceURL && header.sourceURL.includes(parentURL));
        return header?.sourceURL;
    }
    #fetchCurrentStyleSheet(cssSourceUrl) {
        const stylesheetIds = this.#cssModel.getStyleSheetIdsForURL(cssSourceUrl);
        return stylesheetIds.length > 0 ? stylesheetIds[0] : undefined;
    }
    static #transformStyleSheet(x, y, width, height, originalStyleSheet) {
        if (!originalStyleSheet) {
            return undefined;
        }
        const stylesheetText = originalStyleSheet;
        const updatedStylesheet = stylesheetText.replace(/: env\(titlebar-area-x(?:,[^)]*)?\);/g, `: env(titlebar-area-x, ${x}px);`)
            .replace(/: env\(titlebar-area-y(?:,[^)]*)?\);/g, `: env(titlebar-area-y, ${y}px);`)
            .replace(/: env\(titlebar-area-width(?:,[^)]*)?\);/g, `: env(titlebar-area-width, calc(100% - ${width}px));`)
            .replace(/: env\(titlebar-area-height(?:,[^)]*)?\);/g, `: env(titlebar-area-height, ${height}px);`);
        return updatedStylesheet;
    }
    transformStyleSheetforTesting(x, y, width, height, originalStyleSheet) {
        return WindowControls.#transformStyleSheet(x, y, width, height, originalStyleSheet);
    }
}
class DefaultHighlighter {
    #model;
    constructor(model) {
        this.#model = model;
    }
    highlightInOverlay(data, highlightConfig) {
        const { node, deferredNode, object, selectorList } = { node: undefined, deferredNode: undefined, object: undefined, selectorList: undefined, ...data };
        const nodeId = node ? node.id : undefined;
        const backendNodeId = deferredNode ? deferredNode.backendNodeId() : undefined;
        const objectId = object ? object.objectId : undefined;
        if (nodeId || backendNodeId || objectId) {
            void this.#model.target().overlayAgent().invoke_highlightNode({ highlightConfig, nodeId, backendNodeId, objectId, selector: selectorList });
        }
        else {
            void this.#model.target().overlayAgent().invoke_hideHighlight();
        }
    }
    async setInspectMode(mode, highlightConfig) {
        await this.#model.target().overlayAgent().invoke_setInspectMode({ mode, highlightConfig });
    }
    highlightFrame(frameId) {
        void this.#model.target().overlayAgent().invoke_highlightFrame({
            frameId,
            contentColor: PageHighlight.Content.toProtocolRGBA(),
            contentOutlineColor: PageHighlight.ContentOutline.toProtocolRGBA(),
        });
    }
}
class SourceOrderHighlighter {
    #model;
    constructor(model) {
        this.#model = model;
    }
    highlightSourceOrderInOverlay(node, sourceOrderConfig) {
        this.#model.setSourceOrderActive(true);
        this.#model.setShowViewportSizeOnResize(false);
        void this.#model.getOverlayAgent().invoke_highlightSourceOrder({ sourceOrderConfig, nodeId: node.id });
    }
    hideSourceOrderHighlight() {
        this.#model.setSourceOrderActive(false);
        this.#model.setShowViewportSizeOnResize(true);
        void this.#model.clearHighlight();
    }
}
SDKModel.register(OverlayModel, { capabilities: 2 , autostart: true });

// Copyright 2020 The Chromium Authors
class HeapProfilerModel extends SDKModel {
    #enabled;
    #heapProfilerAgent;
    #runtimeModel;
    #samplingProfilerDepth;
    constructor(target) {
        super(target);
        target.registerHeapProfilerDispatcher(new HeapProfilerDispatcher(this));
        this.#enabled = false;
        this.#heapProfilerAgent = target.heapProfilerAgent();
        this.#runtimeModel = target.model(RuntimeModel);
        this.#samplingProfilerDepth = 0;
    }
    debuggerModel() {
        return this.#runtimeModel.debuggerModel();
    }
    runtimeModel() {
        return this.#runtimeModel;
    }
    async enable() {
        if (this.#enabled) {
            return;
        }
        this.#enabled = true;
        await this.#heapProfilerAgent.invoke_enable();
    }
    async startSampling(samplingRateInBytes) {
        if (this.#samplingProfilerDepth++) {
            return false;
        }
        const defaultSamplingIntervalInBytes = 16384;
        const response = await this.#heapProfilerAgent.invoke_startSampling({ samplingInterval: samplingRateInBytes || defaultSamplingIntervalInBytes });
        return Boolean(response.getError());
    }
    async stopSampling() {
        if (!this.#samplingProfilerDepth) {
            throw new Error('Sampling profiler is not running.');
        }
        if (--this.#samplingProfilerDepth) {
            return await this.getSamplingProfile();
        }
        const response = await this.#heapProfilerAgent.invoke_stopSampling();
        if (response.getError()) {
            return null;
        }
        return response.profile;
    }
    async getSamplingProfile() {
        const response = await this.#heapProfilerAgent.invoke_getSamplingProfile();
        if (response.getError()) {
            return null;
        }
        return response.profile;
    }
    async collectGarbage() {
        const response = await this.#heapProfilerAgent.invoke_collectGarbage();
        return Boolean(response.getError());
    }
    async snapshotObjectIdForObjectId(objectId) {
        const response = await this.#heapProfilerAgent.invoke_getHeapObjectId({ objectId });
        if (response.getError()) {
            return null;
        }
        return response.heapSnapshotObjectId;
    }
    async objectForSnapshotObjectId(snapshotObjectId, objectGroupName) {
        const result = await this.#heapProfilerAgent.invoke_getObjectByHeapObjectId({ objectId: snapshotObjectId, objectGroup: objectGroupName });
        if (result.getError()) {
            return null;
        }
        return this.#runtimeModel.createRemoteObject(result.result);
    }
    async addInspectedHeapObject(snapshotObjectId) {
        const response = await this.#heapProfilerAgent.invoke_addInspectedHeapObject({ heapObjectId: snapshotObjectId });
        return Boolean(response.getError());
    }
    async takeHeapSnapshot(heapSnapshotOptions) {
        await TargetManager.instance().suspendAllTargets('heap-snapshot');
        try {
            await this.#heapProfilerAgent.invoke_takeHeapSnapshot(heapSnapshotOptions);
        }
        finally {
            await TargetManager.instance().resumeAllTargets();
        }
    }
    async startTrackingHeapObjects(recordAllocationStacks) {
        const response = await this.#heapProfilerAgent.invoke_startTrackingHeapObjects({ trackAllocations: recordAllocationStacks });
        return Boolean(response.getError());
    }
    async stopTrackingHeapObjects(reportProgress) {
        const response = await this.#heapProfilerAgent.invoke_stopTrackingHeapObjects({ reportProgress });
        return Boolean(response.getError());
    }
    heapStatsUpdate(samples) {
        this.dispatchEventToListeners("HeapStatsUpdate" , samples);
    }
    lastSeenObjectId(lastSeenObjectId, timestamp) {
        this.dispatchEventToListeners("LastSeenObjectId" , { lastSeenObjectId, timestamp });
    }
    addHeapSnapshotChunk(chunk) {
        this.dispatchEventToListeners("AddHeapSnapshotChunk" , chunk);
    }
    reportHeapSnapshotProgress(done, total, finished) {
        this.dispatchEventToListeners("ReportHeapSnapshotProgress" , { done, total, finished });
    }
    resetProfiles() {
        this.dispatchEventToListeners("ResetProfiles" , this);
    }
}
class HeapProfilerDispatcher {
    #heapProfilerModel;
    constructor(model) {
        this.#heapProfilerModel = model;
    }
    heapStatsUpdate({ statsUpdate }) {
        this.#heapProfilerModel.heapStatsUpdate(statsUpdate);
    }
    lastSeenObjectId({ lastSeenObjectId, timestamp }) {
        this.#heapProfilerModel.lastSeenObjectId(lastSeenObjectId, timestamp);
    }
    addHeapSnapshotChunk({ chunk }) {
        this.#heapProfilerModel.addHeapSnapshotChunk(chunk);
    }
    reportHeapSnapshotProgress({ done, total, finished }) {
        this.#heapProfilerModel.reportHeapSnapshotProgress(done, total, finished);
    }
    resetProfiles() {
        this.#heapProfilerModel.resetProfiles();
    }
}
SDKModel.register(HeapProfilerModel, { capabilities: 4 , autostart: false });

// Copyright 2012 The Chromium Authors
class RuntimeModel extends SDKModel {
    agent;
    #executionContextById = new Map();
    #executionContextComparator = ExecutionContext.comparator;
    constructor(target) {
        super(target);
        this.agent = target.runtimeAgent();
        this.target().registerRuntimeDispatcher(new RuntimeDispatcher(this));
        void this.agent.invoke_enable();
        if (Settings.instance().moduleSetting('custom-formatters').get()) {
            void this.agent.invoke_setCustomObjectFormatterEnabled({ enabled: true });
        }
        Settings.instance()
            .moduleSetting('custom-formatters')
            .addChangeListener(this.customFormattersStateChanged.bind(this));
    }
    static isSideEffectFailure(response) {
        const exceptionDetails = 'exceptionDetails' in response && response.exceptionDetails;
        return Boolean(exceptionDetails &&
            exceptionDetails.exception?.description?.startsWith('EvalError: Possible side-effect in debug-evaluate'));
    }
    debuggerModel() {
        return this.target().model(DebuggerModel);
    }
    heapProfilerModel() {
        return this.target().model(HeapProfilerModel);
    }
    executionContexts() {
        return [...this.#executionContextById.values()].sort(this.executionContextComparator());
    }
    setExecutionContextComparator(comparator) {
        this.#executionContextComparator = comparator;
    }
    executionContextComparator() {
        return this.#executionContextComparator;
    }
    defaultExecutionContext() {
        for (const context of this.executionContexts()) {
            if (context.isDefault) {
                return context;
            }
        }
        return null;
    }
    executionContext(id) {
        return this.#executionContextById.get(id) || null;
    }
    executionContextCreated(context) {
        const data = context.auxData || { isDefault: true };
        const executionContext = new ExecutionContext(this, context.id, context.uniqueId, context.name, context.origin, data['isDefault'], data['frameId']);
        this.#executionContextById.set(executionContext.id, executionContext);
        this.dispatchEventToListeners(Events$9.ExecutionContextCreated, executionContext);
    }
    executionContextDestroyed(executionContextId) {
        const executionContext = this.#executionContextById.get(executionContextId);
        if (!executionContext) {
            return;
        }
        this.debuggerModel().executionContextDestroyed(executionContext);
        this.#executionContextById.delete(executionContextId);
        this.dispatchEventToListeners(Events$9.ExecutionContextDestroyed, executionContext);
    }
    fireExecutionContextOrderChanged() {
        this.dispatchEventToListeners(Events$9.ExecutionContextOrderChanged, this);
    }
    executionContextsCleared() {
        this.debuggerModel().globalObjectCleared();
        const contexts = this.executionContexts();
        this.#executionContextById.clear();
        for (let i = 0; i < contexts.length; ++i) {
            this.dispatchEventToListeners(Events$9.ExecutionContextDestroyed, contexts[i]);
        }
    }
    createRemoteObject(payload) {
        console.assert(typeof payload === 'object', 'Remote object payload should only be an object');
        return new RemoteObjectImpl(this, payload.objectId, payload.type, payload.subtype, payload.value, payload.unserializableValue, payload.description, payload.preview, payload.customPreview, payload.className);
    }
    createScopeRemoteObject(payload, scopeRef) {
        return new ScopeRemoteObject(this, payload.objectId, scopeRef, payload.type, payload.subtype, payload.value, payload.unserializableValue, payload.description, payload.preview);
    }
    createRemoteObjectFromPrimitiveValue(value) {
        const type = typeof value;
        let unserializableValue = undefined;
        const unserializableDescription = RemoteObject$1.unserializableDescription(value);
        if (unserializableDescription !== null) {
            unserializableValue = (unserializableDescription);
        }
        if (typeof unserializableValue !== 'undefined') {
            value = undefined;
        }
        return new RemoteObjectImpl(this, undefined, type, undefined, value, unserializableValue);
    }
    createRemotePropertyFromPrimitiveValue(name, value) {
        return new RemoteObjectProperty(name, this.createRemoteObjectFromPrimitiveValue(value));
    }
    discardConsoleEntries() {
        void this.agent.invoke_discardConsoleEntries();
    }
    releaseObjectGroup(objectGroup) {
        void this.agent.invoke_releaseObjectGroup({ objectGroup });
    }
    releaseEvaluationResult(result) {
        if ('object' in result && result.object) {
            result.object.release();
        }
        if ('exceptionDetails' in result && result.exceptionDetails?.exception) {
            const exception = result.exceptionDetails.exception;
            const exceptionObject = this.createRemoteObject({ type: exception.type, objectId: exception.objectId });
            exceptionObject.release();
        }
    }
    runIfWaitingForDebugger() {
        void this.agent.invoke_runIfWaitingForDebugger();
    }
    customFormattersStateChanged({ data: enabled }) {
        void this.agent.invoke_setCustomObjectFormatterEnabled({ enabled });
    }
    async compileScript(expression, sourceURL, persistScript, executionContextId) {
        const response = await this.agent.invoke_compileScript({
            expression,
            sourceURL,
            persistScript,
            executionContextId,
        });
        if (response.getError()) {
            console.error(response.getError());
            return null;
        }
        return { scriptId: response.scriptId, exceptionDetails: response.exceptionDetails };
    }
    async runScript(scriptId, executionContextId, objectGroup, silent, includeCommandLineAPI, returnByValue, generatePreview, awaitPromise) {
        const response = await this.agent.invoke_runScript({
            scriptId,
            executionContextId,
            objectGroup,
            silent,
            includeCommandLineAPI,
            returnByValue,
            generatePreview,
            awaitPromise,
        });
        const error = response.getError();
        if (error) {
            console.error(error);
            return { error };
        }
        return { object: this.createRemoteObject(response.result), exceptionDetails: response.exceptionDetails };
    }
    async queryObjects(prototype) {
        if (!prototype.objectId) {
            return { error: 'Prototype should be an Object.' };
        }
        const response = await this.agent.invoke_queryObjects({ prototypeObjectId: prototype.objectId, objectGroup: 'console' });
        const error = response.getError();
        if (error) {
            console.error(error);
            return { error };
        }
        return { objects: this.createRemoteObject(response.objects) };
    }
    async isolateId() {
        const response = await this.agent.invoke_getIsolateId();
        if (response.getError() || !response.id) {
            return this.target().id();
        }
        return response.id;
    }
    async heapUsage() {
        const result = await this.agent.invoke_getHeapUsage();
        return result.getError() ? null : result;
    }
    inspectRequested(payload, hints, executionContextId) {
        const object = this.createRemoteObject(payload);
        if (hints !== null && typeof hints === 'object') {
            if ('copyToClipboard' in hints && Boolean(hints.copyToClipboard)) {
                this.copyRequested(object);
                return;
            }
            if ('queryObjects' in hints && hints.queryObjects) {
                void this.queryObjectsRequested(object, executionContextId);
                return;
            }
        }
        if (object.isNode()) {
            const omitFocus = hints !== null && typeof hints === 'object' && 'omitFocus' in hints && Boolean(hints.omitFocus);
            void reveal(object, omitFocus).then(object.release.bind(object));
            return;
        }
        if (object.type === 'function') {
            void RemoteFunction.objectAsFunction(object).targetFunctionDetails().then(didGetDetails);
            return;
        }
        function didGetDetails(response) {
            object.release();
            if (!response?.location) {
                return;
            }
            void reveal(response.location);
        }
        object.release();
    }
    async addBinding(event) {
        return await this.agent.invoke_addBinding(event);
    }
    async removeBinding(request) {
        return await this.agent.invoke_removeBinding(request);
    }
    bindingCalled(event) {
        this.dispatchEventToListeners(Events$9.BindingCalled, event);
    }
    copyRequested(object) {
        if (!object.objectId) {
            InspectorFrontendHostInstance.copyText(object.unserializableValue() || object.value);
            return;
        }
        const indent = Settings.instance().moduleSetting('text-editor-indent').get();
        void object
            .callFunctionJSON(toStringForClipboard, [{
                value: {
                    subtype: object.subtype,
                    indent,
                },
            }])
            .then(InspectorFrontendHostInstance.copyText.bind(InspectorFrontendHostInstance));
        function toStringForClipboard(data) {
            const subtype = data.subtype;
            const indent = data.indent;
            if (subtype === 'node') {
                return this instanceof Element ? this.outerHTML : undefined;
            }
            if (subtype && typeof this === 'undefined') {
                return String(subtype);
            }
            try {
                return JSON.stringify(this, null, indent);
            }
            catch {
                return String(this);
            }
        }
    }
    async queryObjectsRequested(object, executionContextId) {
        const result = await this.queryObjects(object);
        object.release();
        if ('error' in result) {
            Console.instance().error(result.error);
            return;
        }
        this.dispatchEventToListeners(Events$9.QueryObjectRequested, { objects: result.objects, executionContextId });
    }
    static simpleTextFromException(exceptionDetails) {
        let text = exceptionDetails.text;
        if (exceptionDetails.exception?.description) {
            let description = exceptionDetails.exception.description;
            if (description.indexOf('\n') !== -1) {
                description = description.substring(0, description.indexOf('\n'));
            }
            text += ' ' + description;
        }
        return text;
    }
    exceptionThrown(timestamp, exceptionDetails) {
        const exceptionWithTimestamp = { timestamp, details: exceptionDetails };
        this.dispatchEventToListeners(Events$9.ExceptionThrown, exceptionWithTimestamp);
    }
    exceptionRevoked(exceptionId) {
        this.dispatchEventToListeners(Events$9.ExceptionRevoked, exceptionId);
    }
    consoleAPICalled(type, args, executionContextId, timestamp, stackTrace, context) {
        const consoleAPICall = {
            type,
            args,
            executionContextId,
            timestamp,
            stackTrace,
            context,
        };
        this.dispatchEventToListeners(Events$9.ConsoleAPICalled, consoleAPICall);
    }
    executionContextIdForScriptId(scriptId) {
        const script = this.debuggerModel().scriptForId(scriptId);
        return script ? script.executionContextId : 0;
    }
    executionContextForStackTrace(stackTrace) {
        let currentStackTrace = stackTrace;
        while (currentStackTrace && !currentStackTrace.callFrames.length) {
            currentStackTrace = currentStackTrace.parent || null;
        }
        if (!currentStackTrace?.callFrames.length) {
            return 0;
        }
        return this.executionContextIdForScriptId(currentStackTrace.callFrames[0].scriptId);
    }
    terminateExecution() {
        return this.agent.invoke_terminateExecution();
    }
    async getExceptionDetails(errorObjectId) {
        const response = await this.agent.invoke_getExceptionDetails({ errorObjectId });
        if (response.getError()) {
            return undefined;
        }
        return response.exceptionDetails;
    }
}
var Events$9;
(function (Events) {
    Events["BindingCalled"] = "BindingCalled";
    Events["ExecutionContextCreated"] = "ExecutionContextCreated";
    Events["ExecutionContextDestroyed"] = "ExecutionContextDestroyed";
    Events["ExecutionContextChanged"] = "ExecutionContextChanged";
    Events["ExecutionContextOrderChanged"] = "ExecutionContextOrderChanged";
    Events["ExceptionThrown"] = "ExceptionThrown";
    Events["ExceptionRevoked"] = "ExceptionRevoked";
    Events["ConsoleAPICalled"] = "ConsoleAPICalled";
    Events["QueryObjectRequested"] = "QueryObjectRequested";
})(Events$9 || (Events$9 = {}));
class RuntimeDispatcher {
    #runtimeModel;
    constructor(runtimeModel) {
        this.#runtimeModel = runtimeModel;
    }
    executionContextCreated({ context }) {
        this.#runtimeModel.executionContextCreated(context);
    }
    executionContextDestroyed({ executionContextId }) {
        this.#runtimeModel.executionContextDestroyed(executionContextId);
    }
    executionContextsCleared() {
        this.#runtimeModel.executionContextsCleared();
    }
    exceptionThrown({ timestamp, exceptionDetails }) {
        this.#runtimeModel.exceptionThrown(timestamp, exceptionDetails);
    }
    exceptionRevoked({ exceptionId }) {
        this.#runtimeModel.exceptionRevoked(exceptionId);
    }
    consoleAPICalled({ type, args, executionContextId, timestamp, stackTrace, context }) {
        this.#runtimeModel.consoleAPICalled(type, args, executionContextId, timestamp, stackTrace, context);
    }
    inspectRequested({ object, hints, executionContextId }) {
        this.#runtimeModel.inspectRequested(object, hints, executionContextId);
    }
    bindingCalled(event) {
        this.#runtimeModel.bindingCalled(event);
    }
}
class ExecutionContext {
    id;
    uniqueId;
    name;
    #label;
    origin;
    isDefault;
    runtimeModel;
    debuggerModel;
    frameId;
    constructor(runtimeModel, id, uniqueId, name, origin, isDefault, frameId) {
        this.id = id;
        this.uniqueId = uniqueId;
        this.name = name;
        this.#label = null;
        this.origin = origin;
        this.isDefault = isDefault;
        this.runtimeModel = runtimeModel;
        this.debuggerModel = runtimeModel.debuggerModel();
        this.frameId = frameId;
        this.#setLabel('');
    }
    target() {
        return this.runtimeModel.target();
    }
    static comparator(a, b) {
        function targetWeight(target) {
            if (target.parentTarget()?.type() !== Type$2.FRAME) {
                return 5;
            }
            if (target.type() === Type$2.FRAME) {
                return 4;
            }
            if (target.type() === Type$2.ServiceWorker) {
                return 3;
            }
            if (target.type() === Type$2.Worker || target.type() === Type$2.SHARED_WORKER) {
                return 2;
            }
            return 1;
        }
        function targetPath(target) {
            let currentTarget = target;
            const parents = [];
            while (currentTarget) {
                parents.push(currentTarget);
                currentTarget = currentTarget.parentTarget();
            }
            return parents.reverse();
        }
        const tagetsA = targetPath(a.target());
        const targetsB = targetPath(b.target());
        let targetA;
        let targetB;
        for (let i = 0;; i++) {
            if (!tagetsA[i] || !targetsB[i] || (tagetsA[i] !== targetsB[i])) {
                targetA = tagetsA[i];
                targetB = targetsB[i];
                break;
            }
        }
        if (!targetA && targetB) {
            return -1;
        }
        if (!targetB && targetA) {
            return 1;
        }
        if (targetA && targetB) {
            const weightDiff = targetWeight(targetA) - targetWeight(targetB);
            if (weightDiff) {
                return -weightDiff;
            }
            return targetA.id().localeCompare(targetB.id());
        }
        if (a.isDefault) {
            return -1;
        }
        if (b.isDefault) {
            return 1;
        }
        return a.name.localeCompare(b.name);
    }
    async evaluate(options, userGesture, awaitPromise) {
        if (this.debuggerModel.selectedCallFrame()) {
            return await this.debuggerModel.evaluateOnSelectedCallFrame(options);
        }
        return await this.evaluateGlobal(options, userGesture, awaitPromise);
    }
    globalObject(objectGroup, generatePreview) {
        const evaluationOptions = {
            expression: 'this',
            objectGroup,
            includeCommandLineAPI: false,
            silent: true,
            returnByValue: false,
            generatePreview,
        };
        return this.evaluateGlobal(evaluationOptions, false, false);
    }
    async callFunctionOn(options) {
        const response = await this.runtimeModel.agent.invoke_callFunctionOn({
            functionDeclaration: options.functionDeclaration,
            returnByValue: options.returnByValue,
            userGesture: options.userGesture,
            awaitPromise: options.awaitPromise,
            throwOnSideEffect: options.throwOnSideEffect,
            arguments: options.arguments,
            ...(this.uniqueId ? { uniqueContextId: this.uniqueId } : { contextId: this.id }),
        });
        const error = response.getError();
        if (error) {
            return { error };
        }
        return { object: this.runtimeModel.createRemoteObject(response.result), exceptionDetails: response.exceptionDetails };
    }
    async evaluateGlobal(options, userGesture, awaitPromise) {
        if (!options.expression) {
            options.expression = 'this';
        }
        const response = await this.runtimeModel.agent.invoke_evaluate({
            expression: options.expression,
            objectGroup: options.objectGroup,
            includeCommandLineAPI: options.includeCommandLineAPI,
            silent: options.silent,
            returnByValue: options.returnByValue,
            generatePreview: options.generatePreview,
            userGesture,
            awaitPromise,
            throwOnSideEffect: options.throwOnSideEffect,
            timeout: options.timeout,
            disableBreaks: options.disableBreaks,
            replMode: options.replMode,
            allowUnsafeEvalBlockedByCSP: options.allowUnsafeEvalBlockedByCSP,
            ...(this.uniqueId ? { uniqueContextId: this.uniqueId } : { contextId: this.id }),
        });
        const error = response.getError();
        if (error) {
            console.error(error);
            return { error };
        }
        return { object: this.runtimeModel.createRemoteObject(response.result), exceptionDetails: response.exceptionDetails };
    }
    async globalLexicalScopeNames() {
        const response = await this.runtimeModel.agent.invoke_globalLexicalScopeNames({ executionContextId: this.id });
        return response.getError() ? [] : response.names;
    }
    label() {
        return this.#label;
    }
    setLabel(label) {
        this.#setLabel(label);
        this.runtimeModel.dispatchEventToListeners(Events$9.ExecutionContextChanged, this);
    }
    #setLabel(label) {
        if (label) {
            this.#label = label;
            return;
        }
        if (this.name) {
            this.#label = this.name;
            return;
        }
        const parsedUrl = ParsedURL.fromString(this.origin);
        this.#label = parsedUrl ? parsedUrl.lastPathComponentWithFragment() : '';
    }
}
SDKModel.register(RuntimeModel, { capabilities: 4 , autostart: true });

// Copyright 2021 The Chromium Authors
var DOMNodeEvents;
(function (DOMNodeEvents) {
    DOMNodeEvents["TOP_LAYER_INDEX_CHANGED"] = "TopLayerIndexChanged";
    DOMNodeEvents["SCROLLABLE_FLAG_UPDATED"] = "ScrollableFlagUpdated";
    DOMNodeEvents["AD_RELATED_STATE_UPDATED"] = "AdRelatedStateUpdated";
    DOMNodeEvents["GRID_OVERLAY_STATE_CHANGED"] = "GridOverlayStateChanged";
    DOMNodeEvents["FLEX_CONTAINER_OVERLAY_STATE_CHANGED"] = "FlexContainerOverlayStateChanged";
    DOMNodeEvents["SCROLL_SNAP_OVERLAY_STATE_CHANGED"] = "ScrollSnapOverlayStateChanged";
    DOMNodeEvents["CONTAINER_QUERY_OVERLAY_STATE_CHANGED"] = "ContainerQueryOverlayStateChanged";
})(DOMNodeEvents || (DOMNodeEvents = {}));
class DOMNode extends ObjectWrapper {
    #domModel;
    #agent;
    ownerDocument;
    #isInShadowTree;
    id;
    index = undefined;
    #backendNodeId;
    #nodeType;
    #nodeName;
    #localName;
    nodeValueInternal;
    #pseudoType;
    #pseudoIdentifier;
    #shadowRootType;
    #frameOwnerFrameId;
    #xmlVersion;
    #isSVGNode;
    #isScrollable;
    #affectedByStartingStyles;
    #creationStackTrace = null;
    #pseudoElements = new Map();
    #distributedNodes = [];
    assignedSlot = null;
    shadowRootsInternal = [];
    #attributes = new Map();
    #markers = new Map();
    #subtreeMarkerCount = 0;
    childNodeCountInternal;
    childrenInternal = null;
    nextSibling = null;
    previousSibling = null;
    firstChild = null;
    lastChild = null;
    parentNode = null;
    templateContentInternal;
    contentDocumentInternal;
    childDocumentPromiseForTesting;
    #importedDocument;
    publicId;
    systemId;
    internalSubset;
    name;
    value;
    retained = false;
    detached = false;
    #retainedNodes;
    #adoptedStyleSheets = [];
    #topLayerIndex = -1;
    #isAdRelatedInternal = false;
    constructor(domModel) {
        super();
        this.#domModel = domModel;
        this.#agent = this.#domModel.getAgent();
    }
    static create(domModel, doc, isInShadowTree, payload, retainedNodes) {
        const node = new DOMNode(domModel);
        node.init(doc, isInShadowTree, payload, retainedNodes);
        return node;
    }
    init(doc, isInShadowTree, payload, retainedNodes) {
        this.#agent = this.#domModel.getAgent();
        this.ownerDocument = doc;
        this.#isInShadowTree = isInShadowTree;
        this.id = payload.nodeId;
        this.#backendNodeId = payload.backendNodeId;
        this.#frameOwnerFrameId = payload.frameId || null;
        this.#domModel.registerNode(this);
        this.#nodeType = payload.nodeType;
        this.#nodeName = payload.nodeName;
        this.#localName = payload.localName;
        this.nodeValueInternal = payload.nodeValue;
        this.#pseudoType = payload.pseudoType;
        this.#pseudoIdentifier = payload.pseudoIdentifier;
        this.#shadowRootType = payload.shadowRootType;
        this.#xmlVersion = payload.xmlVersion;
        this.#isSVGNode = Boolean(payload.isSVG);
        this.#isScrollable = Boolean(payload.isScrollable);
        this.#affectedByStartingStyles = Boolean(payload.affectedByStartingStyles);
        this.#retainedNodes = retainedNodes;
        if (this.#retainedNodes?.has(this.backendNodeId())) {
            this.retained = true;
        }
        if (payload.attributes) {
            this.setAttributesPayload(payload.attributes);
        }
        if (payload.adoptedStyleSheets) {
            this.#adoptedStyleSheets = this.toAdoptedStyleSheets(payload.adoptedStyleSheets);
        }
        this.childNodeCountInternal = payload.childNodeCount || 0;
        if (payload.shadowRoots) {
            for (let i = 0; i < payload.shadowRoots.length; ++i) {
                const root = payload.shadowRoots[i];
                const node = DOMNode.create(this.#domModel, this.ownerDocument, true, root, retainedNodes);
                this.shadowRootsInternal.push(node);
                node.parentNode = this;
            }
        }
        if (payload.templateContent) {
            this.templateContentInternal =
                DOMNode.create(this.#domModel, this.ownerDocument, true, payload.templateContent, retainedNodes);
            this.templateContentInternal.parentNode = this;
            this.childrenInternal = [];
        }
        const frameOwnerTags = new Set(['EMBED', 'IFRAME', 'OBJECT', 'FENCEDFRAME']);
        if (payload.contentDocument) {
            this.contentDocumentInternal = new DOMDocument(this.#domModel, payload.contentDocument);
            this.contentDocumentInternal.parentNode = this;
            this.childrenInternal = [];
        }
        else if (payload.frameId && frameOwnerTags.has(payload.nodeName)) {
            this.childDocumentPromiseForTesting = this.requestChildDocument(payload.frameId, this.#domModel.target());
            this.childrenInternal = [];
        }
        if (payload.importedDocument) {
            this.#importedDocument =
                DOMNode.create(this.#domModel, this.ownerDocument, true, payload.importedDocument, retainedNodes);
            this.#importedDocument.parentNode = this;
            this.childrenInternal = [];
        }
        if (payload.distributedNodes) {
            this.setDistributedNodePayloads(payload.distributedNodes);
        }
        if (payload.assignedSlot) {
            this.setAssignedSlot(payload.assignedSlot);
        }
        if (payload.children) {
            this.setChildrenPayload(payload.children);
        }
        this.setPseudoElements(payload.pseudoElements);
        if (payload.isAdRelated) {
            this.#isAdRelatedInternal = true;
        }
        if (this.#nodeType === Node.ELEMENT_NODE) {
            if (this.ownerDocument && !this.ownerDocument.documentElement && this.#nodeName === 'HTML') {
                this.ownerDocument.documentElement = this;
            }
            if (this.ownerDocument && !this.ownerDocument.body && this.#nodeName === 'BODY') {
                this.ownerDocument.body = this;
            }
        }
        else if (this.#nodeType === Node.DOCUMENT_TYPE_NODE) {
            this.publicId = payload.publicId;
            this.systemId = payload.systemId;
            this.internalSubset = payload.internalSubset;
        }
        else if (this.#nodeType === Node.ATTRIBUTE_NODE) {
            this.name = payload.name;
            this.value = payload.value;
        }
    }
    async requestChildDocument(frameId, notInTarget) {
        const frame = await FrameManager.instance().getOrWaitForFrame(frameId, notInTarget);
        const childModel = frame.resourceTreeModel()?.target().model(DOMModel);
        return await (childModel?.requestDocument() || null);
    }
    setTopLayerIndex(idx) {
        const oldIndex = this.#topLayerIndex;
        this.#topLayerIndex = idx;
        if (oldIndex !== idx) {
            this.dispatchEventToListeners(DOMNodeEvents.TOP_LAYER_INDEX_CHANGED);
        }
    }
    topLayerIndex() {
        return this.#topLayerIndex;
    }
    isAdRelatedNode() {
        if (this.isIframe() && this.#frameOwnerFrameId) {
            const frame = FrameManager.instance().getFrame(this.#frameOwnerFrameId);
            if (!frame) {
                return false;
            }
            return frame.adFrameType() !== "none" ;
        }
        return this.#isAdRelatedInternal;
    }
    isRootNode() {
        if (this.nodeType() === Node.ELEMENT_NODE && this.nodeName() === 'HTML') {
            return true;
        }
        return false;
    }
    isSVGNode() {
        return this.#isSVGNode;
    }
    isScrollable() {
        return this.#isScrollable;
    }
    affectedByStartingStyles() {
        return this.#affectedByStartingStyles;
    }
    isMediaNode() {
        return this.#nodeName === 'AUDIO' || this.#nodeName === 'VIDEO';
    }
    isViewTransitionPseudoNode() {
        if (!this.#pseudoType) {
            return false;
        }
        return [
            "view-transition" ,
            "view-transition-group" ,
            "view-transition-group-children" ,
            "view-transition-image-pair" ,
            "view-transition-old" ,
            "view-transition-new" ,
        ].includes(this.#pseudoType);
    }
    creationStackTrace() {
        if (this.#creationStackTrace) {
            return this.#creationStackTrace;
        }
        const stackTracesPromise = this.#agent.invoke_getNodeStackTraces({ nodeId: this.id });
        this.#creationStackTrace = stackTracesPromise.then(res => res.creation || null);
        return this.#creationStackTrace;
    }
    get subtreeMarkerCount() {
        return this.#subtreeMarkerCount;
    }
    domModel() {
        return this.#domModel;
    }
    backendNodeId() {
        return this.#backendNodeId;
    }
    children() {
        return this.childrenInternal ? this.childrenInternal.slice() : null;
    }
    setChildren(children) {
        this.childrenInternal = children;
    }
    setIsScrollable(isScrollable) {
        this.#isScrollable = isScrollable;
        this.dispatchEventToListeners(DOMNodeEvents.SCROLLABLE_FLAG_UPDATED);
        if (this.nodeName() === '#document') {
            this.ownerDocument?.documentElement?.setIsScrollable(isScrollable);
        }
    }
    setIsAdRelated(isAdRelated) {
        this.#isAdRelatedInternal = isAdRelated;
        this.dispatchEventToListeners(DOMNodeEvents.AD_RELATED_STATE_UPDATED);
    }
    setAffectedByStartingStyles(affectedByStartingStyles) {
        this.#affectedByStartingStyles = affectedByStartingStyles;
    }
    hasAttributes() {
        return this.#attributes.size > 0;
    }
    childNodeCount() {
        return this.childNodeCountInternal;
    }
    setChildNodeCount(childNodeCount) {
        this.childNodeCountInternal = childNodeCount;
    }
    shadowRoots() {
        return this.shadowRootsInternal.slice();
    }
    templateContent() {
        return this.templateContentInternal || null;
    }
    contentDocument() {
        return this.contentDocumentInternal || null;
    }
    setContentDocument(node) {
        this.contentDocumentInternal = node;
    }
    isIframe() {
        return this.#nodeName === 'IFRAME';
    }
    importedDocument() {
        return this.#importedDocument || null;
    }
    nodeType() {
        return this.#nodeType;
    }
    nodeName() {
        return this.#nodeName;
    }
    pseudoType() {
        return this.#pseudoType;
    }
    pseudoIdentifier() {
        return this.#pseudoIdentifier;
    }
    hasPseudoElements() {
        return this.#pseudoElements.size > 0;
    }
    pseudoElements() {
        return this.#pseudoElements;
    }
    checkmarkPseudoElement() {
        return this.#pseudoElements.get("checkmark" )?.at(-1);
    }
    beforePseudoElement() {
        return this.#pseudoElements.get("before" )?.at(-1);
    }
    afterPseudoElement() {
        return this.#pseudoElements.get("after" )?.at(-1);
    }
    pickerIconPseudoElement() {
        return this.#pseudoElements.get("picker-icon" )?.at(-1);
    }
    markerPseudoElement() {
        return this.#pseudoElements.get("marker" )?.at(-1);
    }
    backdropPseudoElement() {
        return this.#pseudoElements.get("backdrop" )?.at(-1);
    }
    viewTransitionPseudoElements() {
        return [
            ...this.#pseudoElements.get("view-transition" ) || [],
            ...this.#pseudoElements.get("view-transition-group" ) || [],
            ...this.#pseudoElements.get("view-transition-group-children" ) || [],
            ...this.#pseudoElements.get("view-transition-image-pair" ) || [],
            ...this.#pseudoElements.get("view-transition-old" ) || [],
            ...this.#pseudoElements.get("view-transition-new" ) || [],
        ];
    }
    carouselPseudoElements() {
        return [
            ...this.#pseudoElements.get("scroll-button" ) || [],
            ...this.#pseudoElements.get("column" ) || [],
            ...this.#pseudoElements.get("scroll-marker" ) || [],
            ...this.#pseudoElements.get("scroll-marker-group" ) || [],
        ];
    }
    hasAssignedSlot() {
        return this.assignedSlot !== null;
    }
    isInsertionPoint() {
        return !this.isXMLNode() &&
            (this.#nodeName === 'SHADOW' || this.#nodeName === 'CONTENT' || this.#nodeName === 'SLOT');
    }
    distributedNodes() {
        return this.#distributedNodes;
    }
    isInShadowTree() {
        return this.#isInShadowTree;
    }
    getTreeRoot() {
        return this.isShadowRoot() ? this : (this.ancestorShadowRoot() ?? this.ownerDocument ?? this);
    }
    ancestorShadowHost() {
        const ancestorShadowRoot = this.ancestorShadowRoot();
        return ancestorShadowRoot ? ancestorShadowRoot.parentNode : null;
    }
    ancestorShadowRoot() {
        if (!this.#isInShadowTree) {
            return null;
        }
        let current = this;
        while (current && !current.isShadowRoot()) {
            current = current.parentNode;
        }
        return current;
    }
    ancestorUserAgentShadowRoot() {
        const ancestorShadowRoot = this.ancestorShadowRoot();
        if (!ancestorShadowRoot) {
            return null;
        }
        return ancestorShadowRoot.shadowRootType() === DOMNode.ShadowRootTypes.UserAgent ? ancestorShadowRoot : null;
    }
    isShadowRoot() {
        return Boolean(this.#shadowRootType);
    }
    shadowRootType() {
        return this.#shadowRootType || null;
    }
    nodeNameInCorrectCase() {
        const shadowRootType = this.shadowRootType();
        if (shadowRootType) {
            return '#shadow-root (' + shadowRootType + ')';
        }
        if (!this.localName()) {
            return this.nodeName();
        }
        if (this.localName().length !== this.nodeName().length) {
            return this.nodeName();
        }
        return this.localName();
    }
    setNodeName(name, callback) {
        void this.#agent.invoke_setNodeName({ nodeId: this.id, name }).then(response => {
            if (!response.getError()) {
                this.#domModel.markUndoableState();
            }
            if (callback) {
                callback(response.getError() || null, this.#domModel.nodeForId(response.nodeId));
            }
        });
    }
    localName() {
        return this.#localName;
    }
    nodeValue() {
        return this.nodeValueInternal;
    }
    setNodeValueInternal(nodeValue) {
        this.nodeValueInternal = nodeValue;
    }
    setNodeValue(value, callback) {
        void this.#agent.invoke_setNodeValue({ nodeId: this.id, value }).then(response => {
            if (!response.getError()) {
                this.#domModel.markUndoableState();
            }
            if (callback) {
                callback(response.getError() || null);
            }
        });
    }
    getAttribute(name) {
        const attr = this.#attributes.get(name);
        return attr ? attr.value : undefined;
    }
    setAttribute(name, text, callback) {
        void this.#agent.invoke_setAttributesAsText({ nodeId: this.id, text, name }).then(response => {
            if (!response.getError()) {
                this.#domModel.markUndoableState();
            }
            if (callback) {
                callback(response.getError() || null);
            }
        });
    }
    setAttributeValue(name, value, callback) {
        void this.#agent.invoke_setAttributeValue({ nodeId: this.id, name, value }).then(response => {
            if (!response.getError()) {
                this.#domModel.markUndoableState();
            }
            if (callback) {
                callback(response.getError() || null);
            }
        });
    }
    setAttributeValuePromise(name, value) {
        return new Promise(fulfill => this.setAttributeValue(name, value, fulfill));
    }
    attributes() {
        return [...this.#attributes.values()];
    }
    async removeAttribute(name) {
        const response = await this.#agent.invoke_removeAttribute({ nodeId: this.id, name });
        if (response.getError()) {
            return;
        }
        this.#attributes.delete(name);
        this.#domModel.markUndoableState();
    }
    getChildNodesPromise() {
        return new Promise(resolve => {
            return this.getChildNodes(childNodes => resolve(childNodes));
        });
    }
    getChildNodes(callback) {
        if (this.childrenInternal) {
            callback(this.children());
            return;
        }
        void this.#agent.invoke_requestChildNodes({ nodeId: this.id }).then(response => {
            callback(response.getError() ? null : this.children());
        });
    }
    async getSubtree(depth, pierce) {
        console.assert(depth > 0, 'Do not fetch an infinite subtree to avoid crashing the renderer for large documents');
        const response = await this.#agent.invoke_requestChildNodes({ nodeId: this.id, depth, pierce });
        return response.getError() ? null : this.childrenInternal;
    }
    async getOuterHTML(includeShadowDOM = false) {
        const { outerHTML } = await this.#agent.invoke_getOuterHTML({ nodeId: this.id, includeShadowDOM });
        return outerHTML;
    }
    setOuterHTML(html, callback) {
        void this.#agent.invoke_setOuterHTML({ nodeId: this.id, outerHTML: html }).then(response => {
            if (!response.getError()) {
                this.#domModel.markUndoableState();
            }
            if (callback) {
                callback(response.getError() || null);
            }
        });
    }
    removeNode(callback) {
        return this.#agent.invoke_removeNode({ nodeId: this.id }).then(response => {
            if (!response.getError()) {
                this.#domModel.markUndoableState();
            }
            if (callback) {
                callback(response.getError() || null);
            }
        });
    }
    path() {
        function getNodeKey(node) {
            if (!node.#nodeName.length) {
                return null;
            }
            if (node.index !== undefined) {
                return node.index;
            }
            if (!node.parentNode) {
                return null;
            }
            if (node.isShadowRoot()) {
                return node.shadowRootType() === DOMNode.ShadowRootTypes.UserAgent ? 'u' : 'a';
            }
            if (node.nodeType() === Node.DOCUMENT_NODE) {
                return 'd';
            }
            return null;
        }
        const path = [];
        let node = this;
        while (node) {
            const key = getNodeKey(node);
            if (key === null) {
                break;
            }
            path.push([key, node.#nodeName]);
            node = node.parentNode;
        }
        path.reverse();
        return path.join(',');
    }
    isAncestor(node) {
        if (!node) {
            return false;
        }
        let currentNode = node.parentNode;
        while (currentNode) {
            if (this === currentNode) {
                return true;
            }
            currentNode = currentNode.parentNode;
        }
        return false;
    }
    isDescendant(descendant) {
        return descendant.isAncestor(this);
    }
    frameOwnerFrameId() {
        return this.#frameOwnerFrameId;
    }
    frameId() {
        let node = this.parentNode || this;
        while (!node.#frameOwnerFrameId && node.parentNode) {
            node = node.parentNode;
        }
        return node.#frameOwnerFrameId;
    }
    setAttributesPayload(attrs) {
        let attributesChanged = !this.#attributes || attrs.length !== this.#attributes.size * 2;
        const oldAttributesMap = this.#attributes || new Map();
        this.#attributes = new Map();
        for (let i = 0; i < attrs.length; i += 2) {
            const name = attrs[i];
            const value = attrs[i + 1];
            this.addAttribute(name, value);
            if (attributesChanged) {
                continue;
            }
            const oldAttribute = oldAttributesMap.get(name);
            if (oldAttribute?.value !== value) {
                attributesChanged = true;
            }
        }
        return attributesChanged;
    }
    insertChild(prev, payload) {
        if (!this.childrenInternal) {
            throw new Error('DOMNode._children is expected to not be null.');
        }
        const node = DOMNode.create(this.#domModel, this.ownerDocument, this.#isInShadowTree, payload, this.#retainedNodes);
        this.childrenInternal.splice(prev ? this.childrenInternal.indexOf(prev) + 1 : 0, 0, node);
        this.renumber();
        return node;
    }
    removeChild(node) {
        const pseudoType = node.pseudoType();
        if (pseudoType) {
            const updatedPseudoElements = this.#pseudoElements.get(pseudoType)?.filter(element => element !== node);
            if (updatedPseudoElements && updatedPseudoElements.length > 0) {
                this.#pseudoElements.set(pseudoType, updatedPseudoElements);
            }
            else {
                this.#pseudoElements.delete(pseudoType);
            }
        }
        else {
            const shadowRootIndex = this.shadowRootsInternal.indexOf(node);
            if (shadowRootIndex !== -1) {
                this.shadowRootsInternal.splice(shadowRootIndex, 1);
            }
            else {
                if (!this.childrenInternal) {
                    throw new Error('DOMNode._children is expected to not be null.');
                }
                if (this.childrenInternal.indexOf(node) === -1) {
                    throw new Error('DOMNode._children is expected to contain the node to be removed.');
                }
                this.childrenInternal.splice(this.childrenInternal.indexOf(node), 1);
            }
        }
        node.parentNode = null;
        this.#subtreeMarkerCount -= node.#subtreeMarkerCount;
        if (node.#subtreeMarkerCount) {
            this.#domModel.dispatchEventToListeners(Events$8.MarkersChanged, this);
        }
        this.renumber();
    }
    setChildrenPayload(payloads) {
        this.childrenInternal = [];
        for (let i = 0; i < payloads.length; ++i) {
            const payload = payloads[i];
            const node = DOMNode.create(this.#domModel, this.ownerDocument, this.#isInShadowTree, payload, this.#retainedNodes);
            this.childrenInternal.push(node);
        }
        this.renumber();
    }
    setPseudoElements(payloads) {
        if (!payloads) {
            return;
        }
        for (let i = 0; i < payloads.length; ++i) {
            const node = DOMNode.create(this.#domModel, this.ownerDocument, this.#isInShadowTree, payloads[i], this.#retainedNodes);
            node.parentNode = this;
            const pseudoType = node.pseudoType();
            if (!pseudoType) {
                throw new Error('DOMNode.pseudoType() is expected to be defined.');
            }
            const currentPseudoElements = this.#pseudoElements.get(pseudoType);
            if (currentPseudoElements) {
                currentPseudoElements.push(node);
            }
            else {
                this.#pseudoElements.set(pseudoType, [node]);
            }
        }
    }
    toAdoptedStyleSheets(ids) {
        return ids.map(id => (new AdoptedStyleSheet(id, this)));
    }
    setAdoptedStyleSheets(ids) {
        this.#adoptedStyleSheets = this.toAdoptedStyleSheets(ids);
        this.#domModel.dispatchEventToListeners(Events$8.AdoptedStyleSheetsModified, this);
    }
    get adoptedStyleSheetsForNode() {
        return this.#adoptedStyleSheets;
    }
    setDistributedNodePayloads(payloads) {
        this.#distributedNodes = [];
        for (const payload of payloads) {
            this.#distributedNodes.push(new DOMNodeShortcut(this.#domModel.target(), payload.backendNodeId, payload.nodeType, payload.nodeName));
        }
    }
    setAssignedSlot(payload) {
        this.assignedSlot =
            new DOMNodeShortcut(this.#domModel.target(), payload.backendNodeId, payload.nodeType, payload.nodeName);
    }
    renumber() {
        if (!this.childrenInternal) {
            throw new Error('DOMNode._children is expected to not be null.');
        }
        this.childNodeCountInternal = this.childrenInternal.length;
        if (this.childNodeCountInternal === 0) {
            this.firstChild = null;
            this.lastChild = null;
            return;
        }
        this.firstChild = this.childrenInternal[0];
        this.lastChild = this.childrenInternal[this.childNodeCountInternal - 1];
        for (let i = 0; i < this.childNodeCountInternal; ++i) {
            const child = this.childrenInternal[i];
            child.index = i;
            child.nextSibling = i + 1 < this.childNodeCountInternal ? this.childrenInternal[i + 1] : null;
            child.previousSibling = i - 1 >= 0 ? this.childrenInternal[i - 1] : null;
            child.parentNode = this;
        }
    }
    addAttribute(name, value) {
        const attr = { name, value, _node: this };
        this.#attributes.set(name, attr);
    }
    setAttributeInternal(name, value) {
        const attr = this.#attributes.get(name);
        if (attr) {
            attr.value = value;
        }
        else {
            this.addAttribute(name, value);
        }
    }
    removeAttributeInternal(name) {
        this.#attributes.delete(name);
    }
    copyTo(targetNode, anchorNode, callback) {
        void this.#agent
            .invoke_copyTo({ nodeId: this.id, targetNodeId: targetNode.id, insertBeforeNodeId: anchorNode ? anchorNode.id : undefined })
            .then(response => {
            if (!response.getError()) {
                this.#domModel.markUndoableState();
            }
            const pastedNode = this.#domModel.nodeForId(response.nodeId);
            if (pastedNode) {
                for (const [name, value] of this.#markers) {
                    pastedNode.setMarker(name, value);
                }
            }
            if (callback) {
                callback(response.getError() || null, pastedNode);
            }
        });
    }
    moveTo(targetNode, anchorNode, callback) {
        void this.#agent
            .invoke_moveTo({ nodeId: this.id, targetNodeId: targetNode.id, insertBeforeNodeId: anchorNode ? anchorNode.id : undefined })
            .then(response => {
            if (!response.getError()) {
                this.#domModel.markUndoableState();
            }
            if (callback) {
                callback(response.getError() || null, this.#domModel.nodeForId(response.nodeId));
            }
        });
    }
    isXMLNode() {
        return Boolean(this.#xmlVersion);
    }
    setMarker(name, value) {
        if (value === null) {
            if (!this.#markers.has(name)) {
                return;
            }
            this.#markers.delete(name);
            for (let node = this; node; node = node.parentNode) {
                --node.#subtreeMarkerCount;
            }
            for (let node = this; node; node = node.parentNode) {
                this.#domModel.dispatchEventToListeners(Events$8.MarkersChanged, node);
            }
            return;
        }
        if (this.parentNode && !this.#markers.has(name)) {
            for (let node = this; node; node = node.parentNode) {
                ++node.#subtreeMarkerCount;
            }
        }
        this.#markers.set(name, value);
        for (let node = this; node; node = node.parentNode) {
            this.#domModel.dispatchEventToListeners(Events$8.MarkersChanged, node);
        }
    }
    marker(name) {
        return this.#markers.get(name) || null;
    }
    getMarkerKeysForTest() {
        return [...this.#markers.keys()];
    }
    traverseMarkers(visitor) {
        function traverse(node) {
            if (!node.#subtreeMarkerCount) {
                return;
            }
            for (const marker of node.#markers.keys()) {
                visitor(node, marker);
            }
            if (!node.childrenInternal) {
                return;
            }
            for (const child of node.childrenInternal) {
                traverse(child);
            }
        }
        traverse(this);
    }
    resolveURL(url) {
        if (!url) {
            return url;
        }
        for (let frameOwnerCandidate = this; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
            if (frameOwnerCandidate instanceof DOMDocument && frameOwnerCandidate.baseURL) {
                return ParsedURL.completeURL(frameOwnerCandidate.baseURL, url);
            }
        }
        return null;
    }
    highlight(mode) {
        this.#domModel.overlayModel().highlightInOverlay({ node: this }, mode);
    }
    highlightForTwoSeconds() {
        this.#domModel.overlayModel().highlightInOverlayForTwoSeconds({ node: this });
    }
    async resolveToObject(objectGroup, executionContextId) {
        const { object } = await this.#agent.invoke_resolveNode({
            nodeId: this.id,
            executionContextId,
            objectGroup,
        });
        return object && this.#domModel.runtimeModelInternal.createRemoteObject(object) || null;
    }
    async boxModel() {
        const { model } = await this.#agent.invoke_getBoxModel({ nodeId: this.id });
        return model;
    }
    async setAsInspectedNode() {
        let node = this;
        if (node?.pseudoType()) {
            node = node.parentNode;
        }
        while (node) {
            let ancestor = node.ancestorUserAgentShadowRoot();
            if (!ancestor) {
                break;
            }
            ancestor = node.ancestorShadowHost();
            if (!ancestor) {
                break;
            }
            node = ancestor;
        }
        if (!node) {
            throw new Error('In DOMNode.setAsInspectedNode: node is expected to not be null.');
        }
        await this.#agent.invoke_setInspectedNode({ nodeId: node.id });
    }
    enclosingElementOrSelf() {
        let node = this;
        if (node && node.nodeType() === Node.TEXT_NODE && node.parentNode) {
            node = node.parentNode;
        }
        if (node && node.nodeType() !== Node.ELEMENT_NODE) {
            node = null;
        }
        return node;
    }
    async callFunction(fn, args = []) {
        const object = await this.resolveToObject();
        if (!object) {
            return null;
        }
        const result = await object.callFunction(fn, args.map(arg => RemoteObject$1.toCallArgument(arg)));
        object.release();
        if (result.wasThrown || !result.object) {
            return null;
        }
        return {
            value: result.object.value,
        };
    }
    async scrollIntoView() {
        const node = this.enclosingElementOrSelf();
        if (!node) {
            return;
        }
        const result = await node.callFunction(scrollIntoViewInPage);
        if (!result) {
            return;
        }
        node.highlightForTwoSeconds();
        function scrollIntoViewInPage() {
            this.scrollIntoViewIfNeeded(true);
        }
    }
    async focus() {
        const node = this.enclosingElementOrSelf();
        if (!node) {
            throw new Error('DOMNode.focus expects node to not be null.');
        }
        const result = await node.callFunction(focusInPage);
        if (!result) {
            return;
        }
        node.highlightForTwoSeconds();
        await this.#domModel.target().pageAgent().invoke_bringToFront();
        function focusInPage() {
            this.focus();
        }
    }
    simpleSelector() {
        const lowerCaseName = this.localName() || this.nodeName().toLowerCase();
        if (this.nodeType() !== Node.ELEMENT_NODE) {
            return lowerCaseName;
        }
        const type = this.getAttribute('type');
        const id = this.getAttribute('id');
        const classes = this.getAttribute('class');
        if (lowerCaseName === 'input' && type && !id && !classes) {
            return lowerCaseName + '[type="' + CSS.escape(type) + '"]';
        }
        if (id) {
            return lowerCaseName + '#' + CSS.escape(id);
        }
        if (classes) {
            const classList = classes.trim().split(/\s+/g);
            return (lowerCaseName === 'div' ? '' : lowerCaseName) + '.' + classList.map(cls => CSS.escape(cls)).join('.');
        }
        if (this.pseudoIdentifier()) {
            return `${lowerCaseName}(${this.pseudoIdentifier()})`;
        }
        return lowerCaseName;
    }
    async getAnchorBySpecifier(specifier) {
        const response = await this.#agent.invoke_getAnchorElement({
            nodeId: this.id,
            anchorSpecifier: specifier,
        });
        if (response.getError()) {
            return null;
        }
        return this.domModel().nodeForId(response.nodeId);
    }
    classNames() {
        const classes = this.getAttribute('class');
        return classes ? classes.split(/\s+/) : [];
    }
}
(function (DOMNode) {
    (function (ShadowRootTypes) {
        ShadowRootTypes["UserAgent"] = "user-agent";
        ShadowRootTypes["Open"] = "open";
        ShadowRootTypes["Closed"] = "closed";
    })(DOMNode.ShadowRootTypes || (DOMNode.ShadowRootTypes = {}));
})(DOMNode || (DOMNode = {}));
class DeferredDOMNode {
    #domModelInternal;
    #backendNodeIdInternal;
    constructor(target, backendNodeId) {
        this.#domModelInternal = target.model(DOMModel);
        this.#backendNodeIdInternal = backendNodeId;
    }
    resolve(callback) {
        void this.resolvePromise().then(callback);
    }
    async resolvePromise() {
        const nodeIds = await this.#domModelInternal.pushNodesByBackendIdsToFrontend(new Set([this.#backendNodeIdInternal]));
        return nodeIds?.get(this.#backendNodeIdInternal) || null;
    }
    backendNodeId() {
        return this.#backendNodeIdInternal;
    }
    domModel() {
        return this.#domModelInternal;
    }
    highlight() {
        this.#domModelInternal.overlayModel().highlightInOverlay({ deferredNode: this, selectorList: undefined });
    }
}
class DOMNodeShortcut {
    nodeType;
    nodeName;
    deferredNode;
    childShortcuts = [];
    constructor(target, backendNodeId, nodeType, nodeName, childShortcuts = []) {
        this.nodeType = nodeType;
        this.nodeName = nodeName;
        this.deferredNode = new DeferredDOMNode(target, backendNodeId);
        this.childShortcuts = childShortcuts;
    }
}
class DOMDocument extends DOMNode {
    body;
    documentElement;
    documentURL;
    baseURL;
    constructor(domModel, payload) {
        super(domModel);
        this.body = null;
        this.documentElement = null;
        this.init(this, false, payload);
        this.documentURL = (payload.documentURL || '');
        this.baseURL = (payload.baseURL || '');
    }
}
class AdoptedStyleSheet {
    id;
    parent;
    constructor(id, parent) {
        this.id = id;
        this.parent = parent;
    }
    get cssModel() {
        return this.parent.domModel().cssModel();
    }
}
class DOMModel extends SDKModel {
    agent;
    idToDOMNode = new Map();
    frameIdToOwnerNode = new Map();
    #document = null;
    #attributeLoadNodeIds = new Set();
    runtimeModelInternal;
    #lastMutationId;
    #pendingDocumentRequestPromise = null;
    #frameOwnerNode;
    #loadNodeAttributesTimeout;
    #searchId;
    #topLayerThrottler = new Throttler(100);
    #topLayerNodes = [];
    #resourceTreeModel = null;
    constructor(target) {
        super(target);
        this.agent = target.domAgent();
        target.registerDOMDispatcher(new DOMDispatcher(this));
        this.runtimeModelInternal = target.model(RuntimeModel);
        this.#resourceTreeModel = target.model(ResourceTreeModel);
        this.#resourceTreeModel?.addEventListener(Events$6.DocumentOpened, this.onDocumentOpened, this);
        if (!target.suspended()) {
            void this.agent.invoke_enable({});
        }
        if (experiments.isEnabled(ExperimentName.CAPTURE_NODE_CREATION_STACKS)) {
            void this.agent.invoke_setNodeStackTracesEnabled({ enable: true });
        }
    }
    runtimeModel() {
        return this.runtimeModelInternal;
    }
    cssModel() {
        return this.target().model(CSSModel);
    }
    overlayModel() {
        return this.target().model(OverlayModel);
    }
    static cancelSearch() {
        for (const domModel of TargetManager.instance().models(DOMModel)) {
            domModel.cancelSearch();
        }
    }
    scheduleMutationEvent(node) {
        if (!this.hasEventListeners(Events$8.DOMMutated)) {
            return;
        }
        this.#lastMutationId = (this.#lastMutationId || 0) + 1;
        void Promise.resolve().then(callObserve.bind(this, node, this.#lastMutationId));
        function callObserve(node, mutationId) {
            if (!this.hasEventListeners(Events$8.DOMMutated) || this.#lastMutationId !== mutationId) {
                return;
            }
            this.dispatchEventToListeners(Events$8.DOMMutated, node);
        }
    }
    onDocumentOpened(event) {
        const frame = event.data;
        const node = this.frameIdToOwnerNode.get(frame.id);
        if (node) {
            const contentDocument = node.contentDocument();
            if (contentDocument && contentDocument.documentURL !== frame.url) {
                contentDocument.documentURL = frame.url;
                contentDocument.baseURL = frame.url;
                this.dispatchEventToListeners(Events$8.DocumentURLChanged, contentDocument);
            }
        }
    }
    requestDocument() {
        if (this.#document) {
            return Promise.resolve(this.#document);
        }
        if (!this.#pendingDocumentRequestPromise) {
            this.#pendingDocumentRequestPromise = this.requestDocumentInternal();
        }
        return this.#pendingDocumentRequestPromise;
    }
    async getOwnerNodeForFrame(frameId) {
        const response = await this.agent.invoke_getFrameOwner({ frameId });
        if (response.getError()) {
            return null;
        }
        return new DeferredDOMNode(this.target(), response.backendNodeId);
    }
    async requestDocumentInternal() {
        const response = await this.agent.invoke_getDocument({});
        if (response.getError()) {
            return null;
        }
        const { root: documentPayload } = response;
        this.#pendingDocumentRequestPromise = null;
        if (documentPayload) {
            this.setDocument(documentPayload);
        }
        if (!this.#document) {
            console.error('No document');
            return null;
        }
        const parentModel = this.parentModel();
        if (parentModel && !this.#frameOwnerNode) {
            await parentModel.requestDocument();
            const mainFrame = this.target().model(ResourceTreeModel)?.mainFrame;
            if (mainFrame) {
                const response = await parentModel.agent.invoke_getFrameOwner({ frameId: mainFrame.id });
                if (!response.getError() && response.nodeId) {
                    this.#frameOwnerNode = parentModel.nodeForId(response.nodeId);
                }
            }
        }
        if (this.#frameOwnerNode) {
            const oldDocument = this.#frameOwnerNode.contentDocument();
            this.#frameOwnerNode.setContentDocument(this.#document);
            this.#frameOwnerNode.setChildren([]);
            if (this.#document) {
                this.#document.parentNode = this.#frameOwnerNode;
                this.dispatchEventToListeners(Events$8.NodeInserted, this.#document);
            }
            else if (oldDocument) {
                this.dispatchEventToListeners(Events$8.NodeRemoved, { node: oldDocument, parent: this.#frameOwnerNode });
            }
        }
        return this.#document;
    }
    existingDocument() {
        return this.#document;
    }
    async pushNodeToFrontend(objectId) {
        await this.requestDocument();
        const { nodeId } = await this.agent.invoke_requestNode({ objectId });
        return this.nodeForId(nodeId);
    }
    pushNodeByPathToFrontend(path) {
        return this.requestDocument()
            .then(() => this.agent.invoke_pushNodeByPathToFrontend({ path }))
            .then(({ nodeId }) => nodeId);
    }
    async pushNodesByBackendIdsToFrontend(backendNodeIds) {
        await this.requestDocument();
        const backendNodeIdsArray = [...backendNodeIds];
        const { nodeIds } = await this.agent.invoke_pushNodesByBackendIdsToFrontend({ backendNodeIds: backendNodeIdsArray });
        if (!nodeIds) {
            return null;
        }
        const map = new Map();
        for (let i = 0; i < nodeIds.length; ++i) {
            if (nodeIds[i]) {
                map.set(backendNodeIdsArray[i], this.nodeForId(nodeIds[i]));
            }
        }
        return map;
    }
    attributeModified(nodeId, name, value) {
        const node = this.idToDOMNode.get(nodeId);
        if (!node) {
            return;
        }
        node.setAttributeInternal(name, value);
        this.dispatchEventToListeners(Events$8.AttrModified, { node, name });
        this.scheduleMutationEvent(node);
    }
    attributeRemoved(nodeId, name) {
        const node = this.idToDOMNode.get(nodeId);
        if (!node) {
            return;
        }
        node.removeAttributeInternal(name);
        this.dispatchEventToListeners(Events$8.AttrRemoved, { node, name });
        this.scheduleMutationEvent(node);
    }
    inlineStyleInvalidated(nodeIds) {
        nodeIds.forEach(nodeId => this.#attributeLoadNodeIds.add(nodeId));
        if (!this.#loadNodeAttributesTimeout) {
            this.#loadNodeAttributesTimeout = window.setTimeout(this.loadNodeAttributes.bind(this), 20);
        }
    }
    loadNodeAttributes() {
        this.#loadNodeAttributesTimeout = undefined;
        for (const nodeId of this.#attributeLoadNodeIds) {
            void this.agent.invoke_getAttributes({ nodeId }).then(({ attributes }) => {
                if (!attributes) {
                    return;
                }
                const node = this.idToDOMNode.get(nodeId);
                if (!node) {
                    return;
                }
                if (node.setAttributesPayload(attributes)) {
                    this.dispatchEventToListeners(Events$8.AttrModified, { node, name: 'style' });
                    this.scheduleMutationEvent(node);
                }
            });
        }
        this.#attributeLoadNodeIds.clear();
    }
    characterDataModified(nodeId, newValue) {
        const node = this.idToDOMNode.get(nodeId);
        if (!node) {
            console.error('nodeId could not be resolved to a node');
            return;
        }
        node.setNodeValueInternal(newValue);
        this.dispatchEventToListeners(Events$8.CharacterDataModified, node);
        this.scheduleMutationEvent(node);
    }
    nodeForId(nodeId) {
        return nodeId ? this.idToDOMNode.get(nodeId) || null : null;
    }
    documentUpdated() {
        const alreadyHasDocument = Boolean(this.#document);
        this.setDocument(null);
        if (this.parentModel() && alreadyHasDocument && !this.#pendingDocumentRequestPromise) {
            void this.requestDocument();
        }
    }
    setDocument(payload) {
        this.idToDOMNode = new Map();
        this.frameIdToOwnerNode = new Map();
        if (payload && 'nodeId' in payload) {
            this.#document = new DOMDocument(this, payload);
        }
        else {
            this.#document = null;
        }
        DOMModelUndoStack.instance().dispose(this);
        if (!this.parentModel()) {
            this.dispatchEventToListeners(Events$8.DocumentUpdated, this);
        }
    }
    setDocumentForTest(document) {
        this.setDocument(document);
    }
    setDetachedRoot(payload) {
        if (payload.nodeName === '#document') {
            new DOMDocument(this, payload);
        }
        else {
            DOMNode.create(this, null, false, payload);
        }
    }
    setChildNodes(parentId, payloads) {
        if (!parentId && payloads.length) {
            this.setDetachedRoot(payloads[0]);
            return;
        }
        const parent = this.idToDOMNode.get(parentId);
        parent?.setChildrenPayload(payloads);
    }
    childNodeCountUpdated(nodeId, newValue) {
        const node = this.idToDOMNode.get(nodeId);
        if (!node) {
            console.error('nodeId could not be resolved to a node');
            return;
        }
        node.setChildNodeCount(newValue);
        this.dispatchEventToListeners(Events$8.ChildNodeCountUpdated, node);
        this.scheduleMutationEvent(node);
    }
    childNodeInserted(parentId, prevId, payload) {
        const parent = this.idToDOMNode.get(parentId);
        const prev = this.idToDOMNode.get(prevId);
        if (!parent) {
            console.error('parentId could not be resolved to a node');
            return;
        }
        const node = parent.insertChild(prev, payload);
        this.idToDOMNode.set(node.id, node);
        this.dispatchEventToListeners(Events$8.NodeInserted, node);
        this.scheduleMutationEvent(node);
    }
    childNodeRemoved(parentId, nodeId) {
        const parent = this.idToDOMNode.get(parentId);
        const node = this.idToDOMNode.get(nodeId);
        if (!parent || !node) {
            console.error('parentId or nodeId could not be resolved to a node');
            return;
        }
        parent.removeChild(node);
        this.unbind(node);
        this.dispatchEventToListeners(Events$8.NodeRemoved, { node, parent });
        this.scheduleMutationEvent(node);
    }
    shadowRootPushed(hostId, root) {
        const host = this.idToDOMNode.get(hostId);
        if (!host) {
            return;
        }
        const node = DOMNode.create(this, host.ownerDocument, true, root);
        node.parentNode = host;
        this.idToDOMNode.set(node.id, node);
        host.shadowRootsInternal.unshift(node);
        this.dispatchEventToListeners(Events$8.NodeInserted, node);
        this.scheduleMutationEvent(node);
    }
    shadowRootPopped(hostId, rootId) {
        const host = this.idToDOMNode.get(hostId);
        if (!host) {
            return;
        }
        const root = this.idToDOMNode.get(rootId);
        if (!root) {
            return;
        }
        host.removeChild(root);
        this.unbind(root);
        this.dispatchEventToListeners(Events$8.NodeRemoved, { node: root, parent: host });
        this.scheduleMutationEvent(root);
    }
    pseudoElementAdded(parentId, pseudoElement) {
        const parent = this.idToDOMNode.get(parentId);
        if (!parent) {
            return;
        }
        const node = DOMNode.create(this, parent.ownerDocument, false, pseudoElement);
        node.parentNode = parent;
        this.idToDOMNode.set(node.id, node);
        const pseudoType = node.pseudoType();
        if (!pseudoType) {
            throw new Error('DOMModel._pseudoElementAdded expects pseudoType to be defined.');
        }
        const currentPseudoElements = parent.pseudoElements().get(pseudoType);
        if (currentPseudoElements && currentPseudoElements.length > 0) {
            if (!(pseudoType.startsWith('view-transition') || pseudoType.startsWith('scroll-') || pseudoType === 'column')) {
                throw new Error('DOMModel.pseudoElementAdded expects parent to not already have this pseudo type added; only view-transition* and scrolling pseudo elements can coexist under the same parent.' +
                    ` ${currentPseudoElements.length} elements of type ${pseudoType} already exist on parent.`);
            }
            currentPseudoElements.push(node);
        }
        else {
            parent.pseudoElements().set(pseudoType, [node]);
        }
        this.dispatchEventToListeners(Events$8.NodeInserted, node);
        this.scheduleMutationEvent(node);
    }
    adoptedStyleSheetsModified(parentId, styleSheets) {
        const parent = this.idToDOMNode.get(parentId);
        if (!parent) {
            return;
        }
        parent.setAdoptedStyleSheets(styleSheets);
    }
    scrollableFlagUpdated(nodeId, isScrollable) {
        const node = this.nodeForId(nodeId);
        if (!node || node.isScrollable() === isScrollable) {
            return;
        }
        node.setIsScrollable(isScrollable);
    }
    adRelatedStateUpdated(nodeId, isAdRelated) {
        const node = this.nodeForId(nodeId);
        if (!node || node.isAdRelatedNode() === isAdRelated) {
            return;
        }
        node.setIsAdRelated(isAdRelated);
    }
    affectedByStartingStylesFlagUpdated(nodeId, affectedByStartingStyles) {
        const node = this.nodeForId(nodeId);
        if (!node || node.affectedByStartingStyles() === affectedByStartingStyles) {
            return;
        }
        node.setAffectedByStartingStyles(affectedByStartingStyles);
        this.dispatchEventToListeners(Events$8.AffectedByStartingStylesFlagUpdated, { node });
    }
    pseudoElementRemoved(parentId, pseudoElementId) {
        const parent = this.idToDOMNode.get(parentId);
        if (!parent) {
            return;
        }
        const pseudoElement = this.idToDOMNode.get(pseudoElementId);
        if (!pseudoElement) {
            return;
        }
        parent.removeChild(pseudoElement);
        this.unbind(pseudoElement);
        this.dispatchEventToListeners(Events$8.NodeRemoved, { node: pseudoElement, parent });
        this.scheduleMutationEvent(pseudoElement);
    }
    distributedNodesUpdated(insertionPointId, distributedNodes) {
        const insertionPoint = this.idToDOMNode.get(insertionPointId);
        if (!insertionPoint) {
            return;
        }
        insertionPoint.setDistributedNodePayloads(distributedNodes);
        this.dispatchEventToListeners(Events$8.DistributedNodesChanged, insertionPoint);
        this.scheduleMutationEvent(insertionPoint);
    }
    unbind(node) {
        this.idToDOMNode.delete(node.id);
        const frameId = node.frameOwnerFrameId();
        if (frameId) {
            this.frameIdToOwnerNode.delete(frameId);
        }
        const children = node.children();
        for (let i = 0; children && i < children.length; ++i) {
            this.unbind(children[i]);
        }
        for (let i = 0; i < node.shadowRootsInternal.length; ++i) {
            this.unbind(node.shadowRootsInternal[i]);
        }
        const pseudoElements = node.pseudoElements();
        for (const value of pseudoElements.values()) {
            for (const pseudoElement of value) {
                this.unbind(pseudoElement);
            }
        }
        const templateContent = node.templateContent();
        if (templateContent) {
            this.unbind(templateContent);
        }
    }
    async getNodesByStyle(computedStyles, pierce = false) {
        await this.requestDocument();
        if (!this.#document) {
            throw new Error('DOMModel.getNodesByStyle expects to have a document.');
        }
        const response = await this.agent.invoke_getNodesForSubtreeByStyle({ nodeId: this.#document.id, computedStyles, pierce });
        if (response.getError()) {
            throw new Error(response.getError());
        }
        return response.nodeIds;
    }
    async performSearch(query, includeUserAgentShadowDOM) {
        const response = await this.agent.invoke_performSearch({ query, includeUserAgentShadowDOM });
        if (!response.getError()) {
            this.#searchId = response.searchId;
        }
        return response.getError() ? 0 : response.resultCount;
    }
    async searchResult(index) {
        if (!this.#searchId) {
            return null;
        }
        const { nodeIds } = await this.agent.invoke_getSearchResults({ searchId: this.#searchId, fromIndex: index, toIndex: index + 1 });
        return nodeIds?.length === 1 ? this.nodeForId(nodeIds[0]) : null;
    }
    cancelSearch() {
        if (!this.#searchId) {
            return;
        }
        void this.agent.invoke_discardSearchResults({ searchId: this.#searchId });
        this.#searchId = undefined;
    }
    classNamesPromise(nodeId) {
        return this.agent.invoke_collectClassNamesFromSubtree({ nodeId }).then(({ classNames }) => classNames || []);
    }
    querySelector(nodeId, selector) {
        return this.agent.invoke_querySelector({ nodeId, selector }).then(({ nodeId }) => nodeId);
    }
    querySelectorAll(nodeId, selector) {
        return this.agent.invoke_querySelectorAll({ nodeId, selector }).then(({ nodeIds }) => nodeIds);
    }
    getTopLayerElements() {
        return this.agent.invoke_getTopLayerElements().then(({ nodeIds }) => nodeIds);
    }
    topLayerElementsUpdated() {
        void this.#topLayerThrottler.schedule(async () => {
            const result = await this.agent.invoke_getTopLayerElements();
            if (result.getError()) {
                return;
            }
            const previousDocs = new Set();
            for (const node of this.#topLayerNodes) {
                node.setTopLayerIndex(-1);
                if (node.ownerDocument) {
                    previousDocs.add(node.ownerDocument);
                }
            }
            this.#topLayerNodes.splice(0);
            const nodes = result.nodeIds.map(id => this.idToDOMNode.get(id)).filter((node) => Boolean(node));
            const nodesByDocument = new Map();
            for (const node of nodes) {
                const document = node.ownerDocument;
                if (!document) {
                    continue;
                }
                if (!nodesByDocument.has(document)) {
                    nodesByDocument.set(document, []);
                }
                nodesByDocument.get(document)?.push(node);
            }
            for (const [document, nodes] of nodesByDocument) {
                let topLayerIdx = 1;
                const documentShortcuts = [];
                for (const [idx, node] of nodes.entries()) {
                    if (node.nodeName() === '::backdrop') {
                        continue;
                    }
                    const childShortcuts = [];
                    const previousNode = result.nodeIds[idx - 1] ? this.idToDOMNode.get(result.nodeIds[idx - 1]) : null;
                    if (previousNode && previousNode.nodeName() === '::backdrop') {
                        childShortcuts.push(new DOMNodeShortcut(this.target(), previousNode.backendNodeId(), 0, previousNode.nodeName()));
                    }
                    const shortcut = new DOMNodeShortcut(this.target(), node.backendNodeId(), 0, node.nodeName(), childShortcuts);
                    node.setTopLayerIndex(topLayerIdx++);
                    this.#topLayerNodes.push(node);
                    documentShortcuts.push(shortcut);
                    previousDocs.delete(document);
                }
                this.dispatchEventToListeners(Events$8.TopLayerElementsChanged, {
                    document,
                    documentShortcuts,
                });
            }
            for (const document of previousDocs) {
                this.dispatchEventToListeners(Events$8.TopLayerElementsChanged, {
                    document,
                    documentShortcuts: [],
                });
            }
        });
    }
    getDetachedDOMNodes() {
        return this.agent.invoke_getDetachedDomNodes().then(({ detachedNodes }) => detachedNodes);
    }
    getElementByRelation(nodeId, relation) {
        return this.agent.invoke_getElementByRelation({ nodeId, relation }).then(({ nodeId }) => nodeId);
    }
    markUndoableState(minorChange) {
        void DOMModelUndoStack.instance().markUndoableState(this, minorChange || false);
    }
    async nodeForLocation(x, y, includeUserAgentShadowDOM) {
        const response = await this.agent.invoke_getNodeForLocation({ x, y, includeUserAgentShadowDOM });
        if (response.getError() || !response.nodeId) {
            return null;
        }
        return this.nodeForId(response.nodeId);
    }
    async getContainerForNode(nodeId, containerName, physicalAxes, logicalAxes, queriesScrollState, queriesAnchored) {
        const { nodeId: containerNodeId } = await this.agent.invoke_getContainerForNode({ nodeId, containerName, physicalAxes, logicalAxes, queriesScrollState, queriesAnchored });
        if (!containerNodeId) {
            return null;
        }
        return this.nodeForId(containerNodeId);
    }
    pushObjectAsNodeToFrontend(object) {
        return object.isNode() && object.objectId ? this.pushNodeToFrontend(object.objectId) : Promise.resolve(null);
    }
    suspendModel() {
        return this.agent.invoke_disable().then(() => this.setDocument(null));
    }
    async resumeModel() {
        await this.agent.invoke_enable({});
    }
    dispose() {
        this.#resourceTreeModel?.removeEventListener(Events$6.DocumentOpened, this.onDocumentOpened, this);
        DOMModelUndoStack.instance().dispose(this);
    }
    parentModel() {
        const parentTarget = this.target().parentTarget();
        return parentTarget ? parentTarget.model(DOMModel) : null;
    }
    getAgent() {
        return this.agent;
    }
    registerNode(node) {
        this.idToDOMNode.set(node.id, node);
        const frameId = node.frameOwnerFrameId();
        if (frameId) {
            this.frameIdToOwnerNode.set(frameId, node);
        }
    }
}
var Events$8;
(function (Events) {
    Events["AttrModified"] = "AttrModified";
    Events["AttrRemoved"] = "AttrRemoved";
    Events["CharacterDataModified"] = "CharacterDataModified";
    Events["DOMMutated"] = "DOMMutated";
    Events["DocumentURLChanged"] = "DocumentURLChanged";
    Events["NodeInserted"] = "NodeInserted";
    Events["NodeRemoved"] = "NodeRemoved";
    Events["DocumentUpdated"] = "DocumentUpdated";
    Events["ChildNodeCountUpdated"] = "ChildNodeCountUpdated";
    Events["DistributedNodesChanged"] = "DistributedNodesChanged";
    Events["MarkersChanged"] = "MarkersChanged";
    Events["TopLayerElementsChanged"] = "TopLayerElementsChanged";
    Events["AffectedByStartingStylesFlagUpdated"] = "AffectedByStartingStylesFlagUpdated";
    Events["AdoptedStyleSheetsModified"] = "AdoptedStyleSheetsModified";
})(Events$8 || (Events$8 = {}));
class DOMDispatcher {
    #domModel;
    constructor(domModel) {
        this.#domModel = domModel;
    }
    documentUpdated() {
        this.#domModel.documentUpdated();
    }
    attributeModified({ nodeId, name, value }) {
        this.#domModel.attributeModified(nodeId, name, value);
    }
    attributeRemoved({ nodeId, name }) {
        this.#domModel.attributeRemoved(nodeId, name);
    }
    adoptedStyleSheetsModified({ nodeId, adoptedStyleSheets }) {
        this.#domModel.adoptedStyleSheetsModified(nodeId, adoptedStyleSheets);
    }
    inlineStyleInvalidated({ nodeIds }) {
        this.#domModel.inlineStyleInvalidated(nodeIds);
    }
    characterDataModified({ nodeId, characterData }) {
        this.#domModel.characterDataModified(nodeId, characterData);
    }
    setChildNodes({ parentId, nodes }) {
        this.#domModel.setChildNodes(parentId, nodes);
    }
    childNodeCountUpdated({ nodeId, childNodeCount }) {
        this.#domModel.childNodeCountUpdated(nodeId, childNodeCount);
    }
    childNodeInserted({ parentNodeId, previousNodeId, node }) {
        this.#domModel.childNodeInserted(parentNodeId, previousNodeId, node);
    }
    childNodeRemoved({ parentNodeId, nodeId }) {
        this.#domModel.childNodeRemoved(parentNodeId, nodeId);
    }
    shadowRootPushed({ hostId, root }) {
        this.#domModel.shadowRootPushed(hostId, root);
    }
    shadowRootPopped({ hostId, rootId }) {
        this.#domModel.shadowRootPopped(hostId, rootId);
    }
    pseudoElementAdded({ parentId, pseudoElement }) {
        this.#domModel.pseudoElementAdded(parentId, pseudoElement);
    }
    pseudoElementRemoved({ parentId, pseudoElementId }) {
        this.#domModel.pseudoElementRemoved(parentId, pseudoElementId);
    }
    distributedNodesUpdated({ insertionPointId, distributedNodes }) {
        this.#domModel.distributedNodesUpdated(insertionPointId, distributedNodes);
    }
    topLayerElementsUpdated() {
        this.#domModel.topLayerElementsUpdated();
    }
    scrollableFlagUpdated({ nodeId, isScrollable }) {
        this.#domModel.scrollableFlagUpdated(nodeId, isScrollable);
    }
    affectedByStartingStylesFlagUpdated({ nodeId, affectedByStartingStyles }) {
        this.#domModel.affectedByStartingStylesFlagUpdated(nodeId, affectedByStartingStyles);
    }
    adRelatedStateUpdated({ nodeId, isAdRelated }) {
        this.#domModel.adRelatedStateUpdated(nodeId, isAdRelated);
    }
}
let domModelUndoStackInstance = null;
class DOMModelUndoStack {
    #stack;
    #index;
    #lastModelWithMinorChange;
    constructor() {
        this.#stack = [];
        this.#index = 0;
        this.#lastModelWithMinorChange = null;
    }
    static instance(opts = { forceNew: null }) {
        const { forceNew } = opts;
        if (!domModelUndoStackInstance || forceNew) {
            domModelUndoStackInstance = new DOMModelUndoStack();
        }
        return domModelUndoStackInstance;
    }
    async markUndoableState(model, minorChange) {
        if (this.#lastModelWithMinorChange && model !== this.#lastModelWithMinorChange) {
            this.#lastModelWithMinorChange.markUndoableState();
            this.#lastModelWithMinorChange = null;
        }
        if (minorChange && this.#lastModelWithMinorChange === model) {
            return;
        }
        this.#stack = this.#stack.slice(0, this.#index);
        this.#stack.push(model);
        this.#index = this.#stack.length;
        if (minorChange) {
            this.#lastModelWithMinorChange = model;
        }
        else {
            await model.getAgent().invoke_markUndoableState();
            this.#lastModelWithMinorChange = null;
        }
    }
    async undo() {
        if (this.#index === 0) {
            return await Promise.resolve();
        }
        --this.#index;
        this.#lastModelWithMinorChange = null;
        await this.#stack[this.#index].getAgent().invoke_undo();
    }
    async redo() {
        if (this.#index >= this.#stack.length) {
            return await Promise.resolve();
        }
        ++this.#index;
        this.#lastModelWithMinorChange = null;
        await this.#stack[this.#index - 1].getAgent().invoke_redo();
    }
    dispose(model) {
        let shift = 0;
        for (let i = 0; i < this.#index; ++i) {
            if (this.#stack[i] === model) {
                ++shift;
            }
        }
        removeElement(this.#stack, model);
        this.#index -= shift;
        if (this.#lastModelWithMinorChange === model) {
            this.#lastModelWithMinorChange = null;
        }
    }
}
SDKModel.register(DOMModel, { capabilities: 2 , autostart: true });

// Copyright 2021 The Chromium Authors
class Resource {
    #resourceTreeModel;
    #request;
    #url;
    #documentURL;
    #frameId;
    #loaderId;
    #type;
    #mimeType;
    #isGenerated;
    #lastModified;
    #contentSize;
    #parsedURL;
    #contentData = null;
    #pendingContentData = null;
    constructor(resourceTreeModel, request, url, documentURL, frameId, loaderId, type, mimeType, lastModified, contentSize) {
        this.#resourceTreeModel = resourceTreeModel;
        this.#request = request;
        this.url = url;
        this.#documentURL = documentURL;
        this.#frameId = frameId;
        this.#loaderId = loaderId;
        this.#type = type || resourceTypes.Other;
        this.#mimeType = mimeType;
        this.#isGenerated = false;
        this.#lastModified = lastModified && isValid(lastModified) ? lastModified : null;
        this.#contentSize = contentSize;
    }
    lastModified() {
        if (this.#lastModified || !this.#request) {
            return this.#lastModified;
        }
        const lastModifiedHeader = this.#request.responseLastModified();
        const date = lastModifiedHeader ? new Date(lastModifiedHeader) : null;
        this.#lastModified = date && isValid(date) ? date : null;
        return this.#lastModified;
    }
    contentSize() {
        if (typeof this.#contentSize === 'number' || !this.#request) {
            return this.#contentSize;
        }
        return this.#request.resourceSize;
    }
    get request() {
        return this.#request;
    }
    get url() {
        return this.#url;
    }
    set url(x) {
        this.#url = x;
        this.#parsedURL = new ParsedURL(x);
    }
    get parsedURL() {
        return this.#parsedURL;
    }
    get documentURL() {
        return this.#documentURL;
    }
    get frameId() {
        return this.#frameId;
    }
    get loaderId() {
        return this.#loaderId;
    }
    get displayName() {
        return this.#parsedURL ? this.#parsedURL.displayName : '';
    }
    resourceType() {
        return this.#request ? this.#request.resourceType() : this.#type;
    }
    get mimeType() {
        return this.#request ? this.#request.mimeType : this.#mimeType;
    }
    get content() {
        if (this.#contentData?.isTextContent) {
            return this.#contentData.text;
        }
        return this.#contentData?.base64 ?? null;
    }
    get isGenerated() {
        return this.#isGenerated;
    }
    set isGenerated(val) {
        this.#isGenerated = val;
    }
    contentURL() {
        return this.#url;
    }
    contentType() {
        if (this.resourceType() === resourceTypes.Document &&
            this.mimeType.indexOf('javascript') !== -1) {
            return resourceTypes.Script;
        }
        return this.resourceType();
    }
    async requestContentData() {
        if (this.#contentData) {
            return this.#contentData;
        }
        if (this.#pendingContentData) {
            return await this.#pendingContentData;
        }
        this.#pendingContentData = this.innerRequestContent().then(contentData => {
            if (!ContentData.isError(contentData)) {
                this.#contentData = contentData;
            }
            this.#pendingContentData = null;
            return contentData;
        });
        return await this.#pendingContentData;
    }
    canonicalMimeType() {
        return this.contentType().canonicalMimeType() || this.mimeType;
    }
    async searchInContent(query, caseSensitive, isRegex) {
        if (!this.frameId) {
            return [];
        }
        if (this.request) {
            return await this.request.searchInContent(query, caseSensitive, isRegex);
        }
        const result = await this.#resourceTreeModel.target().pageAgent().invoke_searchInResource({ frameId: this.frameId, url: this.url, query, caseSensitive, isRegex });
        return performSearchInSearchMatches(result.result || [], query, caseSensitive, isRegex);
    }
    async populateImageSource(image) {
        const contentData = await this.requestContentData();
        if (ContentData.isError(contentData)) {
            return;
        }
        image.src = contentData.asDataUrl() ?? this.#url;
    }
    async innerRequestContent() {
        if (this.request) {
            return await this.request.requestContentData();
        }
        const response = await this.#resourceTreeModel.target().pageAgent().invoke_getResourceContent({ frameId: this.frameId, url: this.url });
        const error = response.getError();
        if (error) {
            return { error };
        }
        return new ContentData(response.content, response.base64Encoded, this.mimeType);
    }
    frame() {
        return this.#frameId ? this.#resourceTreeModel.frameForId(this.#frameId) : null;
    }
    statusCode() {
        return this.#request ? this.#request.statusCode : 0;
    }
}

// Copyright 2016 The Chromium Authors
class SecurityOriginManager extends SDKModel {
    #mainSecurityOrigin = '';
    #unreachableMainSecurityOrigin = '';
    #securityOrigins = new Set();
    updateSecurityOrigins(securityOrigins) {
        const oldOrigins = this.#securityOrigins;
        this.#securityOrigins = securityOrigins;
        for (const origin of oldOrigins) {
            if (!this.#securityOrigins.has(origin)) {
                this.dispatchEventToListeners(Events$7.SecurityOriginRemoved, origin);
            }
        }
        for (const origin of this.#securityOrigins) {
            if (!oldOrigins.has(origin)) {
                this.dispatchEventToListeners(Events$7.SecurityOriginAdded, origin);
            }
        }
    }
    securityOrigins() {
        return [...this.#securityOrigins];
    }
    mainSecurityOrigin() {
        return this.#mainSecurityOrigin;
    }
    unreachableMainSecurityOrigin() {
        return this.#unreachableMainSecurityOrigin;
    }
    setMainSecurityOrigin(securityOrigin, unreachableSecurityOrigin) {
        this.#mainSecurityOrigin = securityOrigin;
        this.#unreachableMainSecurityOrigin = unreachableSecurityOrigin || null;
        this.dispatchEventToListeners(Events$7.MainSecurityOriginChanged, {
            mainSecurityOrigin: this.#mainSecurityOrigin,
            unreachableMainSecurityOrigin: this.#unreachableMainSecurityOrigin,
        });
    }
}
var Events$7;
(function (Events) {
    Events["SecurityOriginAdded"] = "SecurityOriginAdded";
    Events["SecurityOriginRemoved"] = "SecurityOriginRemoved";
    Events["MainSecurityOriginChanged"] = "MainSecurityOriginChanged";
})(Events$7 || (Events$7 = {}));
SDKModel.register(SecurityOriginManager, { capabilities: 0 , autostart: false });

// Copyright 2022 The Chromium Authors
class StorageKeyManager extends SDKModel {
    #mainStorageKey;
    #storageKeys;
    constructor(target) {
        super(target);
        this.#mainStorageKey = '';
        this.#storageKeys = new Set();
    }
    updateStorageKeys(storageKeys) {
        const oldStorageKeys = this.#storageKeys;
        this.#storageKeys = storageKeys;
        for (const storageKey of oldStorageKeys) {
            if (!this.#storageKeys.has(storageKey)) {
                this.dispatchEventToListeners("StorageKeyRemoved" , storageKey);
            }
        }
        for (const storageKey of this.#storageKeys) {
            if (!oldStorageKeys.has(storageKey)) {
                this.dispatchEventToListeners("StorageKeyAdded" , storageKey);
            }
        }
    }
    storageKeys() {
        return [...this.#storageKeys];
    }
    mainStorageKey() {
        return this.#mainStorageKey;
    }
    setMainStorageKey(storageKey) {
        this.#mainStorageKey = storageKey;
        this.dispatchEventToListeners("MainStorageKeyChanged" , {
            mainStorageKey: this.#mainStorageKey,
        });
    }
}
SDKModel.register(StorageKeyManager, { capabilities: 0 , autostart: false });

// Copyright 2011 The Chromium Authors
class ResourceTreeModel extends SDKModel {
    agent;
    storageAgent;
    #securityOriginManager;
    #storageKeyManager;
    framesInternal = new Map();
    #cachedResourcesProcessed = false;
    #pendingReloadOptions = null;
    #reloadSuspensionCount = 0;
    isInterstitialShowing = false;
    mainFrame = null;
    #pendingBackForwardCacheNotUsedEvents = new Set();
    constructor(target) {
        super(target);
        const networkManager = target.model(NetworkManager);
        if (networkManager) {
            networkManager.addEventListener(Events$c.RequestFinished, this.onRequestFinished, this);
            networkManager.addEventListener(Events$c.RequestUpdateDropped, this.onRequestUpdateDropped, this);
        }
        this.agent = target.pageAgent();
        this.storageAgent = target.storageAgent();
        void this.agent.invoke_enable({});
        this.#securityOriginManager = target.model(SecurityOriginManager);
        this.#storageKeyManager = target.model(StorageKeyManager);
        target.registerPageDispatcher(new PageDispatcher(this));
        void this.#buildResourceTree();
    }
    async #buildResourceTree() {
        return await this.agent.invoke_getResourceTree().then(event => {
            this.processCachedResources(event.getError() ? null : event.frameTree);
            if (this.mainFrame) {
                this.processPendingEvents(this.mainFrame);
            }
        });
    }
    static frameForRequest(request) {
        const networkManager = NetworkManager.forRequest(request);
        const resourceTreeModel = networkManager ? networkManager.target().model(ResourceTreeModel) : null;
        if (!resourceTreeModel) {
            return null;
        }
        return request.frameId ? resourceTreeModel.frameForId(request.frameId) : null;
    }
    static frames() {
        const result = [];
        for (const resourceTreeModel of TargetManager.instance().models(ResourceTreeModel)) {
            result.push(...resourceTreeModel.frames());
        }
        return result;
    }
    static resourceForURL(url) {
        for (const resourceTreeModel of TargetManager.instance().models(ResourceTreeModel)) {
            const mainFrame = resourceTreeModel.mainFrame;
            const result = mainFrame ? mainFrame.resourceForURL(url) : null;
            if (result) {
                return result;
            }
        }
        return null;
    }
    static reloadAllPages(bypassCache, scriptToEvaluateOnLoad) {
        for (const resourceTreeModel of TargetManager.instance().models(ResourceTreeModel)) {
            if (resourceTreeModel.target().parentTarget()?.type() !== Type$2.FRAME) {
                resourceTreeModel.reloadPage(bypassCache, scriptToEvaluateOnLoad);
            }
        }
    }
    async storageKeyForFrame(frameId) {
        if (!this.framesInternal.has(frameId)) {
            return null;
        }
        const response = await this.storageAgent.invoke_getStorageKey({ frameId });
        if (response.getError() === 'Frame tree node for given frame not found') {
            return null;
        }
        return response.storageKey;
    }
    domModel() {
        return this.target().model(DOMModel);
    }
    processCachedResources(mainFramePayload) {
        if (mainFramePayload && mainFramePayload.frame.url !== ':') {
            this.dispatchEventToListeners(Events$6.WillLoadCachedResources);
            this.addFramesRecursively(null, mainFramePayload);
            this.target().setInspectedURL(mainFramePayload.frame.url);
        }
        this.#cachedResourcesProcessed = true;
        const runtimeModel = this.target().model(RuntimeModel);
        if (runtimeModel) {
            runtimeModel.setExecutionContextComparator(this.executionContextComparator.bind(this));
            runtimeModel.fireExecutionContextOrderChanged();
        }
        this.dispatchEventToListeners(Events$6.CachedResourcesLoaded, this);
    }
    cachedResourcesLoaded() {
        return this.#cachedResourcesProcessed;
    }
    addFrame(frame, _aboutToNavigate) {
        this.framesInternal.set(frame.id, frame);
        if (frame.isMainFrame()) {
            this.mainFrame = frame;
        }
        this.dispatchEventToListeners(Events$6.FrameAdded, frame);
        this.updateSecurityOrigins();
        void this.updateStorageKeys();
    }
    frameAttached(frameId, parentFrameId, stackTrace) {
        const sameTargetParentFrame = parentFrameId ? (this.framesInternal.get(parentFrameId) || null) : null;
        if (!this.#cachedResourcesProcessed && sameTargetParentFrame) {
            return null;
        }
        if (this.framesInternal.has(frameId)) {
            return null;
        }
        const frame = new ResourceTreeFrame(this, sameTargetParentFrame, frameId, null, stackTrace || null);
        if (parentFrameId && !sameTargetParentFrame) {
            frame.crossTargetParentFrameId = parentFrameId;
        }
        if (frame.isMainFrame() && this.mainFrame) {
            this.frameDetached(this.mainFrame.id, false);
        }
        this.addFrame(frame, true);
        return frame;
    }
    frameNavigated(framePayload, type) {
        const sameTargetParentFrame = framePayload.parentId ? (this.framesInternal.get(framePayload.parentId) || null) : null;
        if (!this.#cachedResourcesProcessed && sameTargetParentFrame) {
            return;
        }
        let frame = this.framesInternal.get(framePayload.id) || null;
        if (!frame) {
            frame = this.frameAttached(framePayload.id, framePayload.parentId || null);
            console.assert(Boolean(frame));
            if (!frame) {
                return;
            }
        }
        this.dispatchEventToListeners(Events$6.FrameWillNavigate, frame);
        frame.navigate(framePayload);
        if (type) {
            frame.backForwardCacheDetails.restoredFromCache = type === "BackForwardCacheRestore" ;
        }
        if (frame.isMainFrame()) {
            this.target().setInspectedURL(frame.url);
        }
        this.dispatchEventToListeners(Events$6.FrameNavigated, frame);
        if (frame.isPrimaryFrame()) {
            this.primaryPageChanged(frame, "Navigation" );
        }
        const resources = frame.resources();
        for (let i = 0; i < resources.length; ++i) {
            this.dispatchEventToListeners(Events$6.ResourceAdded, resources[i]);
        }
        this.updateSecurityOrigins();
        void this.updateStorageKeys();
        if (frame.backForwardCacheDetails.restoredFromCache) {
            FrameManager.instance().modelRemoved(this);
            FrameManager.instance().modelAdded(this);
            void this.#buildResourceTree();
        }
    }
    primaryPageChanged(frame, type) {
        this.processPendingEvents(frame);
        this.dispatchEventToListeners(Events$6.PrimaryPageChanged, { frame, type });
        const networkManager = this.target().model(NetworkManager);
        if (networkManager && frame.isOutermostFrame()) {
            networkManager.clearRequests();
        }
    }
    documentOpened(framePayload) {
        this.frameNavigated(framePayload, undefined);
        const frame = this.framesInternal.get(framePayload.id);
        if (frame) {
            this.dispatchEventToListeners(Events$6.DocumentOpened, frame);
            if (!frame.getResourcesMap().get(framePayload.url)) {
                const frameResource = this.createResourceFromFramePayload(framePayload, framePayload.url, resourceTypes.Document, framePayload.mimeType, null, null);
                frameResource.isGenerated = true;
                frame.addResource(frameResource);
            }
        }
    }
    frameDetached(frameId, isSwap) {
        if (!this.#cachedResourcesProcessed) {
            return;
        }
        const frame = this.framesInternal.get(frameId);
        if (!frame) {
            return;
        }
        const sameTargetParentFrame = frame.sameTargetParentFrame();
        if (sameTargetParentFrame) {
            sameTargetParentFrame.removeChildFrame(frame, isSwap);
        }
        else {
            frame.remove(isSwap);
        }
        this.updateSecurityOrigins();
        void this.updateStorageKeys();
    }
    onRequestFinished(event) {
        if (!this.#cachedResourcesProcessed) {
            return;
        }
        const request = event.data;
        if (request.failed) {
            return;
        }
        const frame = request.frameId ? this.framesInternal.get(request.frameId) : null;
        if (frame) {
            frame.addRequest(request);
        }
    }
    onRequestUpdateDropped(event) {
        if (!this.#cachedResourcesProcessed) {
            return;
        }
        const data = event.data;
        const frameId = data.frameId;
        if (!frameId) {
            return;
        }
        const frame = this.framesInternal.get(frameId);
        if (!frame) {
            return;
        }
        const url = data.url;
        if (frame.getResourcesMap().get(url)) {
            return;
        }
        const resource = new Resource(this, null, url, frame.url, frameId, data.loaderId, resourceTypes[data.resourceType], data.mimeType, data.lastModified, null);
        frame.addResource(resource);
    }
    frameForId(frameId) {
        return this.framesInternal.get(frameId) || null;
    }
    forAllResources(callback) {
        if (this.mainFrame) {
            return this.mainFrame.callForFrameResources(callback);
        }
        return false;
    }
    frames() {
        return [...this.framesInternal.values()];
    }
    addFramesRecursively(sameTargetParentFrame, frameTreePayload) {
        const framePayload = frameTreePayload.frame;
        let frame = this.framesInternal.get(framePayload.id);
        if (!frame) {
            frame = new ResourceTreeFrame(this, sameTargetParentFrame, framePayload.id, framePayload, null);
        }
        if (!sameTargetParentFrame && framePayload.parentId) {
            frame.crossTargetParentFrameId = framePayload.parentId;
        }
        this.addFrame(frame);
        for (const childFrame of frameTreePayload.childFrames || []) {
            this.addFramesRecursively(frame, childFrame);
        }
        for (let i = 0; i < frameTreePayload.resources.length; ++i) {
            const subresource = frameTreePayload.resources[i];
            const resource = this.createResourceFromFramePayload(framePayload, subresource.url, resourceTypes[subresource.type], subresource.mimeType, subresource.lastModified || null, subresource.contentSize || null);
            frame.addResource(resource);
        }
        if (!frame.getResourcesMap().get(framePayload.url)) {
            const frameResource = this.createResourceFromFramePayload(framePayload, framePayload.url, resourceTypes.Document, framePayload.mimeType, null, null);
            frame.addResource(frameResource);
        }
    }
    createResourceFromFramePayload(frame, url, type, mimeType, lastModifiedTime, contentSize) {
        const lastModified = typeof lastModifiedTime === 'number' ? new Date(lastModifiedTime * 1000) : null;
        return new Resource(this, null, url, frame.url, frame.id, frame.loaderId, type, mimeType, lastModified, contentSize);
    }
    suspendReload() {
        this.#reloadSuspensionCount++;
    }
    resumeReload() {
        this.#reloadSuspensionCount--;
        console.assert(this.#reloadSuspensionCount >= 0, 'Unbalanced call to ResourceTreeModel.resumeReload()');
        if (!this.#reloadSuspensionCount && this.#pendingReloadOptions) {
            const { ignoreCache, scriptToEvaluateOnLoad } = this.#pendingReloadOptions;
            this.reloadPage(ignoreCache, scriptToEvaluateOnLoad);
        }
    }
    reloadPage(ignoreCache, scriptToEvaluateOnLoad) {
        const loaderId = this.mainFrame?.loaderId;
        if (!loaderId) {
            return;
        }
        if (!this.#pendingReloadOptions) {
            this.dispatchEventToListeners(Events$6.PageReloadRequested, this);
        }
        if (this.#reloadSuspensionCount) {
            this.#pendingReloadOptions = { ignoreCache, scriptToEvaluateOnLoad };
            return;
        }
        this.#pendingReloadOptions = null;
        const networkManager = this.target().model(NetworkManager);
        if (networkManager) {
            networkManager.clearRequests();
        }
        this.dispatchEventToListeners(Events$6.WillReloadPage);
        void this.agent.invoke_reload({ ignoreCache, scriptToEvaluateOnLoad, loaderId });
    }
    navigate(url) {
        return this.agent.invoke_navigate({ url });
    }
    async navigationHistory() {
        const response = await this.agent.invoke_getNavigationHistory();
        if (response.getError()) {
            return null;
        }
        return { currentIndex: response.currentIndex, entries: response.entries };
    }
    navigateToHistoryEntry(entry) {
        void this.agent.invoke_navigateToHistoryEntry({ entryId: entry.id });
    }
    setLifecycleEventsEnabled(enabled) {
        return this.agent.invoke_setLifecycleEventsEnabled({ enabled });
    }
    async fetchAppManifest() {
        const response = await this.agent.invoke_getAppManifest({});
        if (response.getError()) {
            return { url: response.url, data: null, errors: [] };
        }
        return { url: response.url, data: response.data || null, errors: response.errors };
    }
    async getInstallabilityErrors() {
        const response = await this.agent.invoke_getInstallabilityErrors();
        return response.installabilityErrors || [];
    }
    async getAppId() {
        return await this.agent.invoke_getAppId();
    }
    executionContextComparator(a, b) {
        function framePath(frame) {
            let currentFrame = frame;
            const parents = [];
            while (currentFrame) {
                parents.push(currentFrame);
                currentFrame = currentFrame.sameTargetParentFrame();
            }
            return parents.reverse();
        }
        if (a.target() !== b.target()) {
            return ExecutionContext.comparator(a, b);
        }
        const framesA = a.frameId ? framePath(this.frameForId(a.frameId)) : [];
        const framesB = b.frameId ? framePath(this.frameForId(b.frameId)) : [];
        let frameA;
        let frameB;
        for (let i = 0;; i++) {
            if (!framesA[i] || !framesB[i] || (framesA[i] !== framesB[i])) {
                frameA = framesA[i];
                frameB = framesB[i];
                break;
            }
        }
        if (!frameA && frameB) {
            return -1;
        }
        if (!frameB && frameA) {
            return 1;
        }
        if (frameA && frameB) {
            return frameA.id.localeCompare(frameB.id);
        }
        return ExecutionContext.comparator(a, b);
    }
    getSecurityOriginData() {
        const securityOrigins = new Set();
        let mainSecurityOrigin = null;
        let unreachableMainSecurityOrigin = null;
        for (const frame of this.framesInternal.values()) {
            const origin = frame.securityOrigin;
            if (!origin) {
                continue;
            }
            securityOrigins.add(origin);
            if (frame.isMainFrame()) {
                mainSecurityOrigin = origin;
                if (frame.unreachableUrl()) {
                    const unreachableParsed = new ParsedURL(frame.unreachableUrl());
                    unreachableMainSecurityOrigin = unreachableParsed.securityOrigin();
                }
            }
        }
        return {
            securityOrigins,
            mainSecurityOrigin,
            unreachableMainSecurityOrigin,
        };
    }
    async getStorageKeyData() {
        const storageKeys = new Set();
        let mainStorageKey = null;
        for (const { isMainFrame, storageKey } of await Promise.all([...this.framesInternal.values()].map(f => f.getStorageKey( false).then(k => ({
            isMainFrame: f.isMainFrame(),
            storageKey: k,
        }))))) {
            if (isMainFrame) {
                mainStorageKey = storageKey;
            }
            if (storageKey) {
                storageKeys.add(storageKey);
            }
        }
        return { storageKeys, mainStorageKey };
    }
    updateSecurityOrigins() {
        const data = this.getSecurityOriginData();
        this.#securityOriginManager.setMainSecurityOrigin(data.mainSecurityOrigin || '', data.unreachableMainSecurityOrigin || '');
        this.#securityOriginManager.updateSecurityOrigins(data.securityOrigins);
    }
    async updateStorageKeys() {
        const data = await this.getStorageKeyData();
        this.#storageKeyManager.setMainStorageKey(data.mainStorageKey || '');
        this.#storageKeyManager.updateStorageKeys(data.storageKeys);
    }
    async getMainStorageKey() {
        return this.mainFrame ? await this.mainFrame.getStorageKey( false) : null;
    }
    getMainSecurityOrigin() {
        const data = this.getSecurityOriginData();
        return data.mainSecurityOrigin || data.unreachableMainSecurityOrigin;
    }
    onBackForwardCacheNotUsed(event) {
        if (this.mainFrame && this.mainFrame.id === event.frameId && this.mainFrame.loaderId === event.loaderId) {
            this.mainFrame.setBackForwardCacheDetails(event);
            this.dispatchEventToListeners(Events$6.BackForwardCacheDetailsUpdated, this.mainFrame);
        }
        else {
            this.#pendingBackForwardCacheNotUsedEvents.add(event);
        }
    }
    processPendingEvents(frame) {
        if (!frame.isMainFrame()) {
            return;
        }
        for (const event of this.#pendingBackForwardCacheNotUsedEvents) {
            if (frame.id === event.frameId && frame.loaderId === event.loaderId) {
                frame.setBackForwardCacheDetails(event);
                this.#pendingBackForwardCacheNotUsedEvents.delete(event);
                break;
            }
        }
    }
}
var Events$6;
(function (Events) {
    Events["FrameAdded"] = "FrameAdded";
    Events["FrameNavigated"] = "FrameNavigated";
    Events["FrameDetached"] = "FrameDetached";
    Events["FrameResized"] = "FrameResized";
    Events["FrameWillNavigate"] = "FrameWillNavigate";
    Events["DocumentOpened"] = "DocumentOpened";
    Events["PrimaryPageChanged"] = "PrimaryPageChanged";
    Events["ResourceAdded"] = "ResourceAdded";
    Events["WillLoadCachedResources"] = "WillLoadCachedResources";
    Events["CachedResourcesLoaded"] = "CachedResourcesLoaded";
    Events["DOMContentLoaded"] = "DOMContentLoaded";
    Events["LifecycleEvent"] = "LifecycleEvent";
    Events["Load"] = "Load";
    Events["PageReloadRequested"] = "PageReloadRequested";
    Events["WillReloadPage"] = "WillReloadPage";
    Events["InterstitialShown"] = "InterstitialShown";
    Events["InterstitialHidden"] = "InterstitialHidden";
    Events["BackForwardCacheDetailsUpdated"] = "BackForwardCacheDetailsUpdated";
    Events["JavaScriptDialogOpening"] = "JavaScriptDialogOpening";
})(Events$6 || (Events$6 = {}));
class ResourceTreeFrame {
    #model;
    #sameTargetParentFrame;
    #id;
    crossTargetParentFrameId = null;
    #loaderId;
    #name;
    #url;
    #domainAndRegistry;
    #securityOrigin;
    #securityOriginDetails;
    #storageKey;
    #unreachableUrl;
    #adFrameStatus;
    #secureContextType;
    #crossOriginIsolatedContextType;
    #gatedAPIFeatures;
    #creationStackTrace;
    #creationStackTraceTarget = null;
    #childFrames = new Set();
    resourcesMap = new Map();
    backForwardCacheDetails = {
        explanations: [],
    };
    constructor(model, parentFrame, frameId, payload, creationStackTrace) {
        this.#model = model;
        this.#sameTargetParentFrame = parentFrame;
        this.#id = frameId;
        this.#loaderId = payload?.loaderId ?? '';
        this.#name = payload?.name;
        this.#url = payload && payload.url || EmptyUrlString;
        this.#domainAndRegistry = (payload?.domainAndRegistry) || '';
        this.#securityOrigin = payload?.securityOrigin ?? null;
        this.#securityOriginDetails = payload?.securityOriginDetails;
        this.#unreachableUrl =
            (payload && payload.unreachableUrl) || EmptyUrlString;
        this.#adFrameStatus = payload?.adFrameStatus;
        this.#secureContextType = payload?.secureContextType ?? null;
        this.#crossOriginIsolatedContextType = payload?.crossOriginIsolatedContextType ?? null;
        this.#gatedAPIFeatures = payload?.gatedAPIFeatures ?? null;
        this.#creationStackTrace = creationStackTrace;
        if (this.#sameTargetParentFrame) {
            this.#sameTargetParentFrame.#childFrames.add(this);
        }
    }
    isSecureContext() {
        return this.#secureContextType !== null && this.#secureContextType.startsWith('Secure');
    }
    getSecureContextType() {
        return this.#secureContextType;
    }
    isCrossOriginIsolated() {
        return this.#crossOriginIsolatedContextType !== null && this.#crossOriginIsolatedContextType.startsWith('Isolated');
    }
    getCrossOriginIsolatedContextType() {
        return this.#crossOriginIsolatedContextType;
    }
    getGatedAPIFeatures() {
        return this.#gatedAPIFeatures;
    }
    getCreationStackTraceData() {
        return {
            creationStackTrace: this.#creationStackTrace,
            creationStackTraceTarget: this.#creationStackTraceTarget || this.resourceTreeModel().target(),
        };
    }
    navigate(framePayload) {
        this.#loaderId = framePayload.loaderId;
        this.#name = framePayload.name;
        this.#url = framePayload.url;
        this.#domainAndRegistry = framePayload.domainAndRegistry;
        this.#securityOrigin = framePayload.securityOrigin;
        this.#securityOriginDetails = framePayload.securityOriginDetails;
        void this.getStorageKey( true);
        this.#unreachableUrl =
            framePayload.unreachableUrl || EmptyUrlString;
        this.#adFrameStatus = framePayload?.adFrameStatus;
        this.#secureContextType = framePayload.secureContextType;
        this.#crossOriginIsolatedContextType = framePayload.crossOriginIsolatedContextType;
        this.#gatedAPIFeatures = framePayload.gatedAPIFeatures;
        this.backForwardCacheDetails = {
            explanations: [],
        };
        const mainResource = this.resourcesMap.get(this.#url);
        this.resourcesMap.clear();
        this.removeChildFrames();
        if (mainResource && mainResource.loaderId === this.#loaderId) {
            this.addResource(mainResource);
        }
    }
    resourceTreeModel() {
        return this.#model;
    }
    get id() {
        return this.#id;
    }
    get name() {
        return this.#name || '';
    }
    get url() {
        return this.#url;
    }
    domainAndRegistry() {
        return this.#domainAndRegistry;
    }
    async getAdScriptAncestry(frameId) {
        const res = await this.#model.agent.invoke_getAdScriptAncestry({ frameId });
        return res.adScriptAncestry || null;
    }
    get securityOrigin() {
        return this.#securityOrigin;
    }
    get securityOriginDetails() {
        return this.#securityOriginDetails ?? null;
    }
    getStorageKey(forceFetch) {
        if (!this.#storageKey || forceFetch) {
            this.#storageKey = this.#model.storageKeyForFrame(this.#id);
        }
        return this.#storageKey;
    }
    unreachableUrl() {
        return this.#unreachableUrl;
    }
    get loaderId() {
        return this.#loaderId;
    }
    adFrameType() {
        return this.#adFrameStatus?.adFrameType || "none" ;
    }
    adFrameStatus() {
        return this.#adFrameStatus;
    }
    get childFrames() {
        return [...this.#childFrames];
    }
    sameTargetParentFrame() {
        return this.#sameTargetParentFrame;
    }
    crossTargetParentFrame() {
        if (!this.crossTargetParentFrameId) {
            return null;
        }
        const parentTarget = this.#model.target().parentTarget();
        if (parentTarget?.type() !== Type$2.FRAME) {
            return null;
        }
        const parentModel = parentTarget.model(ResourceTreeModel);
        if (!parentModel) {
            return null;
        }
        return parentModel.framesInternal.get(this.crossTargetParentFrameId) || null;
    }
    parentFrame() {
        return this.sameTargetParentFrame() || this.crossTargetParentFrame();
    }
    isMainFrame() {
        return !this.#sameTargetParentFrame;
    }
    isOutermostFrame() {
        return this.#model.target().parentTarget()?.type() !== Type$2.FRAME && !this.#sameTargetParentFrame &&
            !this.crossTargetParentFrameId;
    }
    isPrimaryFrame() {
        return !this.#sameTargetParentFrame && this.#model.target() === TargetManager.instance().primaryPageTarget();
    }
    removeChildFrame(frame, isSwap) {
        this.#childFrames.delete(frame);
        frame.remove(isSwap);
    }
    removeChildFrames() {
        const frames = this.#childFrames;
        this.#childFrames = new Set();
        for (const frame of frames) {
            frame.remove(false);
        }
    }
    remove(isSwap) {
        this.removeChildFrames();
        this.#model.framesInternal.delete(this.id);
        this.#model.dispatchEventToListeners(Events$6.FrameDetached, { frame: this, isSwap });
    }
    addResource(resource) {
        if (this.resourcesMap.get(resource.url) === resource) {
            return;
        }
        this.resourcesMap.set(resource.url, resource);
        this.#model.dispatchEventToListeners(Events$6.ResourceAdded, resource);
    }
    addRequest(request) {
        let resource = this.resourcesMap.get(request.url());
        if (resource?.request === request) {
            return;
        }
        resource = new Resource(this.#model, request, request.url(), request.documentURL, request.frameId, request.loaderId, request.resourceType(), request.mimeType, null, null);
        this.resourcesMap.set(resource.url, resource);
        this.#model.dispatchEventToListeners(Events$6.ResourceAdded, resource);
    }
    resources() {
        return Array.from(this.resourcesMap.values());
    }
    resourceForURL(url) {
        const resource = this.resourcesMap.get(url);
        if (resource) {
            return resource;
        }
        for (const frame of this.#childFrames) {
            const resource = frame.resourceForURL(url);
            if (resource) {
                return resource;
            }
        }
        return null;
    }
    callForFrameResources(callback) {
        for (const resource of this.resourcesMap.values()) {
            if (callback(resource)) {
                return true;
            }
        }
        for (const frame of this.#childFrames) {
            if (frame.callForFrameResources(callback)) {
                return true;
            }
        }
        return false;
    }
    displayName() {
        if (this.isOutermostFrame()) {
            return lockedString('top');
        }
        const subtitle = new ParsedURL(this.#url).displayName;
        if (subtitle) {
            if (!this.#name) {
                return subtitle;
            }
            return this.#name + ' (' + subtitle + ')';
        }
        return lockedString('iframe');
    }
    async getOwnerDeferredDOMNode() {
        const parentFrame = this.parentFrame();
        if (!parentFrame) {
            return null;
        }
        return await parentFrame.resourceTreeModel().domModel().getOwnerNodeForFrame(this.#id);
    }
    async getOwnerDOMNodeOrDocument() {
        const deferredNode = await this.getOwnerDeferredDOMNode();
        if (deferredNode) {
            return await deferredNode.resolvePromise();
        }
        if (this.isOutermostFrame()) {
            return await this.resourceTreeModel().domModel().requestDocument();
        }
        return null;
    }
    async highlight() {
        const parentFrame = this.parentFrame();
        const parentTarget = this.resourceTreeModel().target().parentTarget();
        const highlightFrameOwner = async (domModel) => {
            const deferredNode = await domModel.getOwnerNodeForFrame(this.#id);
            if (deferredNode) {
                domModel.overlayModel().highlightInOverlay({ deferredNode, selectorList: '' }, 'all', true);
            }
        };
        if (parentFrame) {
            return await highlightFrameOwner(parentFrame.resourceTreeModel().domModel());
        }
        if (parentTarget?.type() === Type$2.FRAME) {
            const domModel = parentTarget.model(DOMModel);
            if (domModel) {
                return await highlightFrameOwner(domModel);
            }
        }
        const document = await this.resourceTreeModel().domModel().requestDocument();
        if (document) {
            this.resourceTreeModel().domModel().overlayModel().highlightInOverlay({ node: document, selectorList: '' }, 'all', true);
        }
    }
    async getPermissionsPolicyState() {
        const response = await this.resourceTreeModel().target().pageAgent().invoke_getPermissionsPolicyState({ frameId: this.#id });
        if (response.getError()) {
            return null;
        }
        return response.states;
    }
    async getOriginTrials() {
        const response = await this.resourceTreeModel().target().pageAgent().invoke_getOriginTrials({ frameId: this.#id });
        if (response.getError()) {
            return [];
        }
        return response.originTrials;
    }
    setCreationStackTrace(creationStackTraceData) {
        this.#creationStackTrace = creationStackTraceData.creationStackTrace;
        this.#creationStackTraceTarget = creationStackTraceData.creationStackTraceTarget;
    }
    setBackForwardCacheDetails(event) {
        this.backForwardCacheDetails.restoredFromCache = false;
        this.backForwardCacheDetails.explanations = event.notRestoredExplanations;
        this.backForwardCacheDetails.explanationsTree = event.notRestoredExplanationsTree;
    }
    getResourcesMap() {
        return this.resourcesMap;
    }
}
class PageDispatcher {
    #resourceTreeModel;
    constructor(resourceTreeModel) {
        this.#resourceTreeModel = resourceTreeModel;
    }
    backForwardCacheNotUsed(params) {
        this.#resourceTreeModel.onBackForwardCacheNotUsed(params);
    }
    domContentEventFired({ timestamp }) {
        this.#resourceTreeModel.dispatchEventToListeners(Events$6.DOMContentLoaded, timestamp);
    }
    loadEventFired({ timestamp }) {
        this.#resourceTreeModel.dispatchEventToListeners(Events$6.Load, { resourceTreeModel: this.#resourceTreeModel, loadTime: timestamp });
    }
    lifecycleEvent({ frameId, name }) {
        this.#resourceTreeModel.dispatchEventToListeners(Events$6.LifecycleEvent, { frameId, name });
    }
    frameAttached({ frameId, parentFrameId, stack }) {
        this.#resourceTreeModel.frameAttached(frameId, parentFrameId, stack);
    }
    frameNavigated({ frame, type }) {
        this.#resourceTreeModel.frameNavigated(frame, type);
    }
    documentOpened({ frame }) {
        this.#resourceTreeModel.documentOpened(frame);
    }
    frameDetached({ frameId, reason }) {
        this.#resourceTreeModel.frameDetached(frameId, reason === "swap" );
    }
    frameSubtreeWillBeDetached(_params) {
    }
    frameStartedLoading({}) {
    }
    frameStoppedLoading({}) {
    }
    frameRequestedNavigation({}) {
    }
    frameScheduledNavigation({}) {
    }
    frameClearedScheduledNavigation({}) {
    }
    frameStartedNavigating({}) {
    }
    navigatedWithinDocument({}) {
    }
    frameResized() {
        this.#resourceTreeModel.dispatchEventToListeners(Events$6.FrameResized);
    }
    javascriptDialogOpening(event) {
        this.#resourceTreeModel.dispatchEventToListeners(Events$6.JavaScriptDialogOpening, event);
        if (!event.hasBrowserHandler) {
            void this.#resourceTreeModel.agent.invoke_handleJavaScriptDialog({ accept: false });
        }
    }
    javascriptDialogClosed({}) {
    }
    screencastFrame({}) {
    }
    screencastVisibilityChanged({}) {
    }
    interstitialShown() {
        this.#resourceTreeModel.isInterstitialShowing = true;
        this.#resourceTreeModel.dispatchEventToListeners(Events$6.InterstitialShown);
    }
    interstitialHidden() {
        this.#resourceTreeModel.isInterstitialShowing = false;
        this.#resourceTreeModel.dispatchEventToListeners(Events$6.InterstitialHidden);
    }
    windowOpen({}) {
    }
    compilationCacheProduced({}) {
    }
    fileChooserOpened({}) {
    }
    downloadWillBegin({}) {
    }
    downloadProgress() {
    }
}
SDKModel.register(ResourceTreeModel, { capabilities: 2 , autostart: true, early: true });

// Copyright 2021 The Chromium Authors
/*
 * Copyright (C) 2008 Apple Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
const UIStrings$_ = {
    scriptRemovedOrDeleted: 'Script removed or deleted.',
    unableToFetchScriptSource: 'Unable to fetch script source.',
};
const str_$Z = registerUIStrings('core/sdk/Script.ts', UIStrings$_);
const i18nString$H = getLocalizedString.bind(undefined, str_$Z);
let scriptCacheInstance = null;
class Script {
    debuggerModel;
    scriptId;
    sourceURL;
    lineOffset;
    columnOffset;
    endLine;
    endColumn;
    executionContextId;
    hash;
    #isContentScript;
    #isLiveEdit;
    sourceMapURL;
    debugSymbols;
    hasSourceURL;
    contentLength;
    originStackTrace;
    #codeOffset;
    #language;
    #contentPromise;
    #embedderName;
    isModule;
    buildId;
    constructor(debuggerModel, scriptId, sourceURL, startLine, startColumn, endLine, endColumn, executionContextId, hash, isContentScript, isLiveEdit, sourceMapURL, hasSourceURL, length, isModule, originStackTrace, codeOffset, scriptLanguage, debugSymbols, embedderName, buildId) {
        this.debuggerModel = debuggerModel;
        this.scriptId = scriptId;
        this.sourceURL = sourceURL;
        this.lineOffset = startLine;
        this.columnOffset = startColumn;
        this.endLine = endLine;
        this.endColumn = endColumn;
        this.isModule = isModule;
        this.buildId = buildId;
        this.executionContextId = executionContextId;
        this.hash = hash;
        this.#isContentScript = isContentScript;
        this.#isLiveEdit = isLiveEdit;
        this.sourceMapURL = sourceMapURL;
        this.debugSymbols = debugSymbols;
        this.hasSourceURL = hasSourceURL;
        this.contentLength = length;
        this.originStackTrace = originStackTrace;
        this.#codeOffset = codeOffset;
        this.#language = scriptLanguage;
        this.#contentPromise = null;
        this.#embedderName = embedderName;
    }
    embedderName() {
        return this.#embedderName;
    }
    target() {
        return this.debuggerModel.target();
    }
    static trimSourceURLComment(source) {
        let sourceURLIndex = source.lastIndexOf('//# sourceURL=');
        if (sourceURLIndex === -1) {
            sourceURLIndex = source.lastIndexOf('//@ sourceURL=');
            if (sourceURLIndex === -1) {
                return source;
            }
        }
        const sourceURLLineIndex = source.lastIndexOf('\n', sourceURLIndex);
        if (sourceURLLineIndex === -1) {
            return source;
        }
        const sourceURLLine = source.substr(sourceURLLineIndex + 1);
        if (!sourceURLLine.match(sourceURLRegex)) {
            return source;
        }
        return source.substr(0, sourceURLLineIndex);
    }
    isContentScript() {
        return this.#isContentScript;
    }
    codeOffset() {
        return this.#codeOffset;
    }
    isJavaScript() {
        return this.#language === "JavaScript" ;
    }
    isWasm() {
        return this.#language === "WebAssembly" ;
    }
    scriptLanguage() {
        return this.#language;
    }
    executionContext() {
        return this.debuggerModel.runtimeModel().executionContext(this.executionContextId);
    }
    isLiveEdit() {
        return this.#isLiveEdit;
    }
    contentURL() {
        return this.sourceURL;
    }
    contentType() {
        return resourceTypes.Script;
    }
    async loadTextContent() {
        const result = await this.debuggerModel.target().debuggerAgent().invoke_getScriptSource({ scriptId: this.scriptId });
        if (result.getError()) {
            throw new Error(result.getError());
        }
        const { scriptSource, bytecode } = result;
        if (bytecode) {
            return new ContentData(bytecode,  true, 'application/wasm');
        }
        let content = scriptSource || '';
        if (this.hasSourceURL && schemeIs(this.sourceURL, 'snippet:')) {
            content = Script.trimSourceURLComment(content);
        }
        return new ContentData(content,  false, 'text/javascript');
    }
    async loadWasmContent() {
        if (!this.isWasm()) {
            throw new Error('Not a wasm script');
        }
        const result = await this.debuggerModel.target().debuggerAgent().invoke_disassembleWasmModule({ scriptId: this.scriptId });
        if (result.getError()) {
            const contentData = await this.loadTextContent();
            return await disassembleWasm(contentData.base64);
        }
        const { streamId, functionBodyOffsets, chunk: { lines, bytecodeOffsets } } = result;
        const lineChunks = [];
        const bytecodeOffsetChunks = [];
        let totalLength = lines.reduce((sum, line) => sum + line.length + 1, 0);
        const truncationMessage = '<truncated>';
        const cmSizeLimit = 1000000000 - truncationMessage.length;
        if (streamId) {
            while (true) {
                const result = await this.debuggerModel.target().debuggerAgent().invoke_nextWasmDisassemblyChunk({ streamId });
                if (result.getError()) {
                    throw new Error(result.getError());
                }
                const { chunk: { lines: linesChunk, bytecodeOffsets: bytecodeOffsetsChunk } } = result;
                totalLength += linesChunk.reduce((sum, line) => sum + line.length + 1, 0);
                if (linesChunk.length === 0) {
                    break;
                }
                if (totalLength >= cmSizeLimit) {
                    lineChunks.push([truncationMessage]);
                    bytecodeOffsetChunks.push([0]);
                    break;
                }
                lineChunks.push(linesChunk);
                bytecodeOffsetChunks.push(bytecodeOffsetsChunk);
            }
        }
        const functionBodyRanges = [];
        for (let i = 0; i < functionBodyOffsets.length; i += 2) {
            functionBodyRanges.push({ start: functionBodyOffsets[i], end: functionBodyOffsets[i + 1] });
        }
        return new WasmDisassembly(lines.concat(...lineChunks), bytecodeOffsets.concat(...bytecodeOffsetChunks), functionBodyRanges);
    }
    requestContentData() {
        if (!this.#contentPromise) {
            const fileSizeToCache = 65535;
            if (this.hash && !this.#isLiveEdit && this.contentLength > fileSizeToCache) {
                if (!scriptCacheInstance) {
                    scriptCacheInstance = {
                        cache: new Map(),
                        registry: new FinalizationRegistry(hashCode => scriptCacheInstance?.cache.delete(hashCode)),
                    };
                }
                const fullHash = [
                    this.#language,
                    this.contentLength,
                    this.lineOffset,
                    this.columnOffset,
                    this.endLine,
                    this.endColumn,
                    this.#codeOffset,
                    this.hash,
                ].join(':');
                const cachedContentPromise = scriptCacheInstance.cache.get(fullHash)?.deref();
                if (cachedContentPromise) {
                    this.#contentPromise = cachedContentPromise;
                }
                else {
                    this.#contentPromise = this.#requestContent();
                    scriptCacheInstance.cache.set(fullHash, new WeakRef(this.#contentPromise));
                    scriptCacheInstance.registry.register(this.#contentPromise, fullHash);
                }
            }
            else {
                this.#contentPromise = this.#requestContent();
            }
        }
        return this.#contentPromise;
    }
    async #requestContent() {
        if (!this.scriptId) {
            return { error: i18nString$H(UIStrings$_.scriptRemovedOrDeleted) };
        }
        try {
            return this.isWasm() ? await this.loadWasmContent() : await this.loadTextContent();
        }
        catch {
            return { error: i18nString$H(UIStrings$_.unableToFetchScriptSource) };
        }
    }
    async getWasmBytecode() {
        const base64 = await this.debuggerModel.target().debuggerAgent().invoke_getWasmBytecode({ scriptId: this.scriptId });
        const response = await fetch(`data:application/wasm;base64,${base64.bytecode}`);
        return await response.arrayBuffer();
    }
    originalContentProvider() {
        return new StaticContentProvider(this.contentURL(), this.contentType(), () => this.requestContentData());
    }
    async searchInContent(query, caseSensitive, isRegex) {
        if (!this.scriptId) {
            return [];
        }
        const matches = await this.debuggerModel.target().debuggerAgent().invoke_searchInContent({ scriptId: this.scriptId, query, caseSensitive, isRegex });
        return performSearchInSearchMatches(matches.result || [], query, caseSensitive, isRegex);
    }
    appendSourceURLCommentIfNeeded(source) {
        if (!this.hasSourceURL) {
            return source;
        }
        return source + '\n //# sourceURL=' + this.sourceURL;
    }
    async editSource(newSource) {
        newSource = Script.trimSourceURLComment(newSource);
        newSource = this.appendSourceURLCommentIfNeeded(newSource);
        const oldSource = ContentData.textOr(await this.requestContentData(), null);
        if (oldSource === newSource) {
            return { changed: false, status: "Ok"  };
        }
        const response = await this.debuggerModel.target().debuggerAgent().invoke_setScriptSource({ scriptId: this.scriptId, scriptSource: newSource, allowTopFrameEditing: true });
        if (response.getError()) {
            throw new Error(`Script#editSource failed for script with id ${this.scriptId}: ${response.getError()}`);
        }
        if (!response.getError() && response.status === "Ok" ) {
            this.#contentPromise =
                Promise.resolve(new ContentData(newSource,  false, 'text/javascript'));
        }
        this.debuggerModel.dispatchEventToListeners(Events$5.ScriptSourceWasEdited, { script: this, status: response.status });
        return { changed: true, status: response.status, exceptionDetails: response.exceptionDetails };
    }
    rawLocation(lineNumber, columnNumber) {
        if (this.containsLocation(lineNumber, columnNumber)) {
            return new Location$1(this.debuggerModel, this.scriptId, lineNumber, columnNumber);
        }
        return null;
    }
    isInlineScript() {
        const startsAtZero = !this.lineOffset && !this.columnOffset;
        return !this.isWasm() && Boolean(this.sourceURL) && !startsAtZero;
    }
    isAnonymousScript() {
        return !this.sourceURL;
    }
    async setBlackboxedRanges(positions) {
        const response = await this.debuggerModel.target().debuggerAgent().invoke_setBlackboxedRanges({ scriptId: this.scriptId, positions });
        return !response.getError();
    }
    containsLocation(lineNumber, columnNumber) {
        const afterStart = (lineNumber === this.lineOffset && columnNumber >= this.columnOffset) || lineNumber > this.lineOffset;
        const beforeEnd = lineNumber < this.endLine || (lineNumber === this.endLine && columnNumber <= this.endColumn);
        return afterStart && beforeEnd;
    }
    get frameId() {
        if (typeof this[frameIdSymbol] !== 'string') {
            this[frameIdSymbol] = frameIdForScript(this);
        }
        return this[frameIdSymbol];
    }
    get isBreakpointCondition() {
        return [COND_BREAKPOINT_SOURCE_URL, LOGPOINT_SOURCE_URL].includes(this.sourceURL);
    }
    sourceMap() {
        return this.debuggerModel.sourceMapManager().sourceMapForClient(this);
    }
    createPageResourceLoadInitiator() {
        return { target: this.target(), frameId: this.frameId, initiatorUrl: this.embedderName() };
    }
    debugId() {
        return this.buildId;
    }
    rawLocationToRelativeLocation(rawLocation) {
        let { lineNumber, columnNumber } = rawLocation;
        if (!this.hasSourceURL && this.isInlineScript()) {
            lineNumber -= this.lineOffset;
            if (lineNumber === 0 && columnNumber !== undefined) {
                columnNumber -= this.columnOffset;
            }
        }
        return { lineNumber, columnNumber };
    }
    relativeLocationToRawLocation(relativeLocation) {
        let { lineNumber, columnNumber } = relativeLocation;
        if (!this.hasSourceURL && this.isInlineScript()) {
            if (lineNumber === 0 && columnNumber !== undefined) {
                columnNumber += this.columnOffset;
            }
            lineNumber += this.lineOffset;
        }
        return { lineNumber, columnNumber };
    }
}
const frameIdSymbol = Symbol('frameid');
function frameIdForScript(script) {
    const executionContext = script.executionContext();
    if (executionContext) {
        return executionContext.frameId || null;
    }
    const resourceTreeModel = script.debuggerModel.target().model(ResourceTreeModel);
    if (!resourceTreeModel?.mainFrame) {
        return null;
    }
    return resourceTreeModel.mainFrame.id;
}
const sourceURLRegex = /^[\x20\t]*\/\/[@#] sourceURL=\s*(\S*?)\s*$/;
async function disassembleWasm(content) {
    const worker = HOST_RUNTIME.createWorker(new URL('../../entrypoints/wasmparser_worker/wasmparser_worker-entrypoint.js', import.meta.url).toString());
    const promise = new Promise((resolve, reject) => {
        worker.onmessage = ({ data }) => {
            if ('method' in data) {
                switch (data.method) {
                    case 'disassemble':
                        if ('error' in data) {
                            reject(data.error);
                        }
                        else if ('result' in data) {
                            const { lines, offsets, functionBodyOffsets } = data.result;
                            resolve(new WasmDisassembly(lines, offsets, functionBodyOffsets));
                        }
                        break;
                }
            }
        };
        worker.onerror = reject;
    });
    worker.postMessage({ method: 'disassemble', params: { content } });
    try {
        return await promise;
    }
    finally {
        worker.terminate();
    }
}

// Copyright 2010 The Chromium Authors
const UIStrings$Z = {
    local: 'Local',
    closure: 'Closure',
    block: 'Block',
    script: 'Script',
    withBlock: '`With` block',
    catchBlock: '`Catch` block',
    global: 'Global',
    module: 'Module',
    expression: 'Expression',
    exception: 'Exception',
    returnValue: 'Return value',
};
const str_$Y = registerUIStrings('core/sdk/DebuggerModel.ts', UIStrings$Z);
const i18nString$G = getLocalizedString.bind(undefined, str_$Y);
function sortAndMergeRanges(locationRanges) {
    function compare(p1, p2) {
        return (p1.lineNumber - p2.lineNumber) || (p1.columnNumber - p2.columnNumber);
    }
    function overlap(r1, r2) {
        if (r1.scriptId !== r2.scriptId) {
            return false;
        }
        const n = compare(r1.start, r2.start);
        if (n < 0) {
            return compare(r1.end, r2.start) >= 0;
        }
        if (n > 0) {
            return compare(r1.start, r2.end) <= 0;
        }
        return true;
    }
    if (locationRanges.length === 0) {
        return [];
    }
    locationRanges.sort((r1, r2) => {
        if (r1.scriptId < r2.scriptId) {
            return -1;
        }
        if (r1.scriptId > r2.scriptId) {
            return 1;
        }
        return compare(r1.start, r2.start) || compare(r1.end, r2.end);
    });
    let prev = locationRanges[0];
    const merged = [];
    for (let i = 1; i < locationRanges.length; ++i) {
        const curr = locationRanges[i];
        if (overlap(prev, curr)) {
            if (compare(prev.end, curr.end) <= 0) {
                prev = { ...prev, end: curr.end };
            }
        }
        else {
            merged.push(prev);
            prev = curr;
        }
    }
    merged.push(prev);
    return merged;
}
const WASM_SYMBOLS_PRIORITY = [
    "ExternalDWARF" ,
    "EmbeddedDWARF" ,
    "SourceMap" ,
];
class DebuggerModel extends SDKModel {
    agent;
    #runtimeModel;
    #sourceMapManager;
    #debuggerPausedDetails = null;
    #scripts = new Map();
    #scriptsBySourceURL = new Map();
    #discardableScripts = [];
    continueToLocationCallback = null;
    #selectedCallFrame = null;
    #debuggerEnabled = false;
    #debuggerId = null;
    #skipAllPausesTimeout = 0;
    #beforePausedCallback = null;
    #computeAutoStepRangesCallback = null;
    evaluateOnCallFrameCallback = null;
    #synchronizeBreakpointsCallback = null;
    #breakpointResolvedEventTarget = new ObjectWrapper();
    #autoSteppingContext = null;
    #isPausing = false;
    constructor(target) {
        super(target);
        target.registerDebuggerDispatcher(new DebuggerDispatcher(this));
        this.agent = target.debuggerAgent();
        this.#runtimeModel = target.model(RuntimeModel);
        this.#sourceMapManager = new SourceMapManager(target, (compiledURL, sourceMappingURL, payload, script) => new SourceMap(compiledURL, sourceMappingURL, payload, script));
        Settings.instance()
            .moduleSetting('pause-on-exception-enabled')
            .addChangeListener(this.pauseOnExceptionStateChanged, this);
        Settings.instance()
            .moduleSetting('pause-on-caught-exception')
            .addChangeListener(this.pauseOnExceptionStateChanged, this);
        Settings.instance()
            .moduleSetting('pause-on-uncaught-exception')
            .addChangeListener(this.pauseOnExceptionStateChanged, this);
        Settings.instance()
            .moduleSetting('disable-async-stack-traces')
            .addChangeListener(this.asyncStackTracesStateChanged, this);
        Settings.instance()
            .moduleSetting('breakpoints-active')
            .addChangeListener(this.breakpointsActiveChanged, this);
        if (!target.suspended()) {
            void this.enableDebugger();
        }
        this.#sourceMapManager.setEnabled(Settings.instance().moduleSetting('js-source-maps-enabled').get());
        Settings.instance()
            .moduleSetting('js-source-maps-enabled')
            .addChangeListener(event => this.#sourceMapManager.setEnabled(event.data));
        const resourceTreeModel = target.model(ResourceTreeModel);
        if (resourceTreeModel) {
            resourceTreeModel.addEventListener(Events$6.FrameNavigated, this.onFrameNavigated, this);
        }
    }
    static selectSymbolSource(debugSymbols) {
        if (!debugSymbols || debugSymbols.length === 0) {
            return null;
        }
        if ('type' in debugSymbols) {
            if (debugSymbols.type === 'None') {
                return null;
            }
            return debugSymbols;
        }
        let debugSymbolsSource = null;
        const symbolTypes = new Map(debugSymbols.map(symbol => [symbol.type, symbol]));
        for (const symbol of WASM_SYMBOLS_PRIORITY) {
            if (symbolTypes.has(symbol)) {
                debugSymbolsSource = symbolTypes.get(symbol) || null;
                break;
            }
        }
        console.assert(debugSymbolsSource !== null, 'Unknown symbol types. Front-end and back-end should be kept in sync regarding Protocol.Debugger.DebugSymbolTypes');
        if (debugSymbolsSource && debugSymbols.length > 1) {
            Console.instance().warn(`Multiple debug symbols for script were found. Using ${debugSymbolsSource.type}`);
        }
        return debugSymbolsSource;
    }
    sourceMapManager() {
        return this.#sourceMapManager;
    }
    runtimeModel() {
        return this.#runtimeModel;
    }
    debuggerEnabled() {
        return Boolean(this.#debuggerEnabled);
    }
    debuggerId() {
        return this.#debuggerId;
    }
    async enableDebugger() {
        if (this.#debuggerEnabled) {
            return;
        }
        this.#debuggerEnabled = true;
        const maxScriptsCacheSize = 100e6;
        const enablePromise = this.agent.invoke_enable({ maxScriptsCacheSize });
        let instrumentationPromise;
        if (experiments.isEnabled(ExperimentName.INSTRUMENTATION_BREAKPOINTS)) {
            instrumentationPromise = this.agent.invoke_setInstrumentationBreakpoint({
                instrumentation: "beforeScriptExecution" ,
            });
        }
        this.pauseOnExceptionStateChanged();
        void this.asyncStackTracesStateChanged();
        if (!Settings.instance().moduleSetting('breakpoints-active').get()) {
            this.breakpointsActiveChanged();
        }
        this.dispatchEventToListeners(Events$5.DebuggerWasEnabled, this);
        const [enableResult] = await Promise.all([enablePromise, instrumentationPromise]);
        this.registerDebugger(enableResult);
    }
    async syncDebuggerId() {
        const maxScriptsCacheSize = 100e6;
        const enablePromise = this.agent.invoke_enable({ maxScriptsCacheSize });
        void enablePromise.then(this.registerDebugger.bind(this));
        return await enablePromise;
    }
    onFrameNavigated() {
        if (DebuggerModel.shouldResyncDebuggerId) {
            return;
        }
        DebuggerModel.shouldResyncDebuggerId = true;
    }
    registerDebugger(response) {
        if (response.getError()) {
            this.#debuggerEnabled = false;
            return;
        }
        const { debuggerId } = response;
        debuggerIdToModel.set(debuggerId, this);
        this.#debuggerId = debuggerId;
        this.dispatchEventToListeners(Events$5.DebuggerIsReadyToPause, this);
    }
    isReadyToPause() {
        return Boolean(this.#debuggerId);
    }
    static async modelForDebuggerId(debuggerId) {
        if (DebuggerModel.shouldResyncDebuggerId) {
            await DebuggerModel.resyncDebuggerIdForModels();
            DebuggerModel.shouldResyncDebuggerId = false;
        }
        return debuggerIdToModel.get(debuggerId) || null;
    }
    static async resyncDebuggerIdForModels() {
        const dbgModels = debuggerIdToModel.values();
        for (const dbgModel of dbgModels) {
            if (dbgModel.debuggerEnabled()) {
                await dbgModel.syncDebuggerId();
            }
        }
    }
    async disableDebugger() {
        if (!this.#debuggerEnabled) {
            return;
        }
        this.#debuggerEnabled = false;
        await this.asyncStackTracesStateChanged();
        await this.agent.invoke_disable();
        this.#isPausing = false;
        this.globalObjectCleared();
        this.dispatchEventToListeners(Events$5.DebuggerWasDisabled, this);
        if (typeof this.#debuggerId === 'string') {
            debuggerIdToModel.delete(this.#debuggerId);
        }
        this.#debuggerId = null;
    }
    skipAllPauses(skip) {
        if (this.#skipAllPausesTimeout) {
            clearTimeout(this.#skipAllPausesTimeout);
            this.#skipAllPausesTimeout = 0;
        }
        void this.agent.invoke_setSkipAllPauses({ skip });
    }
    skipAllPausesUntilReloadOrTimeout(timeout) {
        if (this.#skipAllPausesTimeout) {
            clearTimeout(this.#skipAllPausesTimeout);
        }
        void this.agent.invoke_setSkipAllPauses({ skip: true });
        this.#skipAllPausesTimeout = window.setTimeout(this.skipAllPauses.bind(this, false), timeout);
    }
    pauseOnExceptionStateChanged() {
        const pauseOnCaughtEnabled = Settings.instance().moduleSetting('pause-on-caught-exception').get();
        let state;
        const pauseOnUncaughtEnabled = Settings.instance().moduleSetting('pause-on-uncaught-exception').get();
        if (pauseOnCaughtEnabled && pauseOnUncaughtEnabled) {
            state = "all" ;
        }
        else if (pauseOnCaughtEnabled) {
            state = "caught" ;
        }
        else if (pauseOnUncaughtEnabled) {
            state = "uncaught" ;
        }
        else {
            state = "none" ;
        }
        void this.agent.invoke_setPauseOnExceptions({ state });
    }
    asyncStackTracesStateChanged() {
        const maxAsyncStackChainDepth = 32;
        const enabled = !Settings.instance().moduleSetting('disable-async-stack-traces').get() && this.#debuggerEnabled;
        const maxDepth = enabled ? maxAsyncStackChainDepth : 0;
        return this.agent.invoke_setAsyncCallStackDepth({ maxDepth });
    }
    breakpointsActiveChanged() {
        void this.agent.invoke_setBreakpointsActive({ active: Settings.instance().moduleSetting('breakpoints-active').get() });
    }
    setComputeAutoStepRangesCallback(callback) {
        this.#computeAutoStepRangesCallback = callback;
    }
    async computeAutoStepSkipList(mode) {
        let ranges = [];
        if (this.#computeAutoStepRangesCallback && this.#debuggerPausedDetails &&
            this.#debuggerPausedDetails.callFrames.length > 0) {
            const [callFrame] = this.#debuggerPausedDetails.callFrames;
            ranges = await this.#computeAutoStepRangesCallback.call(null, mode, callFrame);
        }
        const skipList = ranges.map(({ start, end }) => ({
            scriptId: start.scriptId,
            start: { lineNumber: start.lineNumber, columnNumber: start.columnNumber },
            end: { lineNumber: end.lineNumber, columnNumber: end.columnNumber },
        }));
        return sortAndMergeRanges(skipList);
    }
    async stepInto() {
        const skipList = await this.computeAutoStepSkipList("StepInto" );
        void this.agent.invoke_stepInto({ breakOnAsyncCall: false, skipList });
    }
    async stepOver() {
        this.#autoSteppingContext = this.#debuggerPausedDetails?.callFrames[0]?.functionLocation() ?? null;
        const skipList = await this.computeAutoStepSkipList("StepOver" );
        void this.agent.invoke_stepOver({ skipList });
    }
    async stepOut() {
        const skipList = await this.computeAutoStepSkipList("StepOut" );
        if (skipList.length !== 0) {
            void this.agent.invoke_stepOver({ skipList });
        }
        else {
            void this.agent.invoke_stepOut();
        }
    }
    scheduleStepIntoAsync() {
        void this.computeAutoStepSkipList("StepInto" ).then(skipList => {
            void this.agent.invoke_stepInto({ breakOnAsyncCall: true, skipList });
        });
    }
    resume() {
        void this.agent.invoke_resume({ terminateOnResume: false });
        this.#isPausing = false;
    }
    pause() {
        this.#isPausing = true;
        this.skipAllPauses(false);
        void this.agent.invoke_pause();
    }
    async setBreakpointByURL(url, lineNumber, columnNumber, condition) {
        let minColumnNumber = 0;
        const scripts = this.#scriptsBySourceURL.get(url) || [];
        for (let i = 0, l = scripts.length; i < l; ++i) {
            const script = scripts[i];
            if (lineNumber === script.lineOffset) {
                minColumnNumber = minColumnNumber ? Math.min(minColumnNumber, script.columnOffset) : script.columnOffset;
            }
        }
        columnNumber = Math.max(columnNumber || 0, minColumnNumber);
        const response = await this.agent.invoke_setBreakpointByUrl({
            lineNumber,
            url,
            columnNumber,
            condition,
        });
        if (response.getError()) {
            return { locations: [], breakpointId: null };
        }
        let locations = [];
        if (response.locations) {
            locations = response.locations.map(payload => Location$1.fromPayload(this, payload));
        }
        return { locations, breakpointId: response.breakpointId };
    }
    async setBreakpointInAnonymousScript(scriptHash, lineNumber, columnNumber, condition) {
        const response = await this.agent.invoke_setBreakpointByUrl({ lineNumber, scriptHash, columnNumber, condition });
        if (response.getError()) {
            return { locations: [], breakpointId: null };
        }
        let locations = [];
        if (response.locations) {
            locations = response.locations.map(payload => Location$1.fromPayload(this, payload));
        }
        return { locations, breakpointId: response.breakpointId };
    }
    async removeBreakpoint(breakpointId) {
        await this.agent.invoke_removeBreakpoint({ breakpointId });
    }
    async getPossibleBreakpoints(startLocation, endLocation, restrictToFunction) {
        const response = await this.agent.invoke_getPossibleBreakpoints({
            start: startLocation.payload(),
            end: endLocation ? endLocation.payload() : undefined,
            restrictToFunction,
        });
        if (response.getError() || !response.locations) {
            return [];
        }
        return response.locations.map(location => BreakLocation.fromPayload(this, location));
    }
    async fetchAsyncStackTrace(stackId) {
        const response = await this.agent.invoke_getStackTrace({ stackTraceId: stackId });
        return response.getError() ? null : response.stackTrace;
    }
    breakpointResolved(breakpointId, location) {
        this.#breakpointResolvedEventTarget.dispatchEventToListeners(breakpointId, Location$1.fromPayload(this, location));
    }
    globalObjectCleared() {
        this.resetDebuggerPausedDetails();
        this.reset();
        this.dispatchEventToListeners(Events$5.GlobalObjectCleared, this);
    }
    reset() {
        for (const script of this.#scripts.values()) {
            this.#sourceMapManager.detachSourceMap(script);
        }
        this.#scripts.clear();
        this.#scriptsBySourceURL.clear();
        this.#discardableScripts = [];
        this.#autoSteppingContext = null;
    }
    scripts() {
        return Array.from(this.#scripts.values());
    }
    scriptForId(scriptId) {
        return this.#scripts.get(scriptId) || null;
    }
    scriptsForSourceURL(sourceURL) {
        return this.#scriptsBySourceURL.get(sourceURL) || [];
    }
    scriptsForExecutionContext(executionContext) {
        const result = [];
        for (const script of this.#scripts.values()) {
            if (script.executionContextId === executionContext.id) {
                result.push(script);
            }
        }
        return result;
    }
    get callFrames() {
        return this.#debuggerPausedDetails ? this.#debuggerPausedDetails.callFrames : null;
    }
    debuggerPausedDetails() {
        return this.#debuggerPausedDetails;
    }
    async setDebuggerPausedDetails(debuggerPausedDetails) {
        this.#isPausing = false;
        this.#debuggerPausedDetails = debuggerPausedDetails;
        if (this.#beforePausedCallback) {
            if (!await this.#beforePausedCallback.call(null, debuggerPausedDetails, this.#autoSteppingContext)) {
                return false;
            }
        }
        this.#autoSteppingContext = null;
        this.dispatchEventToListeners(Events$5.DebuggerPaused, this);
        this.setSelectedCallFrame(debuggerPausedDetails.callFrames[0]);
        return true;
    }
    resetDebuggerPausedDetails() {
        this.#isPausing = false;
        this.#debuggerPausedDetails = null;
        this.setSelectedCallFrame(null);
    }
    setBeforePausedCallback(callback) {
        this.#beforePausedCallback = callback;
    }
    setEvaluateOnCallFrameCallback(callback) {
        this.evaluateOnCallFrameCallback = callback;
    }
    setSynchronizeBreakpointsCallback(callback) {
        this.#synchronizeBreakpointsCallback = callback;
    }
    async pausedScript(callFrames, reason, auxData, breakpointIds, asyncStackTrace, asyncStackTraceId) {
        if (reason === "instrumentation" ) {
            const script = this.scriptForId(auxData.scriptId);
            if (this.#synchronizeBreakpointsCallback && script) {
                await this.#synchronizeBreakpointsCallback(script);
            }
            this.resume();
            return;
        }
        const pausedDetails = new DebuggerPausedDetails(this, callFrames, reason, auxData, breakpointIds, asyncStackTrace, asyncStackTraceId);
        if (this.continueToLocationCallback) {
            const callback = this.continueToLocationCallback;
            this.continueToLocationCallback = null;
            if (callback(pausedDetails)) {
                return;
            }
        }
        if (!await this.setDebuggerPausedDetails(pausedDetails)) {
            if (this.#autoSteppingContext) {
                void this.stepOver();
            }
            else {
                void this.stepInto();
            }
        }
        else {
            fireEvent('DevTools.DebuggerPaused');
        }
    }
    resumedScript() {
        this.resetDebuggerPausedDetails();
        this.dispatchEventToListeners(Events$5.DebuggerResumed, this);
    }
    parsedScriptSource(scriptId, sourceURL, startLine, startColumn, endLine, endColumn,
    executionContextId, hash, executionContextAuxData, isLiveEdit, sourceMapURL, hasSourceURLComment, hasSyntaxError, length, isModule, originStackTrace, codeOffset, scriptLanguage, debugSymbols, embedderName, buildId) {
        const knownScript = this.#scripts.get(scriptId);
        if (knownScript) {
            return knownScript;
        }
        let isContentScript = false;
        if (executionContextAuxData && ('isDefault' in executionContextAuxData)) {
            isContentScript = !executionContextAuxData['isDefault'];
        }
        const selectedDebugSymbol = DebuggerModel.selectSymbolSource(debugSymbols);
        const script = new Script(this, scriptId, sourceURL, startLine, startColumn, endLine, endColumn, executionContextId, hash, isContentScript, isLiveEdit, sourceMapURL, hasSourceURLComment, length, isModule, originStackTrace, codeOffset, scriptLanguage, selectedDebugSymbol, embedderName, buildId);
        this.registerScript(script);
        this.dispatchEventToListeners(Events$5.ParsedScriptSource, script);
        if ((!selectedDebugSymbol || selectedDebugSymbol.type === "SourceMap" ) &&
            script.sourceMapURL && !hasSyntaxError) {
            this.#sourceMapManager.attachSourceMap(script, script.sourceURL, script.sourceMapURL);
        }
        const isDiscardable = hasSyntaxError && script.isAnonymousScript();
        if (isDiscardable) {
            this.#discardableScripts.push(script);
            this.collectDiscardedScripts();
        }
        return script;
    }
    setSourceMapURL(script, newSourceMapURL) {
        this.#sourceMapManager.detachSourceMap(script);
        script.sourceMapURL = newSourceMapURL;
        this.#sourceMapManager.attachSourceMap(script, script.sourceURL, script.sourceMapURL);
    }
    async setDebugInfoURL(script, _externalURL) {
        this.dispatchEventToListeners(Events$5.DebugInfoAttached, script);
    }
    executionContextDestroyed(executionContext) {
        for (const script of this.#scripts.values()) {
            if (script.executionContextId === executionContext.id) {
                this.#sourceMapManager.detachSourceMap(script);
            }
        }
    }
    registerScript(script) {
        this.#scripts.set(script.scriptId, script);
        if (script.isAnonymousScript()) {
            return;
        }
        let scripts = this.#scriptsBySourceURL.get(script.sourceURL);
        if (!scripts) {
            scripts = [];
            this.#scriptsBySourceURL.set(script.sourceURL, scripts);
        }
        scripts.unshift(script);
    }
    unregisterScript(script) {
        console.assert(script.isAnonymousScript());
        this.#scripts.delete(script.scriptId);
    }
    collectDiscardedScripts() {
        if (this.#discardableScripts.length < 1000) {
            return;
        }
        const scriptsToDiscard = this.#discardableScripts.splice(0, 100);
        for (const script of scriptsToDiscard) {
            this.unregisterScript(script);
            this.dispatchEventToListeners(Events$5.DiscardedAnonymousScriptSource, script);
        }
    }
    createRawLocation(script, lineNumber, columnNumber, inlineFrameIndex) {
        return this.createRawLocationByScriptId(script.scriptId, lineNumber, columnNumber, inlineFrameIndex);
    }
    createRawLocationByURL(sourceURL, lineNumber, columnNumber, inlineFrameIndex) {
        for (const script of this.#scriptsBySourceURL.get(sourceURL) || []) {
            if (script.lineOffset > lineNumber ||
                (script.lineOffset === lineNumber && columnNumber !== undefined && script.columnOffset > columnNumber)) {
                continue;
            }
            if (script.endLine < lineNumber ||
                (script.endLine === lineNumber && columnNumber !== undefined && script.endColumn <= columnNumber)) {
                continue;
            }
            return new Location$1(this, script.scriptId, lineNumber, columnNumber, inlineFrameIndex);
        }
        return null;
    }
    createRawLocationByScriptId(scriptId, lineNumber, columnNumber, inlineFrameIndex) {
        return new Location$1(this, scriptId, lineNumber, columnNumber, inlineFrameIndex);
    }
    createRawLocationsByStackTrace(stackTrace) {
        const rawLocations = [];
        for (let current = stackTrace; current; current = current.parent) {
            for (const { scriptId, lineNumber, columnNumber } of current.callFrames) {
                rawLocations.push(this.createRawLocationByScriptId(scriptId, lineNumber, columnNumber));
            }
        }
        return rawLocations;
    }
    isPaused() {
        return Boolean(this.debuggerPausedDetails());
    }
    isPausing() {
        return this.#isPausing;
    }
    setSelectedCallFrame(callFrame) {
        if (this.#selectedCallFrame === callFrame) {
            return;
        }
        this.#selectedCallFrame = callFrame;
        this.dispatchEventToListeners(Events$5.CallFrameSelected, this);
    }
    selectedCallFrame() {
        return this.#selectedCallFrame;
    }
    async evaluateOnSelectedCallFrame(options) {
        const callFrame = this.selectedCallFrame();
        if (!callFrame) {
            throw new Error('No call frame selected');
        }
        return await callFrame.evaluate(options);
    }
    functionDetailsPromise(remoteObject) {
        return remoteObject.getAllProperties(false , false )
            .then(buildDetails.bind(this));
        function buildDetails(response) {
            if (!response) {
                return null;
            }
            let location = null;
            if (response.internalProperties) {
                for (const prop of response.internalProperties) {
                    if (prop.name === '[[FunctionLocation]]') {
                        location = prop.value;
                    }
                }
            }
            let functionName = null;
            if (response.properties) {
                for (const prop of response.properties) {
                    if (prop.name === 'name' && prop.value?.type === 'string') {
                        functionName = prop.value;
                    }
                }
            }
            let debuggerLocation = null;
            if (location) {
                debuggerLocation = this.createRawLocationByScriptId(location.value.scriptId, location.value.lineNumber, location.value.columnNumber);
            }
            return { location: debuggerLocation, functionName: functionName ? functionName.value : '' };
        }
    }
    async setVariableValue(scopeNumber, variableName, newValue, callFrameId) {
        const response = await this.agent.invoke_setVariableValue({ scopeNumber, variableName, newValue, callFrameId });
        const error = response.getError();
        return error;
    }
    addBreakpointListener(breakpointId, listener, thisObject) {
        this.#breakpointResolvedEventTarget.addEventListener(breakpointId, listener, thisObject);
    }
    removeBreakpointListener(breakpointId, listener, thisObject) {
        this.#breakpointResolvedEventTarget.removeEventListener(breakpointId, listener, thisObject);
    }
    async setBlackboxPatterns(patterns, skipAnonymous) {
        const response = await this.agent.invoke_setBlackboxPatterns({ patterns, skipAnonymous });
        const error = response.getError();
        return !error;
    }
    async setBlackboxExecutionContexts(uniqueIds) {
        const response = await this.agent.invoke_setBlackboxExecutionContexts({ uniqueIds });
        const error = response.getError();
        return !error;
    }
    dispose() {
        if (this.#debuggerId) {
            debuggerIdToModel.delete(this.#debuggerId);
        }
        Settings.instance()
            .moduleSetting('pause-on-exception-enabled')
            .removeChangeListener(this.pauseOnExceptionStateChanged, this);
        Settings.instance()
            .moduleSetting('pause-on-caught-exception')
            .removeChangeListener(this.pauseOnExceptionStateChanged, this);
        Settings.instance()
            .moduleSetting('disable-async-stack-traces')
            .removeChangeListener(this.asyncStackTracesStateChanged, this);
    }
    async suspendModel() {
        await this.disableDebugger();
    }
    async resumeModel() {
        await this.enableDebugger();
    }
    static shouldResyncDebuggerId = false;
    getEvaluateOnCallFrameCallback() {
        return this.evaluateOnCallFrameCallback;
    }
    async *iterateAsyncParents(stackTraceOrPausedDetails) {
        const isPausedDetails = (details) => !('parent' in details) && !('parentId' in details);
        let stackTrace = isPausedDetails(stackTraceOrPausedDetails) ?
            {
                callFrames: [],
                parent: stackTraceOrPausedDetails.asyncStackTrace,
                parentId: stackTraceOrPausedDetails.asyncStackTraceId
            } :
            stackTraceOrPausedDetails;
        let target = this.target();
        while (true) {
            if (stackTrace.parent) {
                stackTrace = stackTrace.parent;
            }
            else if (stackTrace.parentId) {
                const model = stackTrace.parentId.debuggerId ?
                    await DebuggerModel.modelForDebuggerId(stackTrace.parentId.debuggerId) :
                    this;
                if (!model) {
                    return;
                }
                const maybeStackTrace = await model.fetchAsyncStackTrace(stackTrace.parentId);
                if (!maybeStackTrace) {
                    return;
                }
                stackTrace = maybeStackTrace;
                target = model.target();
            }
            else {
                return;
            }
            yield { stackTrace, target };
        }
    }
}
const debuggerIdToModel = new Map();
var PauseOnExceptionsState;
(function (PauseOnExceptionsState) {
    PauseOnExceptionsState["DontPauseOnExceptions"] = "none";
    PauseOnExceptionsState["PauseOnAllExceptions"] = "all";
    PauseOnExceptionsState["PauseOnCaughtExceptions"] = "caught";
    PauseOnExceptionsState["PauseOnUncaughtExceptions"] = "uncaught";
})(PauseOnExceptionsState || (PauseOnExceptionsState = {}));
var Events$5;
(function (Events) {
    Events["DebuggerWasEnabled"] = "DebuggerWasEnabled";
    Events["DebuggerWasDisabled"] = "DebuggerWasDisabled";
    Events["DebuggerPaused"] = "DebuggerPaused";
    Events["DebuggerResumed"] = "DebuggerResumed";
    Events["DebugInfoAttached"] = "DebugInfoAttached";
    Events["ParsedScriptSource"] = "ParsedScriptSource";
    Events["DiscardedAnonymousScriptSource"] = "DiscardedAnonymousScriptSource";
    Events["GlobalObjectCleared"] = "GlobalObjectCleared";
    Events["CallFrameSelected"] = "CallFrameSelected";
    Events["DebuggerIsReadyToPause"] = "DebuggerIsReadyToPause";
    Events["ScriptSourceWasEdited"] = "ScriptSourceWasEdited";
})(Events$5 || (Events$5 = {}));
class DebuggerDispatcher {
    #debuggerModel;
    constructor(debuggerModel) {
        this.#debuggerModel = debuggerModel;
    }
    paused({ callFrames, reason, data, hitBreakpoints, asyncStackTrace, asyncStackTraceId }) {
        if (!this.#debuggerModel.debuggerEnabled()) {
            return;
        }
        void this.#debuggerModel.pausedScript(callFrames, reason, data, hitBreakpoints || [], asyncStackTrace, asyncStackTraceId);
    }
    resumed() {
        if (!this.#debuggerModel.debuggerEnabled()) {
            return;
        }
        this.#debuggerModel.resumedScript();
    }
    scriptParsed({ scriptId, url, startLine, startColumn, endLine, endColumn, executionContextId, hash, executionContextAuxData, isLiveEdit, sourceMapURL, hasSourceURL, length, isModule, stackTrace, codeOffset, scriptLanguage, debugSymbols, embedderName, buildId, }) {
        if (!this.#debuggerModel.debuggerEnabled()) {
            return;
        }
        this.#debuggerModel.parsedScriptSource(scriptId, url, startLine, startColumn, endLine, endColumn, executionContextId, hash, executionContextAuxData, Boolean(isLiveEdit), sourceMapURL, Boolean(hasSourceURL), false, length || 0, isModule || null, stackTrace || null, codeOffset || null, scriptLanguage || null, debugSymbols || null, embedderName || null, buildId || null);
    }
    scriptFailedToParse({ scriptId, url, startLine, startColumn, endLine, endColumn, executionContextId, hash, executionContextAuxData, sourceMapURL, hasSourceURL, length, isModule, stackTrace, codeOffset, scriptLanguage, embedderName, buildId, }) {
        if (!this.#debuggerModel.debuggerEnabled()) {
            return;
        }
        this.#debuggerModel.parsedScriptSource(scriptId, url, startLine, startColumn, endLine, endColumn, executionContextId, hash, executionContextAuxData, false, sourceMapURL, Boolean(hasSourceURL), true, length || 0, isModule || null, stackTrace || null, codeOffset || null, scriptLanguage || null, null, embedderName || null, buildId || null);
    }
    breakpointResolved({ breakpointId, location }) {
        if (!this.#debuggerModel.debuggerEnabled()) {
            return;
        }
        this.#debuggerModel.breakpointResolved(breakpointId, location);
    }
}
let Location$1 = class Location {
    debuggerModel;
    scriptId;
    lineNumber;
    columnNumber;
    inlineFrameIndex;
    constructor(debuggerModel, scriptId, lineNumber, columnNumber, inlineFrameIndex) {
        this.debuggerModel = debuggerModel;
        this.scriptId = scriptId;
        this.lineNumber = lineNumber;
        this.columnNumber = columnNumber || 0;
        this.inlineFrameIndex = inlineFrameIndex || 0;
    }
    static fromPayload(debuggerModel, payload, inlineFrameIndex) {
        return new Location(debuggerModel, payload.scriptId, payload.lineNumber, payload.columnNumber, inlineFrameIndex);
    }
    payload() {
        return { scriptId: this.scriptId, lineNumber: this.lineNumber, columnNumber: this.columnNumber };
    }
    script() {
        return this.debuggerModel.scriptForId(this.scriptId);
    }
    continueToLocation(pausedCallback) {
        if (pausedCallback) {
            this.debuggerModel.continueToLocationCallback = this.paused.bind(this, pausedCallback);
        }
        void this.debuggerModel.agent.invoke_continueToLocation({
            location: this.payload(),
            targetCallFrames: "current" ,
        });
    }
    paused(pausedCallback, debuggerPausedDetails) {
        const location = debuggerPausedDetails.callFrames[0].location();
        if (location.scriptId === this.scriptId && location.lineNumber === this.lineNumber &&
            location.columnNumber === this.columnNumber) {
            pausedCallback();
            return true;
        }
        return false;
    }
    id() {
        return this.debuggerModel.target().id() + ':' + this.scriptId + ':' + this.lineNumber + ':' + this.columnNumber;
    }
};
class BreakLocation extends Location$1 {
    type;
    constructor(debuggerModel, scriptId, lineNumber, columnNumber, type) {
        super(debuggerModel, scriptId, lineNumber, columnNumber);
        if (type) {
            this.type = type;
        }
    }
    static fromPayload(debuggerModel, payload) {
        return new BreakLocation(debuggerModel, payload.scriptId, payload.lineNumber, payload.columnNumber, payload.type);
    }
}
class CallFrame {
    debuggerModel;
    script;
    payload;
    #location;
    #scopeChain;
    #localScope;
    inlineFrameIndex;
    functionName;
    #functionLocation;
    #returnValue;
    exception;
    canBeRestarted;
    constructor(debuggerModel, script, payload, inlineFrameIndex, functionName, exception = null) {
        this.debuggerModel = debuggerModel;
        this.script = script;
        this.payload = payload;
        this.#location = Location$1.fromPayload(debuggerModel, payload.location, inlineFrameIndex);
        this.#scopeChain = [];
        this.#localScope = null;
        this.inlineFrameIndex = inlineFrameIndex || 0;
        this.functionName = functionName ?? payload.functionName;
        this.canBeRestarted = Boolean(payload.canBeRestarted);
        this.exception = exception;
        for (let i = 0; i < payload.scopeChain.length; ++i) {
            const scope = new Scope(this, i);
            this.#scopeChain.push(scope);
            if (scope.type() === "local" ) {
                this.#localScope = scope;
            }
        }
        if (payload.functionLocation) {
            this.#functionLocation = Location$1.fromPayload(debuggerModel, payload.functionLocation);
        }
        this.#returnValue =
            payload.returnValue ? this.debuggerModel.runtimeModel().createRemoteObject(payload.returnValue) : null;
    }
    static fromPayloadArray(debuggerModel, callFrames, exception) {
        const result = [];
        for (let i = 0; i < callFrames.length; ++i) {
            const callFrame = callFrames[i];
            const script = debuggerModel.scriptForId(callFrame.location.scriptId);
            if (script) {
                const ex = i === 0 ? exception : null;
                result.push(new CallFrame(debuggerModel, script, callFrame, undefined, undefined, ex));
            }
        }
        return result;
    }
    createVirtualCallFrame(inlineFrameIndex, name) {
        return new CallFrame(this.debuggerModel, this.script, this.payload, inlineFrameIndex, name, this.exception);
    }
    get id() {
        return this.payload.callFrameId;
    }
    scopeChain() {
        return this.#scopeChain;
    }
    localScope() {
        return this.#localScope;
    }
    thisObject() {
        return this.payload.this ? this.debuggerModel.runtimeModel().createRemoteObject(this.payload.this) : null;
    }
    returnValue() {
        return this.#returnValue;
    }
    async setReturnValue(expression) {
        if (!this.#returnValue) {
            return null;
        }
        const evaluateResponse = await this.debuggerModel.agent.invoke_evaluateOnCallFrame({ callFrameId: this.id, expression, silent: true, objectGroup: 'backtrace' });
        if (evaluateResponse.getError() || evaluateResponse.exceptionDetails) {
            return null;
        }
        const response = await this.debuggerModel.agent.invoke_setReturnValue({ newValue: evaluateResponse.result });
        if (response.getError()) {
            return null;
        }
        this.#returnValue = this.debuggerModel.runtimeModel().createRemoteObject(evaluateResponse.result);
        return this.#returnValue;
    }
    location() {
        return this.#location;
    }
    functionLocation() {
        return this.#functionLocation || null;
    }
    async evaluate(options) {
        const debuggerModel = this.debuggerModel;
        const runtimeModel = debuggerModel.runtimeModel();
        const evaluateOnCallFrameCallback = debuggerModel.getEvaluateOnCallFrameCallback();
        if (evaluateOnCallFrameCallback) {
            const result = await evaluateOnCallFrameCallback(this, options);
            if (result) {
                return result;
            }
        }
        const response = await this.debuggerModel.agent.invoke_evaluateOnCallFrame({
            callFrameId: this.id,
            expression: options.expression,
            objectGroup: options.objectGroup,
            includeCommandLineAPI: options.includeCommandLineAPI,
            silent: options.silent,
            returnByValue: options.returnByValue,
            generatePreview: options.generatePreview,
            throwOnSideEffect: options.throwOnSideEffect,
            timeout: options.timeout,
        });
        const error = response.getError();
        if (error) {
            return { error };
        }
        return { object: runtimeModel.createRemoteObject(response.result), exceptionDetails: response.exceptionDetails };
    }
    async restart() {
        console.assert(this.canBeRestarted, 'This frame can not be restarted.');
        await this.debuggerModel.agent.invoke_restartFrame({ callFrameId: this.id, mode: "StepInto"  });
    }
    getPayload() {
        return this.payload;
    }
}
class Scope {
    #callFrame;
    #payload;
    #type;
    #name;
    #ordinal;
    #locationRange;
    #object = null;
    constructor(callFrame, ordinal) {
        this.#callFrame = callFrame;
        this.#payload = callFrame.getPayload().scopeChain[ordinal];
        this.#type = this.#payload.type;
        this.#name = this.#payload.name;
        this.#ordinal = ordinal;
        const start = this.#payload.startLocation ? Location$1.fromPayload(callFrame.debuggerModel, this.#payload.startLocation) : null;
        const end = this.#payload.endLocation ? Location$1.fromPayload(callFrame.debuggerModel, this.#payload.endLocation) : null;
        if (start && end && start.scriptId === end.scriptId) {
            this.#locationRange = { start, end };
        }
        else {
            this.#locationRange = null;
        }
    }
    callFrame() {
        return this.#callFrame;
    }
    type() {
        return this.#type;
    }
    typeName() {
        switch (this.#type) {
            case "local" :
                return i18nString$G(UIStrings$Z.local);
            case "closure" :
                return i18nString$G(UIStrings$Z.closure);
            case "catch" :
                return i18nString$G(UIStrings$Z.catchBlock);
            case "eval" :
                return lockedString('Eval');
            case "block" :
                return i18nString$G(UIStrings$Z.block);
            case "script" :
                return i18nString$G(UIStrings$Z.script);
            case "with" :
                return i18nString$G(UIStrings$Z.withBlock);
            case "global" :
                return i18nString$G(UIStrings$Z.global);
            case "module" :
                return i18nString$G(UIStrings$Z.module);
            case "wasm-expression-stack" :
                return i18nString$G(UIStrings$Z.expression);
        }
        return '';
    }
    name() {
        return this.#name;
    }
    range() {
        return this.#locationRange;
    }
    object() {
        if (this.#object) {
            return this.#object;
        }
        const runtimeModel = this.#callFrame.debuggerModel.runtimeModel();
        const declarativeScope = this.#type !== "with"  && this.#type !== "global" ;
        if (declarativeScope) {
            this.#object =
                runtimeModel.createScopeRemoteObject(this.#payload.object, new ScopeRef(this.#ordinal, this.#callFrame.id));
        }
        else {
            this.#object = runtimeModel.createRemoteObject(this.#payload.object);
        }
        return this.#object;
    }
    description() {
        const declarativeScope = this.#type !== "with"  && this.#type !== "global" ;
        return declarativeScope ? '' : (this.#payload.object.description || '');
    }
    icon() {
        return undefined;
    }
    extraProperties() {
        if (this.#ordinal !== 0 || this.#type !== "local"  || this.#callFrame.script.isWasm()) {
            return [];
        }
        const extraProperties = [];
        const exception = this.#callFrame.exception;
        if (exception) {
            extraProperties.push(new RemoteObjectProperty(i18nString$G(UIStrings$Z.exception), exception, undefined, undefined, undefined, undefined, undefined,
             true));
        }
        const returnValue = this.#callFrame.returnValue();
        if (returnValue) {
            extraProperties.push(new RemoteObjectProperty(i18nString$G(UIStrings$Z.returnValue), returnValue, undefined, undefined, undefined, undefined, undefined,
             true, this.#callFrame.setReturnValue.bind(this.#callFrame)));
        }
        return extraProperties;
    }
}
class DebuggerPausedDetails {
    debuggerModel;
    callFrames;
    reason;
    auxData;
    breakpointIds;
    asyncStackTrace;
    asyncStackTraceId;
    constructor(debuggerModel, callFrames, reason,
    auxData, breakpointIds, asyncStackTrace, asyncStackTraceId) {
        this.debuggerModel = debuggerModel;
        this.reason = reason;
        this.auxData = auxData;
        this.breakpointIds = breakpointIds;
        if (asyncStackTrace) {
            this.asyncStackTrace = this.cleanRedundantFrames(asyncStackTrace);
        }
        this.asyncStackTraceId = asyncStackTraceId;
        this.callFrames = CallFrame.fromPayloadArray(debuggerModel, callFrames, this.exception());
    }
    exception() {
        if (this.reason !== "exception"  &&
            this.reason !== "promiseRejection" ) {
            return null;
        }
        return this.debuggerModel.runtimeModel().createRemoteObject(this.auxData);
    }
    cleanRedundantFrames(asyncStackTrace) {
        let stack = asyncStackTrace;
        let previous = null;
        while (stack) {
            if (previous && !stack.callFrames.length) {
                previous.parent = stack.parent;
            }
            else {
                previous = stack;
            }
            stack = stack.parent;
        }
        return asyncStackTrace;
    }
}
SDKModel.register(DebuggerModel, { capabilities: 4 , autostart: true });
const LOGPOINT_SOURCE_URL = 'debugger://logpoint';
const COND_BREAKPOINT_SOURCE_URL = 'debugger://breakpoint';

// Copyright 2014 The Chromium Authors
class AccessibilityNode {
    #accessibilityModel;
    #id;
    #backendDOMNodeId;
    #deferredDOMNode;
    #ignored;
    #ignoredReasons;
    #role;
    #name;
    #description;
    #value;
    #properties;
    #parentId;
    #frameId;
    #childIds;
    constructor(accessibilityModel, payload) {
        this.#accessibilityModel = accessibilityModel;
        this.#id = payload.nodeId;
        accessibilityModel.setAXNodeForAXId(this.#id, this);
        if (payload.backendDOMNodeId) {
            accessibilityModel.setAXNodeForBackendDOMNodeId(payload.backendDOMNodeId, this);
            this.#backendDOMNodeId = payload.backendDOMNodeId;
            this.#deferredDOMNode = new DeferredDOMNode(accessibilityModel.target(), payload.backendDOMNodeId);
        }
        else {
            this.#backendDOMNodeId = null;
            this.#deferredDOMNode = null;
        }
        this.#ignored = payload.ignored;
        if (this.#ignored && 'ignoredReasons' in payload) {
            this.#ignoredReasons = payload.ignoredReasons;
        }
        this.#role = payload.role || null;
        this.#name = payload.name || null;
        this.#description = payload.description || null;
        this.#value = payload.value || null;
        this.#properties = payload.properties || null;
        this.#childIds = [...new Set(payload.childIds)];
        this.#parentId = payload.parentId || null;
        if (payload.frameId && !payload.parentId) {
            this.#frameId = payload.frameId;
            accessibilityModel.setRootAXNodeForFrameId(payload.frameId, this);
        }
        else {
            this.#frameId = null;
        }
    }
    id() {
        return this.#id;
    }
    accessibilityModel() {
        return this.#accessibilityModel;
    }
    ignored() {
        return this.#ignored;
    }
    ignoredReasons() {
        return this.#ignoredReasons || null;
    }
    role() {
        return this.#role || null;
    }
    coreProperties() {
        const properties = [];
        if (this.#name) {
            properties.push({ name: "name" , value: this.#name });
        }
        if (this.#description) {
            properties.push({ name: "description" , value: this.#description });
        }
        if (this.#value) {
            properties.push({ name: "value" , value: this.#value });
        }
        return properties;
    }
    name() {
        return this.#name || null;
    }
    description() {
        return this.#description || null;
    }
    value() {
        return this.#value || null;
    }
    properties() {
        return this.#properties || null;
    }
    parentNode() {
        if (this.#parentId) {
            return this.#accessibilityModel.axNodeForId(this.#parentId);
        }
        return null;
    }
    isDOMNode() {
        return Boolean(this.#backendDOMNodeId);
    }
    backendDOMNodeId() {
        return this.#backendDOMNodeId;
    }
    deferredDOMNode() {
        return this.#deferredDOMNode;
    }
    highlightDOMNode() {
        const deferredNode = this.deferredDOMNode();
        if (!deferredNode) {
            return;
        }
        deferredNode.highlight();
    }
    children() {
        if (!this.#childIds) {
            return [];
        }
        const children = [];
        for (const childId of this.#childIds) {
            const child = this.#accessibilityModel.axNodeForId(childId);
            if (child) {
                children.push(child);
            }
        }
        return children;
    }
    numChildren() {
        if (!this.#childIds) {
            return 0;
        }
        return this.#childIds.length;
    }
    hasOnlyUnloadedChildren() {
        if (!this.#childIds || !this.#childIds.length) {
            return false;
        }
        return this.#childIds.every(id => this.#accessibilityModel.axNodeForId(id) === null);
    }
    hasUnloadedChildren() {
        if (!this.#childIds || !this.#childIds.length) {
            return false;
        }
        return this.#childIds.some(id => this.#accessibilityModel.axNodeForId(id) === null);
    }
    getFrameId() {
        return this.#frameId || this.parentNode()?.getFrameId() || null;
    }
}
class AccessibilityModel extends SDKModel {
    agent;
    #axIdToAXNode = new Map();
    #backendDOMNodeIdToAXNode = new Map();
    #frameIdToAXNode = new Map();
    #pendingChildRequests = new Map();
    #root = null;
    constructor(target) {
        super(target);
        target.registerAccessibilityDispatcher(this);
        this.agent = target.accessibilityAgent();
        void this.resumeModel();
    }
    clear() {
        this.#root = null;
        this.#axIdToAXNode.clear();
        this.#backendDOMNodeIdToAXNode.clear();
        this.#frameIdToAXNode.clear();
    }
    async resumeModel() {
        await this.agent.invoke_enable();
    }
    async suspendModel() {
        await this.agent.invoke_disable();
    }
    async requestPartialAXTree(node) {
        const { nodes } = await this.agent.invoke_getPartialAXTree({ nodeId: node.id, fetchRelatives: true });
        if (!nodes) {
            return;
        }
        const axNodes = [];
        for (const payload of nodes) {
            axNodes.push(new AccessibilityNode(this, payload));
        }
    }
    loadComplete({ root }) {
        this.clear();
        this.#root = new AccessibilityNode(this, root);
        this.dispatchEventToListeners("TreeUpdated" , { root: this.#root });
    }
    nodesUpdated({ nodes }) {
        this.createNodesFromPayload(nodes);
        this.dispatchEventToListeners("TreeUpdated" , {});
        return;
    }
    createNodesFromPayload(payloadNodes) {
        const accessibilityNodes = payloadNodes.map(node => {
            const sdkNode = new AccessibilityNode(this, node);
            return sdkNode;
        });
        return accessibilityNodes;
    }
    async requestRootNode(frameId) {
        if (frameId && this.#frameIdToAXNode.has(frameId)) {
            return this.#frameIdToAXNode.get(frameId);
        }
        if (!frameId && this.#root) {
            return this.#root;
        }
        const { node } = await this.agent.invoke_getRootAXNode({ frameId });
        if (!node) {
            return;
        }
        return this.createNodesFromPayload([node])[0];
    }
    async requestAXChildren(nodeId, frameId) {
        const parent = this.#axIdToAXNode.get(nodeId);
        if (!parent) {
            throw new Error('Cannot request children before parent');
        }
        if (!parent.hasUnloadedChildren()) {
            return parent.children();
        }
        const request = this.#pendingChildRequests.get(nodeId);
        if (request) {
            await request;
        }
        else {
            const request = this.agent.invoke_getChildAXNodes({ id: nodeId, frameId });
            this.#pendingChildRequests.set(nodeId, request);
            const result = await request;
            if (!result.getError()) {
                this.createNodesFromPayload(result.nodes);
                this.#pendingChildRequests.delete(nodeId);
            }
        }
        return parent.children();
    }
    async requestAndLoadSubTreeToNode(node) {
        const result = [];
        let ancestor = this.axNodeForDOMNode(node);
        while (ancestor) {
            result.push(ancestor);
            const parent = ancestor.parentNode();
            if (!parent) {
                return result;
            }
            ancestor = parent;
        }
        const { nodes } = await this.agent.invoke_getAXNodeAndAncestors({ backendNodeId: node.backendNodeId() });
        if (!nodes) {
            return null;
        }
        const ancestors = this.createNodesFromPayload(nodes);
        return ancestors;
    }
    axNodeForId(axId) {
        return this.#axIdToAXNode.get(axId) || null;
    }
    setRootAXNodeForFrameId(frameId, axNode) {
        this.#frameIdToAXNode.set(frameId, axNode);
    }
    setAXNodeForAXId(axId, axNode) {
        this.#axIdToAXNode.set(axId, axNode);
    }
    axNodeForDOMNode(domNode) {
        if (!domNode) {
            return null;
        }
        return this.#backendDOMNodeIdToAXNode.get(domNode.backendNodeId()) ?? null;
    }
    setAXNodeForBackendDOMNodeId(backendDOMNodeId, axNode) {
        this.#backendDOMNodeIdToAXNode.set(backendDOMNodeId, axNode);
    }
    getAgent() {
        return this.agent;
    }
}
SDKModel.register(AccessibilityModel, { capabilities: 2 , autostart: false });

// Copyright 2014 The Chromium Authors
const DEVTOOLS_ANIMATIONS_WORLD_NAME = 'devtools_animations';
const REPORT_SCROLL_POSITION_BINDING_NAME = '__devtools_report_scroll_position__';
const getScrollListenerNameInPage = (id) => `__devtools_scroll_listener_${id}__`;
async function resolveToObjectInWorld(domNode, worldName) {
    const resourceTreeModel = domNode.domModel().target().model(ResourceTreeModel);
    const pageAgent = domNode.domModel().target().pageAgent();
    for (const frame of resourceTreeModel.frames()) {
        const { executionContextId } = await pageAgent.invoke_createIsolatedWorld({ frameId: frame.id, worldName });
        const object = await domNode.resolveToObject(undefined, executionContextId);
        if (object) {
            return object;
        }
    }
    return null;
}
class AnimationDOMNode {
    #domNode;
    #scrollListenersById = new Map();
    #scrollBindingListener;
    static lastAddedListenerId = 0;
    constructor(domNode) {
        this.#domNode = domNode;
    }
    async #addReportScrollPositionBinding() {
        if (this.#scrollBindingListener) {
            return;
        }
        this.#scrollBindingListener = ev => {
            const { name, payload } = ev.data;
            if (name !== REPORT_SCROLL_POSITION_BINDING_NAME) {
                return;
            }
            const { scrollTop, scrollLeft, id } = JSON.parse(payload);
            const scrollListener = this.#scrollListenersById.get(id);
            if (!scrollListener) {
                return;
            }
            scrollListener({ scrollTop, scrollLeft });
        };
        const runtimeModel = this.#domNode.domModel().target().model(RuntimeModel);
        await runtimeModel.addBinding({
            name: REPORT_SCROLL_POSITION_BINDING_NAME,
            executionContextName: DEVTOOLS_ANIMATIONS_WORLD_NAME,
        });
        runtimeModel.addEventListener(Events$9.BindingCalled, this.#scrollBindingListener);
    }
    async #removeReportScrollPositionBinding() {
        if (!this.#scrollBindingListener) {
            return;
        }
        const runtimeModel = this.#domNode.domModel().target().model(RuntimeModel);
        await runtimeModel.removeBinding({
            name: REPORT_SCROLL_POSITION_BINDING_NAME,
        });
        runtimeModel.removeEventListener(Events$9.BindingCalled, this.#scrollBindingListener);
        this.#scrollBindingListener = undefined;
    }
    async addScrollEventListener(onScroll) {
        AnimationDOMNode.lastAddedListenerId++;
        const id = AnimationDOMNode.lastAddedListenerId;
        this.#scrollListenersById.set(id, onScroll);
        if (!this.#scrollBindingListener) {
            await this.#addReportScrollPositionBinding();
        }
        const object = await resolveToObjectInWorld(this.#domNode, DEVTOOLS_ANIMATIONS_WORLD_NAME);
        if (!object) {
            return null;
        }
        await object.callFunction(scrollListenerInPage, [
            id,
            REPORT_SCROLL_POSITION_BINDING_NAME,
            getScrollListenerNameInPage(id),
        ].map(arg => RemoteObject$1.toCallArgument(arg)));
        object.release();
        return id;
        function scrollListenerInPage(id, reportScrollPositionBindingName, scrollListenerNameInPage) {
            if ('scrollingElement' in this && !this.scrollingElement) {
                return;
            }
            const scrollingElement = ('scrollingElement' in this ? this.scrollingElement : this);
            this[scrollListenerNameInPage] = () => {
                globalThis[reportScrollPositionBindingName](JSON.stringify({ scrollTop: scrollingElement.scrollTop, scrollLeft: scrollingElement.scrollLeft, id }));
            };
            this.addEventListener('scroll', this[scrollListenerNameInPage], true);
        }
    }
    async removeScrollEventListener(id) {
        const object = await resolveToObjectInWorld(this.#domNode, DEVTOOLS_ANIMATIONS_WORLD_NAME);
        if (!object) {
            return;
        }
        await object.callFunction(removeScrollListenerInPage, [getScrollListenerNameInPage(id)].map(arg => RemoteObject$1.toCallArgument(arg)));
        object.release();
        this.#scrollListenersById.delete(id);
        if (this.#scrollListenersById.size === 0) {
            await this.#removeReportScrollPositionBinding();
        }
        function removeScrollListenerInPage(scrollListenerNameInPage) {
            this.removeEventListener('scroll', this[scrollListenerNameInPage]);
            delete this[scrollListenerNameInPage];
        }
    }
    async scrollTop() {
        return await this.#domNode.callFunction(scrollTopInPage).then(res => res?.value ?? null);
        function scrollTopInPage() {
            if ('scrollingElement' in this) {
                if (!this.scrollingElement) {
                    return 0;
                }
                return this.scrollingElement.scrollTop;
            }
            return this.scrollTop;
        }
    }
    async scrollLeft() {
        return await this.#domNode.callFunction(scrollLeftInPage).then(res => res?.value ?? null);
        function scrollLeftInPage() {
            if ('scrollingElement' in this) {
                if (!this.scrollingElement) {
                    return 0;
                }
                return this.scrollingElement.scrollLeft;
            }
            return this.scrollLeft;
        }
    }
    async setScrollTop(offset) {
        await this.#domNode.callFunction(setScrollTopInPage, [offset]);
        function setScrollTopInPage(offsetInPage) {
            if ('scrollingElement' in this) {
                if (!this.scrollingElement) {
                    return;
                }
                this.scrollingElement.scrollTop = offsetInPage;
            }
            else {
                this.scrollTop = offsetInPage;
            }
        }
    }
    async setScrollLeft(offset) {
        await this.#domNode.callFunction(setScrollLeftInPage, [offset]);
        function setScrollLeftInPage(offsetInPage) {
            if ('scrollingElement' in this) {
                if (!this.scrollingElement) {
                    return;
                }
                this.scrollingElement.scrollLeft = offsetInPage;
            }
            else {
                this.scrollLeft = offsetInPage;
            }
        }
    }
    async verticalScrollRange() {
        return await this.#domNode.callFunction(verticalScrollRangeInPage).then(res => res?.value ?? null);
        function verticalScrollRangeInPage() {
            if ('scrollingElement' in this) {
                if (!this.scrollingElement) {
                    return 0;
                }
                return this.scrollingElement.scrollHeight - this.scrollingElement.clientHeight;
            }
            return this.scrollHeight - this.clientHeight;
        }
    }
    async horizontalScrollRange() {
        return await this.#domNode.callFunction(horizontalScrollRangeInPage).then(res => res?.value ?? null);
        function horizontalScrollRangeInPage() {
            if ('scrollingElement' in this) {
                if (!this.scrollingElement) {
                    return 0;
                }
                return this.scrollingElement.scrollWidth - this.scrollingElement.clientWidth;
            }
            return this.scrollWidth - this.clientWidth;
        }
    }
}
function shouldGroupAnimations(firstAnimation, anim) {
    const firstAnimationTimeline = firstAnimation.viewOrScrollTimeline();
    const animationTimeline = anim.viewOrScrollTimeline();
    if (firstAnimationTimeline) {
        return Boolean(animationTimeline && firstAnimationTimeline.sourceNodeId === animationTimeline.sourceNodeId &&
            firstAnimationTimeline.axis === animationTimeline.axis);
    }
    return !animationTimeline && firstAnimation.startTime() === anim.startTime();
}
class AnimationModel extends SDKModel {
    runtimeModel;
    agent;
    #animationsById = new Map();
    animationGroups = new Map();
    #pendingAnimations = new Set();
    playbackRate = 1;
    #flushPendingAnimations;
    constructor(target) {
        super(target);
        this.runtimeModel = target.model(RuntimeModel);
        this.agent = target.animationAgent();
        target.registerAnimationDispatcher(new AnimationDispatcher(this));
        if (!target.suspended()) {
            void this.agent.invoke_enable();
        }
        const resourceTreeModel = target.model(ResourceTreeModel);
        resourceTreeModel.addEventListener(Events$6.PrimaryPageChanged, this.reset, this);
        this.#flushPendingAnimations = debounce(() => {
            while (this.#pendingAnimations.size) {
                this.matchExistingGroups(this.createGroupFromPendingAnimations());
            }
        }, 100);
    }
    reset() {
        this.#animationsById.clear();
        this.animationGroups.clear();
        this.#pendingAnimations.clear();
        this.dispatchEventToListeners(Events$4.ModelReset);
    }
    async devicePixelRatio() {
        const evaluateResult = await this.target().runtimeAgent().invoke_evaluate({ expression: 'window.devicePixelRatio' });
        if (evaluateResult?.result.type === 'number') {
            return evaluateResult?.result.value ?? 1;
        }
        return 1;
    }
    async getAnimationGroupForAnimation(name, nodeId) {
        for (const animationGroup of this.animationGroups.values()) {
            for (const animation of animationGroup.animations()) {
                if (animation.name() === name) {
                    const animationNode = await animation.source().node();
                    if (animationNode?.id === nodeId) {
                        return animationGroup;
                    }
                }
            }
        }
        return null;
    }
    animationCanceled(id) {
        this.#pendingAnimations.delete(id);
    }
    async animationUpdated(payload) {
        let foundAnimationGroup;
        let foundAnimation;
        for (const animationGroup of this.animationGroups.values()) {
            foundAnimation = animationGroup.animations().find(animation => animation.id() === payload.id);
            if (foundAnimation) {
                foundAnimationGroup = animationGroup;
                break;
            }
        }
        if (!foundAnimation || !foundAnimationGroup) {
            return;
        }
        await foundAnimation.setPayload(payload);
        this.dispatchEventToListeners(Events$4.AnimationGroupUpdated, foundAnimationGroup);
    }
    async animationStarted(payload) {
        if (!payload.source?.backendNodeId) {
            return;
        }
        const animation = await AnimationImpl.parsePayload(this, payload);
        const keyframesRule = animation.source().keyframesRule();
        if (animation.type() === 'WebAnimation' && keyframesRule?.keyframes().length === 0) {
            this.#pendingAnimations.delete(animation.id());
        }
        else {
            this.#animationsById.set(animation.id(), animation);
            this.#pendingAnimations.add(animation.id());
        }
        this.#flushPendingAnimations();
    }
    matchExistingGroups(incomingGroup) {
        let matchedGroup = null;
        for (const group of this.animationGroups.values()) {
            if (group.matches(incomingGroup)) {
                matchedGroup = group;
                group.rebaseTo(incomingGroup);
                break;
            }
            if (group.shouldInclude(incomingGroup)) {
                matchedGroup = group;
                group.appendAnimations(incomingGroup.animations());
                break;
            }
        }
        if (!matchedGroup) {
            this.animationGroups.set(incomingGroup.id(), incomingGroup);
            this.dispatchEventToListeners(Events$4.AnimationGroupStarted, incomingGroup);
        }
        else {
            this.dispatchEventToListeners(Events$4.AnimationGroupUpdated, matchedGroup);
        }
        return Boolean(matchedGroup);
    }
    createGroupFromPendingAnimations() {
        console.assert(this.#pendingAnimations.size > 0);
        const firstAnimationId = this.#pendingAnimations.values().next().value;
        this.#pendingAnimations.delete(firstAnimationId);
        const firstAnimation = this.#animationsById.get(firstAnimationId);
        if (!firstAnimation) {
            throw new Error('Unable to locate first animation');
        }
        const groupedAnimations = [firstAnimation];
        const remainingAnimations = new Set();
        for (const id of this.#pendingAnimations) {
            const anim = this.#animationsById.get(id);
            if (shouldGroupAnimations(firstAnimation, anim)) {
                groupedAnimations.push(anim);
            }
            else {
                remainingAnimations.add(id);
            }
        }
        this.#pendingAnimations = remainingAnimations;
        groupedAnimations.sort((anim1, anim2) => anim1.startTime() - anim2.startTime());
        return new AnimationGroup(this, firstAnimationId, groupedAnimations);
    }
    setPlaybackRate(playbackRate) {
        this.playbackRate = playbackRate;
        void this.agent.invoke_setPlaybackRate({ playbackRate });
    }
    releaseAnimations(animations) {
        void this.agent.invoke_releaseAnimations({ animations });
    }
    async suspendModel() {
        await this.agent.invoke_disable().then(() => this.reset());
    }
    async resumeModel() {
        await this.agent.invoke_enable();
    }
}
var Events$4;
(function (Events) {
    Events["AnimationGroupStarted"] = "AnimationGroupStarted";
    Events["AnimationGroupUpdated"] = "AnimationGroupUpdated";
    Events["ModelReset"] = "ModelReset";
})(Events$4 || (Events$4 = {}));
class AnimationImpl {
    #animationModel;
    #payload;
    #source;
    #playState;
    constructor(animationModel) {
        this.#animationModel = animationModel;
    }
    static async parsePayload(animationModel, payload) {
        const animation = new AnimationImpl(animationModel);
        await animation.setPayload(payload);
        return animation;
    }
    async setPayload(payload) {
        if (payload.viewOrScrollTimeline) {
            const devicePixelRatio = await this.#animationModel.devicePixelRatio();
            if (payload.viewOrScrollTimeline.startOffset) {
                payload.viewOrScrollTimeline.startOffset /= devicePixelRatio;
            }
            if (payload.viewOrScrollTimeline.endOffset) {
                payload.viewOrScrollTimeline.endOffset /= devicePixelRatio;
            }
        }
        this.#payload = payload;
        if (this.#source && payload.source) {
            this.#source.setPayload(payload.source);
        }
        else if (!this.#source && payload.source) {
            this.#source = new AnimationEffect(this.#animationModel, payload.source);
        }
    }
    percentageToPixels(percentage, viewOrScrollTimeline) {
        const { startOffset, endOffset } = viewOrScrollTimeline;
        if (startOffset === undefined || endOffset === undefined) {
            throw new Error('startOffset or endOffset does not exist in viewOrScrollTimeline');
        }
        return (endOffset - startOffset) * (percentage / 100);
    }
    viewOrScrollTimeline() {
        return this.#payload.viewOrScrollTimeline;
    }
    id() {
        return this.#payload.id;
    }
    name() {
        return this.#payload.name;
    }
    paused() {
        return this.#payload.pausedState;
    }
    playState() {
        return this.#playState || this.#payload.playState;
    }
    playbackRate() {
        return this.#payload.playbackRate;
    }
    startTime() {
        const viewOrScrollTimeline = this.viewOrScrollTimeline();
        if (viewOrScrollTimeline) {
            return this.percentageToPixels(this.playbackRate() > 0 ? this.#payload.startTime : 100 - this.#payload.startTime, viewOrScrollTimeline) +
                (this.viewOrScrollTimeline()?.startOffset ?? 0);
        }
        return this.#payload.startTime;
    }
    iterationDuration() {
        const viewOrScrollTimeline = this.viewOrScrollTimeline();
        if (viewOrScrollTimeline) {
            return this.percentageToPixels(this.source().duration(), viewOrScrollTimeline);
        }
        return this.source().duration();
    }
    endTime() {
        if (!this.source().iterations) {
            return Infinity;
        }
        if (this.viewOrScrollTimeline()) {
            return this.startTime() + this.iterationDuration() * this.source().iterations();
        }
        return this.startTime() + this.source().delay() + this.source().duration() * this.source().iterations() +
            this.source().endDelay();
    }
    finiteDuration() {
        const iterations = Math.min(this.source().iterations(), 3);
        if (this.viewOrScrollTimeline()) {
            return this.iterationDuration() * iterations;
        }
        return this.source().delay() + this.source().duration() * iterations;
    }
    currentTime() {
        const viewOrScrollTimeline = this.viewOrScrollTimeline();
        if (viewOrScrollTimeline) {
            return this.percentageToPixels(this.#payload.currentTime, viewOrScrollTimeline);
        }
        return this.#payload.currentTime;
    }
    source() {
        return this.#source;
    }
    type() {
        return this.#payload.type;
    }
    overlaps(animation) {
        if (!this.source().iterations() || !animation.source().iterations()) {
            return true;
        }
        const firstAnimation = this.startTime() < animation.startTime() ? this : animation;
        const secondAnimation = firstAnimation === this ? animation : this;
        return firstAnimation.endTime() >= secondAnimation.startTime();
    }
    delayOrStartTime() {
        if (this.viewOrScrollTimeline()) {
            return this.startTime();
        }
        return this.source().delay();
    }
    setTiming(duration, delay) {
        void this.#source.node().then(node => {
            if (!node) {
                throw new Error('Unable to find node');
            }
            this.updateNodeStyle(duration, delay, node);
        });
        this.#source.durationInternal = duration;
        this.#source.delayInternal = delay;
        void this.#animationModel.agent.invoke_setTiming({ animationId: this.id(), duration, delay });
    }
    updateNodeStyle(duration, delay, node) {
        let animationPrefix;
        if (this.type() === "CSSTransition" ) {
            animationPrefix = 'transition-';
        }
        else if (this.type() === "CSSAnimation" ) {
            animationPrefix = 'animation-';
        }
        else {
            return;
        }
        if (!node.id) {
            throw new Error('Node has no id');
        }
        const cssModel = node.domModel().cssModel();
        cssModel.setEffectivePropertyValueForNode(node.id, animationPrefix + 'duration', duration + 'ms');
        cssModel.setEffectivePropertyValueForNode(node.id, animationPrefix + 'delay', delay + 'ms');
    }
    async remoteObjectPromise() {
        const payload = await this.#animationModel.agent.invoke_resolveAnimation({ animationId: this.id() });
        if (!payload) {
            return null;
        }
        return this.#animationModel.runtimeModel.createRemoteObject(payload.remoteObject);
    }
    cssId() {
        return this.#payload.cssId || '';
    }
}
class AnimationEffect {
    #animationModel;
    #payload;
    delayInternal;
    durationInternal;
    #keyframesRule;
    #deferredNode;
    constructor(animationModel, payload) {
        this.#animationModel = animationModel;
        this.setPayload(payload);
    }
    setPayload(payload) {
        this.#payload = payload;
        if (!this.#keyframesRule && payload.keyframesRule) {
            this.#keyframesRule = new KeyframesRule(payload.keyframesRule);
        }
        else if (this.#keyframesRule && payload.keyframesRule) {
            this.#keyframesRule.setPayload(payload.keyframesRule);
        }
        this.delayInternal = payload.delay;
        this.durationInternal = payload.duration;
    }
    delay() {
        return this.delayInternal;
    }
    endDelay() {
        return this.#payload.endDelay;
    }
    iterations() {
        if (!this.delay() && !this.endDelay() && !this.duration()) {
            return 0;
        }
        return this.#payload.iterations || Infinity;
    }
    duration() {
        return this.durationInternal;
    }
    direction() {
        return this.#payload.direction;
    }
    fill() {
        return this.#payload.fill;
    }
    node() {
        if (!this.#deferredNode) {
            this.#deferredNode = new DeferredDOMNode(this.#animationModel.target(), this.backendNodeId());
        }
        return this.#deferredNode.resolvePromise();
    }
    deferredNode() {
        return new DeferredDOMNode(this.#animationModel.target(), this.backendNodeId());
    }
    backendNodeId() {
        return this.#payload.backendNodeId;
    }
    keyframesRule() {
        return this.#keyframesRule || null;
    }
    easing() {
        return this.#payload.easing;
    }
}
class KeyframesRule {
    #payload;
    #keyframes;
    constructor(payload) {
        this.setPayload(payload);
    }
    setPayload(payload) {
        this.#payload = payload;
        if (!this.#keyframes) {
            this.#keyframes = this.#payload.keyframes.map(keyframeStyle => new KeyframeStyle(keyframeStyle));
        }
        else {
            this.#payload.keyframes.forEach((keyframeStyle, index) => {
                this.#keyframes[index]?.setPayload(keyframeStyle);
            });
        }
    }
    name() {
        return this.#payload.name;
    }
    keyframes() {
        return this.#keyframes;
    }
}
class KeyframeStyle {
    #payload;
    #offset;
    constructor(payload) {
        this.setPayload(payload);
    }
    setPayload(payload) {
        this.#payload = payload;
        this.#offset = payload.offset;
    }
    offset() {
        return this.#offset;
    }
    setOffset(offset) {
        this.#offset = offset * 100 + '%';
    }
    offsetAsNumber() {
        return parseFloat(this.#offset) / 100;
    }
    easing() {
        return this.#payload.easing;
    }
}
class AnimationGroup {
    #animationModel;
    #id;
    #scrollNode;
    #animations;
    #paused = false;
    constructor(animationModel, id, animations) {
        this.#animationModel = animationModel;
        this.#id = id;
        this.#animations = animations;
    }
    isScrollDriven() {
        return Boolean(this.#animations[0]?.viewOrScrollTimeline());
    }
    id() {
        return this.#id;
    }
    animations() {
        return this.#animations;
    }
    release() {
        this.#animationModel.animationGroups.delete(this.id());
        this.#animationModel.releaseAnimations(this.animationIds());
    }
    animationIds() {
        function extractId(animation) {
            return animation.id();
        }
        return this.#animations.map(extractId);
    }
    startTime() {
        return this.#animations[0].startTime();
    }
    groupDuration() {
        let duration = 0;
        for (const anim of this.#animations) {
            duration = Math.max(duration, anim.delayOrStartTime() + anim.iterationDuration());
        }
        return duration;
    }
    finiteDuration() {
        let maxDuration = 0;
        for (let i = 0; i < this.#animations.length; ++i) {
            maxDuration = Math.max(maxDuration, this.#animations[i].finiteDuration());
        }
        return maxDuration;
    }
    scrollOrientation() {
        const timeline = this.#animations[0]?.viewOrScrollTimeline();
        if (!timeline) {
            return null;
        }
        return timeline.axis;
    }
    async scrollNode() {
        if (this.#scrollNode) {
            return this.#scrollNode;
        }
        if (!this.isScrollDriven()) {
            return null;
        }
        const sourceNodeId = this.#animations[0]?.viewOrScrollTimeline()?.sourceNodeId;
        if (!sourceNodeId) {
            return null;
        }
        const deferredScrollNode = new DeferredDOMNode(this.#animationModel.target(), sourceNodeId);
        const scrollNode = await deferredScrollNode.resolvePromise();
        if (!scrollNode) {
            return null;
        }
        this.#scrollNode = new AnimationDOMNode(scrollNode);
        return this.#scrollNode;
    }
    seekTo(currentTime) {
        void this.#animationModel.agent.invoke_seekAnimations({ animations: this.animationIds(), currentTime });
    }
    paused() {
        return this.#paused;
    }
    togglePause(paused) {
        if (paused === this.#paused) {
            return;
        }
        this.#paused = paused;
        void this.#animationModel.agent.invoke_setPaused({ animations: this.animationIds(), paused });
    }
    currentTimePromise() {
        let longestAnim = null;
        for (const anim of this.#animations) {
            if (!longestAnim || anim.endTime() > longestAnim.endTime()) {
                longestAnim = anim;
            }
        }
        if (!longestAnim) {
            throw new Error('No longest animation found');
        }
        return this.#animationModel.agent.invoke_getCurrentTime({ id: longestAnim.id() })
            .then(({ currentTime }) => currentTime || 0);
    }
    matches(group) {
        function extractId(anim) {
            const timelineId = (anim.viewOrScrollTimeline()?.sourceNodeId ?? '') + (anim.viewOrScrollTimeline()?.axis ?? '');
            const regularId = anim.type() === "WebAnimation"  ? anim.type() + anim.id() : anim.cssId();
            return regularId + timelineId;
        }
        if (this.#animations.length !== group.#animations.length) {
            return false;
        }
        const left = this.#animations.map(extractId).sort();
        const right = group.#animations.map(extractId).sort();
        for (let i = 0; i < left.length; i++) {
            if (left[i] !== right[i]) {
                return false;
            }
        }
        return true;
    }
    shouldInclude(group) {
        const [firstIncomingAnimation] = group.#animations;
        const [firstAnimation] = this.#animations;
        return shouldGroupAnimations(firstAnimation, firstIncomingAnimation);
    }
    appendAnimations(animations) {
        this.#animations.push(...animations);
    }
    rebaseTo(group) {
        this.#animationModel.releaseAnimations(this.animationIds());
        this.#animations = group.#animations;
        this.#scrollNode = undefined;
    }
}
class AnimationDispatcher {
    #animationModel;
    constructor(animationModel) {
        this.#animationModel = animationModel;
    }
    animationCreated(_event) {
    }
    animationCanceled({ id }) {
        this.#animationModel.animationCanceled(id);
    }
    animationStarted({ animation }) {
        void this.#animationModel.animationStarted(animation);
    }
    animationUpdated({ animation }) {
        void this.#animationModel.animationUpdated(animation);
    }
}
SDKModel.register(AnimationModel, { capabilities: 2 , autostart: true });

// Copyright 2023 The Chromium Authors
class AutofillModel extends SDKModel {
    agent;
    #enabled;
    #showTestAddressesInAutofillMenu;
    constructor(target) {
        super(target);
        this.agent = target.autofillAgent();
        this.#showTestAddressesInAutofillMenu =
            Settings.instance().createSetting('show-test-addresses-in-autofill-menu-on-event', false);
        this.#showTestAddressesInAutofillMenu.addChangeListener(this.#setTestAddresses, this);
        target.registerAutofillDispatcher(this);
        this.enable();
    }
    dispose() {
        this.#showTestAddressesInAutofillMenu.removeChangeListener(this.#setTestAddresses, this);
        super.dispose();
    }
    #setTestAddresses() {
        void this.agent.invoke_setAddresses({
            addresses: this.#showTestAddressesInAutofillMenu.get() ?
                [
                    {
                        fields: [
                            { name: 'ADDRESS_HOME_COUNTRY', value: 'US' },
                            { name: 'NAME_FULL', value: 'Jon Stewart Doe' },
                            { name: 'NAME_FIRST', value: 'Jon' },
                            { name: 'NAME_MIDDLE', value: 'Stewart' },
                            { name: 'NAME_LAST', value: 'Doe' },
                            { name: 'COMPANY_NAME', value: 'Fake Company' },
                            { name: 'ADDRESS_HOME_LINE1', value: '1600 Fake Street' },
                            { name: 'ADDRESS_HOME_LINE2', value: 'Apartment 1' },
                            { name: 'ADDRESS_HOME_ZIP', value: '94043' },
                            { name: 'ADDRESS_HOME_CITY', value: 'Mountain View' },
                            { name: 'ADDRESS_HOME_STATE', value: 'CA' },
                            { name: 'EMAIL_ADDRESS', value: 'test@example.us' },
                            { name: 'PHONE_HOME_WHOLE_NUMBER', value: '+16019521325' },
                        ],
                    },
                    {
                        fields: [
                            { name: 'ADDRESS_HOME_COUNTRY', value: 'BR' },
                            { name: 'NAME_FULL', value: 'João Souza Silva' },
                            { name: 'NAME_FIRST', value: 'João' },
                            { name: 'NAME_LAST', value: 'Souza Silva' },
                            { name: 'NAME_LAST_FIRST', value: 'Souza' },
                            { name: 'NAME_LAST_SECOND', value: 'Silva' },
                            { name: 'COMPANY_NAME', value: 'Empresa Falsa' },
                            { name: 'ADDRESS_HOME_STREET_ADDRESS', value: 'Rua Inexistente, 2000\nAndar 2, Apartamento 1' },
                            { name: 'ADDRESS_HOME_STREET_LOCATION', value: 'Rua Inexistente, 2000' },
                            { name: 'ADDRESS_HOME_STREET_NAME', value: 'Rua Inexistente' },
                            { name: 'ADDRESS_HOME_HOUSE_NUMBER', value: '2000' },
                            { name: 'ADDRESS_HOME_SUBPREMISE', value: 'Andar 2, Apartamento 1' },
                            { name: 'ADDRESS_HOME_APT_NUM', value: '1' },
                            { name: 'ADDRESS_HOME_FLOOR', value: '2' },
                            { name: 'ADDRESS_HOME_APT', value: 'Apartamento 1' },
                            { name: 'ADDRESS_HOME_APT_TYPE', value: 'Apartamento' },
                            { name: 'ADDRESS_HOME_APT_NUM', value: '1' },
                            { name: 'ADDRESS_HOME_DEPENDENT_LOCALITY', value: 'Santa Efigênia' },
                            { name: 'ADDRESS_HOME_LANDMARK', value: 'Próximo à estação Santa Efigênia' },
                            { name: 'ADDRESS_HOME_OVERFLOW', value: 'Andar 2, Apartamento 1' },
                            { name: 'ADDRESS_HOME_ZIP', value: '30260-080' },
                            { name: 'ADDRESS_HOME_CITY', value: 'Belo Horizonte' },
                            { name: 'ADDRESS_HOME_STATE', value: 'MG' },
                            { name: 'EMAIL_ADDRESS', value: 'teste@exemplo.us' },
                            { name: 'PHONE_HOME_WHOLE_NUMBER', value: '+553121286800' },
                        ],
                    },
                    {
                        fields: [
                            { name: 'ADDRESS_HOME_COUNTRY', value: 'MX' },
                            { name: 'NAME_FULL', value: 'Juan Francisco García Flores' },
                            { name: 'NAME_FIRST', value: 'Juan Francisco' },
                            { name: 'NAME_LAST', value: 'García Flores' },
                            { name: 'NAME_LAST_FIRST', value: 'García' },
                            { name: 'NAME_LAST_SECOND', value: 'Flores' },
                            { name: 'COMPANY_NAME', value: 'Empresa Falsa' },
                            {
                                name: 'ADDRESS_HOME_STREET_ADDRESS',
                                value: 'C. Falsa 445\nPiso 2, Apartamento 1\nEntre calle Volcán y calle Montes Blancos, cerca de la estación de metro',
                            },
                            { name: 'ADDRESS_HOME_STREET_LOCATION', value: 'C. Falsa 445' },
                            { name: 'ADDRESS_HOME_STREET_NAME', value: 'C. Falsa' },
                            { name: 'ADDRESS_HOME_HOUSE_NUMBER', value: '445' },
                            { name: 'ADDRESS_HOME_SUBPREMISE', value: 'Piso 2, Apartamento 1' },
                            { name: 'ADDRESS_HOME_FLOOR', value: '2' },
                            { name: 'ADDRESS_HOME_APT', value: 'Apartamento 1' },
                            { name: 'ADDRESS_HOME_APT_TYPE', value: 'Apartamento' },
                            { name: 'ADDRESS_HOME_APT_NUM', value: '1' },
                            { name: 'ADDRESS_HOME_DEPENDENT_LOCALITY', value: 'Lomas de Chapultepec' },
                            {
                                name: 'ADDRESS_HOME_OVERFLOW',
                                value: 'Entre calle Volcán y calle Montes Celestes, cerca de la estación de metro',
                            },
                            {
                                name: 'ADDRESS_HOME_BETWEEN_STREETS_OR_LANDMARK',
                                value: 'Entre calle Volcán y calle Montes Blancos, cerca de la estación de metro',
                            },
                            { name: 'ADDRESS_HOME_LANDMARK', value: 'Cerca de la estación de metro' },
                            { name: 'ADDRESS_HOME_BETWEEN_STREETS', value: 'Entre calle Volcán y calle Montes Blancos' },
                            { name: 'ADDRESS_HOME_BETWEEN_STREETS_1', value: 'calle Volcán' },
                            { name: 'ADDRESS_HOME_BETWEEN_STREETS_2', value: 'calle Montes Blancos' },
                            { name: 'ADDRESS_HOME_ADMIN_LEVEL2', value: 'Miguel Hidalgo' },
                            { name: 'ADDRESS_HOME_ZIP', value: '11001' },
                            { name: 'ADDRESS_HOME_CITY', value: 'Ciudad de México' },
                            { name: 'ADDRESS_HOME_STATE', value: 'Distrito Federal' },
                            { name: 'EMAIL_ADDRESS', value: 'ejemplo@ejemplo.mx' },
                            { name: 'PHONE_HOME_WHOLE_NUMBER', value: '+525553428400' },
                        ],
                    },
                    {
                        fields: [
                            { name: 'ADDRESS_HOME_COUNTRY', value: 'DE' },
                            { name: 'NAME_FULL', value: 'Gottfried Wilhelm Leibniz' },
                            { name: 'NAME_FIRST', value: 'Gottfried' },
                            { name: 'NAME_MIDDLE', value: 'Wilhelm' },
                            { name: 'NAME_LAST', value: 'Leibniz' },
                            { name: 'COMPANY_NAME', value: 'Erfundenes Unternehmen' },
                            { name: 'ADDRESS_HOME_LINE1', value: 'Erfundene Straße 33' },
                            { name: 'ADDRESS_HOME_LINE2', value: 'Wohnung 1' },
                            { name: 'ADDRESS_HOME_ZIP', value: '80732' },
                            { name: 'ADDRESS_HOME_CITY', value: 'München' },
                            { name: 'EMAIL_ADDRESS', value: 'test@beispiel.de' },
                            { name: 'PHONE_HOME_WHOLE_NUMBER', value: '+4930303986300' },
                        ],
                    },
                ] :
                [],
        });
    }
    enable() {
        if (this.#enabled || isUnderTest()) {
            return;
        }
        void this.agent.invoke_enable();
        this.#setTestAddresses();
        this.#enabled = true;
    }
    disable() {
        if (!this.#enabled || isUnderTest()) {
            return;
        }
        this.#enabled = false;
        void this.agent.invoke_disable();
    }
    addressFormFilled(addressFormFilledEvent) {
        this.dispatchEventToListeners("AddressFormFilled" , { autofillModel: this, event: addressFormFilledEvent });
    }
}
SDKModel.register(AutofillModel, { capabilities: 2 , autostart: true });

// Copyright 2018 The Chromium Authors
const UIStrings$Y = {
    main: 'Main',
};
const str_$X = registerUIStrings('core/sdk/ChildTargetManager.ts', UIStrings$Y);
getLocalizedString.bind(undefined, str_$X);

// Copyright 2011 The Chromium Authors
const UIStrings$X = {
    couldNotLoadContentForSS: 'Could not load content for {PH1} ({PH2})',
};
const str_$W = registerUIStrings('core/sdk/CompilerSourceMappingContentProvider.ts', UIStrings$X);
const i18nString$F = getLocalizedString.bind(undefined, str_$W);
class CompilerSourceMappingContentProvider {
    #sourceURL;
    #contentType;
    #initiator;
    constructor(sourceURL, contentType, initiator) {
        this.#sourceURL = sourceURL;
        this.#contentType = contentType;
        this.#initiator = initiator;
    }
    contentURL() {
        return this.#sourceURL;
    }
    contentType() {
        return this.#contentType;
    }
    async requestContentData() {
        try {
            const { content } = await PageResourceLoader.instance().loadResource(this.#sourceURL, this.#initiator);
            return new ContentData(content,  false, this.#contentType.canonicalMimeType());
        }
        catch (e) {
            const error = i18nString$F(UIStrings$X.couldNotLoadContentForSS, { PH1: this.#sourceURL, PH2: e.message });
            console.error(error);
            return { error };
        }
    }
    async searchInContent(query, caseSensitive, isRegex) {
        const contentData = await this.requestContentData();
        return performSearchInContentData(contentData, query, caseSensitive, isRegex);
    }
}

// Copyright 2024 The Chromium Authors
const UIStrings$W = {
    noSourceText: 'No source text available',
    noHostWindow: 'Can not find host window',
    errorLoadingLog: 'Error loading log',
};
const str_$V = registerUIStrings('core/sdk/RehydratingConnection.ts', UIStrings$W);
getLocalizedString.bind(undefined, str_$V);

// Copyright 2015 The Chromium Authors
const UIStrings$V = {
    websocketDisconnected: 'WebSocket disconnected',
};
const str_$U = registerUIStrings('core/sdk/Connections.ts', UIStrings$V);
getLocalizedString.bind(undefined, str_$U);

// Copyright 2020 The Chromium Authors
var FrontendMessageType;
(function (FrontendMessageType) {
    FrontendMessageType["Result"] = "result";
    FrontendMessageType["Command"] = "command";
    FrontendMessageType["System"] = "system";
    FrontendMessageType["QueryObjectResult"] = "queryObjectResult";
})(FrontendMessageType || (FrontendMessageType = {}));

// Copyright 2014 The Chromium Authors
const UIStrings$U = {
    profileD: 'Profile {PH1}',
};
const str_$T = registerUIStrings('core/sdk/CPUProfilerModel.ts', UIStrings$U);
const i18nString$E = getLocalizedString.bind(undefined, str_$T);
class CPUProfilerModel extends SDKModel {
    #nextAnonymousConsoleProfileNumber;
    #anonymousConsoleProfileIdToTitle;
    #profilerAgent;
    #preciseCoverageDeltaUpdateCallback;
    #debuggerModel;
    registeredConsoleProfileMessages = [];
    constructor(target) {
        super(target);
        this.#nextAnonymousConsoleProfileNumber = 1;
        this.#anonymousConsoleProfileIdToTitle = new Map();
        this.#profilerAgent = target.profilerAgent();
        this.#preciseCoverageDeltaUpdateCallback = null;
        target.registerProfilerDispatcher(this);
        void this.#profilerAgent.invoke_enable();
        this.#debuggerModel = target.model(DebuggerModel);
    }
    runtimeModel() {
        return this.#debuggerModel.runtimeModel();
    }
    debuggerModel() {
        return this.#debuggerModel;
    }
    consoleProfileStarted({ id, location, title }) {
        if (!title) {
            title = i18nString$E(UIStrings$U.profileD, { PH1: this.#nextAnonymousConsoleProfileNumber++ });
            this.#anonymousConsoleProfileIdToTitle.set(id, title);
        }
        const eventData = this.createEventDataFrom(id, location, title);
        this.dispatchEventToListeners("ConsoleProfileStarted" , eventData);
    }
    consoleProfileFinished({ id, location, profile, title }) {
        if (!title) {
            title = this.#anonymousConsoleProfileIdToTitle.get(id);
            this.#anonymousConsoleProfileIdToTitle.delete(id);
        }
        const eventData = {
            ...this.createEventDataFrom(id, location, title),
            cpuProfile: profile,
        };
        this.registeredConsoleProfileMessages.push(eventData);
        this.dispatchEventToListeners("ConsoleProfileFinished" , eventData);
    }
    createEventDataFrom(id, scriptLocation, title) {
        const debuggerLocation = Location$1.fromPayload(this.#debuggerModel, scriptLocation);
        const globalId = this.target().id() + '.' + id;
        return {
            id: globalId,
            scriptLocation: debuggerLocation,
            title: title || '',
            cpuProfilerModel: this,
        };
    }
    startRecording() {
        const intervalUs = 100;
        void this.#profilerAgent.invoke_setSamplingInterval({ interval: intervalUs });
        return this.#profilerAgent.invoke_start();
    }
    stopRecording() {
        return this.#profilerAgent.invoke_stop().then(response => response.profile || null);
    }
    startPreciseCoverage(jsCoveragePerBlock, preciseCoverageDeltaUpdateCallback) {
        const callCount = false;
        this.#preciseCoverageDeltaUpdateCallback = preciseCoverageDeltaUpdateCallback;
        const allowUpdatesTriggeredByBackend = true;
        return this.#profilerAgent.invoke_startPreciseCoverage({ callCount, detailed: jsCoveragePerBlock, allowTriggeredUpdates: allowUpdatesTriggeredByBackend });
    }
    async takePreciseCoverage() {
        const r = await this.#profilerAgent.invoke_takePreciseCoverage();
        const timestamp = (r?.timestamp) || 0;
        const coverage = (r?.result) || [];
        return { timestamp, coverage };
    }
    stopPreciseCoverage() {
        this.#preciseCoverageDeltaUpdateCallback = null;
        return this.#profilerAgent.invoke_stopPreciseCoverage();
    }
    preciseCoverageDeltaUpdate({ timestamp, result }) {
        if (this.#preciseCoverageDeltaUpdateCallback) {
            void this.#preciseCoverageDeltaUpdateCallback(timestamp, result);
        }
    }
}
SDKModel.register(CPUProfilerModel, { capabilities: 4 , autostart: true });

// Copyright 2017 The Chromium Authors
class LogModel extends SDKModel {
    #logAgent;
    constructor(target) {
        super(target);
        target.registerLogDispatcher(this);
        this.#logAgent = target.logAgent();
        void this.#logAgent.invoke_enable();
        if (!isUnderTest()) {
            void this.#logAgent.invoke_startViolationsReport({
                config: [
                    { name: "longTask" , threshold: 200 },
                    { name: "longLayout" , threshold: 30 },
                    { name: "blockedEvent" , threshold: 100 },
                    { name: "blockedParser" , threshold: -1 },
                    { name: "handler" , threshold: 150 },
                    { name: "recurringHandler" , threshold: 50 },
                    { name: "discouragedAPIUse" , threshold: -1 },
                ],
            });
        }
    }
    entryAdded({ entry }) {
        this.dispatchEventToListeners("EntryAdded" , { logModel: this, entry });
    }
    requestClear() {
        void this.#logAgent.invoke_clear();
    }
}
SDKModel.register(LogModel, { capabilities: 8 , autostart: true });

// Copyright 2011 The Chromium Authors
const UIStrings$T = {
    navigatedToS: 'Navigated to {PH1}',
    bfcacheNavigation: 'Navigation to {PH1} was restored from back/forward cache (see https://web.dev/bfcache/)',
    profileSStarted: 'Profile \'\'{PH1}\'\' started.',
    profileSFinished: 'Profile \'\'{PH1}\'\' finished.',
    failedToSaveToTempVariable: 'Failed to save to temp variable.',
};
const str_$S = registerUIStrings('core/sdk/ConsoleModel.ts', UIStrings$T);
const i18nString$D = getLocalizedString.bind(undefined, str_$S);
class ConsoleModel extends SDKModel {
    #messages = [];
    #messagesByTimestamp = new Multimap();
    #messageByExceptionId = new Map();
    #warnings = 0;
    #errors = 0;
    #violations = 0;
    #pageLoadSequenceNumber = 0;
    #targetListeners = new WeakMap();
    constructor(target) {
        super(target);
        const resourceTreeModel = target.model(ResourceTreeModel);
        if (!resourceTreeModel || resourceTreeModel.cachedResourcesLoaded()) {
            this.initTarget(target);
            return;
        }
        const eventListener = resourceTreeModel.addEventListener(Events$6.CachedResourcesLoaded, () => {
            removeEventListeners([eventListener]);
            this.initTarget(target);
        });
    }
    initTarget(target) {
        const eventListeners = [];
        const cpuProfilerModel = target.model(CPUProfilerModel);
        if (cpuProfilerModel) {
            eventListeners.push(cpuProfilerModel.addEventListener("ConsoleProfileStarted" , this.consoleProfileStarted.bind(this, cpuProfilerModel)));
            eventListeners.push(cpuProfilerModel.addEventListener("ConsoleProfileFinished" , this.consoleProfileFinished.bind(this, cpuProfilerModel)));
        }
        const resourceTreeModel = target.model(ResourceTreeModel);
        if (resourceTreeModel && target.parentTarget()?.type() !== Type$2.FRAME) {
            eventListeners.push(resourceTreeModel.addEventListener(Events$6.PrimaryPageChanged, this.primaryPageChanged, this));
        }
        const runtimeModel = target.model(RuntimeModel);
        if (runtimeModel) {
            eventListeners.push(runtimeModel.addEventListener(Events$9.ExceptionThrown, this.exceptionThrown.bind(this, runtimeModel)));
            eventListeners.push(runtimeModel.addEventListener(Events$9.ExceptionRevoked, this.exceptionRevoked.bind(this, runtimeModel)));
            eventListeners.push(runtimeModel.addEventListener(Events$9.ConsoleAPICalled, this.consoleAPICalled.bind(this, runtimeModel)));
            if (target.parentTarget()?.type() !== Type$2.FRAME) {
                eventListeners.push(runtimeModel.debuggerModel().addEventListener(Events$5.GlobalObjectCleared, this.clearIfNecessary, this));
            }
            eventListeners.push(runtimeModel.addEventListener(Events$9.QueryObjectRequested, this.queryObjectRequested.bind(this, runtimeModel)));
        }
        this.#targetListeners.set(target, eventListeners);
    }
    targetRemoved(target) {
        const runtimeModel = target.model(RuntimeModel);
        if (runtimeModel) {
            this.#messageByExceptionId.delete(runtimeModel);
        }
        removeEventListeners(this.#targetListeners.get(target) || []);
    }
    async evaluateCommandInConsole(executionContext, originatingMessage, expression, useCommandLineAPI) {
        const result = await executionContext.evaluate({
            expression,
            objectGroup: 'console',
            includeCommandLineAPI: useCommandLineAPI,
            silent: false,
            returnByValue: false,
            generatePreview: true,
            replMode: true,
            allowUnsafeEvalBlockedByCSP: false,
        }, Settings.instance().moduleSetting('console-user-activation-eval').get(),
         false);
        userMetrics.actionTaken(Action.ConsoleEvaluated);
        if ('error' in result) {
            return;
        }
        await Console.instance().showPromise();
        this.dispatchEventToListeners(Events$3.CommandEvaluated, { result: result.object, commandMessage: originatingMessage, exceptionDetails: result.exceptionDetails });
    }
    addCommandMessage(executionContext, text) {
        const commandMessage = new ConsoleMessage(executionContext.runtimeModel, "javascript" , null, text, { type: FrontendMessageType.Command });
        commandMessage.setExecutionContextId(executionContext.id);
        this.addMessage(commandMessage);
        return commandMessage;
    }
    addMessage(msg) {
        msg.setPageLoadSequenceNumber(this.#pageLoadSequenceNumber);
        if (msg.source === FrontendMessageSource.ConsoleAPI &&
            msg.type === "clear" ) {
            this.clearIfNecessary();
        }
        this.#messages.push(msg);
        this.#messagesByTimestamp.set(msg.timestamp, msg);
        const runtimeModel = msg.runtimeModel();
        const exceptionId = msg.getExceptionId();
        if (exceptionId && runtimeModel) {
            let modelMap = this.#messageByExceptionId.get(runtimeModel);
            if (!modelMap) {
                modelMap = new Map();
                this.#messageByExceptionId.set(runtimeModel, modelMap);
            }
            modelMap.set(exceptionId, msg);
        }
        this.incrementErrorWarningCount(msg);
        this.dispatchEventToListeners(Events$3.MessageAdded, msg);
    }
    exceptionThrown(runtimeModel, event) {
        const exceptionWithTimestamp = event.data;
        const affectedResources = extractExceptionMetaData(exceptionWithTimestamp.details.exceptionMetaData);
        const consoleMessage = ConsoleMessage.fromException(runtimeModel, exceptionWithTimestamp.details, undefined, exceptionWithTimestamp.timestamp, undefined, affectedResources);
        consoleMessage.setExceptionId(exceptionWithTimestamp.details.exceptionId);
        this.addMessage(consoleMessage);
    }
    exceptionRevoked(runtimeModel, event) {
        const exceptionId = event.data;
        const modelMap = this.#messageByExceptionId.get(runtimeModel);
        const exceptionMessage = modelMap ? modelMap.get(exceptionId) : null;
        if (!exceptionMessage) {
            return;
        }
        this.#errors--;
        exceptionMessage.level = "verbose" ;
        this.dispatchEventToListeners(Events$3.MessageUpdated, exceptionMessage);
    }
    consoleAPICalled(runtimeModel, event) {
        const call = event.data;
        let level = "info" ;
        if (call.type === "debug" ) {
            level = "verbose" ;
        }
        else if (call.type === "error"  ||
            call.type === "assert" ) {
            level = "error" ;
        }
        else if (call.type === "warning" ) {
            level = "warning" ;
        }
        else if (call.type === "info"  ||
            call.type === "log" ) {
            level = "info" ;
        }
        let message = '';
        if (call.args.length && call.args[0].unserializableValue) {
            message = call.args[0].unserializableValue;
        }
        else if (call.args.length &&
            ((typeof call.args[0].value !== 'object' && typeof call.args[0].value !== 'undefined') ||
                call.args[0].value === null)) {
            message = String(call.args[0].value);
        }
        else if (call.args.length && call.args[0].description) {
            message = call.args[0].description;
        }
        const callFrame = call.stackTrace?.callFrames.length ? call.stackTrace.callFrames[0] : null;
        const details = {
            type: call.type,
            url: callFrame?.url,
            line: callFrame?.lineNumber,
            column: callFrame?.columnNumber,
            parameters: call.args,
            stackTrace: call.stackTrace,
            timestamp: call.timestamp,
            executionContextId: call.executionContextId,
            context: call.context,
        };
        const consoleMessage = new ConsoleMessage(runtimeModel, FrontendMessageSource.ConsoleAPI, level, (message), details);
        for (const msg of this.#messagesByTimestamp.get(consoleMessage.timestamp).values()) {
            if (consoleMessage.isEqual(msg)) {
                return;
            }
        }
        this.addMessage(consoleMessage);
    }
    queryObjectRequested(runtimeModel, event) {
        const { objects, executionContextId } = event.data;
        const details = {
            type: FrontendMessageType.QueryObjectResult,
            parameters: [objects],
            executionContextId,
        };
        const consoleMessage = new ConsoleMessage(runtimeModel, FrontendMessageSource.ConsoleAPI, "info" , '', details);
        this.addMessage(consoleMessage);
    }
    clearIfNecessary() {
        if (!Settings.instance().moduleSetting('preserve-console-log').get()) {
            this.clear();
        }
        ++this.#pageLoadSequenceNumber;
    }
    primaryPageChanged(event) {
        if (Settings.instance().moduleSetting('preserve-console-log').get()) {
            const { frame } = event.data;
            if (frame.backForwardCacheDetails.restoredFromCache) {
                Console.instance().log(i18nString$D(UIStrings$T.bfcacheNavigation, { PH1: frame.url }));
            }
            else {
                Console.instance().log(i18nString$D(UIStrings$T.navigatedToS, { PH1: frame.url }));
            }
        }
    }
    consoleProfileStarted(cpuProfilerModel, event) {
        const { data } = event;
        this.addConsoleProfileMessage(cpuProfilerModel, "profile" , data.scriptLocation, i18nString$D(UIStrings$T.profileSStarted, { PH1: data.title }));
    }
    consoleProfileFinished(cpuProfilerModel, event) {
        const { data } = event;
        this.addConsoleProfileMessage(cpuProfilerModel, "profileEnd" , data.scriptLocation, i18nString$D(UIStrings$T.profileSFinished, { PH1: data.title }));
    }
    addConsoleProfileMessage(cpuProfilerModel, type, scriptLocation, messageText) {
        const script = scriptLocation.script();
        const callFrames = [{
                functionName: '',
                scriptId: scriptLocation.scriptId,
                url: script ? script.contentURL() : '',
                lineNumber: scriptLocation.lineNumber,
                columnNumber: scriptLocation.columnNumber || 0,
            }];
        this.addMessage(new ConsoleMessage(cpuProfilerModel.runtimeModel(), FrontendMessageSource.ConsoleAPI, "info" , messageText, { type, stackTrace: { callFrames } }));
    }
    incrementErrorWarningCount(msg) {
        if (msg.source === "violation" ) {
            this.#violations++;
            return;
        }
        switch (msg.level) {
            case "warning" :
                this.#warnings++;
                break;
            case "error" :
                this.#errors++;
                break;
        }
    }
    messages() {
        return this.#messages;
    }
    static allMessagesUnordered() {
        const messages = [];
        for (const target of TargetManager.instance().targets()) {
            const targetMessages = target.model(ConsoleModel)?.messages() || [];
            messages.push(...targetMessages);
        }
        return messages;
    }
    static requestClearMessages() {
        for (const logModel of TargetManager.instance().models(LogModel)) {
            logModel.requestClear();
        }
        for (const runtimeModel of TargetManager.instance().models(RuntimeModel)) {
            runtimeModel.discardConsoleEntries();
            runtimeModel.releaseObjectGroup('live-expression');
        }
        for (const target of TargetManager.instance().targets()) {
            target.model(ConsoleModel)?.clear();
        }
    }
    clear() {
        this.#messages = [];
        this.#messagesByTimestamp.clear();
        this.#messageByExceptionId.clear();
        this.#errors = 0;
        this.#warnings = 0;
        this.#violations = 0;
        this.dispatchEventToListeners(Events$3.ConsoleCleared);
    }
    errors() {
        return this.#errors;
    }
    static allErrors() {
        let errors = 0;
        for (const target of TargetManager.instance().targets()) {
            errors += target.model(ConsoleModel)?.errors() || 0;
        }
        return errors;
    }
    warnings() {
        return this.#warnings;
    }
    static allWarnings() {
        let warnings = 0;
        for (const target of TargetManager.instance().targets()) {
            warnings += target.model(ConsoleModel)?.warnings() || 0;
        }
        return warnings;
    }
    violations() {
        return this.#violations;
    }
    async saveToTempVariable(currentExecutionContext, remoteObject) {
        if (!remoteObject || !currentExecutionContext) {
            failedToSave(null);
            return;
        }
        const executionContext = (currentExecutionContext);
        const result = await executionContext.globalObject( '',  false);
        if ('error' in result || Boolean(result.exceptionDetails) || !result.object) {
            failedToSave('object' in result && result.object || null);
            return;
        }
        const globalObject = result.object;
        const callFunctionResult = await globalObject.callFunction(saveVariable, [RemoteObject$1.toCallArgument(remoteObject)]);
        globalObject.release();
        if (callFunctionResult.wasThrown || callFunctionResult.object?.type !== 'string') {
            failedToSave(callFunctionResult.object || null);
        }
        else {
            const text = callFunctionResult.object.value;
            const message = this.addCommandMessage(executionContext, text);
            void this.evaluateCommandInConsole(executionContext, message, text,  false);
        }
        if (callFunctionResult.object) {
            callFunctionResult.object.release();
        }
        function saveVariable(value) {
            const prefix = 'temp';
            let index = 1;
            while ((prefix + index) in this) {
                ++index;
            }
            const name = prefix + index;
            this[name] = value;
            return name;
        }
        function failedToSave(result) {
            let message = i18nString$D(UIStrings$T.failedToSaveToTempVariable);
            if (result) {
                message = message + ' ' + result.description;
            }
            Console.instance().error(message);
        }
    }
}
var Events$3;
(function (Events) {
    Events["ConsoleCleared"] = "ConsoleCleared";
    Events["MessageAdded"] = "MessageAdded";
    Events["MessageUpdated"] = "MessageUpdated";
    Events["CommandEvaluated"] = "CommandEvaluated";
})(Events$3 || (Events$3 = {}));
function extractExceptionMetaData(metaData) {
    if (!metaData) {
        return undefined;
    }
    return { requestId: metaData.requestId || undefined, issueId: metaData.issueId || undefined };
}
function areAffectedResourcesEquivalent(a, b) {
    return a?.requestId === b?.requestId;
}
function areStackTracesEquivalent(stackTrace1, stackTrace2) {
    if (!stackTrace1 !== !stackTrace2) {
        return false;
    }
    if (!stackTrace1 || !stackTrace2) {
        return true;
    }
    const callFrames1 = stackTrace1.callFrames;
    const callFrames2 = stackTrace2.callFrames;
    if (callFrames1.length !== callFrames2.length) {
        return false;
    }
    for (let i = 0, n = callFrames1.length; i < n; ++i) {
        if (callFrames1[i].scriptId !== callFrames2[i].scriptId ||
            callFrames1[i].functionName !== callFrames2[i].functionName ||
            callFrames1[i].lineNumber !== callFrames2[i].lineNumber ||
            callFrames1[i].columnNumber !== callFrames2[i].columnNumber) {
            return false;
        }
    }
    return areStackTracesEquivalent(stackTrace1.parent, stackTrace2.parent);
}
class ConsoleMessage {
    #runtimeModel;
    source;
    level;
    messageText;
    type;
    url;
    line;
    column;
    parameters;
    stackTrace;
    timestamp;
    #executionContextId;
    scriptId;
    workerId;
    context;
    #originatingConsoleMessage = null;
    #pageLoadSequenceNumber = undefined;
    #exceptionId = undefined;
    #affectedResources;
    category;
    stackFrameWithBreakpoint = null;
    #originatingBreakpointType = null;
    constructor(runtimeModel, source, level, messageText, details) {
        this.#runtimeModel = runtimeModel;
        this.source = source;
        this.level = (level);
        this.messageText = messageText;
        this.type = details?.type || "log" ;
        this.url = details?.url;
        this.line = details?.line || 0;
        this.column = details?.column || 0;
        this.parameters = details?.parameters;
        this.stackTrace = details?.stackTrace;
        this.timestamp = details?.timestamp || Date.now();
        this.#executionContextId = details?.executionContextId || 0;
        this.scriptId = details?.scriptId;
        this.workerId = details?.workerId;
        this.#affectedResources = details?.affectedResources;
        this.category = details?.category;
        if (!this.#executionContextId && this.#runtimeModel) {
            if (this.scriptId) {
                this.#executionContextId = this.#runtimeModel.executionContextIdForScriptId(this.scriptId);
            }
            else if (this.stackTrace) {
                this.#executionContextId = this.#runtimeModel.executionContextForStackTrace(this.stackTrace);
            }
        }
        if (details?.context) {
            const match = details?.context.match(/[^#]*/);
            this.context = match?.[0];
        }
        if (this.stackTrace) {
            const { callFrame, type } = ConsoleMessage.#stackFrameWithBreakpoint(this.stackTrace);
            this.stackFrameWithBreakpoint = callFrame;
            this.#originatingBreakpointType = type;
        }
    }
    getAffectedResources() {
        return this.#affectedResources;
    }
    setPageLoadSequenceNumber(pageLoadSequenceNumber) {
        this.#pageLoadSequenceNumber = pageLoadSequenceNumber;
    }
    static fromException(runtimeModel, exceptionDetails, messageType, timestamp, forceUrl, affectedResources) {
        const details = {
            type: messageType,
            url: forceUrl || exceptionDetails.url,
            line: exceptionDetails.lineNumber,
            column: exceptionDetails.columnNumber,
            parameters: exceptionDetails.exception ?
                [RemoteObject$1.fromLocalObject(exceptionDetails.text), exceptionDetails.exception] :
                undefined,
            stackTrace: exceptionDetails.stackTrace,
            timestamp,
            executionContextId: exceptionDetails.executionContextId,
            scriptId: exceptionDetails.scriptId,
            affectedResources,
        };
        return new ConsoleMessage(runtimeModel, "javascript" , "error" , RuntimeModel.simpleTextFromException(exceptionDetails), details);
    }
    runtimeModel() {
        return this.#runtimeModel;
    }
    target() {
        return this.#runtimeModel ? this.#runtimeModel.target() : null;
    }
    setOriginatingMessage(originatingMessage) {
        this.#originatingConsoleMessage = originatingMessage;
        this.#executionContextId = originatingMessage.#executionContextId;
    }
    originatingMessage() {
        return this.#originatingConsoleMessage;
    }
    setExecutionContextId(executionContextId) {
        this.#executionContextId = executionContextId;
    }
    getExecutionContextId() {
        return this.#executionContextId;
    }
    getExceptionId() {
        return this.#exceptionId;
    }
    setExceptionId(exceptionId) {
        this.#exceptionId = exceptionId;
    }
    isGroupMessage() {
        return this.type === "startGroup"  ||
            this.type === "startGroupCollapsed"  ||
            this.type === "endGroup" ;
    }
    isGroupStartMessage() {
        return this.type === "startGroup"  ||
            this.type === "startGroupCollapsed" ;
    }
    isErrorOrWarning() {
        return (this.level === "warning"  || this.level === "error" );
    }
    isGroupable() {
        const isUngroupableError = this.level === "error"  &&
            (this.source === "javascript"  || this.source === "network" );
        return (this.source !== FrontendMessageSource.ConsoleAPI && this.type !== FrontendMessageType.Command &&
            this.type !== FrontendMessageType.Result && this.type !== FrontendMessageType.System && !isUngroupableError);
    }
    groupCategoryKey() {
        return [this.source, this.level, this.type, this.#pageLoadSequenceNumber].join(':');
    }
    isEqual(msg) {
        if (!msg) {
            return false;
        }
        if (this.parameters) {
            if (!msg.parameters || this.parameters.length !== msg.parameters.length) {
                return false;
            }
            for (let i = 0; i < msg.parameters.length; ++i) {
                const msgParam = msg.parameters[i];
                const param = this.parameters[i];
                if (typeof msgParam === 'string' || typeof param === 'string') {
                    return false;
                }
                if (msgParam.type === 'object' && msgParam.subtype !== 'error') {
                    if (!msgParam.objectId || msgParam.objectId !== param.objectId || msg.timestamp !== this.timestamp) {
                        return false;
                    }
                }
                if (param.type !== msgParam.type || param.value !== msgParam.value ||
                    param.description !== msgParam.description) {
                    return false;
                }
            }
        }
        return (this.runtimeModel() === msg.runtimeModel()) && (this.source === msg.source) && (this.type === msg.type) &&
            (this.level === msg.level) && (this.line === msg.line) && (this.url === msg.url) &&
            (this.scriptId === msg.scriptId) && (this.messageText === msg.messageText) &&
            (this.#executionContextId === msg.#executionContextId) &&
            areAffectedResourcesEquivalent(this.#affectedResources, msg.#affectedResources) &&
            areStackTracesEquivalent(this.stackTrace, msg.stackTrace);
    }
    get originatesFromLogpoint() {
        return this.#originatingBreakpointType === "LOGPOINT" ;
    }
    get originatesFromConditionalBreakpoint() {
        return this.#originatingBreakpointType === "CONDITIONAL_BREAKPOINT" ;
    }
    static #stackFrameWithBreakpoint({ callFrames }) {
        const markerSourceUrls = [COND_BREAKPOINT_SOURCE_URL, LOGPOINT_SOURCE_URL];
        const lastBreakpointFrameIndex = callFrames.findLastIndex(({ url }) => markerSourceUrls.includes(url));
        if (lastBreakpointFrameIndex === -1 || lastBreakpointFrameIndex === callFrames.length - 1) {
            return { callFrame: null, type: null };
        }
        const type = callFrames[lastBreakpointFrameIndex].url === LOGPOINT_SOURCE_URL ?
            "LOGPOINT"  :
            "CONDITIONAL_BREAKPOINT" ;
        return { callFrame: callFrames[lastBreakpointFrameIndex + 1], type };
    }
}
SDKModel.register(ConsoleModel, { capabilities: 4 , autostart: true });
new Map(([
    ["xml" , 'xml'],
    ["javascript" , 'javascript'],
    ["network" , 'network'],
    [FrontendMessageSource.ConsoleAPI, 'console-api'],
    ["storage" , 'storage'],
    ["appcache" , 'appcache'],
    ["rendering" , 'rendering'],
    [FrontendMessageSource.CSS, 'css'],
    ["security" , 'security'],
    ["deprecation" , 'deprecation'],
    ["worker" , 'worker'],
    ["violation" , 'violation'],
    ["intervention" , 'intervention'],
    ["recommendation" , 'recommendation'],
    ["other" , 'other'],
    [FrontendMessageSource.ISSUE_PANEL, 'issue-panel'],
]));

// Copyright 2017 The Chromium Authors
class EmulationModel extends SDKModel {
    #emulationAgent;
    #deviceOrientationAgent;
    #cssModel;
    #overlayModel;
    #mediaConfiguration;
    #cpuPressureEnabled;
    #touchEnabled;
    #touchMobile;
    #touchEmulationAllowed;
    #customTouchEnabled;
    #touchConfiguration;
    #screenOrientationLocked;
    #lockedOrientation;
    constructor(target) {
        super(target);
        this.#emulationAgent = target.emulationAgent();
        this.#deviceOrientationAgent = target.deviceOrientationAgent();
        this.#screenOrientationLocked = false;
        this.#lockedOrientation = null;
        this.#cssModel = target.model(CSSModel);
        this.#overlayModel = target.model(OverlayModel);
        if (this.#overlayModel) {
            this.#overlayModel.addEventListener("InspectModeWillBeToggled" , () => {
                void this.updateTouch();
            }, this);
        }
        const disableJavascriptSetting = Settings.instance().moduleSetting('java-script-disabled');
        disableJavascriptSetting.addChangeListener(async () => await this.#emulationAgent.invoke_setScriptExecutionDisabled({ value: disableJavascriptSetting.get() }));
        if (disableJavascriptSetting.get()) {
            void this.#emulationAgent.invoke_setScriptExecutionDisabled({ value: true });
        }
        const touchSetting = Settings.instance().moduleSetting('emulation.touch');
        touchSetting.addChangeListener(() => {
            const settingValue = touchSetting.get();
            void this.overrideEmulateTouch(settingValue === 'force');
        });
        const idleDetectionSetting = Settings.instance().moduleSetting('emulation.idle-detection');
        idleDetectionSetting.addChangeListener(async () => {
            const settingValue = idleDetectionSetting.get();
            if (settingValue === 'none') {
                await this.clearIdleOverride();
                return;
            }
            const emulationParams = JSON.parse(settingValue);
            await this.setIdleOverride(emulationParams);
        });
        const cpuPressureDetectionSetting = Settings.instance().moduleSetting('emulation.cpu-pressure');
        cpuPressureDetectionSetting.addChangeListener(async () => {
            const settingValue = cpuPressureDetectionSetting.get();
            if (settingValue === 'none') {
                await this.setPressureSourceOverrideEnabled(false);
                this.#cpuPressureEnabled = false;
                return;
            }
            if (!this.#cpuPressureEnabled) {
                this.#cpuPressureEnabled = true;
                await this.setPressureSourceOverrideEnabled(true);
            }
            await this.setPressureStateOverride(settingValue);
        });
        const mediaTypeSetting = Settings.instance().moduleSetting('emulated-css-media');
        const mediaFeatureColorGamutSetting = Settings.instance().moduleSetting('emulated-css-media-feature-color-gamut');
        const mediaFeaturePrefersColorSchemeSetting = Settings.instance().moduleSetting('emulated-css-media-feature-prefers-color-scheme');
        const mediaFeatureForcedColorsSetting = Settings.instance().moduleSetting('emulated-css-media-feature-forced-colors');
        const mediaFeaturePrefersContrastSetting = Settings.instance().moduleSetting('emulated-css-media-feature-prefers-contrast');
        const mediaFeaturePrefersReducedDataSetting = Settings.instance().moduleSetting('emulated-css-media-feature-prefers-reduced-data');
        const mediaFeaturePrefersReducedTransparencySetting = Settings.instance().moduleSetting('emulated-css-media-feature-prefers-reduced-transparency');
        const mediaFeaturePrefersReducedMotionSetting = Settings.instance().moduleSetting('emulated-css-media-feature-prefers-reduced-motion');
        this.#mediaConfiguration = new Map([
            ['type', mediaTypeSetting.get()],
            ['color-gamut', mediaFeatureColorGamutSetting.get()],
            ['prefers-color-scheme', mediaFeaturePrefersColorSchemeSetting.get()],
            ['forced-colors', mediaFeatureForcedColorsSetting.get()],
            ['prefers-contrast', mediaFeaturePrefersContrastSetting.get()],
            ['prefers-reduced-data', mediaFeaturePrefersReducedDataSetting.get()],
            ['prefers-reduced-motion', mediaFeaturePrefersReducedMotionSetting.get()],
            ['prefers-reduced-transparency', mediaFeaturePrefersReducedTransparencySetting.get()],
        ]);
        mediaTypeSetting.addChangeListener(() => {
            this.#mediaConfiguration.set('type', mediaTypeSetting.get());
            void this.updateCssMedia();
        });
        mediaFeatureColorGamutSetting.addChangeListener(() => {
            this.#mediaConfiguration.set('color-gamut', mediaFeatureColorGamutSetting.get());
            void this.updateCssMedia();
        });
        mediaFeaturePrefersColorSchemeSetting.addChangeListener(() => {
            this.#mediaConfiguration.set('prefers-color-scheme', mediaFeaturePrefersColorSchemeSetting.get());
            void this.updateCssMedia();
        });
        mediaFeatureForcedColorsSetting.addChangeListener(() => {
            this.#mediaConfiguration.set('forced-colors', mediaFeatureForcedColorsSetting.get());
            void this.updateCssMedia();
        });
        mediaFeaturePrefersContrastSetting.addChangeListener(() => {
            this.#mediaConfiguration.set('prefers-contrast', mediaFeaturePrefersContrastSetting.get());
            void this.updateCssMedia();
        });
        mediaFeaturePrefersReducedDataSetting.addChangeListener(() => {
            this.#mediaConfiguration.set('prefers-reduced-data', mediaFeaturePrefersReducedDataSetting.get());
            void this.updateCssMedia();
        });
        mediaFeaturePrefersReducedMotionSetting.addChangeListener(() => {
            this.#mediaConfiguration.set('prefers-reduced-motion', mediaFeaturePrefersReducedMotionSetting.get());
            void this.updateCssMedia();
        });
        mediaFeaturePrefersReducedTransparencySetting.addChangeListener(() => {
            this.#mediaConfiguration.set('prefers-reduced-transparency', mediaFeaturePrefersReducedTransparencySetting.get());
            void this.updateCssMedia();
        });
        void this.updateCssMedia();
        const autoDarkModeSetting = Settings.instance().moduleSetting('emulate-auto-dark-mode');
        autoDarkModeSetting.addChangeListener(() => {
            const enabled = autoDarkModeSetting.get();
            mediaFeaturePrefersColorSchemeSetting.setDisabled(enabled);
            mediaFeaturePrefersColorSchemeSetting.set(enabled ? 'dark' : '');
            void this.emulateAutoDarkMode(enabled);
        });
        if (autoDarkModeSetting.get()) {
            mediaFeaturePrefersColorSchemeSetting.setDisabled(true);
            mediaFeaturePrefersColorSchemeSetting.set('dark');
            void this.emulateAutoDarkMode(true);
        }
        const visionDeficiencySetting = Settings.instance().moduleSetting('emulated-vision-deficiency');
        visionDeficiencySetting.addChangeListener(() => this.emulateVisionDeficiency(visionDeficiencySetting.get()));
        if (visionDeficiencySetting.get()) {
            void this.emulateVisionDeficiency(visionDeficiencySetting.get());
        }
        const osTextScaleSetting = Settings.instance().moduleSetting('emulated-os-text-scale');
        osTextScaleSetting.addChangeListener(() => {
            void this.emulateOSTextScale(parseFloat(osTextScaleSetting.get()) || undefined);
        });
        if (osTextScaleSetting.get()) {
            void this.emulateOSTextScale(parseFloat(osTextScaleSetting.get()) || undefined);
        }
        const localFontsDisabledSetting = Settings.instance().moduleSetting('local-fonts-disabled');
        localFontsDisabledSetting.addChangeListener(() => this.setLocalFontsDisabled(localFontsDisabledSetting.get()));
        if (localFontsDisabledSetting.get()) {
            this.setLocalFontsDisabled(localFontsDisabledSetting.get());
        }
        const avifFormatDisabledSetting = Settings.instance().moduleSetting('avif-format-disabled');
        const jpegXlFormatDisabledSetting = Settings.instance().moduleSetting('jpeg-xl-format-disabled');
        const webpFormatDisabledSetting = Settings.instance().moduleSetting('webp-format-disabled');
        const updateDisabledImageFormats = () => {
            const types = [];
            if (avifFormatDisabledSetting.get()) {
                types.push("avif" );
            }
            if (jpegXlFormatDisabledSetting.get()) {
                types.push("jxl" );
            }
            if (webpFormatDisabledSetting.get()) {
                types.push("webp" );
            }
            this.setDisabledImageTypes(types);
        };
        avifFormatDisabledSetting.addChangeListener(updateDisabledImageFormats);
        jpegXlFormatDisabledSetting.addChangeListener(updateDisabledImageFormats);
        webpFormatDisabledSetting.addChangeListener(updateDisabledImageFormats);
        if (avifFormatDisabledSetting.get() || jpegXlFormatDisabledSetting.get() || webpFormatDisabledSetting.get()) {
            updateDisabledImageFormats();
        }
        this.#cpuPressureEnabled = false;
        this.#touchEmulationAllowed = true;
        this.#touchEnabled = false;
        this.#touchMobile = false;
        this.#customTouchEnabled = false;
        this.#touchConfiguration = {
            enabled: false,
            configuration: "mobile" ,
        };
        target.registerEmulationDispatcher(this);
    }
    setTouchEmulationAllowed(touchEmulationAllowed) {
        this.#touchEmulationAllowed = touchEmulationAllowed;
    }
    supportsDeviceEmulation() {
        return this.target().hasAllCapabilities(4096 );
    }
    async resetPageScaleFactor() {
        await this.#emulationAgent.invoke_resetPageScaleFactor();
    }
    async emulateDevice(metrics) {
        if (metrics) {
            await this.#emulationAgent.invoke_setDeviceMetricsOverride(metrics);
        }
        else {
            await this.#emulationAgent.invoke_clearDeviceMetricsOverride();
        }
    }
    overlayModel() {
        return this.#overlayModel;
    }
    async setPressureSourceOverrideEnabled(enabled) {
        await this.#emulationAgent.invoke_setPressureSourceOverrideEnabled({ source: "cpu" , enabled });
    }
    async setPressureStateOverride(pressureState) {
        await this.#emulationAgent.invoke_setPressureStateOverride({
            source: "cpu" ,
            state: pressureState,
        });
    }
    async emulateLocation(location) {
        if (!location) {
            await Promise.all([
                this.#emulationAgent.invoke_clearGeolocationOverride(),
                this.#emulationAgent.invoke_setTimezoneOverride({ timezoneId: '' }),
                this.#emulationAgent.invoke_setLocaleOverride({ locale: '' }),
                this.#emulationAgent.invoke_setUserAgentOverride({ userAgent: MultitargetNetworkManager.instance().currentUserAgent() }),
            ]);
        }
        else if (location.unavailable) {
            await Promise.all([
                this.#emulationAgent.invoke_setGeolocationOverride({}),
                this.#emulationAgent.invoke_setTimezoneOverride({ timezoneId: '' }),
                this.#emulationAgent.invoke_setLocaleOverride({ locale: '' }),
                this.#emulationAgent.invoke_setUserAgentOverride({ userAgent: MultitargetNetworkManager.instance().currentUserAgent() }),
            ]);
        }
        else {
            function processEmulationResult(errorType, result) {
                const errorMessage = result.getError();
                if (errorMessage) {
                    return Promise.reject({
                        type: errorType,
                        message: errorMessage,
                    });
                }
                return Promise.resolve();
            }
            await Promise.all([
                this.#emulationAgent
                    .invoke_setGeolocationOverride({
                    latitude: location.latitude,
                    longitude: location.longitude,
                    accuracy: location.accuracy,
                })
                    .then(result => processEmulationResult('emulation-set-location', result)),
                this.#emulationAgent
                    .invoke_setTimezoneOverride({
                    timezoneId: location.timezoneId,
                })
                    .then(result => processEmulationResult('emulation-set-timezone', result)),
                this.#emulationAgent
                    .invoke_setLocaleOverride({
                    locale: location.locale,
                })
                    .then(result => processEmulationResult('emulation-set-locale', result)),
                this.#emulationAgent
                    .invoke_setUserAgentOverride({
                    userAgent: MultitargetNetworkManager.instance().currentUserAgent(),
                    acceptLanguage: location.locale,
                })
                    .then(result => processEmulationResult('emulation-set-user-agent', result)),
            ]);
        }
    }
    async emulateDeviceOrientation(deviceOrientation) {
        if (deviceOrientation) {
            await this.#deviceOrientationAgent.invoke_setDeviceOrientationOverride({ alpha: deviceOrientation.alpha, beta: deviceOrientation.beta, gamma: deviceOrientation.gamma });
        }
        else {
            await this.#deviceOrientationAgent.invoke_clearDeviceOrientationOverride();
        }
    }
    async setIdleOverride(emulationParams) {
        await this.#emulationAgent.invoke_setIdleOverride(emulationParams);
    }
    async clearIdleOverride() {
        await this.#emulationAgent.invoke_clearIdleOverride();
    }
    async emulateCSSMedia(type, features) {
        await this.#emulationAgent.invoke_setEmulatedMedia({ media: type, features });
        if (this.#cssModel) {
            this.#cssModel.mediaQueryResultChanged();
        }
    }
    async emulateAutoDarkMode(enabled) {
        if (enabled) {
            this.#mediaConfiguration.set('prefers-color-scheme', 'dark');
            await this.updateCssMedia();
        }
        await this.#emulationAgent.invoke_setAutoDarkModeOverride({ enabled: enabled || undefined });
    }
    async emulateVisionDeficiency(type) {
        await this.#emulationAgent.invoke_setEmulatedVisionDeficiency({ type });
    }
    async emulateOSTextScale(scale) {
        await this.#emulationAgent.invoke_setEmulatedOSTextScale({ scale: scale || undefined });
    }
    setLocalFontsDisabled(disabled) {
        if (!this.#cssModel) {
            return;
        }
        void this.#cssModel.setLocalFontsEnabled(!disabled);
    }
    setDisabledImageTypes(imageTypes) {
        void this.#emulationAgent.invoke_setDisabledImageTypes({ imageTypes });
    }
    async setDataSaverOverride(dataSaverOverride) {
        const dataSaverEnabled = dataSaverOverride === "unset"  ? undefined :
            dataSaverOverride === "enabled"  ? true :
                false;
        await this.#emulationAgent.invoke_setDataSaverOverride({ dataSaverEnabled });
    }
    async setCPUThrottlingRate(rate) {
        await this.#emulationAgent.invoke_setCPUThrottlingRate({ rate });
    }
    async setHardwareConcurrency(hardwareConcurrency) {
        if (hardwareConcurrency < 1) {
            throw new Error('hardwareConcurrency must be a positive value');
        }
        await this.#emulationAgent.invoke_setHardwareConcurrencyOverride({ hardwareConcurrency });
    }
    async emulateTouch(enabled, mobile) {
        this.#touchEnabled = enabled && this.#touchEmulationAllowed;
        this.#touchMobile = mobile && this.#touchEmulationAllowed;
        await this.updateTouch();
    }
    async overrideEmulateTouch(enabled) {
        this.#customTouchEnabled = enabled && this.#touchEmulationAllowed;
        await this.updateTouch();
    }
    async updateTouch() {
        let configuration = {
            enabled: this.#touchEnabled,
            configuration: this.#touchMobile ? "mobile"  :
                "desktop" ,
        };
        if (this.#customTouchEnabled) {
            configuration = {
                enabled: true,
                configuration: "mobile" ,
            };
        }
        if (this.#overlayModel && this.#overlayModel.inspectModeEnabled()) {
            configuration = {
                enabled: false,
                configuration: "mobile" ,
            };
        }
        if (!this.#touchConfiguration.enabled && !configuration.enabled) {
            return;
        }
        if (this.#touchConfiguration.enabled && configuration.enabled &&
            this.#touchConfiguration.configuration === configuration.configuration) {
            return;
        }
        this.#touchConfiguration = configuration;
        await this.#emulationAgent.invoke_setTouchEmulationEnabled({ enabled: configuration.enabled, maxTouchPoints: 1 });
        await this.#emulationAgent.invoke_setEmitTouchEventsForMouse({ enabled: configuration.enabled, configuration: configuration.configuration });
    }
    async updateCssMedia() {
        const type = this.#mediaConfiguration.get('type') ?? '';
        const features = [
            {
                name: 'color-gamut',
                value: this.#mediaConfiguration.get('color-gamut') ?? '',
            },
            {
                name: 'prefers-color-scheme',
                value: this.#mediaConfiguration.get('prefers-color-scheme') ?? '',
            },
            {
                name: 'forced-colors',
                value: this.#mediaConfiguration.get('forced-colors') ?? '',
            },
            {
                name: 'prefers-contrast',
                value: this.#mediaConfiguration.get('prefers-contrast') ?? '',
            },
            {
                name: 'prefers-reduced-data',
                value: this.#mediaConfiguration.get('prefers-reduced-data') ?? '',
            },
            {
                name: 'prefers-reduced-motion',
                value: this.#mediaConfiguration.get('prefers-reduced-motion') ?? '',
            },
            {
                name: 'prefers-reduced-transparency',
                value: this.#mediaConfiguration.get('prefers-reduced-transparency') ?? '',
            },
        ];
        return await this.emulateCSSMedia(type, features);
    }
    virtualTimeBudgetExpired() {
    }
    screenOrientationLockChanged(event) {
        this.#screenOrientationLocked = event.locked;
        this.#lockedOrientation = event.orientation ?? null;
        this.dispatchEventToListeners("ScreenOrientationLockChanged" , { locked: event.locked, orientation: event.orientation ?? null });
    }
    isScreenOrientationLocked() {
        return this.#screenOrientationLocked;
    }
    lockedOrientation() {
        return this.#lockedOrientation;
    }
}
SDKModel.register(EmulationModel, { capabilities: 256 , autostart: true });

// Copyright 2017 The Chromium Authors
const UIStrings$S = {
    noThrottling: 'No throttling',
    dSlowdown: '{PH1}× slowdown',
    calibratedMidTierMobile: 'Mid-tier mobile',
    calibratedLowTierMobile: 'Low-tier mobile',
    calibrationErrorDeviceTooWeak: 'Device is not powerful enough',
};
const str_$R = registerUIStrings('core/sdk/CPUThrottlingManager.ts', UIStrings$S);
getLocalizedString.bind(undefined, str_$R);
const i18nLazyString$d = getLazilyComputedLocalizedString.bind(undefined, str_$R);
var CPUThrottlingRates;
(function (CPUThrottlingRates) {
    CPUThrottlingRates[CPUThrottlingRates["NO_THROTTLING"] = 1] = "NO_THROTTLING";
    CPUThrottlingRates[CPUThrottlingRates["MID_TIER_MOBILE"] = 4] = "MID_TIER_MOBILE";
    CPUThrottlingRates[CPUThrottlingRates["LOW_TIER_MOBILE"] = 6] = "LOW_TIER_MOBILE";
    CPUThrottlingRates[CPUThrottlingRates["EXTRA_SLOW"] = 20] = "EXTRA_SLOW";
    CPUThrottlingRates[CPUThrottlingRates["MidTierMobile"] = 4] = "MidTierMobile";
    CPUThrottlingRates[CPUThrottlingRates["LowEndMobile"] = 6] = "LowEndMobile";
})(CPUThrottlingRates || (CPUThrottlingRates = {}));
function makeFixedPresetThrottlingOption(rate) {
    return {
        title: rate === 1 ? i18nLazyString$d(UIStrings$S.noThrottling) : i18nLazyString$d(UIStrings$S.dSlowdown, { PH1: rate }),
        rate: () => rate,
        jslogContext: rate === 1 ? 'cpu-no-throttling' : `cpu-throttled-${rate}`,
    };
}
makeFixedPresetThrottlingOption(CPUThrottlingRates.NO_THROTTLING);
makeFixedPresetThrottlingOption(CPUThrottlingRates.MID_TIER_MOBILE);
makeFixedPresetThrottlingOption(CPUThrottlingRates.LOW_TIER_MOBILE);
makeFixedPresetThrottlingOption(CPUThrottlingRates.EXTRA_SLOW);
var CalibrationError;
(function (CalibrationError) {
    CalibrationError["DEVICE_TOO_WEAK"] = "DEVICE_TOO_WEAK";
})(CalibrationError || (CalibrationError = {}));

// Copyright 2017 The Chromium Authors
class DOMDebuggerModel extends SDKModel {
    agent;
    #runtimeModel;
    #domModel;
    #domBreakpoints;
    #domBreakpointsSetting;
    suspended = false;
    constructor(target) {
        super(target);
        this.agent = target.domdebuggerAgent();
        this.#runtimeModel = target.model(RuntimeModel);
        this.#domModel = target.model(DOMModel);
        this.#domModel.addEventListener(Events$8.DocumentUpdated, this.documentUpdated, this);
        this.#domModel.addEventListener(Events$8.NodeRemoved, this.nodeRemoved, this);
        this.#domBreakpoints = [];
        this.#domBreakpointsSetting = Settings.instance().createLocalSetting('dom-breakpoints', []);
        if (this.#domModel.existingDocument()) {
            void this.documentUpdated();
        }
    }
    runtimeModel() {
        return this.#runtimeModel;
    }
    async suspendModel() {
        this.suspended = true;
    }
    async resumeModel() {
        this.suspended = false;
    }
    async eventListeners(remoteObject) {
        console.assert(remoteObject.runtimeModel() === this.#runtimeModel);
        if (!remoteObject.objectId) {
            return [];
        }
        const listeners = await this.agent.invoke_getEventListeners({ objectId: remoteObject.objectId });
        const eventListeners = [];
        for (const payload of listeners.listeners || []) {
            const location = this.#runtimeModel.debuggerModel().createRawLocationByScriptId(payload.scriptId, payload.lineNumber, payload.columnNumber);
            if (!location) {
                continue;
            }
            eventListeners.push(new EventListener(this, remoteObject, payload.type, payload.useCapture, payload.passive, payload.once, payload.handler ? this.#runtimeModel.createRemoteObject(payload.handler) : null, payload.originalHandler ? this.#runtimeModel.createRemoteObject(payload.originalHandler) : null, location, null));
        }
        return eventListeners;
    }
    retrieveDOMBreakpoints() {
        void this.#domModel.requestDocument();
    }
    domBreakpoints() {
        return this.#domBreakpoints.slice();
    }
    hasDOMBreakpoint(node, type) {
        return this.#domBreakpoints.some(breakpoint => (breakpoint.node === node && breakpoint.type === type));
    }
    setDOMBreakpoint(node, type) {
        for (const breakpoint of this.#domBreakpoints) {
            if (breakpoint.node === node && breakpoint.type === type) {
                this.toggleDOMBreakpoint(breakpoint, true);
                return breakpoint;
            }
        }
        const breakpoint = new DOMBreakpoint(this, node, type, true);
        this.#domBreakpoints.push(breakpoint);
        this.enableDOMBreakpoint(breakpoint);
        this.saveDOMBreakpoints();
        this.dispatchEventToListeners("DOMBreakpointAdded" , breakpoint);
        return breakpoint;
    }
    removeDOMBreakpoint(node, type) {
        this.removeDOMBreakpoints(breakpoint => breakpoint.node === node && breakpoint.type === type);
    }
    removeAllDOMBreakpoints() {
        this.removeDOMBreakpoints(_breakpoint => true);
    }
    toggleDOMBreakpoint(breakpoint, enabled) {
        if (enabled === breakpoint.enabled) {
            return;
        }
        breakpoint.enabled = enabled;
        if (enabled) {
            this.enableDOMBreakpoint(breakpoint);
        }
        else {
            this.disableDOMBreakpoint(breakpoint);
        }
        this.saveDOMBreakpoints();
        this.dispatchEventToListeners("DOMBreakpointToggled" , breakpoint);
    }
    enableDOMBreakpoint(breakpoint) {
        if (breakpoint.node.id) {
            void this.agent.invoke_setDOMBreakpoint({ nodeId: breakpoint.node.id, type: breakpoint.type });
            breakpoint.node.setMarker(Marker, true);
        }
    }
    disableDOMBreakpoint(breakpoint) {
        if (breakpoint.node.id) {
            void this.agent.invoke_removeDOMBreakpoint({ nodeId: breakpoint.node.id, type: breakpoint.type });
            breakpoint.node.setMarker(Marker, this.nodeHasBreakpoints(breakpoint.node) ? true : null);
        }
    }
    nodeHasBreakpoints(node) {
        for (const breakpoint of this.#domBreakpoints) {
            if (breakpoint.node === node && breakpoint.enabled) {
                return true;
            }
        }
        return false;
    }
    resolveDOMBreakpointData(auxData) {
        const type = auxData['type'];
        const node = this.#domModel.nodeForId(auxData['nodeId']);
        if (!type || !node) {
            return null;
        }
        let targetNode = null;
        let insertion = false;
        if (type === "subtree-modified" ) {
            insertion = auxData['insertion'] || false;
            targetNode = this.#domModel.nodeForId(auxData['targetNodeId']);
        }
        return { type, node, targetNode, insertion };
    }
    currentURL() {
        const domDocument = this.#domModel.existingDocument();
        return domDocument ? domDocument.documentURL : EmptyUrlString;
    }
    async documentUpdated() {
        if (this.suspended) {
            return;
        }
        const removed = this.#domBreakpoints;
        this.#domBreakpoints = [];
        this.dispatchEventToListeners("DOMBreakpointsRemoved" , removed);
        const document = await this.#domModel.requestDocument();
        const currentURL = document ? document.documentURL : EmptyUrlString;
        for (const breakpoint of this.#domBreakpointsSetting.get()) {
            if (breakpoint.url === currentURL) {
                void this.#domModel.pushNodeByPathToFrontend(breakpoint.path).then(appendBreakpoint.bind(this, breakpoint));
            }
        }
        function appendBreakpoint(breakpoint, nodeId) {
            const node = nodeId ? this.#domModel.nodeForId(nodeId) : null;
            if (!node) {
                return;
            }
            for (const existingBreakpoint of this.#domBreakpoints) {
                if (existingBreakpoint.node === node && existingBreakpoint.type === breakpoint.type) {
                    return;
                }
            }
            const domBreakpoint = new DOMBreakpoint(this, node, breakpoint.type, breakpoint.enabled);
            this.#domBreakpoints.push(domBreakpoint);
            if (breakpoint.enabled) {
                this.enableDOMBreakpoint(domBreakpoint);
            }
            this.dispatchEventToListeners("DOMBreakpointAdded" , domBreakpoint);
        }
    }
    removeDOMBreakpoints(filter) {
        const removed = [];
        const left = [];
        for (const breakpoint of this.#domBreakpoints) {
            if (filter(breakpoint)) {
                removed.push(breakpoint);
                if (breakpoint.enabled) {
                    breakpoint.enabled = false;
                    this.disableDOMBreakpoint(breakpoint);
                }
            }
            else {
                left.push(breakpoint);
            }
        }
        if (!removed.length) {
            return;
        }
        this.#domBreakpoints = left;
        this.saveDOMBreakpoints();
        this.dispatchEventToListeners("DOMBreakpointsRemoved" , removed);
    }
    nodeRemoved(event) {
        if (this.suspended) {
            return;
        }
        const { node } = event.data;
        const children = node.children() || [];
        this.removeDOMBreakpoints(breakpoint => breakpoint.node === node || children.indexOf(breakpoint.node) !== -1);
    }
    saveDOMBreakpoints() {
        const currentURL = this.currentURL();
        const breakpoints = this.#domBreakpointsSetting.get().filter((breakpoint) => breakpoint.url !== currentURL);
        for (const breakpoint of this.#domBreakpoints) {
            breakpoints.push({ url: currentURL, path: breakpoint.node.path(), type: breakpoint.type, enabled: breakpoint.enabled });
        }
        this.#domBreakpointsSetting.set(breakpoints);
    }
}
const Marker = 'breakpoint-marker';
class DOMBreakpoint {
    domDebuggerModel;
    node;
    type;
    enabled;
    constructor(domDebuggerModel, node, type, enabled) {
        this.domDebuggerModel = domDebuggerModel;
        this.node = node;
        this.type = type;
        this.enabled = enabled;
    }
}
class EventListener {
    #domDebuggerModel;
    #eventTarget;
    #type;
    #useCapture;
    #passive;
    #once;
    #handler;
    #originalHandler;
    #location;
    #sourceURL;
    #customRemoveFunction;
    #origin;
    constructor(domDebuggerModel, eventTarget, type, useCapture, passive, once, handler, originalHandler, location, customRemoveFunction, origin) {
        this.#domDebuggerModel = domDebuggerModel;
        this.#eventTarget = eventTarget;
        this.#type = type;
        this.#useCapture = useCapture;
        this.#passive = passive;
        this.#once = once;
        this.#handler = handler;
        this.#originalHandler = originalHandler || handler;
        this.#location = location;
        const script = location.script();
        this.#sourceURL = script ? script.contentURL() : EmptyUrlString;
        this.#customRemoveFunction = customRemoveFunction;
        this.#origin = origin || "Raw" ;
    }
    domDebuggerModel() {
        return this.#domDebuggerModel;
    }
    type() {
        return this.#type;
    }
    useCapture() {
        return this.#useCapture;
    }
    passive() {
        return this.#passive;
    }
    once() {
        return this.#once;
    }
    handler() {
        return this.#handler;
    }
    location() {
        return this.#location;
    }
    sourceURL() {
        return this.#sourceURL;
    }
    originalHandler() {
        return this.#originalHandler;
    }
    canRemove() {
        return Boolean(this.#customRemoveFunction) || this.#origin !== "FrameworkUser" ;
    }
    remove() {
        if (!this.canRemove()) {
            return Promise.resolve(undefined);
        }
        if (this.#origin !== "FrameworkUser" ) {
            function removeListener(type, listener, useCapture) {
                this.removeEventListener(type, listener, useCapture);
                if (this['on' + type]) {
                    this['on' + type] = undefined;
                }
            }
            return this.#eventTarget
                .callFunction(removeListener, [
                RemoteObject$1.toCallArgument(this.#type),
                RemoteObject$1.toCallArgument(this.#originalHandler),
                RemoteObject$1.toCallArgument(this.#useCapture),
            ])
                .then(() => undefined);
        }
        if (this.#customRemoveFunction) {
            function callCustomRemove(type, listener, useCapture, passive) {
                this.call(null, type, listener, useCapture, passive);
            }
            return this.#customRemoveFunction
                .callFunction(callCustomRemove, [
                RemoteObject$1.toCallArgument(this.#type),
                RemoteObject$1.toCallArgument(this.#originalHandler),
                RemoteObject$1.toCallArgument(this.#useCapture),
                RemoteObject$1.toCallArgument(this.#passive),
            ])
                .then(() => undefined);
        }
        return Promise.resolve(undefined);
    }
    canTogglePassive() {
        return this.#origin !== "FrameworkUser" ;
    }
    togglePassive() {
        return this.#eventTarget
            .callFunction(callTogglePassive, [
            RemoteObject$1.toCallArgument(this.#type),
            RemoteObject$1.toCallArgument(this.#originalHandler),
            RemoteObject$1.toCallArgument(this.#useCapture),
            RemoteObject$1.toCallArgument(this.#passive),
        ])
            .then(() => undefined);
        function callTogglePassive(type, listener, useCapture, passive) {
            this.removeEventListener(type, listener, { capture: useCapture });
            this.addEventListener(type, listener, { capture: useCapture, passive: !passive });
        }
    }
    origin() {
        return this.#origin;
    }
    markAsFramework() {
        this.#origin = "Framework" ;
    }
    isScrollBlockingType() {
        return this.#type === 'touchstart' || this.#type === 'touchmove' || this.#type === 'mousewheel' ||
            this.#type === 'wheel';
    }
}
SDKModel.register(DOMDebuggerModel, { capabilities: 2 , autostart: false });

// Copyright 2021 The Chromium Authors
class EventBreakpointsModel extends SDKModel {
    agent;
    constructor(target) {
        super(target);
        this.agent = target.eventBreakpointsAgent();
    }
}
SDKModel.register(EventBreakpointsModel, { capabilities: 524288 , autostart: false });

// Copyright 2019 The Chromium Authors
class IssuesModel extends SDKModel {
    #disposed = false;
    #enabled = false;
    constructor(target) {
        super(target);
        void this.ensureEnabled();
    }
    async ensureEnabled() {
        if (this.#enabled) {
            return;
        }
        this.#enabled = true;
        this.target().registerAuditsDispatcher(this);
        const auditsAgent = this.target().auditsAgent();
        await auditsAgent.invoke_enable();
    }
    issueAdded(issueAddedEvent) {
        this.dispatchEventToListeners("IssueAdded" , { issuesModel: this, inspectorIssue: issueAddedEvent.issue });
    }
    dispose() {
        super.dispose();
        this.#disposed = true;
    }
    getTargetIfNotDisposed() {
        if (!this.#disposed) {
            return this.target();
        }
        return null;
    }
}
SDKModel.register(IssuesModel, { capabilities: 32768 , autostart: true });

// Copyright 2021 The Chromium Authors
class PageLoad {
    id;
    url;
    startTime;
    loadTime;
    contentLoadTime;
    mainRequest;
    constructor(mainRequest) {
        this.id = ++PageLoad.lastIdentifier;
        this.url = mainRequest.url();
        this.startTime = mainRequest.startTime;
        this.mainRequest = mainRequest;
    }
    static forRequest(request) {
        return pageLoadForRequest.get(request) || null;
    }
    bindRequest(request) {
        pageLoadForRequest.set(request, this);
    }
    static lastIdentifier = 0;
}
const pageLoadForRequest = new WeakMap();

// Copyright 2013 The Chromium Authors
class PaintProfilerModel extends SDKModel {
    layerTreeAgent;
    constructor(target) {
        super(target);
        this.layerTreeAgent = target.layerTreeAgent();
    }
    async loadSnapshotFromFragments(tiles) {
        const { snapshotId } = await this.layerTreeAgent.invoke_loadSnapshot({ tiles });
        return snapshotId ? new PaintProfilerSnapshot(this, snapshotId) : null;
    }
    loadSnapshot(encodedPicture) {
        const fragment = { x: 0, y: 0, picture: encodedPicture };
        return this.loadSnapshotFromFragments([fragment]);
    }
    async makeSnapshot(layerId) {
        const { snapshotId } = await this.layerTreeAgent.invoke_makeSnapshot({ layerId });
        return snapshotId ? new PaintProfilerSnapshot(this, snapshotId) : null;
    }
}
class PaintProfilerSnapshot {
    #paintProfilerModel;
    #id;
    #refCount;
    constructor(paintProfilerModel, snapshotId) {
        this.#paintProfilerModel = paintProfilerModel;
        this.#id = snapshotId;
        this.#refCount = 1;
    }
    release() {
        console.assert(this.#refCount > 0, 'release is already called on the object');
        if (!--this.#refCount) {
            void this.#paintProfilerModel.layerTreeAgent.invoke_releaseSnapshot({ snapshotId: this.#id });
        }
    }
    addReference() {
        ++this.#refCount;
        console.assert(this.#refCount > 0, 'Referencing a dead object');
    }
    async replay(scale, fromStep, toStep) {
        const response = await this.#paintProfilerModel.layerTreeAgent.invoke_replaySnapshot({ snapshotId: this.#id, fromStep, toStep, scale: scale || 1.0 });
        return response.dataURL;
    }
    async profile(clipRect) {
        const response = await this.#paintProfilerModel.layerTreeAgent.invoke_profileSnapshot({ snapshotId: this.#id, minRepeatCount: 5, minDuration: 1, clipRect: clipRect || undefined });
        return response.timings;
    }
    async commandLog() {
        const response = await this.#paintProfilerModel.layerTreeAgent.invoke_snapshotCommandLog({ snapshotId: this.#id });
        return response.commandLog ? response.commandLog.map((entry, index) => new PaintProfilerLogItem(entry, index)) :
            null;
    }
}
class PaintProfilerLogItem {
    method;
    params;
    commandIndex;
    constructor(rawEntry, commandIndex) {
        this.method = rawEntry.method;
        this.params = rawEntry.params;
        this.commandIndex = commandIndex;
    }
}
SDKModel.register(PaintProfilerModel, { capabilities: 2 , autostart: false });

// Copyright 2017 The Chromium Authors
class PerformanceMetricsModel extends SDKModel {
    #agent;
    #metricModes = new Map([
        ['TaskDuration', "CumulativeTime" ],
        ['ScriptDuration', "CumulativeTime" ],
        ['LayoutDuration', "CumulativeTime" ],
        ['RecalcStyleDuration', "CumulativeTime" ],
        ['LayoutCount', "CumulativeCount" ],
        ['RecalcStyleCount', "CumulativeCount" ],
    ]);
    #metricData = new Map();
    constructor(target) {
        super(target);
        this.#agent = target.performanceAgent();
    }
    enable() {
        return this.#agent.invoke_enable({});
    }
    disable() {
        return this.#agent.invoke_disable();
    }
    async requestMetrics() {
        const rawMetrics = await this.#agent.invoke_getMetrics() || [];
        const metrics = new Map();
        const timestamp = performance.now();
        for (const metric of rawMetrics.metrics) {
            let data = this.#metricData.get(metric.name);
            if (!data) {
                data = { lastValue: undefined, lastTimestamp: undefined };
                this.#metricData.set(metric.name, data);
            }
            let value;
            switch (this.#metricModes.get(metric.name)) {
                case "CumulativeTime" :
                    value = (data.lastTimestamp && data.lastValue) ?
                        clamp$1((metric.value - data.lastValue) * 1000 / (timestamp - data.lastTimestamp), 0, 1) :
                        0;
                    data.lastValue = metric.value;
                    data.lastTimestamp = timestamp;
                    break;
                case "CumulativeCount" :
                    value = (data.lastTimestamp && data.lastValue) ?
                        Math.max(0, (metric.value - data.lastValue) * 1000 / (timestamp - data.lastTimestamp)) :
                        0;
                    data.lastValue = metric.value;
                    data.lastTimestamp = timestamp;
                    break;
                default:
                    value = metric.value;
                    break;
            }
            metrics.set(metric.name, value);
        }
        return { metrics, timestamp };
    }
}
SDKModel.register(PerformanceMetricsModel, { capabilities: 2 , autostart: false });

// Copyright 2023 The Chromium Authors
class PreloadingModel extends SDKModel {
    agent;
    loaderIds = [];
    targetJustAttached = true;
    lastPrimaryPageModel = null;
    documents = new Map();
    constructor(target) {
        super(target);
        target.registerPreloadDispatcher(new PreloadDispatcher(this));
        this.agent = target.preloadAgent();
        void this.agent.invoke_enable();
        const targetInfo = target.targetInfo();
        if (targetInfo?.subtype === 'prerender') {
            this.lastPrimaryPageModel = TargetManager.instance().primaryPageTarget()?.model(PreloadingModel) || null;
        }
        TargetManager.instance().addModelListener(ResourceTreeModel, Events$6.PrimaryPageChanged, this.onPrimaryPageChanged, this);
    }
    dispose() {
        super.dispose();
        TargetManager.instance().removeModelListener(ResourceTreeModel, Events$6.PrimaryPageChanged, this.onPrimaryPageChanged, this);
        void this.agent.invoke_disable();
    }
    reset() {
        this.documents.clear();
        this.loaderIds = [];
        this.targetJustAttached = true;
        this.dispatchEventToListeners("ModelUpdated" );
    }
    maybeInferLoaderId(loaderId) {
        if (this.currentLoaderId() === null) {
            this.loaderIds = [loaderId];
            this.targetJustAttached = false;
        }
    }
    ensureDocumentPreloadingData(loaderId) {
        if (this.documents.get(loaderId) === undefined) {
            this.documents.set(loaderId, new DocumentPreloadingData());
        }
    }
    currentLoaderId() {
        if (this.targetJustAttached) {
            return null;
        }
        if (this.loaderIds.length === 0) {
            throw new Error('unreachable');
        }
        return this.loaderIds[this.loaderIds.length - 1];
    }
    currentDocument() {
        const loaderId = this.currentLoaderId();
        return loaderId === null ? null : this.documents.get(loaderId) || null;
    }
    getRuleSetById(id) {
        return this.currentDocument()?.ruleSets.getById(id) || null;
    }
    getAllRuleSets() {
        return this.currentDocument()?.ruleSets.getAll() || [];
    }
    getPreloadCountsByRuleSetId() {
        const countsByRuleSetId = new Map();
        for (const { value } of this.getRepresentativePreloadingAttempts(null)) {
            for (const ruleSetId of [null, ...value.ruleSetIds]) {
                if (countsByRuleSetId.get(ruleSetId) === undefined) {
                    countsByRuleSetId.set(ruleSetId, new Map());
                }
                const countsByStatus = countsByRuleSetId.get(ruleSetId);
                assertNotNullOrUndefined(countsByStatus);
                const i = countsByStatus.get(value.status) || 0;
                countsByStatus.set(value.status, i + 1);
            }
        }
        return countsByRuleSetId;
    }
    getPreloadingAttemptById(id) {
        const document = this.currentDocument();
        if (document === null) {
            return null;
        }
        return document.preloadingAttempts.getById(id, document.sources) || null;
    }
    getRepresentativePreloadingAttempts(ruleSetId) {
        const document = this.currentDocument();
        if (document === null) {
            return [];
        }
        return document.preloadingAttempts.getAllRepresentative(ruleSetId, document.sources);
    }
    getRepresentativePreloadingAttemptsOfPreviousPage() {
        if (this.loaderIds.length <= 1) {
            return [];
        }
        const document = this.documents.get(this.loaderIds[this.loaderIds.length - 2]);
        if (document === undefined) {
            return [];
        }
        return document.preloadingAttempts.getAllRepresentative(null, document.sources);
    }
    getPipelineById(pipelineId) {
        const document = this.currentDocument();
        if (document === null) {
            return null;
        }
        return document.preloadingAttempts.getPipeline(pipelineId, document.sources);
    }
    getPipeline(attempt) {
        let pipelineNullable = null;
        if (attempt.pipelineId !== null) {
            pipelineNullable = this.getPipelineById(attempt.pipelineId);
        }
        if (pipelineNullable === null) {
            const pipeline = new Map();
            pipeline.set(attempt.action, attempt);
            return new PreloadPipeline(pipeline);
        }
        return new PreloadPipeline(pipelineNullable);
    }
    onPrimaryPageChanged(event) {
        const { frame, type } = event.data;
        if (this.lastPrimaryPageModel === null && type === "Activation" ) {
            return;
        }
        if (this.lastPrimaryPageModel !== null && type !== "Activation" ) {
            return;
        }
        if (this.lastPrimaryPageModel !== null && type === "Activation" ) {
            this.loaderIds = this.lastPrimaryPageModel.loaderIds;
            for (const [loaderId, prev] of this.lastPrimaryPageModel.documents.entries()) {
                this.ensureDocumentPreloadingData(loaderId);
                this.documents.get(loaderId)?.mergePrevious(prev);
            }
        }
        this.lastPrimaryPageModel = null;
        const currentLoaderId = frame.loaderId;
        this.loaderIds.push(currentLoaderId);
        this.loaderIds = this.loaderIds.slice(-2);
        this.ensureDocumentPreloadingData(currentLoaderId);
        for (const loaderId of this.documents.keys()) {
            if (!this.loaderIds.includes(loaderId)) {
                this.documents.delete(loaderId);
            }
        }
        this.dispatchEventToListeners("ModelUpdated" );
    }
    onRuleSetUpdated(event) {
        const ruleSet = event.ruleSet;
        const loaderId = ruleSet.loaderId;
        this.maybeInferLoaderId(loaderId);
        this.ensureDocumentPreloadingData(loaderId);
        this.documents.get(loaderId)?.ruleSets.upsert(ruleSet);
        this.dispatchEventToListeners("ModelUpdated" );
    }
    onRuleSetRemoved(event) {
        const id = event.id;
        for (const document of this.documents.values()) {
            document.ruleSets.delete(id);
        }
        this.dispatchEventToListeners("ModelUpdated" );
    }
    onPreloadingAttemptSourcesUpdated(event) {
        const loaderId = event.loaderId;
        this.ensureDocumentPreloadingData(loaderId);
        const document = this.documents.get(loaderId);
        if (document === undefined) {
            return;
        }
        document.sources.update(event.preloadingAttemptSources);
        document.preloadingAttempts.maybeRegisterNotTriggered(document.sources);
        document.preloadingAttempts.cleanUpRemovedAttempts(document.sources);
        this.dispatchEventToListeners("ModelUpdated" );
    }
    onPrefetchStatusUpdated(event) {
        if (event.prefetchStatus === "PrefetchEvictedAfterCandidateRemoved" ) {
            return;
        }
        const loaderId = event.key.loaderId;
        this.ensureDocumentPreloadingData(loaderId);
        const attempt = {
            action: "Prefetch" ,
            key: event.key,
            pipelineId: event.pipelineId,
            status: convertPreloadingStatus(event.status),
            prefetchStatus: event.prefetchStatus || null,
            requestId: event.requestId,
        };
        this.documents.get(loaderId)?.preloadingAttempts.upsert(attempt);
        this.dispatchEventToListeners("ModelUpdated" );
    }
    onPrerenderStatusUpdated(event) {
        const loaderId = event.key.loaderId;
        this.ensureDocumentPreloadingData(loaderId);
        let attempt;
        switch (event.key.action) {
            case "Prerender" :
                attempt = {
                    action: event.key.action,
                    key: event.key,
                    pipelineId: event.pipelineId,
                    status: convertPreloadingStatus(event.status),
                    prerenderStatus: event.prerenderStatus || null,
                    disallowedMojoInterface: event.disallowedMojoInterface || null,
                    mismatchedHeaders: event.mismatchedHeaders || null,
                };
                break;
            case "PrerenderUntilScript" :
                attempt = {
                    action: event.key.action,
                    key: event.key,
                    pipelineId: event.pipelineId,
                    status: convertPreloadingStatus(event.status),
                    prerenderStatus: event.prerenderStatus || null,
                    disallowedMojoInterface: event.disallowedMojoInterface || null,
                    mismatchedHeaders: event.mismatchedHeaders || null,
                };
                break;
            default:
                throw new Error(`unreachable: event.key.action: ${event.key.action}`);
        }
        this.documents.get(loaderId)?.preloadingAttempts.upsert(attempt);
        this.dispatchEventToListeners("ModelUpdated" );
    }
    onPreloadEnabledStateUpdated(event) {
        this.dispatchEventToListeners("WarningsUpdated" , event);
    }
}
SDKModel.register(PreloadingModel, { capabilities: 2 , autostart: false });
class PreloadDispatcher {
    model;
    constructor(model) {
        this.model = model;
    }
    ruleSetUpdated(event) {
        this.model.onRuleSetUpdated(event);
    }
    ruleSetRemoved(event) {
        this.model.onRuleSetRemoved(event);
    }
    preloadingAttemptSourcesUpdated(event) {
        this.model.onPreloadingAttemptSourcesUpdated(event);
    }
    prefetchStatusUpdated(event) {
        this.model.onPrefetchStatusUpdated(event);
    }
    prerenderStatusUpdated(event) {
        this.model.onPrerenderStatusUpdated(event);
    }
    preloadEnabledStateUpdated(event) {
        void this.model.onPreloadEnabledStateUpdated(event);
    }
}
class DocumentPreloadingData {
    ruleSets = new RuleSetRegistry();
    preloadingAttempts = new PreloadingAttemptRegistry();
    sources = new SourceRegistry();
    mergePrevious(prev) {
        if (!this.ruleSets.isEmpty() || !this.sources.isEmpty()) {
            throw new Error('unreachable');
        }
        this.ruleSets = prev.ruleSets;
        this.preloadingAttempts.mergePrevious(prev.preloadingAttempts);
        this.sources = prev.sources;
    }
}
class RuleSetRegistry {
    map = new Map();
    isEmpty() {
        return this.map.size === 0;
    }
    getById(id) {
        return this.map.get(id) || null;
    }
    getAll() {
        return Array.from(this.map.entries()).map(([id, value]) => ({ id, value }));
    }
    upsert(ruleSet) {
        this.map.set(ruleSet.id, ruleSet);
    }
    delete(id) {
        this.map.delete(id);
    }
}
function convertPreloadingStatus(status) {
    switch (status) {
        case "Pending" :
            return "Pending" ;
        case "Running" :
            return "Running" ;
        case "Ready" :
            return "Ready" ;
        case "Success" :
            return "Success" ;
        case "Failure" :
            return "Failure" ;
        case "NotSupported" :
            return "NotSupported" ;
    }
    throw new Error('unreachable');
}
function makePreloadingAttemptId(key) {
    let action;
    switch (key.action) {
        case "Prefetch" :
            action = 'Prefetch';
            break;
        case "Prerender" :
            action = 'Prerender';
            break;
        case "PrerenderUntilScript" :
            action = 'PrerenderUntilScript';
            break;
    }
    let targetHint;
    switch (key.targetHint) {
        case undefined:
            targetHint = 'undefined';
            break;
        case "Blank" :
            targetHint = 'Blank';
            break;
        case "Self" :
            targetHint = 'Self';
            break;
    }
    return `${key.loaderId}:${action}:${key.url}:${targetHint}`;
}
class PreloadPipeline {
    inner;
    constructor(inner) {
        if (inner.size === 0) {
            throw new Error('unreachable');
        }
        this.inner = inner;
    }
    static newFromAttemptsForTesting(attempts) {
        const inner = new Map();
        for (const attempt of attempts) {
            inner.set(attempt.action, attempt);
        }
        return new PreloadPipeline(inner);
    }
    getOriginallyTriggered() {
        const attempt = this.getPrerender() || this.getPrerenderUntilScript() || this.getPrefetch();
        assertNotNullOrUndefined(attempt);
        return attempt;
    }
    getPrefetch() {
        return this.inner.get("Prefetch" ) || null;
    }
    getPrerender() {
        return this.inner.get("Prerender" ) || null;
    }
    getPrerenderUntilScript() {
        return this.inner.get("PrerenderUntilScript" ) || null;
    }
    getAttempts() {
        const ret = [];
        const prefetch = this.getPrefetch();
        if (prefetch !== null) {
            ret.push(prefetch);
        }
        const prerender = this.getPrerender();
        if (prerender !== null) {
            ret.push(prerender);
        }
        const prerenderUntilScript = this.getPrerenderUntilScript();
        if (prerenderUntilScript !== null) {
            ret.push(prerenderUntilScript);
        }
        if (ret.length === 0) {
            throw new Error('unreachable');
        }
        return ret;
    }
}
class PreloadingAttemptRegistry {
    map = new Map();
    pipelines = new MapWithDefault();
    enrich(attempt, source) {
        let ruleSetIds = [];
        let nodeIds = [];
        if (source !== null) {
            ruleSetIds = source.ruleSetIds;
            nodeIds = source.nodeIds;
        }
        return {
            ...attempt,
            ruleSetIds,
            nodeIds,
        };
    }
    isAttemptRepresentative(attempt) {
        function getSortKey(action) {
            switch (action) {
                case "Prefetch" :
                    return 0;
                case "PrerenderUntilScript" :
                    return 1;
                case "Prerender" :
                    return 2;
            }
        }
        if (attempt.pipelineId === null) {
            return true;
        }
        const pipeline = this.pipelines.get(attempt.pipelineId);
        assertNotNullOrUndefined(pipeline);
        if (pipeline.size === 0) {
            throw new Error('unreachable');
        }
        return [...pipeline.keys()].every(action => getSortKey(action) <= getSortKey(attempt.action));
    }
    getById(id, sources) {
        const attempt = this.map.get(id) || null;
        if (attempt === null) {
            return null;
        }
        return this.enrich(attempt, sources.getById(id));
    }
    getAllRepresentative(ruleSetId, sources) {
        return [...this.map.entries()]
            .map(([id, value]) => ({ id, value: this.enrich(value, sources.getById(id)) }))
            .filter(({ value }) => !ruleSetId || value.ruleSetIds.includes(ruleSetId))
            .filter(({ value }) => this.isAttemptRepresentative(value));
    }
    getPipeline(pipelineId, sources) {
        const pipeline = this.pipelines.get(pipelineId);
        if (pipeline === undefined || pipeline.size === 0) {
            return null;
        }
        for (const [id, attempt] of this.map.entries()) {
        }
        return new Map(pipeline.entries().map(([action, id]) => {
            const attempt = this.getById(id, sources);
            assertNotNullOrUndefined(attempt);
            return [action, attempt];
        }));
    }
    upsert(attempt) {
        const id = makePreloadingAttemptId(attempt.key);
        this.map.set(id, attempt);
        if (attempt.pipelineId !== null) {
            this.pipelines.getOrInsertComputed(attempt.pipelineId, () => new Map()).set(attempt.action, id);
        }
    }
    reconstructPipelines() {
        this.pipelines.clear();
        for (const [id, attempt] of this.map.entries()) {
            if (attempt.pipelineId === null) {
                continue;
            }
            const pipeline = this.pipelines.getOrInsertComputed(attempt.pipelineId, () => new Map());
            pipeline.set(attempt.action, id);
        }
    }
    maybeRegisterNotTriggered(sources) {
        for (const [id, { key }] of sources.entries()) {
            if (this.map.get(id) !== undefined) {
                continue;
            }
            let attempt;
            switch (key.action) {
                case "Prefetch" :
                    attempt = {
                        action: "Prefetch" ,
                        key,
                        pipelineId: null,
                        status: "NotTriggered" ,
                        prefetchStatus: null,
                        requestId: '',
                    };
                    break;
                case "Prerender" :
                    attempt = {
                        action: "Prerender" ,
                        key,
                        pipelineId: null,
                        status: "NotTriggered" ,
                        prerenderStatus: null,
                        disallowedMojoInterface: null,
                        mismatchedHeaders: null,
                    };
                    break;
                case "PrerenderUntilScript" :
                    attempt = {
                        action: "PrerenderUntilScript" ,
                        key,
                        pipelineId: null,
                        status: "NotTriggered" ,
                        prerenderStatus: null,
                        disallowedMojoInterface: null,
                        mismatchedHeaders: null,
                    };
                    break;
            }
            this.map.set(id, attempt);
        }
    }
    cleanUpRemovedAttempts(sources) {
        const keysToRemove = Array.from(this.map.keys()).filter(key => !sources.getById(key));
        for (const key of keysToRemove) {
            this.map.delete(key);
        }
        this.reconstructPipelines();
    }
    mergePrevious(prev) {
        for (const [id, attempt] of this.map.entries()) {
            prev.map.set(id, attempt);
        }
        this.map = prev.map;
        this.reconstructPipelines();
    }
}
class SourceRegistry {
    map = new Map();
    entries() {
        return this.map.entries();
    }
    isEmpty() {
        return this.map.size === 0;
    }
    getById(id) {
        return this.map.get(id) || null;
    }
    update(sources) {
        this.map = new Map(sources.map(s => [makePreloadingAttemptId(s.key), s]));
    }
}

// Copyright 2017 The Chromium Authors
class ScreenCaptureModel extends SDKModel {
    #agent;
    #nextScreencastOperationId = 1;
    #screencastOperations = [];
    constructor(target) {
        super(target);
        this.#agent = target.pageAgent();
        target.registerPageDispatcher(this);
    }
    async startScreencast(format, quality, maxWidth, maxHeight, everyNthFrame, onFrame, onVisibilityChanged) {
        const currentRequest = this.#screencastOperations.at(-1);
        if (currentRequest) {
            await this.#agent.invoke_stopScreencast();
        }
        const operation = {
            id: this.#nextScreencastOperationId++,
            request: {
                format,
                quality,
                maxWidth,
                maxHeight,
                everyNthFrame,
            },
            callbacks: {
                onScreencastFrame: onFrame,
                onScreencastVisibilityChanged: onVisibilityChanged,
            }
        };
        this.#screencastOperations.push(operation);
        void this.#agent.invoke_startScreencast({ format, quality, maxWidth, maxHeight, everyNthFrame });
        return operation.id;
    }
    stopScreencast(id) {
        const operationToStop = this.#screencastOperations.pop();
        if (!operationToStop) {
            throw new Error('There is no screencast operation to stop.');
        }
        if (operationToStop.id !== id) {
            throw new Error('Trying to stop a screencast operation that is not being served right now.');
        }
        void this.#agent.invoke_stopScreencast();
        const nextOperation = this.#screencastOperations.at(-1);
        if (nextOperation) {
            void this.#agent.invoke_startScreencast({
                format: nextOperation.request.format,
                quality: nextOperation.request.quality,
                maxWidth: nextOperation.request.maxWidth,
                maxHeight: nextOperation.request.maxHeight,
                everyNthFrame: nextOperation.request.everyNthFrame,
            });
        }
    }
    async captureScreenshot(format, quality, mode, clip) {
        const properties = {
            format,
            quality,
            fromSurface: true,
        };
        switch (mode) {
            case "fromClip" :
                properties.captureBeyondViewport = true;
                properties.clip = clip;
                break;
            case "fullpage" :
                properties.captureBeyondViewport = true;
                break;
            case "fromViewport" :
                properties.captureBeyondViewport = false;
                break;
            default:
                throw new Error('Unexpected or unspecified screnshotMode');
        }
        await OverlayModel.muteHighlight();
        const result = await this.#agent.invoke_captureScreenshot(properties);
        await OverlayModel.unmuteHighlight();
        return result.data;
    }
    screencastFrame({ data, metadata, sessionId }) {
        void this.#agent.invoke_screencastFrameAck({ sessionId });
        const currentRequest = this.#screencastOperations.at(-1);
        if (currentRequest) {
            currentRequest.callbacks.onScreencastFrame.call(null, data, metadata);
        }
    }
    screencastVisibilityChanged({ visible }) {
        const currentRequest = this.#screencastOperations.at(-1);
        if (currentRequest) {
            currentRequest.callbacks.onScreencastVisibilityChanged.call(null, visible);
        }
    }
    backForwardCacheNotUsed(_params) {
    }
    domContentEventFired(_params) {
    }
    loadEventFired(_params) {
    }
    lifecycleEvent(_params) {
    }
    navigatedWithinDocument(_params) {
    }
    frameAttached(_params) {
    }
    frameNavigated(_params) {
    }
    documentOpened(_params) {
    }
    frameDetached(_params) {
    }
    frameStartedLoading(_params) {
    }
    frameStoppedLoading(_params) {
    }
    frameRequestedNavigation(_params) {
    }
    frameStartedNavigating(_params) {
    }
    frameSubtreeWillBeDetached(_params) {
    }
    frameScheduledNavigation(_params) {
    }
    frameClearedScheduledNavigation(_params) {
    }
    frameResized() {
    }
    javascriptDialogOpening(_params) {
    }
    javascriptDialogClosed(_params) {
    }
    interstitialShown() {
    }
    interstitialHidden() {
    }
    windowOpen(_params) {
    }
    fileChooserOpened(_params) {
    }
    compilationCacheProduced(_params) {
    }
    downloadWillBegin(_params) {
    }
    downloadProgress() {
    }
    prefetchStatusUpdated(_params) {
    }
    prerenderStatusUpdated(_params) {
    }
}
SDKModel.register(ScreenCaptureModel, { capabilities: 64 , autostart: false });

// Copyright 2023 The Chromium Authors
class StorageBucketsModel extends SDKModel {
    enabled = false;
    storageAgent;
    storageKeyManager;
    bucketsById = new Map();
    trackedStorageKeys = new Set();
    constructor(target) {
        super(target);
        target.registerStorageDispatcher(this);
        this.storageAgent = target.storageAgent();
        this.storageKeyManager = target.model(StorageKeyManager);
    }
    getBuckets() {
        return new Set(this.bucketsById.values());
    }
    getBucketsForStorageKey(storageKey) {
        const buckets = [...this.bucketsById.values()];
        return new Set(buckets.filter(({ bucket }) => bucket.storageKey === storageKey));
    }
    getDefaultBucketForStorageKey(storageKey) {
        const buckets = [...this.bucketsById.values()];
        return buckets.find(({ bucket }) => bucket.storageKey === storageKey && bucket.name === undefined) ?? null;
    }
    getBucketById(bucketId) {
        return this.bucketsById.get(bucketId) ?? null;
    }
    getBucketByName(storageKey, bucketName) {
        if (!bucketName) {
            return this.getDefaultBucketForStorageKey(storageKey);
        }
        const buckets = [...this.bucketsById.values()];
        return buckets.find(({ bucket }) => bucket.storageKey === storageKey && bucket.name === bucketName) ?? null;
    }
    deleteBucket(bucket) {
        void this.storageAgent.invoke_deleteStorageBucket({ bucket });
    }
    enable() {
        if (this.enabled) {
            return;
        }
        if (this.storageKeyManager) {
            this.storageKeyManager.addEventListener("StorageKeyAdded" , this.storageKeyAdded, this);
            this.storageKeyManager.addEventListener("StorageKeyRemoved" , this.storageKeyRemoved, this);
            for (const storageKey of this.storageKeyManager.storageKeys()) {
                this.addStorageKey(storageKey);
            }
        }
        this.enabled = true;
    }
    storageKeyAdded(event) {
        this.addStorageKey(event.data);
    }
    storageKeyRemoved(event) {
        this.removeStorageKey(event.data);
    }
    addStorageKey(storageKey) {
        if (this.trackedStorageKeys.has(storageKey)) {
            throw new Error('Can\'t call addStorageKey for a storage key if it has already been added.');
        }
        this.trackedStorageKeys.add(storageKey);
        void this.storageAgent.invoke_setStorageBucketTracking({ storageKey, enable: true });
    }
    removeStorageKey(storageKey) {
        if (!this.trackedStorageKeys.has(storageKey)) {
            throw new Error('Can\'t call removeStorageKey for a storage key if it hasn\'t already been added.');
        }
        const bucketsForStorageKey = this.getBucketsForStorageKey(storageKey);
        for (const bucket of bucketsForStorageKey) {
            this.bucketRemoved(bucket);
        }
        this.trackedStorageKeys.delete(storageKey);
        void this.storageAgent.invoke_setStorageBucketTracking({ storageKey, enable: false });
    }
    bucketAdded(bucketInfo) {
        this.bucketsById.set(bucketInfo.id, bucketInfo);
        this.dispatchEventToListeners("BucketAdded" , { model: this, bucketInfo });
    }
    bucketRemoved(bucketInfo) {
        this.bucketsById.delete(bucketInfo.id);
        this.dispatchEventToListeners("BucketRemoved" , { model: this, bucketInfo });
    }
    bucketChanged(bucketInfo) {
        this.dispatchEventToListeners("BucketChanged" , { model: this, bucketInfo });
    }
    bucketInfosAreEqual(bucketInfo1, bucketInfo2) {
        return bucketInfo1.bucket.storageKey === bucketInfo2.bucket.storageKey && bucketInfo1.id === bucketInfo2.id &&
            bucketInfo1.bucket.name === bucketInfo2.bucket.name && bucketInfo1.expiration === bucketInfo2.expiration &&
            bucketInfo1.quota === bucketInfo2.quota && bucketInfo1.persistent === bucketInfo2.persistent &&
            bucketInfo1.durability === bucketInfo2.durability;
    }
    storageBucketCreatedOrUpdated({ bucketInfo }) {
        const curBucket = this.getBucketById(bucketInfo.id);
        if (curBucket) {
            if (!this.bucketInfosAreEqual(curBucket, bucketInfo)) {
                this.bucketChanged(bucketInfo);
            }
        }
        else {
            this.bucketAdded(bucketInfo);
        }
    }
    storageBucketDeleted({ bucketId }) {
        const curBucket = this.getBucketById(bucketId);
        if (curBucket) {
            this.bucketRemoved(curBucket);
        }
        else {
            throw new Error(`Received an event that Storage Bucket '${bucketId}' was deleted, but it wasn't in the StorageBucketsModel.`);
        }
    }
    attributionReportingTriggerRegistered(_event) {
    }
    interestGroupAccessed(_event) {
    }
    interestGroupAuctionEventOccurred(_event) {
    }
    interestGroupAuctionNetworkRequestCreated(_event) {
    }
    indexedDBListUpdated(_event) {
    }
    indexedDBContentUpdated(_event) {
    }
    cacheStorageListUpdated(_event) {
    }
    cacheStorageContentUpdated(_event) {
    }
    sharedStorageAccessed(_event) {
    }
    sharedStorageWorkletOperationExecutionFinished(_event) {
    }
    attributionReportingSourceRegistered(_event) {
    }
    attributionReportingReportSent(_event) {
    }
    attributionReportingVerboseDebugReportSent(_event) {
    }
}
SDKModel.register(StorageBucketsModel, { capabilities: 8192 , autostart: false });

// Copyright 2014 The Chromium Authors
const UIStrings$R = {
    serviceworkercacheagentError: '`ServiceWorkerCacheAgent` error deleting cache entry {PH1} in cache: {PH2}',
};
const str_$Q = registerUIStrings('core/sdk/ServiceWorkerCacheModel.ts', UIStrings$R);
const i18nString$C = getLocalizedString.bind(undefined, str_$Q);
class ServiceWorkerCacheModel extends SDKModel {
    cacheAgent;
    #storageAgent;
    #storageBucketModel;
    #caches = new Map();
    #storageKeysTracked = new Set();
    #storageBucketsUpdated = new Set();
    #throttler = new Throttler(2000);
    #enabled = false;
    #scheduleAsSoonAsPossible = false;
    constructor(target) {
        super(target);
        target.registerStorageDispatcher(this);
        this.cacheAgent = target.cacheStorageAgent();
        this.#storageAgent = target.storageAgent();
        this.#storageBucketModel = target.model(StorageBucketsModel);
    }
    enable() {
        if (this.#enabled) {
            return;
        }
        this.#storageBucketModel.addEventListener("BucketAdded" , this.storageBucketAdded, this);
        this.#storageBucketModel.addEventListener("BucketRemoved" , this.storageBucketRemoved, this);
        for (const storageBucket of this.#storageBucketModel.getBuckets()) {
            this.addStorageBucket(storageBucket.bucket);
        }
        this.#enabled = true;
    }
    clearForStorageKey(storageKey) {
        for (const [opaqueId, cache] of this.#caches.entries()) {
            if (cache.storageKey === storageKey) {
                this.#caches.delete((opaqueId));
                this.cacheRemoved((cache));
            }
        }
        for (const storageBucket of this.#storageBucketModel.getBucketsForStorageKey(storageKey)) {
            void this.loadCacheNames(storageBucket.bucket);
        }
    }
    refreshCacheNames() {
        for (const cache of this.#caches.values()) {
            this.cacheRemoved(cache);
        }
        this.#caches.clear();
        const storageBuckets = this.#storageBucketModel.getBuckets();
        for (const storageBucket of storageBuckets) {
            void this.loadCacheNames(storageBucket.bucket);
        }
    }
    async deleteCache(cache) {
        const response = await this.cacheAgent.invoke_deleteCache({ cacheId: cache.cacheId });
        if (response.getError()) {
            console.error(`ServiceWorkerCacheAgent error deleting cache ${cache.toString()}: ${response.getError()}`);
            return;
        }
        this.#caches.delete(cache.cacheId);
        this.cacheRemoved(cache);
    }
    async deleteCacheEntry(cache, request) {
        const response = await this.cacheAgent.invoke_deleteEntry({ cacheId: cache.cacheId, request });
        if (response.getError()) {
            Console.instance().error(i18nString$C(UIStrings$R.serviceworkercacheagentError, { PH1: cache.toString(), PH2: String(response.getError()) }));
            return;
        }
    }
    loadCacheData(cache, skipCount, pageSize, pathFilter, callback) {
        void this.requestEntries(cache, skipCount, pageSize, pathFilter, callback);
    }
    loadAllCacheData(cache, pathFilter, callback) {
        void this.requestAllEntries(cache, pathFilter, callback);
    }
    caches() {
        return [...this.#caches.values()];
    }
    dispose() {
        for (const cache of this.#caches.values()) {
            this.cacheRemoved(cache);
        }
        this.#caches.clear();
        if (this.#enabled) {
            this.#storageBucketModel.removeEventListener("BucketAdded" , this.storageBucketAdded, this);
            this.#storageBucketModel.removeEventListener("BucketRemoved" , this.storageBucketRemoved, this);
        }
    }
    addStorageBucket(storageBucket) {
        void this.loadCacheNames(storageBucket);
        if (!this.#storageKeysTracked.has(storageBucket.storageKey)) {
            this.#storageKeysTracked.add(storageBucket.storageKey);
            void this.#storageAgent.invoke_trackCacheStorageForStorageKey({ storageKey: storageBucket.storageKey });
        }
    }
    removeStorageBucket(storageBucket) {
        let storageKeyCount = 0;
        for (const [opaqueId, cache] of this.#caches.entries()) {
            if (storageBucket.storageKey === cache.storageKey) {
                storageKeyCount++;
            }
            if (cache.inBucket(storageBucket)) {
                storageKeyCount--;
                this.#caches.delete((opaqueId));
                this.cacheRemoved((cache));
            }
        }
        if (storageKeyCount === 0) {
            this.#storageKeysTracked.delete(storageBucket.storageKey);
            void this.#storageAgent.invoke_untrackCacheStorageForStorageKey({ storageKey: storageBucket.storageKey });
        }
    }
    async loadCacheNames(storageBucket) {
        const response = await this.cacheAgent.invoke_requestCacheNames({ storageBucket });
        if (response.getError()) {
            return;
        }
        this.updateCacheNames(storageBucket, response.caches);
    }
    updateCacheNames(storageBucket, cachesJson) {
        function deleteAndSaveOldCaches(cache) {
            if (cache.inBucket(storageBucket) && !updatingCachesIds.has(cache.cacheId)) {
                oldCaches.set(cache.cacheId, cache);
                this.#caches.delete(cache.cacheId);
            }
        }
        const updatingCachesIds = new Set();
        const newCaches = new Map();
        const oldCaches = new Map();
        for (const cacheJson of cachesJson) {
            const storageBucket = cacheJson.storageBucket ??
                this.#storageBucketModel.getDefaultBucketForStorageKey(cacheJson.storageKey)?.bucket;
            if (!storageBucket) {
                continue;
            }
            const cache = new Cache$1(this, storageBucket, cacheJson.cacheName, cacheJson.cacheId);
            updatingCachesIds.add(cache.cacheId);
            if (this.#caches.has(cache.cacheId)) {
                continue;
            }
            newCaches.set(cache.cacheId, cache);
            this.#caches.set(cache.cacheId, cache);
        }
        this.#caches.forEach(deleteAndSaveOldCaches, this);
        newCaches.forEach(this.cacheAdded, this);
        oldCaches.forEach(this.cacheRemoved, this);
    }
    storageBucketAdded({ data: { bucketInfo: { bucket } } }) {
        this.addStorageBucket(bucket);
    }
    storageBucketRemoved({ data: { bucketInfo: { bucket } } }) {
        this.removeStorageBucket(bucket);
    }
    cacheAdded(cache) {
        this.dispatchEventToListeners("CacheAdded" , { model: this, cache });
    }
    cacheRemoved(cache) {
        this.dispatchEventToListeners("CacheRemoved" , { model: this, cache });
    }
    async requestEntries(cache, skipCount, pageSize, pathFilter, callback) {
        const response = await this.cacheAgent.invoke_requestEntries({ cacheId: cache.cacheId, skipCount, pageSize, pathFilter });
        if (response.getError()) {
            console.error('ServiceWorkerCacheAgent error while requesting entries: ', response.getError());
            return;
        }
        callback(response.cacheDataEntries, response.returnCount);
    }
    async requestAllEntries(cache, pathFilter, callback) {
        const response = await this.cacheAgent.invoke_requestEntries({ cacheId: cache.cacheId, pathFilter });
        if (response.getError()) {
            console.error('ServiceWorkerCacheAgent error while requesting entries: ', response.getError());
            return;
        }
        callback(response.cacheDataEntries, response.returnCount);
    }
    cacheStorageListUpdated({ bucketId }) {
        const storageBucket = this.#storageBucketModel.getBucketById(bucketId)?.bucket;
        if (storageBucket) {
            this.#storageBucketsUpdated.add(storageBucket);
            void this.#throttler.schedule(() => {
                const promises = Array.from(this.#storageBucketsUpdated, storageBucket => this.loadCacheNames(storageBucket));
                this.#storageBucketsUpdated.clear();
                return Promise.all(promises);
            }, this.#scheduleAsSoonAsPossible ? "AsSoonAsPossible"  :
                "Default" );
        }
    }
    cacheStorageContentUpdated({ bucketId, cacheName }) {
        const storageBucket = this.#storageBucketModel.getBucketById(bucketId)?.bucket;
        if (storageBucket) {
            this.dispatchEventToListeners("CacheStorageContentUpdated" , { storageBucket, cacheName });
        }
    }
    attributionReportingTriggerRegistered(_event) {
    }
    indexedDBListUpdated(_event) {
    }
    indexedDBContentUpdated(_event) {
    }
    interestGroupAuctionEventOccurred(_event) {
    }
    interestGroupAccessed(_event) {
    }
    interestGroupAuctionNetworkRequestCreated(_event) {
    }
    sharedStorageAccessed(_event) {
    }
    sharedStorageWorkletOperationExecutionFinished(_event) {
    }
    storageBucketCreatedOrUpdated(_event) {
    }
    storageBucketDeleted(_event) {
    }
    setThrottlerSchedulesAsSoonAsPossibleForTest() {
        this.#scheduleAsSoonAsPossible = true;
    }
    attributionReportingSourceRegistered(_event) {
    }
    attributionReportingReportSent(_event) {
    }
    attributionReportingVerboseDebugReportSent(_event) {
    }
}
let Cache$1 = class Cache {
    #model;
    storageKey;
    storageBucket;
    cacheName;
    cacheId;
    constructor(model, storageBucket, cacheName, cacheId) {
        this.#model = model;
        this.storageBucket = storageBucket;
        this.storageKey = storageBucket.storageKey;
        this.cacheName = cacheName;
        this.cacheId = cacheId;
    }
    inBucket(storageBucket) {
        return this.storageKey === storageBucket.storageKey && this.storageBucket.name === storageBucket.name;
    }
    equals(cache) {
        return this.cacheId === cache.cacheId;
    }
    toString() {
        return this.storageKey + this.cacheName;
    }
    async requestCachedResponse(url, requestHeaders) {
        const response = await this.#model.cacheAgent.invoke_requestCachedResponse({ cacheId: this.cacheId, requestURL: url, requestHeaders });
        if (response.getError()) {
            return null;
        }
        return response.response;
    }
};
SDKModel.register(ServiceWorkerCacheModel, { capabilities: 8192 , autostart: false });

// Copyright 2011 The Chromium Authors
const UIStrings$Q = {
    running: 'running',
    starting: 'starting',
    stopped: 'stopped',
    stopping: 'stopping',
    activated: 'activated',
    activating: 'activating',
    installed: 'installed',
    installing: 'installing',
    new: 'new',
    redundant: 'redundant',
    sSS: '{PH1} #{PH2} ({PH3})',
};
const str_$P = registerUIStrings('core/sdk/ServiceWorkerManager.ts', UIStrings$Q);
const i18nString$B = getLocalizedString.bind(undefined, str_$P);
const i18nLazyString$c = getLazilyComputedLocalizedString.bind(undefined, str_$P);
class ServiceWorkerManager extends SDKModel {
    #agent;
    #registrations = new Map();
    #enabled = false;
    #forceUpdateSetting;
    constructor(target) {
        super(target);
        target.registerServiceWorkerDispatcher(new ServiceWorkerDispatcher(this));
        this.#agent = target.serviceWorkerAgent();
        void this.enable();
        this.#forceUpdateSetting =
            Settings.instance().createSetting('service-worker-update-on-reload', false);
        if (this.#forceUpdateSetting.get()) {
            this.forceUpdateSettingChanged();
        }
        this.#forceUpdateSetting.addChangeListener(this.forceUpdateSettingChanged, this);
        new ServiceWorkerContextNamer(target, this);
    }
    async enable() {
        if (this.#enabled) {
            return;
        }
        this.#enabled = true;
        await this.#agent.invoke_enable();
    }
    async disable() {
        if (!this.#enabled) {
            return;
        }
        this.#enabled = false;
        this.#registrations.clear();
        await this.#agent.invoke_enable();
    }
    registrations() {
        return this.#registrations;
    }
    findVersion(versionId) {
        for (const registration of this.registrations().values()) {
            const version = registration.versions.get(versionId);
            if (version) {
                return version;
            }
        }
        return null;
    }
    deleteRegistration(registrationId) {
        const registration = this.#registrations.get(registrationId);
        if (!registration) {
            return;
        }
        if (registration.isRedundant()) {
            this.#registrations.delete(registrationId);
            this.dispatchEventToListeners("RegistrationDeleted" , registration);
            return;
        }
        registration.deleting = true;
        for (const version of registration.versions.values()) {
            void this.stopWorker(version.id);
        }
        void this.unregister(registration.scopeURL);
    }
    async updateRegistration(registrationId) {
        const registration = this.#registrations.get(registrationId);
        if (!registration) {
            return;
        }
        await this.#agent.invoke_updateRegistration({ scopeURL: registration.scopeURL });
    }
    async deliverPushMessage(registrationId, data) {
        const registration = this.#registrations.get(registrationId);
        if (!registration) {
            return;
        }
        const origin = ParsedURL.extractOrigin(registration.scopeURL);
        await this.#agent.invoke_deliverPushMessage({ origin, registrationId, data });
    }
    async dispatchSyncEvent(registrationId, tag, lastChance) {
        const registration = this.#registrations.get(registrationId);
        if (!registration) {
            return;
        }
        const origin = ParsedURL.extractOrigin(registration.scopeURL);
        await this.#agent.invoke_dispatchSyncEvent({ origin, registrationId, tag, lastChance });
    }
    async dispatchPeriodicSyncEvent(registrationId, tag) {
        const registration = this.#registrations.get(registrationId);
        if (!registration) {
            return;
        }
        const origin = ParsedURL.extractOrigin(registration.scopeURL);
        await this.#agent.invoke_dispatchPeriodicSyncEvent({ origin, registrationId, tag });
    }
    async unregister(scopeURL) {
        await this.#agent.invoke_unregister({ scopeURL });
    }
    async startWorker(scopeURL) {
        await this.#agent.invoke_startWorker({ scopeURL });
    }
    async skipWaiting(scopeURL) {
        await this.#agent.invoke_skipWaiting({ scopeURL });
    }
    async stopWorker(versionId) {
        await this.#agent.invoke_stopWorker({ versionId });
    }
    workerRegistrationUpdated(registrations) {
        for (const payload of registrations) {
            let registration = this.#registrations.get(payload.registrationId);
            if (!registration) {
                registration = new ServiceWorkerRegistration(payload);
                this.#registrations.set(payload.registrationId, registration);
                this.dispatchEventToListeners("RegistrationUpdated" , registration);
                continue;
            }
            registration.update(payload);
            if (registration.shouldBeRemoved()) {
                this.#registrations.delete(registration.id);
                this.dispatchEventToListeners("RegistrationDeleted" , registration);
            }
            else {
                this.dispatchEventToListeners("RegistrationUpdated" , registration);
            }
        }
    }
    workerVersionUpdated(versions) {
        const registrations = new Set();
        for (const payload of versions) {
            const registration = this.#registrations.get(payload.registrationId);
            if (!registration) {
                continue;
            }
            registration.updateVersion(payload);
            registrations.add(registration);
        }
        for (const registration of registrations) {
            if (registration.shouldBeRemoved()) {
                this.#registrations.delete(registration.id);
                this.dispatchEventToListeners("RegistrationDeleted" , registration);
            }
            else {
                this.dispatchEventToListeners("RegistrationUpdated" , registration);
            }
        }
    }
    workerErrorReported(payload) {
        const registration = this.#registrations.get(payload.registrationId);
        if (!registration) {
            return;
        }
        registration.errors.push(payload);
        this.dispatchEventToListeners("RegistrationErrorAdded" , { registration, error: payload });
    }
    forceUpdateSettingChanged() {
        const forceUpdateOnPageLoad = this.#forceUpdateSetting.get();
        void this.#agent.invoke_setForceUpdateOnPageLoad({ forceUpdateOnPageLoad });
    }
}
class ServiceWorkerDispatcher {
    #manager;
    constructor(manager) {
        this.#manager = manager;
    }
    workerRegistrationUpdated({ registrations }) {
        this.#manager.workerRegistrationUpdated(registrations);
    }
    workerVersionUpdated({ versions }) {
        this.#manager.workerVersionUpdated(versions);
    }
    workerErrorReported({ errorMessage }) {
        this.#manager.workerErrorReported(errorMessage);
    }
}
class ServiceWorkerVersionState {
    runningStatus;
    status;
    lastUpdatedTimestamp;
    previousState;
    constructor(runningStatus, status, previousState, timestamp) {
        this.runningStatus = runningStatus;
        this.status = status;
        this.lastUpdatedTimestamp = timestamp;
        this.previousState = previousState;
    }
}
class ServiceWorkerRouterRule {
    condition;
    source;
    id;
    constructor(condition, source, id) {
        this.condition = condition;
        this.source = source;
        this.id = id;
    }
}
class ServiceWorkerVersion {
    id;
    scriptURL;
    parsedURL;
    securityOrigin;
    scriptLastModified;
    scriptResponseTime;
    controlledClients;
    targetId;
    routerRules;
    currentState;
    registration;
    constructor(registration, payload) {
        this.registration = registration;
        this.update(payload);
    }
    update(payload) {
        this.id = payload.versionId;
        this.scriptURL = payload.scriptURL;
        const parsedURL = new ParsedURL(payload.scriptURL);
        this.securityOrigin = parsedURL.securityOrigin();
        this.currentState =
            new ServiceWorkerVersionState(payload.runningStatus, payload.status, this.currentState, Date.now());
        this.scriptLastModified = payload.scriptLastModified;
        this.scriptResponseTime = payload.scriptResponseTime;
        if (payload.controlledClients) {
            this.controlledClients = payload.controlledClients.slice();
        }
        else {
            this.controlledClients = [];
        }
        this.targetId = payload.targetId || null;
        this.routerRules = null;
        if (payload.routerRules) {
            this.routerRules = this.parseJSONRules(payload.routerRules);
        }
    }
    isStartable() {
        return !this.registration.isDeleted && this.isActivated() && this.isStopped();
    }
    isStoppedAndRedundant() {
        return this.runningStatus === "stopped"  &&
            this.status === "redundant" ;
    }
    isStopped() {
        return this.runningStatus === "stopped" ;
    }
    isStarting() {
        return this.runningStatus === "starting" ;
    }
    isRunning() {
        return this.runningStatus === "running" ;
    }
    isStopping() {
        return this.runningStatus === "stopping" ;
    }
    isNew() {
        return this.status === "new" ;
    }
    isInstalling() {
        return this.status === "installing" ;
    }
    isInstalled() {
        return this.status === "installed" ;
    }
    isActivating() {
        return this.status === "activating" ;
    }
    isActivated() {
        return this.status === "activated" ;
    }
    isRedundant() {
        return this.status === "redundant" ;
    }
    get status() {
        return this.currentState.status;
    }
    get runningStatus() {
        return this.currentState.runningStatus;
    }
    mode() {
        if (this.isNew() || this.isInstalling()) {
            return "installing" ;
        }
        if (this.isInstalled()) {
            return "waiting" ;
        }
        if (this.isActivating() || this.isActivated()) {
            return "active" ;
        }
        return "redundant" ;
    }
    parseJSONRules(input) {
        try {
            const parsedObject = JSON.parse(input);
            if (!Array.isArray(parsedObject)) {
                console.error('Parse error: `routerRules` in ServiceWorkerVersion should be an array');
                return null;
            }
            const routerRules = [];
            for (const parsedRule of parsedObject) {
                const { condition, source, id } = parsedRule;
                if (condition === undefined || source === undefined || id === undefined) {
                    console.error('Parse error: Missing some fields of `routerRules` in ServiceWorkerVersion');
                    return null;
                }
                routerRules.push(new ServiceWorkerRouterRule(JSON.stringify(condition), JSON.stringify(source), id));
            }
            return routerRules;
        }
        catch {
            console.error('Parse error: Invalid `routerRules` in ServiceWorkerVersion');
            return null;
        }
    }
}
(function (ServiceWorkerVersion) {
    ServiceWorkerVersion.RunningStatus = {
        ["running" ]: i18nLazyString$c(UIStrings$Q.running),
        ["starting" ]: i18nLazyString$c(UIStrings$Q.starting),
        ["stopped" ]: i18nLazyString$c(UIStrings$Q.stopped),
        ["stopping" ]: i18nLazyString$c(UIStrings$Q.stopping),
    };
    ServiceWorkerVersion.Status = {
        ["activated" ]: i18nLazyString$c(UIStrings$Q.activated),
        ["activating" ]: i18nLazyString$c(UIStrings$Q.activating),
        ["installed" ]: i18nLazyString$c(UIStrings$Q.installed),
        ["installing" ]: i18nLazyString$c(UIStrings$Q.installing),
        ["new" ]: i18nLazyString$c(UIStrings$Q.new),
        ["redundant" ]: i18nLazyString$c(UIStrings$Q.redundant),
    };
})(ServiceWorkerVersion || (ServiceWorkerVersion = {}));
class ServiceWorkerRegistration {
    #fingerprint;
    id;
    scopeURL;
    securityOrigin;
    isDeleted;
    versions = new Map();
    deleting = false;
    errors = [];
    constructor(payload) {
        this.update(payload);
    }
    update(payload) {
        this.#fingerprint = Symbol('fingerprint');
        this.id = payload.registrationId;
        this.scopeURL = payload.scopeURL;
        const parsedURL = new ParsedURL(payload.scopeURL);
        this.securityOrigin = parsedURL.securityOrigin();
        this.isDeleted = payload.isDeleted;
    }
    fingerprint() {
        return this.#fingerprint;
    }
    versionsByMode() {
        const result = new Map();
        for (const version of this.versions.values()) {
            result.set(version.mode(), version);
        }
        return result;
    }
    updateVersion(payload) {
        this.#fingerprint = Symbol('fingerprint');
        let version = this.versions.get(payload.versionId);
        if (!version) {
            version = new ServiceWorkerVersion(this, payload);
            this.versions.set(payload.versionId, version);
            return version;
        }
        version.update(payload);
        return version;
    }
    isRedundant() {
        for (const version of this.versions.values()) {
            if (!version.isStoppedAndRedundant()) {
                return false;
            }
        }
        return true;
    }
    shouldBeRemoved() {
        return this.isRedundant() && (!this.errors.length || this.deleting);
    }
    canBeRemoved() {
        return this.isDeleted || this.deleting;
    }
}
class ServiceWorkerContextNamer {
    #target;
    #serviceWorkerManager;
    #versionByTargetId = new Map();
    constructor(target, serviceWorkerManager) {
        this.#target = target;
        this.#serviceWorkerManager = serviceWorkerManager;
        serviceWorkerManager.addEventListener("RegistrationUpdated" , this.registrationsUpdated, this);
        serviceWorkerManager.addEventListener("RegistrationDeleted" , this.registrationsUpdated, this);
        TargetManager.instance().addModelListener(RuntimeModel, Events$9.ExecutionContextCreated, this.executionContextCreated, this);
    }
    registrationsUpdated() {
        this.#versionByTargetId.clear();
        const registrations = this.#serviceWorkerManager.registrations().values();
        for (const registration of registrations) {
            for (const version of registration.versions.values()) {
                if (version.targetId) {
                    this.#versionByTargetId.set(version.targetId, version);
                }
            }
        }
        this.updateAllContextLabels();
    }
    executionContextCreated(event) {
        const executionContext = event.data;
        const serviceWorkerTargetId = this.serviceWorkerTargetId(executionContext.target());
        if (!serviceWorkerTargetId) {
            return;
        }
        this.updateContextLabel(executionContext, this.#versionByTargetId.get(serviceWorkerTargetId) || null);
    }
    serviceWorkerTargetId(target) {
        if (target.parentTarget() !== this.#target || target.type() !== Type$2.ServiceWorker) {
            return null;
        }
        return target.id();
    }
    updateAllContextLabels() {
        for (const target of TargetManager.instance().targets()) {
            const serviceWorkerTargetId = this.serviceWorkerTargetId(target);
            if (!serviceWorkerTargetId) {
                continue;
            }
            const version = this.#versionByTargetId.get(serviceWorkerTargetId) || null;
            const runtimeModel = target.model(RuntimeModel);
            const executionContexts = runtimeModel ? runtimeModel.executionContexts() : [];
            for (const context of executionContexts) {
                this.updateContextLabel(context, version);
            }
        }
    }
    updateContextLabel(context, version) {
        if (!version) {
            context.setLabel('');
            return;
        }
        const parsedUrl = ParsedURL.fromString(context.origin);
        const label = parsedUrl ? parsedUrl.lastPathComponentWithFragment() : context.name;
        const localizedStatus = ServiceWorkerVersion.Status[version.status];
        context.setLabel(i18nString$B(UIStrings$Q.sSS, { PH1: label, PH2: version.id, PH3: localizedStatus() }));
    }
}
SDKModel.register(ServiceWorkerManager, { capabilities: 16384 , autostart: true });

// Copyright 2020 The Chromium Authors
class WebAuthnModel extends SDKModel {
    #agent;
    constructor(target) {
        super(target);
        this.#agent = target.webAuthnAgent();
        target.registerWebAuthnDispatcher(new WebAuthnDispatcher(this));
    }
    setVirtualAuthEnvEnabled(enable) {
        if (enable) {
            return this.#agent.invoke_enable({ enableUI: true });
        }
        return this.#agent.invoke_disable();
    }
    async addAuthenticator(options) {
        const response = await this.#agent.invoke_addVirtualAuthenticator({ options });
        return response.authenticatorId;
    }
    async removeAuthenticator(authenticatorId) {
        await this.#agent.invoke_removeVirtualAuthenticator({ authenticatorId });
    }
    async setAutomaticPresenceSimulation(authenticatorId, enabled) {
        await this.#agent.invoke_setAutomaticPresenceSimulation({ authenticatorId, enabled });
    }
    async getCredentials(authenticatorId) {
        const response = await this.#agent.invoke_getCredentials({ authenticatorId });
        return response.credentials;
    }
    async removeCredential(authenticatorId, credentialId) {
        await this.#agent.invoke_removeCredential({ authenticatorId, credentialId });
    }
    credentialAdded(params) {
        this.dispatchEventToListeners("CredentialAdded" , params);
    }
    credentialAsserted(params) {
        this.dispatchEventToListeners("CredentialAsserted" , params);
    }
    credentialDeleted(params) {
        this.dispatchEventToListeners("CredentialDeleted" , params);
    }
    credentialUpdated(params) {
        this.dispatchEventToListeners("CredentialUpdated" , params);
    }
}
class WebAuthnDispatcher {
    #model;
    constructor(model) {
        this.#model = model;
    }
    credentialAdded(params) {
        this.#model.credentialAdded(params);
    }
    credentialAsserted(params) {
        this.#model.credentialAsserted(params);
    }
    credentialDeleted(params) {
        this.#model.credentialDeleted(params);
    }
    credentialUpdated(params) {
        this.#model.credentialUpdated(params);
    }
}
SDKModel.register(WebAuthnModel, { capabilities: 65536 , autostart: false });

// Copyright 2025 The Chromium Authors
class StackTraceImpl extends ObjectWrapper {
    syncFragment;
    asyncFragments;
    constructor(syncFragment, asyncFragments) {
        super();
        this.syncFragment = syncFragment;
        this.asyncFragments = asyncFragments;
        const fragment = syncFragment instanceof DebuggableFragmentImpl ? syncFragment.fragment : syncFragment;
        fragment.stackTraces.add(this);
        this.asyncFragments.forEach(asyncFragment => asyncFragment.fragment.stackTraces.add(this));
    }
}
class FragmentImpl {
    static EMPTY_FRAGMENT = new FragmentImpl();
    node;
    stackTraces = new Set();
    static getOrCreate(node) {
        if (!node.fragment) {
            node.fragment = new FragmentImpl(node);
        }
        return node.fragment;
    }
    constructor(node) {
        this.node = node;
    }
    get frames() {
        if (!this.node) {
            return [];
        }
        const frames = [];
        for (const node of this.node.getCallStack()) {
            frames.push(...node.frames);
        }
        return frames;
    }
}
class AsyncFragmentImpl {
    description;
    fragment;
    constructor(description, fragment) {
        this.description = description;
        this.fragment = fragment;
    }
    get frames() {
        return this.fragment.frames;
    }
}
class FrameImpl {
    url;
    uiSourceCode;
    name;
    line;
    column;
    missingDebugInfo;
    constructor(url, uiSourceCode, name, line, column, missingDebugInfo) {
        this.url = url;
        this.uiSourceCode = uiSourceCode;
        this.name = name;
        this.line = line;
        this.column = column;
        this.missingDebugInfo = missingDebugInfo;
    }
}
class DebuggableFragmentImpl {
    fragment;
    callFrames;
    constructor(fragment, callFrames) {
        this.fragment = fragment;
        this.callFrames = callFrames;
    }
    get frames() {
        if (!this.fragment.node) {
            return [];
        }
        const frames = [];
        let index = 0;
        for (const node of this.fragment.node.getCallStack()) {
            for (const [inlineIdx, frame] of node.frames.entries()) {
                const sdkFrame = inlineIdx === 0 ? this.callFrames[index] :
                    this.callFrames[index].createVirtualCallFrame(inlineIdx, frame.name ?? '');
                frames.push(new DebuggableFrameImpl(frame, sdkFrame));
            }
            index++;
        }
        return frames;
    }
}
class DebuggableFrameImpl {
    #frame;
    #sdkFrame;
    constructor(frame, sdkFrame) {
        this.#frame = frame;
        this.#sdkFrame = sdkFrame;
    }
    get url() {
        return this.#frame.url;
    }
    get uiSourceCode() {
        return this.#frame.uiSourceCode;
    }
    get name() {
        return this.#frame.name;
    }
    get line() {
        return this.#frame.line;
    }
    get column() {
        return this.#frame.column;
    }
    get missingDebugInfo() {
        return this.#frame.missingDebugInfo;
    }
    get sdkFrame() {
        return this.#sdkFrame;
    }
}

// Copyright 2025 The Chromium Authors
class DebuggableFrameFlavor {
    static #last;
    frame;
    constructor(frame) {
        this.frame = frame;
    }
    get sdkFrame() {
        return this.frame.sdkFrame;
    }
    static for(frame) {
        function equals(a, b) {
            return a.url === b.url && a.uiSourceCode === b.uiSourceCode && a.name === b.name && a.line === b.line &&
                a.column === b.column && a.sdkFrame === b.sdkFrame &&
                JSON.stringify(a.missingDebugInfo) === JSON.stringify(b.missingDebugInfo);
        }
        if (!DebuggableFrameFlavor.#last || !equals(DebuggableFrameFlavor.#last.frame, frame)) {
            DebuggableFrameFlavor.#last = new DebuggableFrameFlavor(frame);
        }
        return DebuggableFrameFlavor.#last;
    }
}

var StackTrace = /*#__PURE__*/Object.freeze({
	__proto__: null,
	DebuggableFrameFlavor: DebuggableFrameFlavor
});

// Copyright 2025 The Chromium Authors

var stack_trace = /*#__PURE__*/Object.freeze({
	__proto__: null,
	StackTrace: StackTrace
});

// Copyright 2025 The Chromium Authors
function isBuiltinFrame(rawFrame) {
    return rawFrame.lineNumber === -1 && rawFrame.columnNumber === -1 && !Boolean(rawFrame.scriptId) &&
        !Boolean(rawFrame.url);
}
class FrameNode {
    parent;
    children = [];
    rawFrame;
    frames = [];
    fragment;
    constructor(rawFrame, parent) {
        this.rawFrame = rawFrame;
        this.parent = parent;
    }
    *getCallStack() {
        for (let node = this; node.parent; node = node.parent) {
            yield node;
        }
    }
}
class Trie {
    #root = { parent: null, children: [] };
    insert(frames) {
        if (frames.length === 0) {
            throw new Error('Trie.insert called with an empty frames array.');
        }
        let currentNode = this.#root;
        for (let i = frames.length - 1; i >= 0; --i) {
            currentNode = this.#insert(currentNode, frames[i]);
        }
        return currentNode;
    }
    #insert(node, rawFrame) {
        let i = 0;
        for (; i < node.children.length; ++i) {
            const maybeChild = node.children[i];
            const child = maybeChild instanceof WeakRef ? maybeChild.deref() : maybeChild;
            if (!child) {
                continue;
            }
            const compareResult = compareRawFrames(child.rawFrame, rawFrame);
            if (compareResult === 0) {
                return child;
            }
            if (compareResult > 0) {
                break;
            }
        }
        const newNode = new FrameNode(rawFrame, node);
        if (node.parent) {
            node.children.splice(i, 0, newNode);
        }
        else {
            node.children.splice(i, 0, new WeakRef(newNode));
        }
        return newNode;
    }
    walk(node, visit) {
        const stack = node ? [node] : [...this.#root.children].map(ref => ref.deref()).filter(node => Boolean(node));
        for (let node = stack.pop(); node; node = stack.pop()) {
            const visitChildren = visit(node);
            if (visitChildren) {
                for (let i = node.children.length - 1; i >= 0; --i) {
                    stack.push(node.children[i]);
                }
            }
        }
    }
}
function compareRawFrames(a, b) {
    const scriptIdCompare = (a.scriptId ?? '').localeCompare(b.scriptId ?? '');
    if (scriptIdCompare !== 0) {
        return scriptIdCompare;
    }
    const urlCompare = (a.url ?? '').localeCompare(b.url ?? '');
    if (urlCompare !== 0) {
        return urlCompare;
    }
    const nameCompare = (a.functionName ?? '').localeCompare(b.functionName ?? '');
    if (nameCompare !== 0) {
        return nameCompare;
    }
    if (a.lineNumber !== b.lineNumber) {
        return a.lineNumber - b.lineNumber;
    }
    return a.columnNumber - b.columnNumber;
}

// Copyright 2025 The Chromium Authors
var _a$4;
class StackTraceModel extends SDKModel {
    #trie = new Trie();
    #mutex = new Mutex();
    static #modelForTarget(target) {
        const model = (target ?? TargetManager.instance().primaryPageTarget())?.model(_a$4);
        if (!model) {
            throw new Error('Unable to find StackTraceModel');
        }
        return model;
    }
    async createFromProtocolRuntime(stackTrace, rawFramesToUIFrames) {
        const [syncFragment, asyncFragments] = await Promise.all([
            this.#createFragment(stackTrace.callFrames, rawFramesToUIFrames),
            this.#createAsyncFragments(stackTrace, rawFramesToUIFrames),
        ]);
        return new StackTraceImpl(syncFragment, asyncFragments);
    }
    async createFromDebuggerPaused(pausedDetails, rawFramesToUIFrames) {
        const [syncFragment, asyncFragments] = await Promise.all([
            this.#createDebuggableFragment(pausedDetails, rawFramesToUIFrames),
            this.#createAsyncFragments(pausedDetails, rawFramesToUIFrames),
        ]);
        return new StackTraceImpl(syncFragment, asyncFragments);
    }
    async scriptInfoChanged(script, translateRawFrames) {
        const release = await this.#mutex.acquire();
        try {
            const translatePromises = [];
            let stackTracesToUpdate = new Set();
            for (const fragment of this.#affectedFragments(script)) {
                if (fragment.node?.children.length === 0) {
                    translatePromises.push(this.#translateFragment(fragment, translateRawFrames));
                }
                stackTracesToUpdate = stackTracesToUpdate.union(fragment.stackTraces);
            }
            await Promise.all(translatePromises);
            for (const stackTrace of stackTracesToUpdate) {
                stackTrace.dispatchEventToListeners("UPDATED" );
            }
        }
        finally {
            release();
        }
    }
    async #createDebuggableFragment(pausedDetails, rawFramesToUIFrames) {
        const fragment = await this.#createFragment(pausedDetails.callFrames.map(frame => ({
            scriptId: frame.script.scriptId,
            url: frame.script.sourceURL,
            functionName: frame.functionName,
            lineNumber: frame.location().lineNumber,
            columnNumber: frame.location().columnNumber,
        })), rawFramesToUIFrames);
        return new DebuggableFragmentImpl(fragment, pausedDetails.callFrames);
    }
    async #createAsyncFragments(stackTraceOrPausedEvent, rawFramesToUIFrames) {
        const asyncFragments = [];
        const debuggerModel = this.target().model(DebuggerModel);
        if (debuggerModel) {
            for await (const { stackTrace: asyncStackTrace, target } of debuggerModel.iterateAsyncParents(stackTraceOrPausedEvent)) {
                if (asyncStackTrace.callFrames.length === 0) {
                    continue;
                }
                const model = _a$4.#modelForTarget(target);
                const asyncFragmentPromise = model.#createFragment(asyncStackTrace.callFrames, rawFramesToUIFrames)
                    .then(fragment => new AsyncFragmentImpl(asyncStackTrace.description ?? '', fragment));
                asyncFragments.push(asyncFragmentPromise);
            }
        }
        return await Promise.all(asyncFragments);
    }
    async #createFragment(frames, rawFramesToUIFrames) {
        if (frames.length === 0) {
            return FragmentImpl.EMPTY_FRAGMENT;
        }
        const release = await this.#mutex.acquire();
        try {
            const node = this.#trie.insert(frames);
            const requiresTranslation = !Boolean(node.fragment);
            const fragment = FragmentImpl.getOrCreate(node);
            if (requiresTranslation) {
                await this.#translateFragment(fragment, rawFramesToUIFrames);
            }
            return fragment;
        }
        finally {
            release();
        }
    }
    async #translateFragment(fragment, rawFramesToUIFrames) {
        if (!fragment.node) {
            return;
        }
        const rawFrames = fragment.node.getCallStack().map(node => node.rawFrame).toArray();
        const uiFrames = await rawFramesToUIFrames(rawFrames, this.target());
        console.assert(rawFrames.length === uiFrames.length, 'Broken rawFramesToUIFrames implementation');
        let i = 0;
        for (const node of fragment.node.getCallStack()) {
            node.frames = uiFrames[i++].map(frame => new FrameImpl(frame.url, frame.uiSourceCode, frame.name, frame.line, frame.column, frame.missingDebugInfo));
        }
    }
    #affectedFragments(script) {
        const affectedBranches = new Set();
        this.#trie.walk(null, node => {
            if (node.rawFrame.scriptId === script.scriptId ||
                (!node.rawFrame.scriptId && node.rawFrame.url === script.sourceURL)) {
                affectedBranches.add(node);
                return false;
            }
            return true;
        });
        const fragments = new Set();
        for (const branch of affectedBranches) {
            this.#trie.walk(branch, node => {
                if (node.fragment) {
                    fragments.add(node.fragment);
                }
                return true;
            });
        }
        return fragments;
    }
}
_a$4 = StackTraceModel;
SDKModel.register(StackTraceModel, { capabilities: 0 , autostart: false });

// Copyright 2011 The Chromium Authors
const UIStrings$P = {
    index: '(index)',
    thisFileWasChangedExternally: 'This file was changed externally. Would you like to reload it?',
};
const str_$O = registerUIStrings('models/workspace/UISourceCode.ts', UIStrings$P);
const i18nString$A = getLocalizedString.bind(undefined, str_$O);
class UISourceCode extends ObjectWrapper {
    #origin;
    #parentURL;
    #project;
    #url;
    #name;
    #contentType;
    #requestContentPromise = null;
    #decorations = new Map();
    #hasCommits = false;
    #messages = null;
    #content = null;
    #forceLoadOnCheckContent = false;
    #checkingContent = false;
    #lastAcceptedContent = null;
    #workingCopy = null;
    #workingCopyGetter = null;
    #disableEdit = false;
    #contentEncoded;
    #isKnownThirdParty = false;
    #isUnconditionallyIgnoreListed = false;
    #containsAiChanges = false;
    constructor(project, url, contentType) {
        super();
        this.#project = project;
        this.#url = url;
        const parsedURL = ParsedURL.fromString(url);
        if (parsedURL) {
            this.#origin = parsedURL.securityOrigin();
            this.#parentURL = ParsedURL.concatenate(this.#origin, parsedURL.folderPathComponents);
            if (parsedURL.queryParams && !(parsedURL.lastPathComponent && contentType.isFromSourceMap())) {
                this.#name = parsedURL.lastPathComponent + '?' + parsedURL.queryParams;
            }
            else {
                try {
                    this.#name = decodeURIComponent(parsedURL.lastPathComponent);
                }
                catch {
                    this.#name = parsedURL.lastPathComponent;
                }
            }
        }
        else {
            this.#origin = EmptyUrlString;
            this.#parentURL = EmptyUrlString;
            this.#name = url;
        }
        this.#contentType = contentType;
    }
    requestMetadata() {
        return this.#project.requestMetadata(this);
    }
    name() {
        return this.#name;
    }
    mimeType() {
        return this.#project.mimeType(this);
    }
    url() {
        return this.#url;
    }
    canonicalScriptId() {
        return `${this.#contentType.name()},${this.#url}`;
    }
    parentURL() {
        return this.#parentURL;
    }
    origin() {
        return this.#origin;
    }
    fullDisplayName() {
        return this.#project.fullDisplayName(this);
    }
    displayName(skipTrim) {
        if (!this.#name) {
            return i18nString$A(UIStrings$P.index);
        }
        const name = this.#name;
        return skipTrim ? name : trimEndWithMaxLength(name, 100);
    }
    canRename() {
        return this.#project.canRename();
    }
    rename(newName) {
        const { resolve, promise } = Promise.withResolvers();
        this.#project.rename(this, newName, innerCallback.bind(this));
        return promise;
        function innerCallback(success, newName, newURL, newContentType) {
            if (success) {
                this.#updateName(newName, newURL, newContentType);
            }
            resolve(success);
        }
    }
    remove() {
        this.#project.deleteFile(this);
    }
    #updateName(name, url, contentType) {
        const oldURL = this.#url;
        this.#name = name;
        if (url) {
            this.#url = url;
        }
        else {
            this.#url = ParsedURL.relativePathToUrlString(name, oldURL);
        }
        if (contentType) {
            this.#contentType = contentType;
        }
        this.dispatchEventToListeners(Events$2.TitleChanged, this);
        this.project().workspace().dispatchEventToListeners(Events$1.UISourceCodeRenamed, { oldURL, uiSourceCode: this });
    }
    contentURL() {
        return this.url();
    }
    contentType() {
        return this.#contentType;
    }
    project() {
        return this.#project;
    }
    requestContentData({ cachedWasmOnly } = {}) {
        if (this.#requestContentPromise) {
            return this.#requestContentPromise;
        }
        if (this.#content) {
            return Promise.resolve(this.#content);
        }
        if (cachedWasmOnly && this.mimeType() === 'application/wasm') {
            return Promise.resolve(new WasmDisassembly([], [], []));
        }
        this.#requestContentPromise = this.#requestContent();
        return this.#requestContentPromise;
    }
    async #requestContent() {
        if (this.#content) {
            throw new Error('Called UISourceCode#requestContentImpl even though content is available for ' + this.#url);
        }
        try {
            this.#content = await this.#project.requestFileContent(this);
        }
        catch (err) {
            this.#content = { error: err ? String(err) : '' };
        }
        return this.#content;
    }
    #decodeContent(content) {
        if (!content) {
            return null;
        }
        return content.isEncoded && content.content ? window.atob(content.content) : content.content;
    }
    #unsafeDecodeContentData(content) {
        if (!content || ContentData.isError(content)) {
            return null;
        }
        return content.createdFromBase64 ? window.atob(content.base64) : content.text;
    }
    async checkContentUpdated() {
        if (!this.#content && !this.#forceLoadOnCheckContent) {
            return;
        }
        if (!this.#project.canSetFileContent() || this.#checkingContent) {
            return;
        }
        this.#checkingContent = true;
        const updatedContent = ContentData.asDeferredContent(await this.#project.requestFileContent(this));
        if ('error' in updatedContent) {
            return;
        }
        this.#checkingContent = false;
        if (updatedContent.content === null) {
            const workingCopy = this.workingCopy();
            this.#contentCommitted('', false);
            this.setWorkingCopy(workingCopy);
            return;
        }
        if (this.#lastAcceptedContent === updatedContent.content) {
            return;
        }
        if (this.#unsafeDecodeContentData(this.#content) === this.#decodeContent(updatedContent)) {
            this.#lastAcceptedContent = null;
            return;
        }
        if (!this.isDirty() || this.#workingCopy === updatedContent.content) {
            this.#contentCommitted(updatedContent.content, false);
            return;
        }
        await reveal(this);
        await new Promise(resolve => window.setTimeout(resolve, 0));
        const shouldUpdate = window.confirm(i18nString$A(UIStrings$P.thisFileWasChangedExternally));
        if (shouldUpdate) {
            this.#contentCommitted(updatedContent.content, false);
        }
        else {
            this.#lastAcceptedContent = updatedContent.content;
        }
    }
    forceLoadOnCheckContent() {
        this.#forceLoadOnCheckContent = true;
    }
    #commitContent(content) {
        if (this.#project.canSetFileContent()) {
            void this.#project.setFileContent(this, content, false);
        }
        this.#contentCommitted(content, true);
    }
    #contentCommitted(content, committedByUser) {
        this.#lastAcceptedContent = null;
        this.#content = new ContentData(content, Boolean(this.#contentEncoded), this.mimeType());
        this.#requestContentPromise = null;
        this.#hasCommits = true;
        this.#resetWorkingCopy();
        const data = { uiSourceCode: this, content, encoded: this.#contentEncoded };
        this.dispatchEventToListeners(Events$2.WorkingCopyCommitted, data);
        this.#project.workspace().dispatchEventToListeners(Events$1.WorkingCopyCommitted, data);
        if (committedByUser) {
            this.#project.workspace().dispatchEventToListeners(Events$1.WorkingCopyCommittedByUser, data);
        }
    }
    addRevision(content) {
        this.#commitContent(content);
    }
    hasCommits() {
        return this.#hasCommits;
    }
    workingCopy() {
        return this.workingCopyContent().content || '';
    }
    workingCopyContent() {
        return this.workingCopyContentData().asDeferedContent();
    }
    workingCopyContentData() {
        if (this.#workingCopyGetter) {
            this.#workingCopy = this.#workingCopyGetter();
            this.#workingCopyGetter = null;
        }
        const contentData = this.#content ? ContentData.contentDataOrEmpty(this.#content) :
            EMPTY_TEXT_CONTENT_DATA;
        if (this.#workingCopy !== null) {
            return new ContentData(this.#workingCopy,  false, contentData.mimeType);
        }
        return contentData;
    }
    resetWorkingCopy() {
        this.#resetWorkingCopy();
        this.#workingCopyChanged();
    }
    #resetWorkingCopy() {
        this.#workingCopy = null;
        this.#workingCopyGetter = null;
        this.setContainsAiChanges(false);
    }
    setWorkingCopy(newWorkingCopy) {
        this.#workingCopy = newWorkingCopy;
        this.#workingCopyGetter = null;
        this.#workingCopyChanged();
    }
    setContainsAiChanges(containsAiChanges) {
        this.#containsAiChanges = containsAiChanges;
    }
    containsAiChanges() {
        return this.#containsAiChanges;
    }
    setContent(content, isBase64) {
        this.#contentEncoded = isBase64;
        if (this.#project.canSetFileContent()) {
            void this.#project.setFileContent(this, content, isBase64);
        }
        this.#contentCommitted(content, true);
    }
    setWorkingCopyGetter(workingCopyGetter) {
        this.#workingCopyGetter = workingCopyGetter;
        this.#workingCopyChanged();
    }
    #workingCopyChanged() {
        this.#removeAllMessages();
        this.dispatchEventToListeners(Events$2.WorkingCopyChanged, this);
        this.#project.workspace().dispatchEventToListeners(Events$1.WorkingCopyChanged, { uiSourceCode: this });
    }
    removeWorkingCopyGetter() {
        if (!this.#workingCopyGetter) {
            return;
        }
        this.#workingCopy = this.#workingCopyGetter();
        this.#workingCopyGetter = null;
    }
    commitWorkingCopy() {
        if (this.isDirty()) {
            this.#commitContent(this.workingCopy());
        }
    }
    isDirty() {
        return this.#workingCopy !== null || this.#workingCopyGetter !== null;
    }
    isKnownThirdParty() {
        return this.#isKnownThirdParty;
    }
    markKnownThirdParty() {
        this.#isKnownThirdParty = true;
    }
    isUnconditionallyIgnoreListed() {
        return this.#isUnconditionallyIgnoreListed;
    }
    isFetchXHR() {
        return [resourceTypes.XHR, resourceTypes.Fetch].includes(this.contentType());
    }
    markAsUnconditionallyIgnoreListed() {
        this.#isUnconditionallyIgnoreListed = true;
    }
    extension() {
        return ParsedURL.extractExtension(this.#name);
    }
    content() {
        if (!this.#content || 'error' in this.#content) {
            return '';
        }
        return this.#content.text;
    }
    loadError() {
        return (this.#content && 'error' in this.#content && this.#content.error) || null;
    }
    searchInContent(query, caseSensitive, isRegex) {
        if (!this.#content || 'error' in this.#content) {
            return this.#project.searchInFileContent(this, query, caseSensitive, isRegex);
        }
        return Promise.resolve(performSearchInContentData(this.#content, query, caseSensitive, isRegex));
    }
    contentLoaded() {
        return Boolean(this.#content);
    }
    uiLocation(lineNumber, columnNumber) {
        return new UILocation(this, lineNumber, columnNumber);
    }
    messages() {
        return this.#messages ? new Set(this.#messages) : new Set();
    }
    addLineMessage(level, text, lineNumber, columnNumber, clickHandler) {
        const range = TextRange.createFromLocation(lineNumber, columnNumber || 0);
        const message = new Message(level, text, clickHandler, range);
        this.addMessage(message);
        return message;
    }
    addMessage(message) {
        if (!this.#messages) {
            this.#messages = new Set();
        }
        this.#messages.add(message);
        this.dispatchEventToListeners(Events$2.MessageAdded, message);
    }
    removeMessage(message) {
        if (this.#messages?.delete(message)) {
            this.dispatchEventToListeners(Events$2.MessageRemoved, message);
        }
    }
    #removeAllMessages() {
        if (!this.#messages) {
            return;
        }
        for (const message of this.#messages) {
            this.dispatchEventToListeners(Events$2.MessageRemoved, message);
        }
        this.#messages = null;
    }
    setDecorationData(type, data) {
        if (data !== this.#decorations.get(type)) {
            this.#decorations.set(type, data);
            this.dispatchEventToListeners(Events$2.DecorationChanged, type);
        }
    }
    getDecorationData(type) {
        return this.#decorations.get(type);
    }
    disableEdit() {
        this.#disableEdit = true;
    }
    editDisabled() {
        return this.#disableEdit;
    }
    isIgnoreListed() {
        return IgnoreListManager.instance().isUserOrSourceMapIgnoreListedUISourceCode(this);
    }
}
var Events$2;
(function (Events) {
    Events["WorkingCopyChanged"] = "WorkingCopyChanged";
    Events["WorkingCopyCommitted"] = "WorkingCopyCommitted";
    Events["TitleChanged"] = "TitleChanged";
    Events["MessageAdded"] = "MessageAdded";
    Events["MessageRemoved"] = "MessageRemoved";
    Events["DecorationChanged"] = "DecorationChanged";
})(Events$2 || (Events$2 = {}));
class UILocation {
    uiSourceCode;
    lineNumber;
    columnNumber;
    constructor(uiSourceCode, lineNumber, columnNumber) {
        this.uiSourceCode = uiSourceCode;
        this.lineNumber = lineNumber;
        this.columnNumber = columnNumber;
    }
    linkText(skipTrim = false, showColumnNumber = false) {
        const displayName = this.uiSourceCode.displayName(skipTrim);
        const lineAndColumnText = this.lineAndColumnText(showColumnNumber);
        let text = lineAndColumnText ? displayName + ':' + lineAndColumnText : displayName;
        if (this.uiSourceCode.isDirty()) {
            text = '*' + text;
        }
        return text;
    }
    lineAndColumnText(showColumnNumber = false) {
        let lineAndColumnText;
        if (this.uiSourceCode.mimeType() === 'application/wasm') {
            if (typeof this.columnNumber === 'number') {
                lineAndColumnText = `0x${this.columnNumber.toString(16)}`;
            }
        }
        else {
            lineAndColumnText = `${this.lineNumber + 1}`;
            if (showColumnNumber && typeof this.columnNumber === 'number') {
                lineAndColumnText += ':' + (this.columnNumber + 1);
            }
        }
        return lineAndColumnText;
    }
    id() {
        if (typeof this.columnNumber === 'number') {
            return this.uiSourceCode.project().id() + ':' + this.uiSourceCode.url() + ':' + this.lineNumber + ':' +
                this.columnNumber;
        }
        return this.lineId();
    }
    lineId() {
        return this.uiSourceCode.project().id() + ':' + this.uiSourceCode.url() + ':' + this.lineNumber;
    }
    static comparator(location1, location2) {
        return location1.compareTo(location2);
    }
    compareTo(other) {
        if (this.uiSourceCode.url() !== other.uiSourceCode.url()) {
            return this.uiSourceCode.url() > other.uiSourceCode.url() ? 1 : -1;
        }
        if (this.lineNumber !== other.lineNumber) {
            return this.lineNumber - other.lineNumber;
        }
        if (this.columnNumber === other.columnNumber) {
            return 0;
        }
        if (typeof this.columnNumber !== 'number') {
            return -1;
        }
        if (typeof other.columnNumber !== 'number') {
            return 1;
        }
        return this.columnNumber - other.columnNumber;
    }
    isIgnoreListed() {
        return this.uiSourceCode.isIgnoreListed();
    }
}
class UIFunctionBounds {
    uiSourceCode;
    range;
    name;
    constructor(uiSourceCode, range, name) {
        this.uiSourceCode = uiSourceCode;
        this.range = range;
        this.name = name;
    }
}
class Message {
    #level;
    #text;
    range;
    #clickHandler;
    constructor(level, text, clickHandler, range) {
        this.#level = level;
        this.#text = text;
        this.range = range ?? new TextRange(0, 0, 0, 0);
        this.#clickHandler = clickHandler;
    }
    level() {
        return this.#level;
    }
    text() {
        return this.#text;
    }
    clickHandler() {
        return this.#clickHandler;
    }
    lineNumber() {
        return this.range.startLine;
    }
    columnNumber() {
        return this.range.startColumn;
    }
    isEqual(another) {
        return this.text() === another.text() && this.level() === another.level() && this.range.equal(another.range);
    }
}
class UISourceCodeMetadata {
    modificationTime;
    contentSize;
    constructor(modificationTime, contentSize) {
        this.modificationTime = modificationTime;
        this.contentSize = contentSize;
    }
}

// Copyright 2012 The Chromium Authors
var projectTypes;
(function (projectTypes) {
    projectTypes["Debugger"] = "debugger";
    projectTypes["Formatter"] = "formatter";
    projectTypes["Network"] = "network";
    projectTypes["FileSystem"] = "filesystem";
    projectTypes["ConnectableFileSystem"] = "connectablefilesystem";
    projectTypes["ContentScripts"] = "contentscripts";
    projectTypes["Service"] = "service";
})(projectTypes || (projectTypes = {}));
class ProjectStore {
    #workspace;
    #id;
    #type;
    #displayName;
    #uiSourceCodes = new Map();
    constructor(workspace, id, type, displayName) {
        this.#workspace = workspace;
        this.#id = id;
        this.#type = type;
        this.#displayName = displayName;
    }
    id() {
        return this.#id;
    }
    type() {
        return this.#type;
    }
    displayName() {
        return this.#displayName;
    }
    workspace() {
        return this.#workspace;
    }
    createUISourceCode(url, contentType) {
        return new UISourceCode(this, url, contentType);
    }
    addUISourceCode(uiSourceCode) {
        const url = uiSourceCode.url();
        if (this.uiSourceCodeForURL(url)) {
            return false;
        }
        this.#uiSourceCodes.set(url, uiSourceCode);
        this.#workspace.dispatchEventToListeners(Events$1.UISourceCodeAdded, uiSourceCode);
        return true;
    }
    removeUISourceCode(url) {
        const uiSourceCode = this.#uiSourceCodes.get(url);
        if (uiSourceCode === undefined) {
            return;
        }
        this.#uiSourceCodes.delete(url);
        this.#workspace.dispatchEventToListeners(Events$1.UISourceCodeRemoved, uiSourceCode);
    }
    removeProject() {
        this.#workspace.removeProject(this);
        this.#uiSourceCodes.clear();
    }
    uiSourceCodeForURL(url) {
        return this.#uiSourceCodes.get(url) ?? null;
    }
    uiSourceCodes() {
        return this.#uiSourceCodes.values();
    }
    renameUISourceCode(uiSourceCode, newName) {
        const oldPath = uiSourceCode.url();
        const newPath = uiSourceCode.parentURL() ?
            ParsedURL.urlFromParentUrlAndName(uiSourceCode.parentURL(), newName) :
            ParsedURL.preEncodeSpecialCharactersInPath(newName);
        this.#uiSourceCodes.set(newPath, uiSourceCode);
        this.#uiSourceCodes.delete(oldPath);
    }
    rename(_uiSourceCode, _newName, _callback) {
    }
    excludeFolder(_path) {
    }
    deleteFile(_uiSourceCode) {
    }
    deleteDirectoryRecursively(_path) {
        return Promise.resolve(false);
    }
    remove() {
    }
    indexContent(_progress) {
    }
}
class WorkspaceImpl extends ObjectWrapper {
    #projects = new Map();
    #hasResourceContentTrackingExtensions = false;
    static instance(opts = { forceNew: null }) {
        const { forceNew } = opts;
        if (!globalInstance().has(WorkspaceImpl) || forceNew) {
            globalInstance().set(WorkspaceImpl, new WorkspaceImpl());
        }
        return globalInstance().get(WorkspaceImpl);
    }
    static removeInstance() {
        globalInstance().delete(WorkspaceImpl);
    }
    uiSourceCode(projectId, url) {
        const project = this.#projects.get(projectId);
        return project ? project.uiSourceCodeForURL(url) : null;
    }
    uiSourceCodeForURL(url) {
        for (const project of this.#projects.values()) {
            const uiSourceCode = project.uiSourceCodeForURL(url);
            if (uiSourceCode) {
                return uiSourceCode;
            }
        }
        return null;
    }
    findCompatibleUISourceCodes(uiSourceCode) {
        const url = uiSourceCode.url();
        const contentType = uiSourceCode.contentType();
        const result = [];
        for (const project of this.#projects.values()) {
            if (uiSourceCode.project().type() !== project.type()) {
                continue;
            }
            const candidate = project.uiSourceCodeForURL(url);
            if (candidate && candidate.url() === url && candidate.contentType() === contentType) {
                result.push(candidate);
            }
        }
        return result;
    }
    uiSourceCodesForProjectType(type) {
        const result = [];
        for (const project of this.#projects.values()) {
            if (project.type() === type) {
                for (const uiSourceCode of project.uiSourceCodes()) {
                    result.push(uiSourceCode);
                }
            }
        }
        return result;
    }
    addProject(project) {
        console.assert(!this.#projects.has(project.id()), `A project with id ${project.id()} already exists!`);
        this.#projects.set(project.id(), project);
        this.dispatchEventToListeners(Events$1.ProjectAdded, project);
    }
    removeProject(project) {
        this.#projects.delete(project.id());
        this.dispatchEventToListeners(Events$1.ProjectRemoved, project);
    }
    project(projectId) {
        return this.#projects.get(projectId) || null;
    }
    projectForFileSystemRoot(root) {
        const projectId = ParsedURL.rawPathToUrlString(root);
        return this.project(projectId);
    }
    projects() {
        return [...this.#projects.values()];
    }
    projectsForType(type) {
        function filterByType(project) {
            return project.type() === type;
        }
        return this.projects().filter(filterByType);
    }
    uiSourceCodes() {
        const result = [];
        for (const project of this.#projects.values()) {
            for (const uiSourceCode of project.uiSourceCodes()) {
                result.push(uiSourceCode);
            }
        }
        return result;
    }
    setHasResourceContentTrackingExtensions(hasExtensions) {
        this.#hasResourceContentTrackingExtensions = hasExtensions;
    }
    hasResourceContentTrackingExtensions() {
        return this.#hasResourceContentTrackingExtensions;
    }
}
var Events$1;
(function (Events) {
    Events["UISourceCodeAdded"] = "UISourceCodeAdded";
    Events["UISourceCodeRemoved"] = "UISourceCodeRemoved";
    Events["UISourceCodeRenamed"] = "UISourceCodeRenamed";
    Events["WorkingCopyChanged"] = "WorkingCopyChanged";
    Events["WorkingCopyCommitted"] = "WorkingCopyCommitted";
    Events["WorkingCopyCommittedByUser"] = "WorkingCopyCommittedByUser";
    Events["ProjectAdded"] = "ProjectAdded";
    Events["ProjectRemoved"] = "ProjectRemoved";
})(Events$1 || (Events$1 = {}));

// Copyright 2014 The Chromium Authors
const UIStrings$O = {
    removeFromIgnoreList: 'Remove from ignore list',
    addScriptToIgnoreList: 'Add script to ignore list',
    addDirectoryToIgnoreList: 'Add directory to ignore list',
    addAllContentScriptsToIgnoreList: 'Add all extension scripts to ignore list',
    addAllThirdPartyScriptsToIgnoreList: 'Add all third-party scripts to ignore list',
    addAllAnonymousScriptsToIgnoreList: 'Add all anonymous scripts to ignore list',
};
const str_$N = registerUIStrings('models/workspace/IgnoreListManager.ts', UIStrings$O);
const i18nString$z = getLocalizedString.bind(undefined, str_$N);
class IgnoreListManager extends ObjectWrapper {
    #settings;
    #targetManager;
    #listeners = new Set();
    #isIgnoreListedURLCache = new Map();
    #contentScriptExecutionContexts = new Set();
    constructor(settings, targetManager) {
        super();
        this.#settings = settings;
        this.#targetManager = targetManager;
        this.#targetManager.addModelListener(DebuggerModel, Events$5.GlobalObjectCleared, this.clearCacheIfNeeded.bind(this), this);
        this.#targetManager.addModelListener(RuntimeModel, Events$9.ExecutionContextCreated, this.onExecutionContextCreated, this, { scoped: true });
        this.#targetManager.addModelListener(RuntimeModel, Events$9.ExecutionContextDestroyed, this.onExecutionContextDestroyed, this, { scoped: true });
        this.#settings.moduleSetting('skip-stack-frames-pattern').addChangeListener(this.patternChanged.bind(this));
        this.#settings.moduleSetting('skip-content-scripts').addChangeListener(this.patternChanged.bind(this));
        this.#settings.moduleSetting('automatically-ignore-list-known-third-party-scripts')
            .addChangeListener(this.patternChanged.bind(this));
        this.#settings.moduleSetting('enable-ignore-listing').addChangeListener(this.patternChanged.bind(this));
        this.#settings.moduleSetting('skip-anonymous-scripts').addChangeListener(this.patternChanged.bind(this));
        this.#targetManager.observeModels(DebuggerModel, this);
    }
    static instance(opts = {
        forceNew: null,
    }) {
        const { forceNew } = opts;
        if (forceNew) {
            globalInstance().set(IgnoreListManager, new IgnoreListManager(opts.settings ?? Settings.instance(), opts.targetManager ?? TargetManager.instance()));
        }
        return globalInstance().get(IgnoreListManager);
    }
    static removeInstance() {
        globalInstance().delete(IgnoreListManager);
    }
    addChangeListener(listener) {
        this.#listeners.add(listener);
    }
    removeChangeListener(listener) {
        this.#listeners.delete(listener);
    }
    modelAdded(debuggerModel) {
        void this.setIgnoreListPatterns(debuggerModel);
        const sourceMapManager = debuggerModel.sourceMapManager();
        sourceMapManager.addEventListener(Events$b.SourceMapAttached, this.sourceMapAttached, this);
        sourceMapManager.addEventListener(Events$b.SourceMapDetached, this.sourceMapDetached, this);
    }
    modelRemoved(debuggerModel) {
        this.clearCacheIfNeeded();
        const sourceMapManager = debuggerModel.sourceMapManager();
        sourceMapManager.removeEventListener(Events$b.SourceMapAttached, this.sourceMapAttached, this);
        sourceMapManager.removeEventListener(Events$b.SourceMapDetached, this.sourceMapDetached, this);
    }
    isContentScript(executionContext) {
        return !executionContext.isDefault;
    }
    onExecutionContextCreated(event) {
        if (this.isContentScript(event.data)) {
            this.#contentScriptExecutionContexts.add(event.data.uniqueId);
            if (this.skipContentScripts) {
                for (const debuggerModel of this.#targetManager.models(DebuggerModel)) {
                    void this.updateIgnoredExecutionContexts(debuggerModel);
                }
            }
        }
    }
    onExecutionContextDestroyed(event) {
        if (this.isContentScript(event.data)) {
            this.#contentScriptExecutionContexts.delete(event.data.uniqueId);
            if (this.skipContentScripts) {
                for (const debuggerModel of this.#targetManager.models(DebuggerModel)) {
                    void this.updateIgnoredExecutionContexts(debuggerModel);
                }
            }
        }
    }
    clearCacheIfNeeded() {
        if (this.#isIgnoreListedURLCache.size > 1024) {
            this.#isIgnoreListedURLCache.clear();
        }
    }
    getSkipStackFramesPatternSetting() {
        return this.#settings.moduleSetting('skip-stack-frames-pattern');
    }
    setIgnoreListPatterns(debuggerModel) {
        const regexPatterns = this.enableIgnoreListing ? this.getSkipStackFramesPatternSetting().getAsArray() : [];
        const patterns = [];
        for (const item of regexPatterns) {
            if (!item.disabled && item.pattern) {
                patterns.push(item.pattern);
            }
        }
        return debuggerModel.setBlackboxPatterns(patterns, this.skipAnonymousScripts);
    }
    updateIgnoredExecutionContexts(debuggerModel) {
        return debuggerModel.setBlackboxExecutionContexts(this.skipContentScripts ? Array.from(this.#contentScriptExecutionContexts) : []);
    }
    getGeneralRulesForUISourceCode(uiSourceCode) {
        const projectType = uiSourceCode.project().type();
        const isContentScript = projectType === projectTypes.ContentScripts;
        const isKnownThirdParty = uiSourceCode.isKnownThirdParty();
        return { isContentScript, isKnownThirdParty };
    }
    isUserOrSourceMapIgnoreListedUISourceCode(uiSourceCode) {
        if (uiSourceCode.isUnconditionallyIgnoreListed()) {
            return true;
        }
        const url = this.uiSourceCodeURL(uiSourceCode);
        return this.isUserIgnoreListedURL(url, this.getGeneralRulesForUISourceCode(uiSourceCode));
    }
    isUserIgnoreListedURL(url, options) {
        if (!this.enableIgnoreListing) {
            return false;
        }
        if (options?.isContentScript && this.skipContentScripts) {
            return true;
        }
        if (options?.isKnownThirdParty && this.automaticallyIgnoreListKnownThirdPartyScripts) {
            return true;
        }
        if (!url) {
            return this.skipAnonymousScripts;
        }
        if (this.#isIgnoreListedURLCache.has(url)) {
            return Boolean(this.#isIgnoreListedURLCache.get(url));
        }
        const isIgnoreListed = this.getFirstMatchedRegex(url) !== null;
        this.#isIgnoreListedURLCache.set(url, isIgnoreListed);
        return isIgnoreListed;
    }
    getFirstMatchedRegex(url) {
        if (!url) {
            return null;
        }
        const regexPatterns = this.getSkipStackFramesPatternSetting().getAsArray();
        const regexValue = this.urlToRegExpString(url);
        if (!regexValue) {
            return null;
        }
        for (let i = 0; i < regexPatterns.length; ++i) {
            const item = regexPatterns[i];
            if (item.disabled || item.disabledForUrl === url) {
                continue;
            }
            const regex = new RegExp(item.pattern);
            if (regex.test(url)) {
                return regex;
            }
        }
        return null;
    }
    sourceMapAttached(event) {
        const script = event.data.client;
        const sourceMap = event.data.sourceMap;
        void this.updateScriptRanges(script, sourceMap);
    }
    sourceMapDetached(event) {
        const script = event.data.client;
        void this.updateScriptRanges(script, undefined);
    }
    async updateScriptRanges(script, sourceMap) {
        let hasIgnoreListedMappings = false;
        if (!this.isUserIgnoreListedURL(script.sourceURL, { isContentScript: script.isContentScript() })) {
            hasIgnoreListedMappings =
                sourceMap?.sourceURLs().some(url => this.isUserIgnoreListedURL(url, { isKnownThirdParty: sourceMap.hasIgnoreListHint(url) })) ??
                    false;
        }
        if (!hasIgnoreListedMappings) {
            if (scriptToRange.get(script) && await script.setBlackboxedRanges([])) {
                scriptToRange.delete(script);
            }
            this.dispatchEventToListeners("IGNORED_SCRIPT_RANGES_UPDATED" , script);
            return;
        }
        if (!sourceMap) {
            return;
        }
        const newRanges = sourceMap
            .findRanges(srcURL => this.isUserIgnoreListedURL(srcURL, { isKnownThirdParty: sourceMap.hasIgnoreListHint(srcURL) }), { isStartMatching: true })
            .flatMap(range => [range.start, range.end]);
        const oldRanges = scriptToRange.get(script) || [];
        if (!isEqual(oldRanges, newRanges) && await script.setBlackboxedRanges(newRanges)) {
            scriptToRange.set(script, newRanges);
        }
        this.dispatchEventToListeners("IGNORED_SCRIPT_RANGES_UPDATED" , script);
        function isEqual(rangesA, rangesB) {
            if (rangesA.length !== rangesB.length) {
                return false;
            }
            for (let i = 0; i < rangesA.length; ++i) {
                if (rangesA[i].lineNumber !== rangesB[i].lineNumber || rangesA[i].columnNumber !== rangesB[i].columnNumber) {
                    return false;
                }
            }
            return true;
        }
    }
    uiSourceCodeURL(uiSourceCode) {
        return uiSourceCode.project().type() === projectTypes.Debugger ? null : uiSourceCode.url();
    }
    canIgnoreListUISourceCode(uiSourceCode) {
        const url = this.uiSourceCodeURL(uiSourceCode);
        return url ? Boolean(this.urlToRegExpString(url)) : false;
    }
    ignoreListUISourceCode(uiSourceCode) {
        const url = this.uiSourceCodeURL(uiSourceCode);
        if (url) {
            this.ignoreListURL(url);
        }
    }
    unIgnoreListUISourceCode(uiSourceCode) {
        this.unIgnoreListURL(this.uiSourceCodeURL(uiSourceCode), this.getGeneralRulesForUISourceCode(uiSourceCode));
    }
    get enableIgnoreListing() {
        return this.#settings.moduleSetting('enable-ignore-listing').get();
    }
    set enableIgnoreListing(value) {
        this.#settings.moduleSetting('enable-ignore-listing').set(value);
    }
    get skipContentScripts() {
        return this.enableIgnoreListing && this.#settings.moduleSetting('skip-content-scripts').get();
    }
    get skipAnonymousScripts() {
        return this.enableIgnoreListing && this.#settings.moduleSetting('skip-anonymous-scripts').get();
    }
    get automaticallyIgnoreListKnownThirdPartyScripts() {
        return this.enableIgnoreListing &&
            this.#settings.moduleSetting('automatically-ignore-list-known-third-party-scripts').get();
    }
    ignoreListContentScripts() {
        if (!this.enableIgnoreListing) {
            this.enableIgnoreListing = true;
        }
        this.#settings.moduleSetting('skip-content-scripts').set(true);
    }
    unIgnoreListContentScripts() {
        this.#settings.moduleSetting('skip-content-scripts').set(false);
    }
    ignoreListAnonymousScripts() {
        if (!this.enableIgnoreListing) {
            this.enableIgnoreListing = true;
        }
        this.#settings.moduleSetting('skip-anonymous-scripts').set(true);
    }
    unIgnoreListAnonymousScripts() {
        this.#settings.moduleSetting('skip-anonymous-scripts').set(false);
    }
    ignoreListThirdParty() {
        if (!this.enableIgnoreListing) {
            this.enableIgnoreListing = true;
        }
        this.#settings.moduleSetting('automatically-ignore-list-known-third-party-scripts').set(true);
    }
    unIgnoreListThirdParty() {
        this.#settings.moduleSetting('automatically-ignore-list-known-third-party-scripts').set(false);
    }
    ignoreListURL(url) {
        const regexValue = this.urlToRegExpString(url);
        if (!regexValue) {
            return;
        }
        this.addRegexToIgnoreList(regexValue, url);
    }
    addRegexToIgnoreList(regexValue, disabledForUrl) {
        const regexPatterns = this.getSkipStackFramesPatternSetting().getAsArray();
        let found = false;
        for (let i = 0; i < regexPatterns.length; ++i) {
            const item = regexPatterns[i];
            if (item.pattern === regexValue || (disabledForUrl && item.disabledForUrl === disabledForUrl)) {
                item.disabled = false;
                item.disabledForUrl = undefined;
                found = true;
            }
        }
        if (!found) {
            regexPatterns.push({ pattern: regexValue, disabled: false });
        }
        if (!this.enableIgnoreListing) {
            this.enableIgnoreListing = true;
        }
        this.getSkipStackFramesPatternSetting().setAsArray(regexPatterns);
    }
    unIgnoreListURL(url, options) {
        if (options?.isContentScript) {
            this.unIgnoreListContentScripts();
        }
        if (options?.isKnownThirdParty) {
            this.unIgnoreListThirdParty();
        }
        if (!url) {
            this.unIgnoreListAnonymousScripts();
            return;
        }
        let regexPatterns = this.getSkipStackFramesPatternSetting().getAsArray();
        const regexValue = IgnoreListManager.instance().urlToRegExpString(url);
        if (!regexValue) {
            return;
        }
        regexPatterns = regexPatterns.filter(function (item) {
            return item.pattern !== regexValue;
        });
        for (let i = 0; i < regexPatterns.length; ++i) {
            const item = regexPatterns[i];
            if (item.disabled) {
                continue;
            }
            try {
                const regex = new RegExp(item.pattern);
                if (regex.test(url)) {
                    item.disabled = true;
                    item.disabledForUrl = url;
                }
            }
            catch {
            }
        }
        this.getSkipStackFramesPatternSetting().setAsArray(regexPatterns);
    }
    removeIgnoreListPattern(regexValue) {
        let regexPatterns = this.getSkipStackFramesPatternSetting().getAsArray();
        regexPatterns = regexPatterns.filter(function (item) {
            return item.pattern !== regexValue;
        });
        this.getSkipStackFramesPatternSetting().setAsArray(regexPatterns);
    }
    ignoreListHasPattern(regexValue, enabledOnly) {
        const regexPatterns = this.getSkipStackFramesPatternSetting().getAsArray();
        return regexPatterns.some(item => !(enabledOnly && item.disabled) && item.pattern === regexValue);
    }
    async patternChanged() {
        this.#isIgnoreListedURLCache.clear();
        const promises = [];
        for (const debuggerModel of this.#targetManager.models(DebuggerModel)) {
            promises.push(this.setIgnoreListPatterns(debuggerModel));
            const sourceMapManager = debuggerModel.sourceMapManager();
            for (const script of debuggerModel.scripts()) {
                promises.push(this.updateScriptRanges(script, sourceMapManager.sourceMapForClient(script)));
            }
            promises.push(this.updateIgnoredExecutionContexts(debuggerModel));
        }
        await Promise.all(promises);
        const listeners = Array.from(this.#listeners);
        for (const listener of listeners) {
            listener();
        }
        this.patternChangeFinishedForTests();
    }
    patternChangeFinishedForTests() {
    }
    urlToRegExpString(url) {
        const parsedURL = new ParsedURL(url);
        if (parsedURL.isAboutBlank() || parsedURL.isDataURL()) {
            return '';
        }
        if (!parsedURL.isValid) {
            return '^' + escapeForRegExp(url) + '$';
        }
        let name = parsedURL.lastPathComponent;
        if (name) {
            name = '/' + name;
        }
        else if (parsedURL.folderPathComponents) {
            name = parsedURL.folderPathComponents + '/';
        }
        if (!name) {
            name = parsedURL.host;
        }
        if (!name) {
            return '';
        }
        const scheme = parsedURL.scheme;
        let prefix = '';
        if (scheme && scheme !== 'http' && scheme !== 'https') {
            prefix = '^' + scheme + '://';
            if (scheme === 'chrome-extension') {
                prefix += parsedURL.host + '\\b';
            }
            prefix += '.*';
        }
        return prefix + escapeForRegExp(name) + (url.endsWith(name) ? '$' : '\\b');
    }
    getIgnoreListURLContextMenuItems(uiSourceCode) {
        if (uiSourceCode.project().type() === projectTypes.FileSystem) {
            return [];
        }
        const menuItems = [];
        const canIgnoreList = this.canIgnoreListUISourceCode(uiSourceCode);
        const isIgnoreListed = this.isUserOrSourceMapIgnoreListedUISourceCode(uiSourceCode);
        const isAnonymous = !this.uiSourceCodeURL(uiSourceCode);
        const { isContentScript, isKnownThirdParty } = this.getGeneralRulesForUISourceCode(uiSourceCode);
        if (isIgnoreListed) {
            if (canIgnoreList || isContentScript || isKnownThirdParty || isAnonymous) {
                menuItems.push({
                    text: i18nString$z(UIStrings$O.removeFromIgnoreList),
                    callback: this.unIgnoreListUISourceCode.bind(this, uiSourceCode),
                    jslogContext: 'remove-script-from-ignorelist',
                });
            }
        }
        else {
            if (canIgnoreList) {
                menuItems.push({
                    text: i18nString$z(UIStrings$O.addScriptToIgnoreList),
                    callback: this.ignoreListUISourceCode.bind(this, uiSourceCode),
                    jslogContext: 'add-script-to-ignorelist',
                });
            }
            else if (isAnonymous) {
                menuItems.push({
                    text: i18nString$z(UIStrings$O.addAllAnonymousScriptsToIgnoreList),
                    callback: this.ignoreListAnonymousScripts.bind(this),
                    jslogContext: 'add-anonymous-scripts-to-ignorelist',
                });
            }
            menuItems.push(...this.getIgnoreListGeneralContextMenuItems({ isContentScript, isKnownThirdParty }));
        }
        return menuItems;
    }
    getIgnoreListGeneralContextMenuItems(options) {
        const menuItems = [];
        if (options?.isContentScript) {
            menuItems.push({
                text: i18nString$z(UIStrings$O.addAllContentScriptsToIgnoreList),
                callback: this.ignoreListContentScripts.bind(this),
                jslogContext: 'add-content-scripts-to-ignorelist',
            });
        }
        if (options?.isKnownThirdParty) {
            menuItems.push({
                text: i18nString$z(UIStrings$O.addAllThirdPartyScriptsToIgnoreList),
                callback: this.ignoreListThirdParty.bind(this),
                jslogContext: 'add-3p-scripts-to-ignorelist',
            });
        }
        return menuItems;
    }
    getIgnoreListFolderContextMenuItems(url, options) {
        const menuItems = [];
        const regexValue = '^' + escapeForRegExp(url) + '/';
        if (this.ignoreListHasPattern(regexValue, true)) {
            menuItems.push({
                text: i18nString$z(UIStrings$O.removeFromIgnoreList),
                callback: this.removeIgnoreListPattern.bind(this, regexValue),
                jslogContext: 'remove-from-ignore-list',
            });
        }
        else if (this.isUserIgnoreListedURL(url, options)) {
            menuItems.push({
                text: i18nString$z(UIStrings$O.removeFromIgnoreList),
                callback: this.unIgnoreListURL.bind(this, url, options),
                jslogContext: 'remove-from-ignore-list',
            });
        }
        else if (!options?.isCurrentlyIgnoreListed) {
            menuItems.push({
                text: i18nString$z(UIStrings$O.addDirectoryToIgnoreList),
                callback: this.addRegexToIgnoreList.bind(this, regexValue),
                jslogContext: 'add-directory-to-ignore-list',
            });
            menuItems.push(...this.getIgnoreListGeneralContextMenuItems(options));
        }
        return menuItems;
    }
}
const scriptToRange = new WeakMap();

// Copyright 2013 The Chromium Authors
const UIStrings$N = {
    unknownErrorLoadingFile: 'Unknown error loading file',
};
const str_$M = registerUIStrings('models/bindings/ContentProviderBasedProject.ts', UIStrings$N);
const i18nString$y = getLocalizedString.bind(undefined, str_$M);
class ContentProviderBasedProject extends ProjectStore {
    #isServiceProject;
    #uiSourceCodeToData = new WeakMap();
    constructor(workspace, id, type, displayName, isServiceProject) {
        super(workspace, id, type, displayName);
        this.#isServiceProject = isServiceProject;
        workspace.addProject(this);
    }
    async requestFileContent(uiSourceCode) {
        const { contentProvider } = this.#uiSourceCodeToData.get(uiSourceCode);
        try {
            return await contentProvider.requestContentData();
        }
        catch (err) {
            return {
                error: err ? String(err) : i18nString$y(UIStrings$N.unknownErrorLoadingFile),
            };
        }
    }
    isServiceProject() {
        return this.#isServiceProject;
    }
    async requestMetadata(uiSourceCode) {
        const { metadata } = this.#uiSourceCodeToData.get(uiSourceCode);
        return metadata;
    }
    canSetFileContent() {
        return false;
    }
    async setFileContent(_uiSourceCode, _newContent, _isBase64) {
    }
    fullDisplayName(uiSourceCode) {
        let parentPath = uiSourceCode.parentURL().replace(/^(?:https?|file)\:\/\//, '');
        try {
            parentPath = decodeURI(parentPath);
        }
        catch {
        }
        return parentPath + '/' + uiSourceCode.displayName(true);
    }
    mimeType(uiSourceCode) {
        const { mimeType } = this.#uiSourceCodeToData.get(uiSourceCode);
        return mimeType;
    }
    canRename() {
        return false;
    }
    rename(_uiSourceCode, _newName, callback) {
        callback(false);
    }
    excludeFolder(_path) {
    }
    canExcludeFolder(_path) {
        return false;
    }
    async createFile(_path, _name, _content, _isBase64) {
        return null;
    }
    canCreateFile() {
        return false;
    }
    deleteFile(_uiSourceCode) {
    }
    remove() {
    }
    searchInFileContent(uiSourceCode, query, caseSensitive, isRegex) {
        const { contentProvider } = this.#uiSourceCodeToData.get(uiSourceCode);
        return contentProvider.searchInContent(query, caseSensitive, isRegex);
    }
    async findFilesMatchingSearchRequest(searchConfig, filesMatchingFileQuery, progress) {
        const result = new Map();
        progress.totalWork = filesMatchingFileQuery.length;
        await Promise.all(filesMatchingFileQuery.map(searchInContent.bind(this)));
        progress.done = true;
        return result;
        async function searchInContent(uiSourceCode) {
            let allMatchesFound = true;
            let matches = [];
            for (const query of searchConfig.queries().slice()) {
                const searchMatches = await this.searchInFileContent(uiSourceCode, query, !searchConfig.ignoreCase(), searchConfig.isRegex());
                if (!searchMatches.length) {
                    allMatchesFound = false;
                    break;
                }
                matches = mergeOrdered(matches, searchMatches, SearchMatch.comparator);
            }
            if (allMatchesFound) {
                result.set(uiSourceCode, matches);
            }
            ++progress.worked;
        }
    }
    indexContent(progress) {
        queueMicrotask(() => {
            progress.done = true;
        });
    }
    addUISourceCodeWithProvider(uiSourceCode, contentProvider, metadata, mimeType) {
        this.#uiSourceCodeToData.set(uiSourceCode, { mimeType, metadata, contentProvider });
        this.addUISourceCode(uiSourceCode);
    }
    addContentProvider(url, contentProvider, mimeType) {
        const uiSourceCode = this.createUISourceCode(url, contentProvider.contentType());
        this.addUISourceCodeWithProvider(uiSourceCode, contentProvider, null, mimeType);
        return uiSourceCode;
    }
    reset() {
        this.removeProject();
        this.workspace().addProject(this);
    }
    dispose() {
        this.removeProject();
    }
}

// Copyright 2012 The Chromium Authors
const uiSourceCodeToAttributionMap = new WeakMap();
const projectToTargetMap = new WeakMap();
let networkProjectManagerInstance;
class NetworkProjectManager extends ObjectWrapper {
    constructor() {
        super();
    }
    static instance({ forceNew } = { forceNew: false }) {
        if (!networkProjectManagerInstance || forceNew) {
            networkProjectManagerInstance = new NetworkProjectManager();
        }
        return networkProjectManagerInstance;
    }
}
class NetworkProject {
    static resolveFrame(uiSourceCode, frameId) {
        const target = NetworkProject.targetForUISourceCode(uiSourceCode);
        const resourceTreeModel = target?.model(ResourceTreeModel);
        return resourceTreeModel ? resourceTreeModel.frameForId(frameId) : null;
    }
    static setInitialFrameAttribution(uiSourceCode, frameId) {
        if (!frameId) {
            return;
        }
        const frame = NetworkProject.resolveFrame(uiSourceCode, frameId);
        if (!frame) {
            return;
        }
        const attribution = new Map();
        attribution.set(frameId, { frame, count: 1 });
        uiSourceCodeToAttributionMap.set(uiSourceCode, attribution);
    }
    static cloneInitialFrameAttribution(fromUISourceCode, toUISourceCode) {
        const fromAttribution = uiSourceCodeToAttributionMap.get(fromUISourceCode);
        if (!fromAttribution) {
            return;
        }
        const toAttribution = new Map();
        for (const frameId of fromAttribution.keys()) {
            const value = fromAttribution.get(frameId);
            if (typeof value !== 'undefined') {
                toAttribution.set(frameId, { frame: value.frame, count: value.count });
            }
        }
        uiSourceCodeToAttributionMap.set(toUISourceCode, toAttribution);
    }
    static addFrameAttribution(uiSourceCode, frameId) {
        const frame = NetworkProject.resolveFrame(uiSourceCode, frameId);
        if (!frame) {
            return;
        }
        const frameAttribution = uiSourceCodeToAttributionMap.get(uiSourceCode);
        if (!frameAttribution) {
            return;
        }
        const attributionInfo = frameAttribution.get(frameId) || { frame, count: 0 };
        attributionInfo.count += 1;
        frameAttribution.set(frameId, attributionInfo);
        if (attributionInfo.count !== 1) {
            return;
        }
        const data = { uiSourceCode, frame };
        NetworkProjectManager.instance().dispatchEventToListeners("FrameAttributionAdded" , data);
    }
    static removeFrameAttribution(uiSourceCode, frameId) {
        const frameAttribution = uiSourceCodeToAttributionMap.get(uiSourceCode);
        if (!frameAttribution) {
            return;
        }
        const attributionInfo = frameAttribution.get(frameId);
        console.assert(Boolean(attributionInfo), 'Failed to remove frame attribution for url: ' + uiSourceCode.url());
        if (!attributionInfo) {
            return;
        }
        attributionInfo.count -= 1;
        if (attributionInfo.count > 0) {
            return;
        }
        frameAttribution.delete(frameId);
        const data = { uiSourceCode, frame: attributionInfo.frame };
        NetworkProjectManager.instance().dispatchEventToListeners("FrameAttributionRemoved" , data);
    }
    static targetForUISourceCode(uiSourceCode) {
        return projectToTargetMap.get(uiSourceCode.project()) || null;
    }
    static setTargetForProject(project, target) {
        projectToTargetMap.set(project, target);
    }
    static getTargetForProject(project) {
        return projectToTargetMap.get(project) || null;
    }
    static framesForUISourceCode(uiSourceCode) {
        const target = NetworkProject.targetForUISourceCode(uiSourceCode);
        const resourceTreeModel = target?.model(ResourceTreeModel);
        const attribution = uiSourceCodeToAttributionMap.get(uiSourceCode);
        if (!resourceTreeModel || !attribution) {
            return [];
        }
        const frames = Array.from(attribution.keys()).map(frameId => resourceTreeModel.frameForId(frameId));
        return frames.filter(frame => !!frame);
    }
}

// Copyright 2012 The Chromium Authors
class CompilerScriptMapping {
    #sourceMapManager;
    #debuggerWorkspaceBinding;
    #stubUISourceCodes = new Map();
    #stubProject;
    #eventListeners;
    #projects = new Map();
    #sourceMapToProject = new Map();
    #uiSourceCodeToSourceMaps = new Multimap();
    #debuggerModel;
    #ignoreListManager;
    constructor(debuggerModel, workspace, debuggerWorkspaceBinding) {
        this.#sourceMapManager = debuggerModel.sourceMapManager();
        this.#debuggerWorkspaceBinding = debuggerWorkspaceBinding;
        this.#debuggerModel = debuggerModel;
        this.#ignoreListManager = debuggerWorkspaceBinding.ignoreListManager;
        this.#stubProject = new ContentProviderBasedProject(workspace, 'jsSourceMaps:stub:' + debuggerModel.target().id(), projectTypes.Service, '', true );
        this.#eventListeners = [
            this.#sourceMapManager.addEventListener(Events$b.SourceMapWillAttach, this.sourceMapWillAttach, this),
            this.#sourceMapManager.addEventListener(Events$b.SourceMapFailedToAttach, this.sourceMapFailedToAttach, this),
            this.#sourceMapManager.addEventListener(Events$b.SourceMapAttached, this.sourceMapAttached, this),
            this.#sourceMapManager.addEventListener(Events$b.SourceMapDetached, this.sourceMapDetached, this),
        ];
    }
    setFunctionRanges(uiSourceCode, ranges) {
        for (const sourceMap of this.#uiSourceCodeToSourceMaps.get(uiSourceCode)) {
            sourceMap.augmentWithScopes(uiSourceCode.url(), ranges);
        }
    }
    addStubUISourceCode(script) {
        const stubUISourceCode = this.#stubProject.addContentProvider(ParsedURL.concatenate(script.sourceURL, ':sourcemap'), StaticContentProvider.fromString(script.sourceURL, resourceTypes.Script, '\n\n\n\n\n// Please wait a bit.\n// Compiled script is not shown while source map is being loaded!'), 'text/javascript');
        this.#stubUISourceCodes.set(script, stubUISourceCode);
    }
    removeStubUISourceCode(script) {
        const uiSourceCode = this.#stubUISourceCodes.get(script);
        this.#stubUISourceCodes.delete(script);
        if (uiSourceCode) {
            this.#stubProject.removeUISourceCode(uiSourceCode.url());
        }
    }
    getLocationRangesForSameSourceLocation(rawLocation) {
        const debuggerModel = rawLocation.debuggerModel;
        const script = rawLocation.script();
        if (!script) {
            return [];
        }
        const sourceMap = this.#sourceMapManager.sourceMapForClient(script);
        if (!sourceMap) {
            return [];
        }
        const { lineNumber, columnNumber } = script.rawLocationToRelativeLocation(rawLocation);
        const entry = sourceMap.findEntry(lineNumber, columnNumber);
        if (!entry?.sourceURL) {
            return [];
        }
        const project = this.#sourceMapToProject.get(sourceMap);
        if (!project) {
            return [];
        }
        const uiSourceCode = project.uiSourceCodeForURL(entry.sourceURL);
        if (!uiSourceCode) {
            return [];
        }
        if (!this.#uiSourceCodeToSourceMaps.hasValue(uiSourceCode, sourceMap)) {
            return [];
        }
        const ranges = sourceMap.findReverseRanges(entry.sourceURL, entry.sourceLineNumber, entry.sourceColumnNumber);
        return ranges.map(({ startLine, startColumn, endLine, endColumn }) => {
            const start = script.relativeLocationToRawLocation({ lineNumber: startLine, columnNumber: startColumn });
            const end = script.relativeLocationToRawLocation({ lineNumber: endLine, columnNumber: endColumn });
            return {
                start: debuggerModel.createRawLocation(script, start.lineNumber, start.columnNumber),
                end: debuggerModel.createRawLocation(script, end.lineNumber, end.columnNumber),
            };
        });
    }
    uiSourceCodeForURL(url, isContentScript) {
        const projectType = isContentScript ? projectTypes.ContentScripts : projectTypes.Network;
        for (const project of this.#projects.values()) {
            if (project.type() !== projectType) {
                continue;
            }
            const uiSourceCode = project.uiSourceCodeForURL(url);
            if (uiSourceCode) {
                return uiSourceCode;
            }
        }
        return null;
    }
    rawLocationToUILocation(rawLocation) {
        const script = rawLocation.script();
        if (!script) {
            return null;
        }
        const { lineNumber, columnNumber } = script.rawLocationToRelativeLocation(rawLocation);
        const stubUISourceCode = this.#stubUISourceCodes.get(script);
        if (stubUISourceCode) {
            return new UILocation(stubUISourceCode, lineNumber, columnNumber);
        }
        const sourceMap = this.#sourceMapManager.sourceMapForClient(script);
        if (!sourceMap) {
            return null;
        }
        const project = this.#sourceMapToProject.get(sourceMap);
        if (!project) {
            return null;
        }
        const entry = sourceMap.findEntry(lineNumber, columnNumber, rawLocation.inlineFrameIndex);
        if (!entry?.sourceURL) {
            return null;
        }
        const uiSourceCode = project.uiSourceCodeForURL(entry.sourceURL);
        if (!uiSourceCode) {
            return null;
        }
        if (!this.#uiSourceCodeToSourceMaps.hasValue(uiSourceCode, sourceMap)) {
            return null;
        }
        return uiSourceCode.uiLocation(entry.sourceLineNumber, entry.sourceColumnNumber);
    }
    uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber) {
        const locations = [];
        for (const sourceMap of this.#uiSourceCodeToSourceMaps.get(uiSourceCode)) {
            const entry = sourceMap.sourceLineMapping(uiSourceCode.url(), lineNumber, columnNumber);
            if (!entry) {
                continue;
            }
            const script = this.#sourceMapManager.clientForSourceMap(sourceMap);
            if (!script) {
                continue;
            }
            const location = script.relativeLocationToRawLocation(entry);
            locations.push(script.debuggerModel.createRawLocation(script, location.lineNumber, location.columnNumber));
        }
        return locations;
    }
    uiLocationRangeToRawLocationRanges(uiSourceCode, textRange) {
        if (!this.#uiSourceCodeToSourceMaps.has(uiSourceCode)) {
            return null;
        }
        const ranges = [];
        for (const sourceMap of this.#uiSourceCodeToSourceMaps.get(uiSourceCode)) {
            const script = this.#sourceMapManager.clientForSourceMap(sourceMap);
            if (!script) {
                continue;
            }
            for (const scriptTextRange of sourceMap.reverseMapTextRanges(uiSourceCode.url(), textRange)) {
                const startLocation = script.relativeLocationToRawLocation(scriptTextRange.start);
                const endLocation = script.relativeLocationToRawLocation(scriptTextRange.end);
                const start = script.debuggerModel.createRawLocation(script, startLocation.lineNumber, startLocation.columnNumber);
                const end = script.debuggerModel.createRawLocation(script, endLocation.lineNumber, endLocation.columnNumber);
                ranges.push({ start, end });
            }
        }
        return ranges;
    }
    async functionBoundsAtRawLocation(rawLocation) {
        const script = rawLocation.script();
        if (!script) {
            return null;
        }
        const sourceMap = this.#sourceMapManager.sourceMapForClient(script);
        if (!sourceMap) {
            return null;
        }
        await sourceMap.waitForScopeInfo();
        const { lineNumber, columnNumber } = script.rawLocationToRelativeLocation(rawLocation);
        const { url, scope } = sourceMap.findOriginalFunctionScope({ line: lineNumber, column: columnNumber }) ?? {};
        if (!scope || !url) {
            return null;
        }
        const project = this.#sourceMapToProject.get(sourceMap);
        if (!project) {
            return null;
        }
        const uiSourceCode = project.uiSourceCodeForURL(url);
        if (!uiSourceCode) {
            return null;
        }
        const contentData = await uiSourceCode.requestContentData();
        if ('error' in contentData) {
            return null;
        }
        const name = scope.name ?? '';
        const range = new TextRange(scope.start.line, scope.start.column, scope.end.line, scope.end.column);
        return new UIFunctionBounds(uiSourceCode, range, name);
    }
    async translateRawFramesStep(rawFrames, translatedFrames) {
        const frame = rawFrames[0];
        if (isBuiltinFrame(frame)) {
            return false;
        }
        const sourceMapWithScopeInfoForFrame = async (rawFrame) => {
            const script = this.#debuggerModel.scriptForId(rawFrame.scriptId ?? '');
            if (!script || this.#stubUISourceCodes.has(script)) {
                return null;
            }
            const sourceMap = script.sourceMap();
            await sourceMap?.waitForScopeInfo();
            return sourceMap?.hasScopeInfo() ? { sourceMap, script } : null;
        };
        const sourceMapAndScript = await sourceMapWithScopeInfoForFrame(frame);
        if (!sourceMapAndScript) {
            return false;
        }
        const { sourceMap, script } = sourceMapAndScript;
        const { lineNumber, columnNumber } = script.relativeLocationToRawLocation(frame);
        if (!sourceMap.isOutlinedFrame(lineNumber, columnNumber)) {
            const frames = sourceMap.translateCallSite(lineNumber, columnNumber);
            if (!frames.length) {
                return false;
            }
            rawFrames.shift();
            const result = [];
            translatedFrames.push(result);
            const project = this.#sourceMapToProject.get(sourceMap);
            for (const frame of frames) {
                const uiSourceCode = frame.url ? project?.uiSourceCodeForURL(frame.url) : undefined;
                result.push({
                    ...frame,
                    url: uiSourceCode ? undefined : frame.url,
                    uiSourceCode: uiSourceCode ?? undefined,
                });
            }
            return true;
        }
        return false;
    }
    getMappedLines(uiSourceCode) {
        if (!this.#uiSourceCodeToSourceMaps.has(uiSourceCode)) {
            return null;
        }
        const mappedLines = new Set();
        for (const sourceMap of this.#uiSourceCodeToSourceMaps.get(uiSourceCode)) {
            for (const entry of sourceMap.mappings()) {
                if (entry.sourceURL !== uiSourceCode.url()) {
                    continue;
                }
                mappedLines.add(entry.sourceLineNumber);
            }
        }
        return mappedLines;
    }
    sourceMapWillAttach(event) {
        const { client: script } = event.data;
        this.addStubUISourceCode(script);
        void this.#debuggerWorkspaceBinding.updateLocations(script);
        if (this.#ignoreListManager.isUserIgnoreListedURL(script.sourceURL, { isContentScript: script.isContentScript() })) {
            this.#sourceMapManager.cancelAttachSourceMap(script);
        }
    }
    sourceMapFailedToAttach(event) {
        const { client: script } = event.data;
        this.removeStubUISourceCode(script);
        void this.#debuggerWorkspaceBinding.updateLocations(script);
    }
    sourceMapAttached(event) {
        const { client: script, sourceMap } = event.data;
        const scripts = new Set([script]);
        this.removeStubUISourceCode(script);
        const target = script.target();
        const projectId = `jsSourceMaps:${script.isContentScript() ? 'extensions' : ''}:${target.id()}`;
        let project = this.#projects.get(projectId);
        if (!project) {
            const projectType = script.isContentScript() ? projectTypes.ContentScripts :
                projectTypes.Network;
            project = new ContentProviderBasedProject(this.#stubProject.workspace(), projectId, projectType,  '',  false);
            NetworkProject.setTargetForProject(project, target);
            this.#projects.set(projectId, project);
        }
        this.#sourceMapToProject.set(sourceMap, project);
        for (const url of sourceMap.sourceURLs()) {
            const contentType = resourceTypes.SourceMapScript;
            const uiSourceCode = project.createUISourceCode(url, contentType);
            if (sourceMap.hasIgnoreListHint(url)) {
                uiSourceCode.markKnownThirdParty();
            }
            const content = sourceMap.embeddedContentByURL(url);
            const contentProvider = content !== null ?
                StaticContentProvider.fromString(url, contentType, content) :
                new CompilerSourceMappingContentProvider(url, contentType, script.createPageResourceLoadInitiator());
            let metadata = null;
            if (content !== null) {
                const encoder = new TextEncoder();
                metadata = new UISourceCodeMetadata(null, encoder.encode(content).length);
            }
            const mimeType = ResourceType.mimeFromURL(url) ?? contentType.canonicalMimeType();
            this.#uiSourceCodeToSourceMaps.set(uiSourceCode, sourceMap);
            NetworkProject.setInitialFrameAttribution(uiSourceCode, script.frameId);
            const otherUISourceCode = project.uiSourceCodeForURL(url);
            if (otherUISourceCode !== null) {
                for (const otherSourceMap of this.#uiSourceCodeToSourceMaps.get(otherUISourceCode)) {
                    this.#uiSourceCodeToSourceMaps.delete(otherUISourceCode, otherSourceMap);
                    const otherScript = this.#sourceMapManager.clientForSourceMap(otherSourceMap);
                    if (!otherScript) {
                        continue;
                    }
                    NetworkProject.removeFrameAttribution(otherUISourceCode, otherScript.frameId);
                    if (sourceMap.compatibleForURL(url, otherSourceMap)) {
                        this.#uiSourceCodeToSourceMaps.set(uiSourceCode, otherSourceMap);
                        NetworkProject.addFrameAttribution(uiSourceCode, otherScript.frameId);
                    }
                    scripts.add(otherScript);
                }
                project.removeUISourceCode(url);
            }
            project.addUISourceCodeWithProvider(uiSourceCode, contentProvider, metadata, mimeType);
        }
        void Promise.all([...scripts].map(script => this.#debuggerWorkspaceBinding.updateLocations(script)))
            .then(() => this.sourceMapAttachedForTest(sourceMap));
    }
    sourceMapDetached(event) {
        const { client: script, sourceMap } = event.data;
        const project = this.#sourceMapToProject.get(sourceMap);
        if (!project) {
            return;
        }
        for (const uiSourceCode of project.uiSourceCodes()) {
            if (this.#uiSourceCodeToSourceMaps.delete(uiSourceCode, sourceMap)) {
                NetworkProject.removeFrameAttribution(uiSourceCode, script.frameId);
                if (!this.#uiSourceCodeToSourceMaps.has(uiSourceCode)) {
                    project.removeUISourceCode(uiSourceCode.url());
                }
            }
        }
        this.#sourceMapToProject.delete(sourceMap);
        void this.#debuggerWorkspaceBinding.updateLocations(script);
    }
    scriptsForUISourceCode(uiSourceCode) {
        const scripts = [];
        for (const sourceMap of this.#uiSourceCodeToSourceMaps.get(uiSourceCode)) {
            const script = this.#sourceMapManager.clientForSourceMap(sourceMap);
            if (script) {
                scripts.push(script);
            }
        }
        return scripts;
    }
    sourceMapAttachedForTest(_sourceMap) {
    }
    dispose() {
        removeEventListeners(this.#eventListeners);
        for (const project of this.#projects.values()) {
            project.dispose();
        }
        this.#stubProject.dispose();
    }
}

// Copyright 2014 The Chromium Authors
class LiveLocationWithPool {
    #updateDelegate;
    #locationPool;
    #updatePromise;
    constructor(updateDelegate, locationPool) {
        this.#updateDelegate = updateDelegate;
        this.#locationPool = locationPool;
        this.#locationPool.add(this);
        this.#updatePromise = null;
    }
    async update() {
        if (!this.#updateDelegate) {
            return;
        }
        if (this.#updatePromise) {
            await this.#updatePromise.then(() => this.update());
        }
        else {
            this.#updatePromise = this.#updateDelegate(this);
            await this.#updatePromise;
            this.#updatePromise = null;
        }
    }
    async uiLocation() {
        throw new Error('Not implemented');
    }
    dispose() {
        this.#locationPool.delete(this);
        this.#updateDelegate = null;
    }
    isDisposed() {
        return !this.#locationPool.has(this);
    }
}
class LiveLocationPool {
    #locations;
    constructor() {
        this.#locations = new Set();
    }
    add(location) {
        this.#locations.add(location);
    }
    delete(location) {
        this.#locations.delete(location);
    }
    has(location) {
        return this.#locations.has(location);
    }
    disposeAll() {
        for (const location of this.#locations) {
            location.dispose();
        }
    }
}

// Copyright 2012 The Chromium Authors
class SASSSourceMapping {
    #sourceMapManager;
    #project;
    #eventListeners;
    #bindings;
    #cssWorkspaceBinding;
    constructor(target, sourceMapManager, workspace, cssWorkspaceBinding) {
        this.#sourceMapManager = sourceMapManager;
        this.#cssWorkspaceBinding = cssWorkspaceBinding;
        this.#project = new ContentProviderBasedProject(workspace, 'cssSourceMaps:' + target.id(), projectTypes.Network, '', false );
        NetworkProject.setTargetForProject(this.#project, target);
        this.#bindings = new Map();
        this.#eventListeners = [
            this.#sourceMapManager.addEventListener(Events$b.SourceMapAttached, this.sourceMapAttached, this),
            this.#sourceMapManager.addEventListener(Events$b.SourceMapDetached, this.sourceMapDetached, this),
        ];
    }
    sourceMapAttachedForTest(_sourceMap) {
    }
    async sourceMapAttached(event) {
        const header = event.data.client;
        const sourceMap = event.data.sourceMap;
        const project = this.#project;
        const bindings = this.#bindings;
        for (const sourceURL of sourceMap.sourceURLs()) {
            let binding = bindings.get(sourceURL);
            if (!binding) {
                binding = new Binding$1(project, sourceURL, header.createPageResourceLoadInitiator());
                bindings.set(sourceURL, binding);
            }
            binding.addSourceMap(sourceMap, header.frameId);
        }
        await this.#cssWorkspaceBinding.updateLocations(header);
        this.sourceMapAttachedForTest(sourceMap);
    }
    async sourceMapDetached(event) {
        const header = event.data.client;
        const sourceMap = event.data.sourceMap;
        const bindings = this.#bindings;
        for (const sourceURL of sourceMap.sourceURLs()) {
            const binding = bindings.get(sourceURL);
            if (binding) {
                binding.removeSourceMap(sourceMap, header.frameId);
                if (!binding.getUiSourceCode()) {
                    bindings.delete(sourceURL);
                }
            }
        }
        await this.#cssWorkspaceBinding.updateLocations(header);
    }
    rawLocationToUILocation(rawLocation) {
        const header = rawLocation.header();
        if (!header) {
            return null;
        }
        const sourceMap = this.#sourceMapManager.sourceMapForClient(header);
        if (!sourceMap) {
            return null;
        }
        let { lineNumber, columnNumber } = rawLocation;
        if (sourceMap.mapsOrigin() && header.isInline) {
            lineNumber -= header.startLine;
            if (lineNumber === 0) {
                columnNumber -= header.startColumn;
            }
        }
        const entry = sourceMap.findEntry(lineNumber, columnNumber);
        if (!entry?.sourceURL) {
            return null;
        }
        const uiSourceCode = this.#project.uiSourceCodeForURL(entry.sourceURL);
        if (!uiSourceCode) {
            return null;
        }
        return uiSourceCode.uiLocation(entry.sourceLineNumber, entry.sourceColumnNumber);
    }
    uiLocationToRawLocations(uiLocation) {
        const { uiSourceCode, lineNumber, columnNumber = 0 } = uiLocation;
        const binding = uiSourceCodeToBinding.get(uiSourceCode);
        if (!binding) {
            return [];
        }
        const locations = [];
        for (const sourceMap of binding.getReferringSourceMaps()) {
            const entries = sourceMap.findReverseEntries(uiSourceCode.url(), lineNumber, columnNumber);
            const header = this.#sourceMapManager.clientForSourceMap(sourceMap);
            if (header) {
                locations.push(...entries.map(entry => new CSSLocation(header, entry.lineNumber, entry.columnNumber)));
            }
        }
        return locations;
    }
    static uiSourceOrigin(uiSourceCode) {
        const binding = uiSourceCodeToBinding.get(uiSourceCode);
        if (binding) {
            return binding.getReferringSourceMaps().map(sourceMap => sourceMap.compiledURL());
        }
        return [];
    }
    dispose() {
        removeEventListeners(this.#eventListeners);
        this.#project.dispose();
    }
}
const uiSourceCodeToBinding = new WeakMap();
let Binding$1 = class Binding {
    #project;
    #url;
    #initiator;
    referringSourceMaps;
    uiSourceCode;
    constructor(project, url, initiator) {
        this.#project = project;
        this.#url = url;
        this.#initiator = initiator;
        this.referringSourceMaps = [];
        this.uiSourceCode = null;
    }
    recreateUISourceCodeIfNeeded(frameId) {
        const sourceMap = this.referringSourceMaps[this.referringSourceMaps.length - 1];
        const contentType = resourceTypes.SourceMapStyleSheet;
        const embeddedContent = sourceMap.embeddedContentByURL(this.#url);
        const contentProvider = embeddedContent !== null ?
            StaticContentProvider.fromString(this.#url, contentType, embeddedContent) :
            new CompilerSourceMappingContentProvider(this.#url, contentType, this.#initiator);
        const newUISourceCode = this.#project.createUISourceCode(this.#url, contentType);
        uiSourceCodeToBinding.set(newUISourceCode, this);
        const mimeType = ResourceType.mimeFromURL(this.#url) || contentType.canonicalMimeType();
        const metadata = typeof embeddedContent === 'string' ?
            new UISourceCodeMetadata(null, embeddedContent.length) :
            null;
        if (this.uiSourceCode) {
            NetworkProject.cloneInitialFrameAttribution(this.uiSourceCode, newUISourceCode);
            this.#project.removeUISourceCode(this.uiSourceCode.url());
        }
        else {
            NetworkProject.setInitialFrameAttribution(newUISourceCode, frameId);
        }
        this.uiSourceCode = newUISourceCode;
        this.#project.addUISourceCodeWithProvider(this.uiSourceCode, contentProvider, metadata, mimeType);
    }
    addSourceMap(sourceMap, frameId) {
        if (this.uiSourceCode) {
            NetworkProject.addFrameAttribution(this.uiSourceCode, frameId);
        }
        this.referringSourceMaps.push(sourceMap);
        this.recreateUISourceCodeIfNeeded(frameId);
    }
    removeSourceMap(sourceMap, frameId) {
        const uiSourceCode = this.uiSourceCode;
        NetworkProject.removeFrameAttribution(uiSourceCode, frameId);
        const lastIndex = this.referringSourceMaps.lastIndexOf(sourceMap);
        if (lastIndex !== -1) {
            this.referringSourceMaps.splice(lastIndex, 1);
        }
        if (!this.referringSourceMaps.length) {
            this.#project.removeUISourceCode(uiSourceCode.url());
            this.uiSourceCode = null;
        }
        else {
            this.recreateUISourceCodeIfNeeded(frameId);
        }
    }
    getReferringSourceMaps() {
        return this.referringSourceMaps;
    }
    getUiSourceCode() {
        return this.uiSourceCode;
    }
};

// Copyright 2021 The Chromium Authors
/*
 * Copyright (C) 2006, 2007, 2008 Apple Inc.  All rights reserved.
 * Copyright (C) 2007 Matt Lilek (pewtermoose@gmail.com).
 * Copyright (C) 2009 Joseph Pecoraro
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
function metadataForURL(target, frameId, url) {
    const resourceTreeModel = target.model(ResourceTreeModel);
    if (!resourceTreeModel) {
        return null;
    }
    const frame = resourceTreeModel.frameForId(frameId);
    if (!frame) {
        return null;
    }
    return resourceMetadata(frame.resourceForURL(url));
}
function resourceMetadata(resource) {
    if (!resource || (typeof resource.contentSize() !== 'number' && !resource.lastModified())) {
        return null;
    }
    return new UISourceCodeMetadata(resource.lastModified(), resource.contentSize());
}

// Copyright 2012 The Chromium Authors
const uiSourceCodeToStyleMap = new WeakMap();
class StylesSourceMapping {
    #cssModel;
    #project;
    #styleFiles = new Map();
    #eventListeners;
    constructor(cssModel, workspace) {
        this.#cssModel = cssModel;
        const target = this.#cssModel.target();
        this.#project = new ContentProviderBasedProject(workspace, 'css:' + target.id(), projectTypes.Network, '', false );
        NetworkProject.setTargetForProject(this.#project, target);
        this.#eventListeners = [
            this.#cssModel.addEventListener(Events$a.StyleSheetAdded, this.styleSheetAdded, this),
            this.#cssModel.addEventListener(Events$a.StyleSheetRemoved, this.styleSheetRemoved, this),
            this.#cssModel.addEventListener(Events$a.StyleSheetChanged, this.styleSheetChanged, this),
        ];
    }
    addSourceMap(sourceUrl, sourceMapUrl) {
        this.#styleFiles.get(sourceUrl)?.addSourceMap(sourceUrl, sourceMapUrl);
    }
    rawLocationToUILocation(rawLocation) {
        const header = rawLocation.header();
        if (!header || !this.acceptsHeader(header)) {
            return null;
        }
        const styleFile = this.#styleFiles.get(header.resourceURL());
        if (!styleFile) {
            return null;
        }
        let lineNumber = rawLocation.lineNumber;
        let columnNumber = rawLocation.columnNumber;
        if (header.isInline && header.hasSourceURL) {
            lineNumber -= header.lineNumberInSource(0);
            const headerColumnNumber = header.columnNumberInSource(lineNumber, 0);
            if (typeof headerColumnNumber === 'undefined') {
                columnNumber = headerColumnNumber;
            }
            else {
                columnNumber -= headerColumnNumber;
            }
        }
        return styleFile.getUiSourceCode().uiLocation(lineNumber, columnNumber);
    }
    uiLocationToRawLocations(uiLocation) {
        const styleFile = uiSourceCodeToStyleMap.get(uiLocation.uiSourceCode);
        if (!styleFile) {
            return [];
        }
        const rawLocations = [];
        for (const header of styleFile.getHeaders()) {
            let lineNumber = uiLocation.lineNumber;
            let columnNumber = uiLocation.columnNumber;
            if (header.isInline && header.hasSourceURL) {
                columnNumber = header.columnNumberInSource(lineNumber, uiLocation.columnNumber || 0);
                lineNumber = header.lineNumberInSource(lineNumber);
            }
            rawLocations.push(new CSSLocation(header, lineNumber, columnNumber));
        }
        return rawLocations;
    }
    acceptsHeader(header) {
        if (header.isConstructedByNew()) {
            return false;
        }
        if (header.isInline && !header.hasSourceURL && header.origin !== 'inspector') {
            return false;
        }
        if (!header.resourceURL()) {
            return false;
        }
        return true;
    }
    styleSheetAdded(event) {
        const header = event.data;
        if (!this.acceptsHeader(header)) {
            return;
        }
        const url = header.resourceURL();
        let styleFile = this.#styleFiles.get(url);
        if (!styleFile) {
            styleFile = new StyleFile(this.#cssModel, this.#project, header);
            this.#styleFiles.set(url, styleFile);
        }
        else {
            styleFile.addHeader(header);
        }
    }
    styleSheetRemoved(event) {
        const header = event.data;
        if (!this.acceptsHeader(header)) {
            return;
        }
        const url = header.resourceURL();
        const styleFile = this.#styleFiles.get(url);
        if (styleFile) {
            if (styleFile.getHeaders().size === 1) {
                styleFile.dispose();
                this.#styleFiles.delete(url);
            }
            else {
                styleFile.removeHeader(header);
            }
        }
    }
    styleSheetChanged(event) {
        const header = this.#cssModel.styleSheetHeaderForId(event.data.styleSheetId);
        if (!header || !this.acceptsHeader(header)) {
            return;
        }
        const styleFile = this.#styleFiles.get(header.resourceURL());
        if (styleFile) {
            styleFile.styleSheetChanged(header);
        }
    }
    dispose() {
        for (const styleFile of this.#styleFiles.values()) {
            styleFile.dispose();
        }
        this.#styleFiles.clear();
        removeEventListeners(this.#eventListeners);
        this.#project.removeProject();
    }
}
class StyleFile {
    #cssModel;
    #project;
    headers;
    uiSourceCode;
    #eventListeners;
    #throttler = new Throttler(200);
    #terminated = false;
    #isAddingRevision;
    #isUpdatingHeaders;
    constructor(cssModel, project, header) {
        this.#cssModel = cssModel;
        this.#project = project;
        this.headers = new Set([header]);
        const target = cssModel.target();
        const url = header.resourceURL();
        const metadata = metadataForURL(target, header.frameId, url);
        this.uiSourceCode = this.#project.createUISourceCode(url, header.contentType());
        uiSourceCodeToStyleMap.set(this.uiSourceCode, this);
        NetworkProject.setInitialFrameAttribution(this.uiSourceCode, header.frameId);
        this.#project.addUISourceCodeWithProvider(this.uiSourceCode, this, metadata, 'text/css');
        this.#eventListeners = [
            this.uiSourceCode.addEventListener(Events$2.WorkingCopyChanged, this.workingCopyChanged, this),
            this.uiSourceCode.addEventListener(Events$2.WorkingCopyCommitted, this.workingCopyCommitted, this),
        ];
    }
    addHeader(header) {
        this.headers.add(header);
        NetworkProject.addFrameAttribution(this.uiSourceCode, header.frameId);
    }
    removeHeader(header) {
        this.headers.delete(header);
        NetworkProject.removeFrameAttribution(this.uiSourceCode, header.frameId);
    }
    styleSheetChanged(header) {
        console.assert(this.headers.has(header));
        if (this.#isUpdatingHeaders || !this.headers.has(header)) {
            return;
        }
        const mirrorContentBound = this.mirrorContent.bind(this, header, true );
        void this.#throttler.schedule(mirrorContentBound, "Default" );
    }
    workingCopyCommitted() {
        if (this.#isAddingRevision) {
            return;
        }
        const mirrorContentBound = this.mirrorContent.bind(this, this.uiSourceCode, true );
        void this.#throttler.schedule(mirrorContentBound, "AsSoonAsPossible" );
    }
    workingCopyChanged() {
        if (this.#isAddingRevision) {
            return;
        }
        const mirrorContentBound = this.mirrorContent.bind(this, this.uiSourceCode, false );
        void this.#throttler.schedule(mirrorContentBound, "Default" );
    }
    async mirrorContent(fromProvider, majorChange) {
        if (this.#terminated) {
            this.styleFileSyncedForTest();
            return;
        }
        let newContent = null;
        if (fromProvider === this.uiSourceCode) {
            newContent = this.uiSourceCode.workingCopy();
        }
        else {
            newContent = ContentData.textOr(await fromProvider.requestContentData(), null);
        }
        if (newContent === null || this.#terminated) {
            this.styleFileSyncedForTest();
            return;
        }
        if (fromProvider !== this.uiSourceCode) {
            this.#isAddingRevision = true;
            this.uiSourceCode.setWorkingCopy(newContent);
            this.#isAddingRevision = false;
        }
        this.#isUpdatingHeaders = true;
        const promises = [];
        for (const header of this.headers) {
            if (header === fromProvider) {
                continue;
            }
            promises.push(this.#cssModel.setStyleSheetText(header.id, newContent, majorChange));
        }
        await Promise.all(promises);
        this.#isUpdatingHeaders = false;
        this.styleFileSyncedForTest();
    }
    styleFileSyncedForTest() {
    }
    dispose() {
        if (this.#terminated) {
            return;
        }
        this.#terminated = true;
        this.#project.removeUISourceCode(this.uiSourceCode.url());
        removeEventListeners(this.#eventListeners);
    }
    contentURL() {
        console.assert(this.headers.size > 0);
        return this.#firstHeader().originalContentProvider().contentURL();
    }
    contentType() {
        console.assert(this.headers.size > 0);
        return this.#firstHeader().originalContentProvider().contentType();
    }
    requestContentData() {
        console.assert(this.headers.size > 0);
        return this.#firstHeader().originalContentProvider().requestContentData();
    }
    searchInContent(query, caseSensitive, isRegex) {
        console.assert(this.headers.size > 0);
        return this.#firstHeader().originalContentProvider().searchInContent(query, caseSensitive, isRegex);
    }
    #firstHeader() {
        console.assert(this.headers.size > 0);
        return this.headers.values().next().value;
    }
    getHeaders() {
        return this.headers;
    }
    getUiSourceCode() {
        return this.uiSourceCode;
    }
    addSourceMap(sourceUrl, sourceMapUrl) {
        const sourceMapManager = this.#cssModel.sourceMapManager();
        this.headers.forEach(header => {
            sourceMapManager.detachSourceMap(header);
            sourceMapManager.attachSourceMap(header, sourceUrl, sourceMapUrl);
        });
    }
}

// Copyright 2014 The Chromium Authors
class CSSWorkspaceBinding {
    #resourceMapping;
    #modelToInfo;
    #liveLocationPromises;
    constructor(resourceMapping, targetManager) {
        this.#resourceMapping = resourceMapping;
        this.#resourceMapping.cssWorkspaceBinding = this;
        this.#modelToInfo = new Map();
        targetManager.observeModels(CSSModel, this);
        this.#liveLocationPromises = new Set();
    }
    static instance(opts = { forceNew: null, resourceMapping: null, targetManager: null }) {
        const { forceNew, resourceMapping, targetManager } = opts;
        if (forceNew) {
            if (!resourceMapping || !targetManager) {
                throw new Error(`Unable to create CSSWorkspaceBinding: resourceMapping and targetManager must be provided: ${new Error().stack}`);
            }
            globalInstance().set(CSSWorkspaceBinding, new CSSWorkspaceBinding(resourceMapping, targetManager));
        }
        return globalInstance().get(CSSWorkspaceBinding);
    }
    static removeInstance() {
        globalInstance().delete(CSSWorkspaceBinding);
    }
    get modelToInfo() {
        return this.#modelToInfo;
    }
    getCSSModelInfo(cssModel) {
        return this.#modelToInfo.get(cssModel);
    }
    modelAdded(cssModel) {
        this.#modelToInfo.set(cssModel, new ModelInfo$1(cssModel, this.#resourceMapping, this));
    }
    modelRemoved(cssModel) {
        this.getCSSModelInfo(cssModel).dispose();
        this.#modelToInfo.delete(cssModel);
    }
    async pendingLiveLocationChangesPromise() {
        await Promise.all(this.#liveLocationPromises);
    }
    recordLiveLocationChange(promise) {
        void promise.then(() => {
            this.#liveLocationPromises.delete(promise);
        });
        this.#liveLocationPromises.add(promise);
    }
    async updateLocations(header) {
        const updatePromise = this.getCSSModelInfo(header.cssModel()).updateLocations(header);
        this.recordLiveLocationChange(updatePromise);
        await updatePromise;
    }
    createLiveLocation(rawLocation, updateDelegate, locationPool) {
        const locationPromise = this.getCSSModelInfo(rawLocation.cssModel()).createLiveLocation(rawLocation, updateDelegate, locationPool);
        this.recordLiveLocationChange(locationPromise);
        return locationPromise;
    }
    propertyRawLocation(cssProperty, forName) {
        const style = cssProperty.ownerStyle;
        if (!style || style.type !== Type$3.Regular || !style.styleSheetId) {
            return null;
        }
        const header = style.cssModel().styleSheetHeaderForId(style.styleSheetId);
        if (!header) {
            return null;
        }
        const range = forName ? cssProperty.nameRange() : cssProperty.valueRange();
        if (!range) {
            return null;
        }
        const lineNumber = range.startLine;
        const columnNumber = range.startColumn;
        return new CSSLocation(header, header.lineNumberInSource(lineNumber), header.columnNumberInSource(lineNumber, columnNumber));
    }
    propertyUILocation(cssProperty, forName) {
        const rawLocation = this.propertyRawLocation(cssProperty, forName);
        if (!rawLocation) {
            return null;
        }
        return this.rawLocationToUILocation(rawLocation);
    }
    rawLocationToUILocation(rawLocation) {
        return this.getCSSModelInfo(rawLocation.cssModel()).rawLocationToUILocation(rawLocation);
    }
    uiLocationToRawLocations(uiLocation) {
        const rawLocations = [];
        for (const modelInfo of this.#modelToInfo.values()) {
            rawLocations.push(...modelInfo.uiLocationToRawLocations(uiLocation));
        }
        return rawLocations;
    }
}
let ModelInfo$1 = class ModelInfo {
    #eventListeners;
    #resourceMapping;
    #stylesSourceMapping;
    #sassSourceMapping;
    #locations;
    #unboundLocations;
    constructor(cssModel, resourceMapping, cssWorkspaceBinding) {
        this.#eventListeners = [
            cssModel.addEventListener(Events$a.StyleSheetAdded, event => {
                void this.styleSheetAdded(event);
            }, this),
            cssModel.addEventListener(Events$a.StyleSheetRemoved, event => {
                void this.styleSheetRemoved(event);
            }, this),
        ];
        this.#resourceMapping = resourceMapping;
        this.#stylesSourceMapping = new StylesSourceMapping(cssModel, resourceMapping.workspace);
        const sourceMapManager = cssModel.sourceMapManager();
        this.#sassSourceMapping =
            new SASSSourceMapping(cssModel.target(), sourceMapManager, resourceMapping.workspace, cssWorkspaceBinding);
        this.#locations = new Multimap();
        this.#unboundLocations = new Multimap();
    }
    get locations() {
        return this.#locations;
    }
    async createLiveLocation(rawLocation, updateDelegate, locationPool) {
        const location = new LiveLocation(rawLocation, this, updateDelegate, locationPool);
        const header = rawLocation.header();
        if (header) {
            location.setHeader(header);
            this.#locations.set(header, location);
            await location.update();
        }
        else {
            this.#unboundLocations.set(rawLocation.url, location);
        }
        return location;
    }
    disposeLocation(location) {
        const header = location.header();
        if (header) {
            this.#locations.delete(header, location);
        }
        else {
            this.#unboundLocations.delete(location.url, location);
        }
    }
    updateLocations(header) {
        const promises = [];
        for (const location of this.#locations.get(header)) {
            promises.push(location.update());
        }
        return Promise.all(promises);
    }
    async styleSheetAdded(event) {
        const header = event.data;
        if (!header.sourceURL) {
            return;
        }
        const promises = [];
        for (const location of this.#unboundLocations.get(header.sourceURL)) {
            location.setHeader(header);
            this.#locations.set(header, location);
            promises.push(location.update());
        }
        await Promise.all(promises);
        this.#unboundLocations.deleteAll(header.sourceURL);
    }
    async styleSheetRemoved(event) {
        const header = event.data;
        const promises = [];
        for (const location of this.#locations.get(header)) {
            location.setHeader(header);
            this.#unboundLocations.set(location.url, location);
            promises.push(location.update());
        }
        await Promise.all(promises);
        this.#locations.deleteAll(header);
    }
    addSourceMap(sourceUrl, sourceMapUrl) {
        this.#stylesSourceMapping.addSourceMap(sourceUrl, sourceMapUrl);
    }
    rawLocationToUILocation(rawLocation) {
        let uiLocation = null;
        uiLocation = uiLocation || this.#sassSourceMapping.rawLocationToUILocation(rawLocation);
        uiLocation = uiLocation || this.#stylesSourceMapping.rawLocationToUILocation(rawLocation);
        uiLocation = uiLocation || this.#resourceMapping.cssLocationToUILocation(rawLocation);
        return uiLocation;
    }
    uiLocationToRawLocations(uiLocation) {
        let rawLocations = this.#sassSourceMapping.uiLocationToRawLocations(uiLocation);
        if (rawLocations.length) {
            return rawLocations;
        }
        rawLocations = this.#stylesSourceMapping.uiLocationToRawLocations(uiLocation);
        if (rawLocations.length) {
            return rawLocations;
        }
        return this.#resourceMapping.uiLocationToCSSLocations(uiLocation);
    }
    dispose() {
        removeEventListeners(this.#eventListeners);
        this.#stylesSourceMapping.dispose();
        this.#sassSourceMapping.dispose();
    }
};
class LiveLocation extends LiveLocationWithPool {
    url;
    #lineNumber;
    #columnNumber;
    #info;
    #header;
    constructor(rawLocation, info, updateDelegate, locationPool) {
        super(updateDelegate, locationPool);
        this.url = rawLocation.url;
        this.#lineNumber = rawLocation.lineNumber;
        this.#columnNumber = rawLocation.columnNumber;
        this.#info = info;
        this.#header = null;
    }
    header() {
        return this.#header;
    }
    setHeader(header) {
        this.#header = header;
    }
    async uiLocation() {
        if (!this.#header) {
            return null;
        }
        const rawLocation = new CSSLocation(this.#header, this.#lineNumber, this.#columnNumber);
        return CSSWorkspaceBinding.instance().rawLocationToUILocation(rawLocation);
    }
    dispose() {
        super.dispose();
        this.#info.disposeLocation(this);
    }
}

// Copyright 2020 The Chromium Authors
const UIStrings$M = {
    errorInDebuggerLanguagePlugin: 'Error in debugger language plugin: {PH1}',
    loadingDebugSymbolsForVia: '[{PH1}] Loading debug symbols for {PH2} (via {PH3})…',
    loadingDebugSymbolsFor: '[{PH1}] Loading debug symbols for {PH2}…',
    loadedDebugSymbolsForButDidnt: '[{PH1}] Loaded debug symbols for {PH2}, but didn\'t find any source files',
    loadedDebugSymbolsForFound: '[{PH1}] Loaded debug symbols for {PH2}, found {PH3} source file(s)',
    failedToLoadDebugSymbolsFor: '[{PH1}] Failed to load debug symbols for {PH2} ({PH3})',
};
const str_$L = registerUIStrings('models/bindings/DebuggerLanguagePlugins.ts', UIStrings$M);
const i18nString$x = getLocalizedString.bind(undefined, str_$L);
function rawModuleIdForScript(script) {
    return `${script.sourceURL}@${script.hash}`;
}
function getRawLocation(callFrame) {
    const { script } = callFrame;
    return {
        rawModuleId: rawModuleIdForScript(script),
        codeOffset: callFrame.location().columnNumber - (script.codeOffset() || 0),
        inlineFrameIndex: callFrame.inlineFrameIndex,
    };
}
class FormattingError extends Error {
    exception;
    exceptionDetails;
    constructor(exception, exceptionDetails) {
        const { description } = exceptionDetails.exception || {};
        super(description || exceptionDetails.text);
        this.exception = exception;
        this.exceptionDetails = exceptionDetails;
    }
    static makeLocal(callFrame, message) {
        const exception = {
            type: "object" ,
            subtype: "error" ,
            description: message,
        };
        const exceptionDetails = { text: 'Uncaught', exceptionId: -1, columnNumber: 0, lineNumber: 0, exception };
        const errorObject = callFrame.debuggerModel.runtimeModel().createRemoteObject(exception);
        return new FormattingError(errorObject, exceptionDetails);
    }
}
class NamespaceObject extends LocalJSONObject {
    get description() {
        return this.type;
    }
    get type() {
        return 'namespace';
    }
}
async function getRemoteObject(callFrame, object) {
    if (!/^(local|global|operand)$/.test(object.valueClass)) {
        return { type: "undefined"  };
    }
    const index = Number(object.index);
    const expression = `${object.valueClass}s[${index}]`;
    const response = await callFrame.debuggerModel.agent.invoke_evaluateOnCallFrame({
        callFrameId: callFrame.id,
        expression,
        silent: true,
        generatePreview: true,
        throwOnSideEffect: true,
    });
    if (response.getError() || response.exceptionDetails) {
        return { type: "undefined"  };
    }
    return response.result;
}
async function wrapRemoteObject(callFrame, object, plugin) {
    if (object.type === 'reftype') {
        const obj = await getRemoteObject(callFrame, object);
        return callFrame.debuggerModel.runtimeModel().createRemoteObject(obj);
    }
    return new ExtensionRemoteObject(callFrame, object, plugin);
}
class SourceScopeRemoteObject extends RemoteObjectImpl {
    variables;
    #callFrame;
    #plugin;
    stopId;
    constructor(callFrame, stopId, plugin) {
        super(callFrame.debuggerModel.runtimeModel(), undefined, 'object', undefined, null);
        this.variables = [];
        this.#callFrame = callFrame;
        this.#plugin = plugin;
        this.stopId = stopId;
    }
    async doGetProperties(_ownProperties, accessorPropertiesOnly, _generatePreview) {
        if (accessorPropertiesOnly) {
            return { properties: [], internalProperties: [] };
        }
        const properties = [];
        const namespaces = {};
        function makeProperty(name, obj) {
            return new RemoteObjectProperty(name, obj,
             false,  false,  true,  false);
        }
        for (const variable of this.variables) {
            let sourceVar;
            try {
                const evalResult = await this.#plugin.evaluate(variable.name, getRawLocation(this.#callFrame), this.stopId);
                sourceVar = evalResult ? await wrapRemoteObject(this.#callFrame, evalResult, this.#plugin) :
                    new LocalJSONObject(undefined);
            }
            catch (e) {
                console.warn(e);
                sourceVar = new LocalJSONObject(undefined);
            }
            if (variable.nestedName && variable.nestedName.length > 1) {
                let parent = namespaces;
                for (let index = 0; index < variable.nestedName.length - 1; index++) {
                    const nestedName = variable.nestedName[index];
                    let child = parent[nestedName];
                    if (!child) {
                        child = new NamespaceObject({});
                        parent[nestedName] = child;
                    }
                    parent = child.value;
                }
                const name = variable.nestedName[variable.nestedName.length - 1];
                parent[name] = sourceVar;
            }
            else {
                properties.push(makeProperty(variable.name, sourceVar));
            }
        }
        for (const namespace in namespaces) {
            properties.push(makeProperty(namespace, (namespaces[namespace])));
        }
        return { properties, internalProperties: [] };
    }
}
class SourceScope {
    #callFrame;
    #type;
    #typeName;
    #icon;
    #object;
    constructor(callFrame, stopId, type, typeName, icon, plugin) {
        if (icon && new URL(icon).protocol !== 'data:') {
            throw new Error('The icon must be a data:-URL');
        }
        this.#callFrame = callFrame;
        this.#type = type;
        this.#typeName = typeName;
        this.#icon = icon;
        this.#object = new SourceScopeRemoteObject(callFrame, stopId, plugin);
    }
    async getVariableValue(name) {
        for (let v = 0; v < this.#object.variables.length; ++v) {
            if (this.#object.variables[v].name !== name) {
                continue;
            }
            const properties = await this.#object.getAllProperties(false, false);
            if (!properties.properties) {
                continue;
            }
            const { value } = properties.properties[v];
            if (value) {
                return value;
            }
        }
        return null;
    }
    callFrame() {
        return this.#callFrame;
    }
    type() {
        return this.#type;
    }
    typeName() {
        return this.#typeName;
    }
    name() {
        return undefined;
    }
    range() {
        return null;
    }
    object() {
        return this.#object;
    }
    description() {
        return '';
    }
    icon() {
        return this.#icon;
    }
    extraProperties() {
        return [];
    }
}
class ExtensionRemoteObject extends RemoteObject$1 {
    extensionObject;
    plugin;
    callFrame;
    constructor(callFrame, extensionObject, plugin) {
        super();
        this.extensionObject = extensionObject;
        this.plugin = plugin;
        this.callFrame = callFrame;
    }
    get linearMemoryAddress() {
        return this.extensionObject.linearMemoryAddress;
    }
    get linearMemorySize() {
        return this.extensionObject.linearMemorySize;
    }
    get objectId() {
        return this.extensionObject.objectId;
    }
    get type() {
        if (this.extensionObject.type === 'array' || this.extensionObject.type === 'null') {
            return 'object';
        }
        return this.extensionObject.type;
    }
    get subtype() {
        if (this.extensionObject.type === 'array' || this.extensionObject.type === 'null') {
            return this.extensionObject.type;
        }
        return undefined;
    }
    get value() {
        return this.extensionObject.value;
    }
    unserializableValue() {
        return undefined;
    }
    get description() {
        return this.extensionObject.description;
    }
    set description(_description) {
    }
    get hasChildren() {
        return this.extensionObject.hasChildren;
    }
    get preview() {
        return undefined;
    }
    get className() {
        return this.extensionObject.className ?? null;
    }
    arrayLength() {
        return 0;
    }
    arrayBufferByteLength() {
        return 0;
    }
    getOwnProperties(_generatePreview, _nonIndexedPropertiesOnly) {
        return this.getAllProperties(false, _generatePreview, _nonIndexedPropertiesOnly);
    }
    async getAllProperties(_accessorPropertiesOnly, _generatePreview, _nonIndexedPropertiesOnly) {
        const { objectId } = this.extensionObject;
        if (objectId) {
            assertNotNullOrUndefined(this.plugin.getProperties);
            const extensionObjectProperties = await this.plugin.getProperties(objectId);
            const properties = await Promise.all(extensionObjectProperties.map(async (p) => new RemoteObjectProperty(p.name, await wrapRemoteObject(this.callFrame, p.value, this.plugin))));
            return { properties, internalProperties: null };
        }
        return { properties: null, internalProperties: null };
    }
    release() {
        const { objectId } = this.extensionObject;
        if (objectId) {
            assertNotNullOrUndefined(this.plugin.releaseObject);
            void this.plugin.releaseObject(objectId);
        }
    }
    debuggerModel() {
        return this.callFrame.debuggerModel;
    }
    runtimeModel() {
        return this.callFrame.debuggerModel.runtimeModel();
    }
    isLinearMemoryInspectable() {
        return this.extensionObject.linearMemoryAddress !== undefined;
    }
}
class DebuggerLanguagePluginManager {
    #workspace;
    #debuggerWorkspaceBinding;
    #plugins;
    #debuggerModelToData;
    #rawModuleHandles;
    callFrameByStopId = new Map();
    stopIdByCallFrame = new Map();
    nextStopId = 0n;
    constructor(targetManager, workspace, debuggerWorkspaceBinding) {
        this.#workspace = workspace;
        this.#debuggerWorkspaceBinding = debuggerWorkspaceBinding;
        this.#plugins = [];
        this.#debuggerModelToData = new Map();
        targetManager.observeModels(DebuggerModel, this);
        this.#rawModuleHandles = new Map();
    }
    async evaluateOnCallFrame(callFrame, options) {
        const { script } = callFrame;
        const { expression, returnByValue, throwOnSideEffect } = options;
        const { plugin } = await this.rawModuleIdAndPluginForScript(script);
        if (!plugin) {
            return null;
        }
        const location = getRawLocation(callFrame);
        const sourceLocations = await plugin.rawLocationToSourceLocation(location);
        if (sourceLocations.length === 0) {
            return null;
        }
        if (returnByValue) {
            return { error: 'Cannot return by value' };
        }
        if (throwOnSideEffect) {
            return { error: 'Cannot guarantee side-effect freedom' };
        }
        try {
            const object = await plugin.evaluate(expression, location, this.stopIdForCallFrame(callFrame));
            if (object) {
                return { object: await wrapRemoteObject(callFrame, object, plugin) };
            }
            return { object: new LocalJSONObject(undefined) };
        }
        catch (error) {
            if (error instanceof FormattingError) {
                const { exception: object, exceptionDetails } = error;
                return { object, exceptionDetails };
            }
            const { exception: object, exceptionDetails } = FormattingError.makeLocal(callFrame, error.message);
            return { object, exceptionDetails };
        }
    }
    stopIdForCallFrame(callFrame) {
        let stopId = this.stopIdByCallFrame.get(callFrame);
        if (stopId !== undefined) {
            return stopId;
        }
        stopId = this.nextStopId++;
        this.stopIdByCallFrame.set(callFrame, stopId);
        this.callFrameByStopId.set(stopId, callFrame);
        return stopId;
    }
    callFrameForStopId(stopId) {
        return this.callFrameByStopId.get(stopId);
    }
    modelAdded(debuggerModel) {
        this.#debuggerModelToData.set(debuggerModel, new ModelData$1(debuggerModel, this.#workspace));
        debuggerModel.addEventListener(Events$5.GlobalObjectCleared, this.globalObjectCleared, this);
        debuggerModel.addEventListener(Events$5.ParsedScriptSource, this.parsedScriptSource, this);
        debuggerModel.addEventListener(Events$5.DebuggerResumed, this.debuggerResumed, this);
        debuggerModel.setEvaluateOnCallFrameCallback(this.evaluateOnCallFrame.bind(this));
    }
    modelRemoved(debuggerModel) {
        debuggerModel.removeEventListener(Events$5.GlobalObjectCleared, this.globalObjectCleared, this);
        debuggerModel.removeEventListener(Events$5.ParsedScriptSource, this.parsedScriptSource, this);
        debuggerModel.removeEventListener(Events$5.DebuggerResumed, this.debuggerResumed, this);
        debuggerModel.setEvaluateOnCallFrameCallback(null);
        const modelData = this.#debuggerModelToData.get(debuggerModel);
        if (modelData) {
            modelData.dispose();
            this.#debuggerModelToData.delete(debuggerModel);
        }
        this.#rawModuleHandles.forEach((rawModuleHandle, rawModuleId) => {
            const scripts = rawModuleHandle.scripts.filter(script => script.debuggerModel !== debuggerModel);
            if (scripts.length === 0) {
                rawModuleHandle.plugin.removeRawModule(rawModuleId).catch(error => {
                    Console.instance().error(i18nString$x(UIStrings$M.errorInDebuggerLanguagePlugin, { PH1: error.message }),  false);
                });
                this.#rawModuleHandles.delete(rawModuleId);
            }
            else {
                rawModuleHandle.scripts = scripts;
            }
        });
    }
    globalObjectCleared(event) {
        const debuggerModel = event.data;
        this.modelRemoved(debuggerModel);
        this.modelAdded(debuggerModel);
    }
    addPlugin(plugin) {
        this.#plugins.push(plugin);
        for (const debuggerModel of this.#debuggerModelToData.keys()) {
            for (const script of debuggerModel.scripts()) {
                if (this.hasPluginForScript(script)) {
                    continue;
                }
                this.parsedScriptSource({ data: script });
            }
        }
    }
    removePlugin(plugin) {
        this.#plugins = this.#plugins.filter(p => p !== plugin);
        const scripts = new Set();
        this.#rawModuleHandles.forEach((rawModuleHandle, rawModuleId) => {
            if (rawModuleHandle.plugin !== plugin) {
                return;
            }
            rawModuleHandle.scripts.forEach(script => scripts.add(script));
            this.#rawModuleHandles.delete(rawModuleId);
        });
        for (const script of scripts) {
            const modelData = this.#debuggerModelToData.get(script.debuggerModel);
            modelData.removeScript(script);
            this.parsedScriptSource({ data: script });
        }
    }
    hasPluginForScript(script) {
        const rawModuleId = rawModuleIdForScript(script);
        const rawModuleHandle = this.#rawModuleHandles.get(rawModuleId);
        return rawModuleHandle?.scripts.includes(script) ?? false;
    }
    async rawModuleIdAndPluginForScript(script) {
        const rawModuleId = rawModuleIdForScript(script);
        const rawModuleHandle = this.#rawModuleHandles.get(rawModuleId);
        if (rawModuleHandle) {
            await rawModuleHandle.addRawModulePromise;
            if (rawModuleHandle === this.#rawModuleHandles.get(rawModuleId)) {
                return { rawModuleId, plugin: rawModuleHandle.plugin };
            }
        }
        return { rawModuleId, plugin: null };
    }
    uiSourceCodeForURL(debuggerModel, url) {
        const modelData = this.#debuggerModelToData.get(debuggerModel);
        if (modelData) {
            return modelData.getProject().uiSourceCodeForURL(url);
        }
        return null;
    }
    async rawLocationToUILocation(rawLocation) {
        const script = rawLocation.script();
        if (!script) {
            return null;
        }
        const { rawModuleId, plugin } = await this.rawModuleIdAndPluginForScript(script);
        if (!plugin) {
            return null;
        }
        const pluginLocation = {
            rawModuleId,
            codeOffset: rawLocation.columnNumber - (script.codeOffset() || 0),
            inlineFrameIndex: rawLocation.inlineFrameIndex,
        };
        try {
            const sourceLocations = await plugin.rawLocationToSourceLocation(pluginLocation);
            for (const sourceLocation of sourceLocations) {
                const uiSourceCode = this.uiSourceCodeForURL(script.debuggerModel, sourceLocation.sourceFileURL);
                if (!uiSourceCode) {
                    continue;
                }
                return uiSourceCode.uiLocation(sourceLocation.lineNumber, sourceLocation.columnNumber >= 0 ? sourceLocation.columnNumber : undefined);
            }
        }
        catch (error) {
            Console.instance().error(i18nString$x(UIStrings$M.errorInDebuggerLanguagePlugin, { PH1: error.message }),  false);
        }
        return null;
    }
    uiLocationToRawLocationRanges(uiSourceCode, lineNumber, columnNumber = -1) {
        const locationPromises = [];
        this.scriptsForUISourceCode(uiSourceCode).forEach(script => {
            const rawModuleId = rawModuleIdForScript(script);
            const rawModuleHandle = this.#rawModuleHandles.get(rawModuleId);
            if (!rawModuleHandle) {
                return;
            }
            const { plugin } = rawModuleHandle;
            locationPromises.push(getLocations(rawModuleId, plugin, script));
        });
        if (locationPromises.length === 0) {
            return Promise.resolve(null);
        }
        return Promise.all(locationPromises).then(locations => locations.flat()).catch(error => {
            Console.instance().error(i18nString$x(UIStrings$M.errorInDebuggerLanguagePlugin, { PH1: error.message }),  false);
            return null;
        });
        async function getLocations(rawModuleId, plugin, script) {
            const pluginLocation = { rawModuleId, sourceFileURL: uiSourceCode.url(), lineNumber, columnNumber };
            const rawLocations = await plugin.sourceLocationToRawLocation(pluginLocation);
            if (!rawLocations) {
                return [];
            }
            return rawLocations.map(m => ({
                start: new Location$1(script.debuggerModel, script.scriptId, 0, Number(m.startOffset) + (script.codeOffset() || 0)),
                end: new Location$1(script.debuggerModel, script.scriptId, 0, Number(m.endOffset) + (script.codeOffset() || 0)),
            }));
        }
    }
    async uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber) {
        const locationRanges = await this.uiLocationToRawLocationRanges(uiSourceCode, lineNumber, columnNumber);
        if (!locationRanges) {
            return null;
        }
        return locationRanges.map(({ start }) => start);
    }
    async uiLocationRangeToRawLocationRanges(uiSourceCode, textRange) {
        const locationRangesPromises = [];
        for (let line = textRange.startLine; line <= textRange.endLine; ++line) {
            locationRangesPromises.push(this.uiLocationToRawLocationRanges(uiSourceCode, line));
        }
        const ranges = [];
        for (const locationRanges of await Promise.all(locationRangesPromises)) {
            if (locationRanges === null) {
                return null;
            }
            for (const range of locationRanges) {
                const [startLocation, endLocation] = await Promise.all([
                    this.rawLocationToUILocation(range.start),
                    this.rawLocationToUILocation(range.end),
                ]);
                if (startLocation === null || endLocation === null) {
                    continue;
                }
                const overlap = textRange.intersection(new TextRange(startLocation.lineNumber, startLocation.columnNumber ?? 0, endLocation.lineNumber, endLocation.columnNumber ?? Infinity));
                if (!overlap.isEmpty()) {
                    ranges.push(range);
                }
            }
        }
        return ranges;
    }
    async translateRawFramesStep(rawFrames, translatedFrames, target) {
        const frame = rawFrames[0];
        const script = target.model(DebuggerModel)?.scriptForId(frame.scriptId ?? '');
        if (!script) {
            return false;
        }
        const functionInfo = await this.getFunctionInfo(script, frame);
        if (!functionInfo) {
            return false;
        }
        rawFrames.shift();
        if ('frames' in functionInfo && functionInfo.frames.length) {
            const framePromises = functionInfo.frames.map(async ({ name }, index) => {
                const rawLocation = new Location$1(script.debuggerModel, script.scriptId, frame.lineNumber, frame.columnNumber, index);
                const uiLocation = await this.rawLocationToUILocation(rawLocation);
                return translatedFromUILocation(uiLocation, name, frame);
            });
            translatedFrames.push(await Promise.all(framePromises));
            return true;
        }
        const uiLocation = await this.#debuggerWorkspaceBinding.rawLocationToUILocation(new Location$1(script.debuggerModel, script.scriptId, frame.lineNumber, frame.columnNumber));
        const mappedFrame = translatedFromUILocation(uiLocation, frame.functionName, frame);
        if ('missingSymbolFiles' in functionInfo && functionInfo.missingSymbolFiles.length) {
            translatedFrames.push([{
                    ...mappedFrame,
                    missingDebugInfo: {
                        type: "PARTIAL_INFO" ,
                        missingDebugFiles: functionInfo.missingSymbolFiles,
                    },
                }]);
        }
        else {
            translatedFrames.push([{
                    ...mappedFrame,
                    missingDebugInfo: {
                        type: "NO_INFO" ,
                    },
                }]);
        }
        return true;
        function translatedFromUILocation(uiLocation, name, fallback) {
            if (uiLocation) {
                return {
                    uiSourceCode: uiLocation.uiSourceCode,
                    name,
                    line: uiLocation.lineNumber,
                    column: uiLocation.columnNumber ?? -1,
                };
            }
            return {
                url: fallback.url,
                name: fallback.functionName,
                line: fallback.lineNumber,
                column: fallback.columnNumber,
            };
        }
    }
    scriptsForUISourceCode(uiSourceCode) {
        for (const modelData of this.#debuggerModelToData.values()) {
            const scripts = modelData.uiSourceCodeToScripts.get(uiSourceCode);
            if (scripts) {
                return scripts;
            }
        }
        return [];
    }
    setDebugInfoURL(script, externalURL) {
        if (this.hasPluginForScript(script)) {
            return;
        }
        script.debugSymbols = { type: "ExternalDWARF" , externalURL };
        this.parsedScriptSource({ data: script });
        void script.debuggerModel.setDebugInfoURL(script, externalURL);
    }
    parsedScriptSource(event) {
        const script = event.data;
        if (!script.sourceURL) {
            return;
        }
        for (const plugin of this.#plugins) {
            if (!plugin.handleScript(script)) {
                continue;
            }
            const rawModuleId = rawModuleIdForScript(script);
            let rawModuleHandle = this.#rawModuleHandles.get(rawModuleId);
            if (!rawModuleHandle) {
                const sourceFileURLsPromise = (async () => {
                    const console = Console.instance();
                    const url = script.sourceURL;
                    const symbolsUrl = (script.debugSymbols?.externalURL) || '';
                    if (symbolsUrl) {
                        console.log(i18nString$x(UIStrings$M.loadingDebugSymbolsForVia, { PH1: plugin.name, PH2: url, PH3: symbolsUrl }));
                    }
                    else {
                        console.log(i18nString$x(UIStrings$M.loadingDebugSymbolsFor, { PH1: plugin.name, PH2: url }));
                    }
                    try {
                        const code = (!symbolsUrl && schemeIs(url, 'wasm:')) ? await script.getWasmBytecode() : undefined;
                        const addModuleResult = await plugin.addRawModule(rawModuleId, symbolsUrl, { url, code });
                        if (rawModuleHandle !== this.#rawModuleHandles.get(rawModuleId)) {
                            return [];
                        }
                        if ('missingSymbolFiles' in addModuleResult) {
                            const initiator = plugin.createPageResourceLoadInitiator();
                            const missingSymbolFiles = addModuleResult.missingSymbolFiles.map(resource => {
                                const resourceUrl = resource;
                                return { resourceUrl, initiator };
                            });
                            return { missingSymbolFiles };
                        }
                        const sourceFileURLs = addModuleResult;
                        if (sourceFileURLs.length === 0) {
                            console.warn(i18nString$x(UIStrings$M.loadedDebugSymbolsForButDidnt, { PH1: plugin.name, PH2: url }));
                        }
                        else {
                            console.log(i18nString$x(UIStrings$M.loadedDebugSymbolsForFound, { PH1: plugin.name, PH2: url, PH3: sourceFileURLs.length }));
                        }
                        return sourceFileURLs;
                    }
                    catch (error) {
                        console.error(i18nString$x(UIStrings$M.failedToLoadDebugSymbolsFor, { PH1: plugin.name, PH2: url, PH3: error.message }),
                         false);
                        this.#rawModuleHandles.delete(rawModuleId);
                        return [];
                    }
                })();
                rawModuleHandle = { rawModuleId, plugin, scripts: [script], addRawModulePromise: sourceFileURLsPromise };
                this.#rawModuleHandles.set(rawModuleId, rawModuleHandle);
            }
            else {
                rawModuleHandle.scripts.push(script);
            }
            void rawModuleHandle.addRawModulePromise.then(sourceFileURLs => {
                if (script.debuggerModel.scriptForId(script.scriptId) === script) {
                    const modelData = this.#debuggerModelToData.get(script.debuggerModel);
                    if (modelData && Array.isArray(sourceFileURLs)) {
                        modelData.addSourceFiles(script, sourceFileURLs);
                    }
                    void this.#debuggerWorkspaceBinding.updateLocations(script);
                }
            });
            return;
        }
    }
    debuggerResumed(event) {
        const resumedFrames = Array.from(this.callFrameByStopId.values()).filter(callFrame => callFrame.debuggerModel === event.data);
        for (const callFrame of resumedFrames) {
            const stopId = this.stopIdByCallFrame.get(callFrame);
            assertNotNullOrUndefined(stopId);
            this.stopIdByCallFrame.delete(callFrame);
            this.callFrameByStopId.delete(stopId);
        }
    }
    getSourcesForScript(script) {
        const rawModuleId = rawModuleIdForScript(script);
        const rawModuleHandle = this.#rawModuleHandles.get(rawModuleId);
        if (rawModuleHandle) {
            return rawModuleHandle.addRawModulePromise;
        }
        return Promise.resolve(undefined);
    }
    async resolveScopeChain(callFrame) {
        const script = callFrame.script;
        const { rawModuleId, plugin } = await this.rawModuleIdAndPluginForScript(script);
        if (!plugin) {
            return null;
        }
        const location = {
            rawModuleId,
            codeOffset: callFrame.location().columnNumber - (script.codeOffset() || 0),
            inlineFrameIndex: callFrame.inlineFrameIndex,
        };
        const stopId = this.stopIdForCallFrame(callFrame);
        try {
            const sourceMapping = await plugin.rawLocationToSourceLocation(location);
            if (sourceMapping.length === 0) {
                return null;
            }
            const scopes = new Map();
            const variables = await plugin.listVariablesInScope(location);
            for (const variable of variables || []) {
                let scope = scopes.get(variable.scope);
                if (!scope) {
                    const { type, typeName, icon } = await plugin.getScopeInfo(variable.scope);
                    scope = new SourceScope(callFrame, stopId, type, typeName, icon, plugin);
                    scopes.set(variable.scope, scope);
                }
                scope.object().variables.push(variable);
            }
            return Array.from(scopes.values());
        }
        catch (error) {
            Console.instance().error(i18nString$x(UIStrings$M.errorInDebuggerLanguagePlugin, { PH1: error.message }),  false);
            return null;
        }
    }
    async getFunctionInfo(script, location) {
        const { rawModuleId, plugin } = await this.rawModuleIdAndPluginForScript(script);
        if (!plugin) {
            return null;
        }
        const rawLocation = {
            rawModuleId,
            codeOffset: location.columnNumber - (script.codeOffset() || 0),
            inlineFrameIndex: 0,
        };
        try {
            const functionInfo = await plugin.getFunctionInfo(rawLocation);
            if ('missingSymbolFiles' in functionInfo) {
                const initiator = plugin.createPageResourceLoadInitiator();
                const missingSymbolFiles = functionInfo.missingSymbolFiles.map(resource => {
                    const resourceUrl = resource;
                    return { resourceUrl, initiator };
                });
                return { missingSymbolFiles, ...('frames' in functionInfo && { frames: functionInfo.frames }) };
            }
            return functionInfo;
        }
        catch (error) {
            Console.instance().warn(i18nString$x(UIStrings$M.errorInDebuggerLanguagePlugin, { PH1: error.message }));
            return { frames: [] };
        }
    }
    async getInlinedFunctionRanges(rawLocation) {
        const script = rawLocation.script();
        if (!script) {
            return [];
        }
        const { rawModuleId, plugin } = await this.rawModuleIdAndPluginForScript(script);
        if (!plugin) {
            return [];
        }
        const pluginLocation = {
            rawModuleId,
            codeOffset: rawLocation.columnNumber - (script.codeOffset() || 0),
        };
        try {
            const locations = await plugin.getInlinedFunctionRanges(pluginLocation);
            return locations.map(m => ({
                start: new Location$1(script.debuggerModel, script.scriptId, 0, Number(m.startOffset) + (script.codeOffset() || 0)),
                end: new Location$1(script.debuggerModel, script.scriptId, 0, Number(m.endOffset) + (script.codeOffset() || 0)),
            }));
        }
        catch (error) {
            Console.instance().warn(i18nString$x(UIStrings$M.errorInDebuggerLanguagePlugin, { PH1: error.message }));
            return [];
        }
    }
    async getInlinedCalleesRanges(rawLocation) {
        const script = rawLocation.script();
        if (!script) {
            return [];
        }
        const { rawModuleId, plugin } = await this.rawModuleIdAndPluginForScript(script);
        if (!plugin) {
            return [];
        }
        const pluginLocation = {
            rawModuleId,
            codeOffset: rawLocation.columnNumber - (script.codeOffset() || 0),
        };
        try {
            const locations = await plugin.getInlinedCalleesRanges(pluginLocation);
            return locations.map(m => ({
                start: new Location$1(script.debuggerModel, script.scriptId, 0, Number(m.startOffset) + (script.codeOffset() || 0)),
                end: new Location$1(script.debuggerModel, script.scriptId, 0, Number(m.endOffset) + (script.codeOffset() || 0)),
            }));
        }
        catch (error) {
            Console.instance().warn(i18nString$x(UIStrings$M.errorInDebuggerLanguagePlugin, { PH1: error.message }));
            return [];
        }
    }
    async getMappedLines(uiSourceCode) {
        const rawModuleIds = await Promise.all(this.scriptsForUISourceCode(uiSourceCode).map(s => this.rawModuleIdAndPluginForScript(s)));
        let mappedLines = null;
        for (const { rawModuleId, plugin } of rawModuleIds) {
            if (!plugin) {
                continue;
            }
            const lines = await plugin.getMappedLines(rawModuleId, uiSourceCode.url());
            if (lines === undefined) {
                continue;
            }
            if (mappedLines === null) {
                mappedLines = new Set(lines);
            }
            else {
                lines.forEach(l => mappedLines.add(l));
            }
        }
        return mappedLines;
    }
}
let ModelData$1 = class ModelData {
    project;
    uiSourceCodeToScripts;
    constructor(debuggerModel, workspace) {
        this.project = new ContentProviderBasedProject(workspace, 'language_plugins::' + debuggerModel.target().id(), projectTypes.Network, '', false );
        NetworkProject.setTargetForProject(this.project, debuggerModel.target());
        this.uiSourceCodeToScripts = new Map();
    }
    addSourceFiles(script, urls) {
        const initiator = script.createPageResourceLoadInitiator();
        for (const url of urls) {
            let uiSourceCode = this.project.uiSourceCodeForURL(url);
            if (!uiSourceCode) {
                uiSourceCode = this.project.createUISourceCode(url, resourceTypes.SourceMapScript);
                NetworkProject.setInitialFrameAttribution(uiSourceCode, script.frameId);
                this.uiSourceCodeToScripts.set(uiSourceCode, [script]);
                const contentProvider = new CompilerSourceMappingContentProvider(url, resourceTypes.SourceMapScript, initiator);
                const mimeType = ResourceType.mimeFromURL(url) || 'text/javascript';
                this.project.addUISourceCodeWithProvider(uiSourceCode, contentProvider, null, mimeType);
            }
            else {
                const scripts = this.uiSourceCodeToScripts.get(uiSourceCode);
                if (!scripts.includes(script)) {
                    scripts.push(script);
                }
            }
        }
    }
    removeScript(script) {
        this.uiSourceCodeToScripts.forEach((scripts, uiSourceCode) => {
            scripts = scripts.filter(s => s !== script);
            if (scripts.length === 0) {
                this.uiSourceCodeToScripts.delete(uiSourceCode);
                this.project.removeUISourceCode(uiSourceCode.url());
            }
            else {
                this.uiSourceCodeToScripts.set(uiSourceCode, scripts);
            }
        });
    }
    dispose() {
        this.project.dispose();
    }
    getProject() {
        return this.project;
    }
};

// Copyright 2012 The Chromium Authors
class DefaultScriptMapping {
    #debuggerWorkspaceBinding;
    #project;
    #eventListeners;
    #uiSourceCodeToScript;
    #scriptToUISourceCode;
    constructor(debuggerModel, workspace, debuggerWorkspaceBinding) {
        defaultScriptMappings.add(this);
        this.#debuggerWorkspaceBinding = debuggerWorkspaceBinding;
        this.#project = new ContentProviderBasedProject(workspace, 'debugger:' + debuggerModel.target().id(), projectTypes.Debugger, '', true );
        this.#eventListeners = [
            debuggerModel.addEventListener(Events$5.GlobalObjectCleared, this.globalObjectCleared, this),
            debuggerModel.addEventListener(Events$5.ParsedScriptSource, this.parsedScriptSource, this),
            debuggerModel.addEventListener(Events$5.DiscardedAnonymousScriptSource, this.discardedScriptSource, this),
        ];
        this.#uiSourceCodeToScript = new Map();
        this.#scriptToUISourceCode = new Map();
    }
    static createV8ScriptURL(script) {
        const name = ParsedURL.extractName(script.sourceURL);
        const url = 'debugger:///VM' + script.scriptId + (name ? ' ' + name : '');
        return url;
    }
    static scriptForUISourceCode(uiSourceCode) {
        for (const defaultScriptMapping of defaultScriptMappings) {
            const script = defaultScriptMapping.#uiSourceCodeToScript.get(uiSourceCode);
            if (script !== undefined) {
                return script;
            }
        }
        return null;
    }
    uiSourceCodeForScript(script) {
        return this.#scriptToUISourceCode.get(script) ?? null;
    }
    rawLocationToUILocation(rawLocation) {
        const script = rawLocation.script();
        if (!script) {
            return null;
        }
        const uiSourceCode = this.#scriptToUISourceCode.get(script);
        if (!uiSourceCode) {
            return null;
        }
        const { lineNumber, columnNumber } = script.rawLocationToRelativeLocation(rawLocation);
        return uiSourceCode.uiLocation(lineNumber, columnNumber);
    }
    uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber) {
        const script = this.#uiSourceCodeToScript.get(uiSourceCode);
        if (!script) {
            return [];
        }
        ({ lineNumber, columnNumber } = script.relativeLocationToRawLocation({ lineNumber, columnNumber }));
        return [script.debuggerModel.createRawLocation(script, lineNumber, columnNumber ?? 0)];
    }
    uiLocationRangeToRawLocationRanges(uiSourceCode, { startLine, startColumn, endLine, endColumn }) {
        const script = this.#uiSourceCodeToScript.get(uiSourceCode);
        if (!script) {
            return [];
        }
        ({ lineNumber: startLine, columnNumber: startColumn } =
            script.relativeLocationToRawLocation({ lineNumber: startLine, columnNumber: startColumn }));
        ({ lineNumber: endLine, columnNumber: endColumn } =
            script.relativeLocationToRawLocation({ lineNumber: endLine, columnNumber: endColumn }));
        const start = script.debuggerModel.createRawLocation(script, startLine, startColumn);
        const end = script.debuggerModel.createRawLocation(script, endLine, endColumn);
        return [{ start, end }];
    }
    parsedScriptSource(event) {
        const script = event.data;
        const url = DefaultScriptMapping.createV8ScriptURL(script);
        const uiSourceCode = this.#project.createUISourceCode(url, resourceTypes.Script);
        if (script.isBreakpointCondition) {
            uiSourceCode.markAsUnconditionallyIgnoreListed();
        }
        this.#uiSourceCodeToScript.set(uiSourceCode, script);
        this.#scriptToUISourceCode.set(script, uiSourceCode);
        this.#project.addUISourceCodeWithProvider(uiSourceCode, script, null, 'text/javascript');
        void this.#debuggerWorkspaceBinding.updateLocations(script);
    }
    discardedScriptSource(event) {
        const script = event.data;
        const uiSourceCode = this.#scriptToUISourceCode.get(script);
        if (uiSourceCode === undefined) {
            return;
        }
        this.#scriptToUISourceCode.delete(script);
        this.#uiSourceCodeToScript.delete(uiSourceCode);
        this.#project.removeUISourceCode(uiSourceCode.url());
    }
    globalObjectCleared() {
        this.#scriptToUISourceCode.clear();
        this.#uiSourceCodeToScript.clear();
        this.#project.reset();
    }
    dispose() {
        defaultScriptMappings.delete(this);
        removeEventListeners(this.#eventListeners);
        this.globalObjectCleared();
        this.#project.dispose();
    }
}
const defaultScriptMappings = new Set();

// Copyright 2012 The Chromium Authors
const UIStrings$L = {
    liveEditFailed: '`LiveEdit` failed: {PH1}',
    liveEditCompileFailed: '`LiveEdit` compile failed: {PH1}',
};
const str_$K = registerUIStrings('models/bindings/ResourceScriptMapping.ts', UIStrings$L);
const i18nString$w = getLocalizedString.bind(undefined, str_$K);
class ResourceScriptMapping {
    debuggerModel;
    #workspace;
    debuggerWorkspaceBinding;
    #uiSourceCodeToScriptFile;
    #projects;
    #scriptToUISourceCode;
    #eventListeners;
    constructor(debuggerModel, workspace, debuggerWorkspaceBinding) {
        this.debuggerModel = debuggerModel;
        this.#workspace = workspace;
        this.debuggerWorkspaceBinding = debuggerWorkspaceBinding;
        this.#uiSourceCodeToScriptFile = new Map();
        this.#projects = new Map();
        this.#scriptToUISourceCode = new Map();
        const runtimeModel = debuggerModel.runtimeModel();
        this.#eventListeners = [
            this.debuggerModel.addEventListener(Events$5.ParsedScriptSource, event => this.addScript(event.data), this),
            this.debuggerModel.addEventListener(Events$5.GlobalObjectCleared, this.globalObjectCleared, this),
            runtimeModel.addEventListener(Events$9.ExecutionContextDestroyed, this.executionContextDestroyed, this),
            runtimeModel.target().targetManager().addEventListener("InspectedURLChanged" , this.inspectedURLChanged, this),
        ];
    }
    project(script) {
        const prefix = script.isContentScript() ? 'js:extensions:' : 'js::';
        const projectId = prefix + this.debuggerModel.target().id() + ':' + script.frameId;
        let project = this.#projects.get(projectId);
        if (!project) {
            const projectType = script.isContentScript() ? projectTypes.ContentScripts :
                projectTypes.Network;
            project = new ContentProviderBasedProject(this.#workspace, projectId, projectType, '' , false );
            NetworkProject.setTargetForProject(project, this.debuggerModel.target());
            this.#projects.set(projectId, project);
        }
        return project;
    }
    uiSourceCodeForScript(script) {
        return this.#scriptToUISourceCode.get(script) ?? null;
    }
    rawLocationToUILocation(rawLocation) {
        const script = rawLocation.script();
        if (!script) {
            return null;
        }
        const uiSourceCode = this.#scriptToUISourceCode.get(script);
        if (!uiSourceCode) {
            return null;
        }
        const scriptFile = this.#uiSourceCodeToScriptFile.get(uiSourceCode);
        if (!scriptFile) {
            return null;
        }
        if ((scriptFile.hasDivergedFromVM() && !scriptFile.isMergingToVM()) || scriptFile.isDivergingFromVM()) {
            return null;
        }
        if (scriptFile.script !== script) {
            return null;
        }
        const { lineNumber, columnNumber = 0 } = rawLocation;
        return uiSourceCode.uiLocation(lineNumber, columnNumber);
    }
    uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber) {
        const scriptFile = this.#uiSourceCodeToScriptFile.get(uiSourceCode);
        if (!scriptFile) {
            return [];
        }
        const { script } = scriptFile;
        if (!script) {
            return [];
        }
        return [this.debuggerModel.createRawLocation(script, lineNumber, columnNumber)];
    }
    uiLocationRangeToRawLocationRanges(uiSourceCode, { startLine, startColumn, endLine, endColumn }) {
        const scriptFile = this.#uiSourceCodeToScriptFile.get(uiSourceCode);
        if (!scriptFile) {
            return null;
        }
        const { script } = scriptFile;
        if (!script) {
            return null;
        }
        const start = this.debuggerModel.createRawLocation(script, startLine, startColumn);
        const end = this.debuggerModel.createRawLocation(script, endLine, endColumn);
        return [{ start, end }];
    }
    inspectedURLChanged(event) {
        for (let target = this.debuggerModel.target(); target !== event.data; target = target.parentTarget()) {
            if (target === null) {
                return;
            }
        }
        for (const script of Array.from(this.#scriptToUISourceCode.keys())) {
            this.removeScripts([script]);
            this.addScript(script);
        }
    }
    async functionBoundsAtRawLocation(rawLocation) {
        const script = rawLocation.script();
        if (!script) {
            return null;
        }
        const uiSourceCode = this.#scriptToUISourceCode.get(script);
        if (!uiSourceCode) {
            return null;
        }
        const scopeTreeAndText = script ? await scopeTreeForScript(script) : null;
        if (!scopeTreeAndText) {
            return null;
        }
        const offset = scopeTreeAndText.text.offsetFromPosition(rawLocation.lineNumber, rawLocation.columnNumber);
        const results = [];
        (function walk(nodes) {
            for (const node of nodes) {
                if (!(offset >= node.start && offset < node.end)) {
                    continue;
                }
                results.push(node);
                walk(node.children);
            }
        })([scopeTreeAndText.scopeTree]);
        const result = results.findLast(node => node.kind === 2  ||
            node.kind === 4 );
        if (!result) {
            return null;
        }
        const startPosition = scopeTreeAndText.text.positionFromOffset(result.start);
        const endPosition = scopeTreeAndText.text.positionFromOffset(result.end);
        const name = '';
        const range = new TextRange(startPosition.lineNumber, startPosition.columnNumber, endPosition.lineNumber, endPosition.columnNumber);
        return new UIFunctionBounds(uiSourceCode, range, name);
    }
    addScript(script) {
        if (script.isLiveEdit() || script.isBreakpointCondition) {
            return;
        }
        let url = script.sourceURL;
        if (!url) {
            return;
        }
        if (script.hasSourceURL) {
            url = SourceMapManager.resolveRelativeSourceURL(script.debuggerModel.target(), url);
        }
        else {
            if (script.isInlineScript()) {
                return;
            }
            if (script.isContentScript()) {
                const parsedURL = new ParsedURL(url);
                if (!parsedURL.isValid) {
                    return;
                }
            }
        }
        const project = this.project(script);
        const oldUISourceCode = project.uiSourceCodeForURL(url);
        if (oldUISourceCode) {
            const oldScriptFile = this.#uiSourceCodeToScriptFile.get(oldUISourceCode);
            if (oldScriptFile?.script) {
                this.removeScripts([oldScriptFile.script]);
            }
        }
        const originalContentProvider = script.originalContentProvider();
        const uiSourceCode = project.createUISourceCode(url, originalContentProvider.contentType());
        NetworkProject.setInitialFrameAttribution(uiSourceCode, script.frameId);
        const metadata = metadataForURL(this.debuggerModel.target(), script.frameId, url);
        const scriptFile = new ResourceScriptFile(this, uiSourceCode, script);
        this.#uiSourceCodeToScriptFile.set(uiSourceCode, scriptFile);
        this.#scriptToUISourceCode.set(script, uiSourceCode);
        const mimeType = script.isWasm() ? 'application/wasm' : 'text/javascript';
        project.addUISourceCodeWithProvider(uiSourceCode, originalContentProvider, metadata, mimeType);
        void this.debuggerWorkspaceBinding.updateLocations(script);
    }
    scriptFile(uiSourceCode) {
        return this.#uiSourceCodeToScriptFile.get(uiSourceCode) || null;
    }
    removeScripts(scripts) {
        const uiSourceCodesByProject = new Multimap();
        for (const script of scripts) {
            const uiSourceCode = this.#scriptToUISourceCode.get(script);
            if (!uiSourceCode) {
                continue;
            }
            const scriptFile = this.#uiSourceCodeToScriptFile.get(uiSourceCode);
            if (scriptFile) {
                scriptFile.dispose();
            }
            this.#uiSourceCodeToScriptFile.delete(uiSourceCode);
            this.#scriptToUISourceCode.delete(script);
            uiSourceCodesByProject.set(uiSourceCode.project(), uiSourceCode);
            void this.debuggerWorkspaceBinding.updateLocations(script);
        }
        for (const project of uiSourceCodesByProject.keysArray()) {
            const uiSourceCodes = uiSourceCodesByProject.get(project);
            let allInProjectRemoved = true;
            for (const projectSourceCode of project.uiSourceCodes()) {
                if (!uiSourceCodes.has(projectSourceCode)) {
                    allInProjectRemoved = false;
                    break;
                }
            }
            if (allInProjectRemoved) {
                this.#projects.delete(project.id());
                project.removeProject();
            }
            else {
                uiSourceCodes.forEach(c => project.removeUISourceCode(c.url()));
            }
        }
    }
    executionContextDestroyed(event) {
        const executionContext = event.data;
        this.removeScripts(this.debuggerModel.scriptsForExecutionContext(executionContext));
    }
    globalObjectCleared() {
        const scripts = Array.from(this.#scriptToUISourceCode.keys());
        this.removeScripts(scripts);
    }
    resetForTest() {
        this.globalObjectCleared();
    }
    dispose() {
        removeEventListeners(this.#eventListeners);
        this.globalObjectCleared();
    }
}
class ResourceScriptFile extends ObjectWrapper {
    #resourceScriptMapping;
    uiSourceCode;
    script;
    #scriptSource;
    #isDivergingFromVM;
    #hasDivergedFromVM;
    #isMergingToVM;
    #updateMutex = new Mutex();
    constructor(resourceScriptMapping, uiSourceCode, script) {
        super();
        this.#resourceScriptMapping = resourceScriptMapping;
        this.uiSourceCode = uiSourceCode;
        this.script = this.uiSourceCode.contentType().isScript() ? script : null;
        this.uiSourceCode.addEventListener(Events$2.WorkingCopyChanged, this.workingCopyChanged, this);
        this.uiSourceCode.addEventListener(Events$2.WorkingCopyCommitted, this.workingCopyCommitted, this);
    }
    isDiverged() {
        if (this.uiSourceCode.isDirty()) {
            return true;
        }
        if (!this.script) {
            return false;
        }
        if (typeof this.#scriptSource === 'undefined' || this.#scriptSource === null) {
            return false;
        }
        const workingCopy = this.uiSourceCode.workingCopy();
        if (!workingCopy) {
            return false;
        }
        if (!workingCopy.startsWith(this.#scriptSource.trimEnd())) {
            return true;
        }
        const suffix = this.uiSourceCode.workingCopy().substr(this.#scriptSource.length);
        return Boolean(suffix.length) && !suffix.match(sourceURLRegex);
    }
    workingCopyChanged() {
        void this.update();
    }
    workingCopyCommitted() {
        if (hostConfig.devToolsLiveEdit?.enabled === false) {
            return;
        }
        if (this.uiSourceCode.project().canSetFileContent()) {
            return;
        }
        if (!this.script) {
            return;
        }
        const source = this.uiSourceCode.workingCopy();
        void this.script.editSource(source).then(({ status, exceptionDetails }) => {
            void this.scriptSourceWasSet(source, status, exceptionDetails);
        });
    }
    async scriptSourceWasSet(source, status, exceptionDetails) {
        if (status === "Ok" ) {
            this.#scriptSource = source;
        }
        await this.update();
        if (status === "Ok" ) {
            return;
        }
        if (!exceptionDetails) {
            Console.instance().addMessage(i18nString$w(UIStrings$L.liveEditFailed, { PH1: getErrorText(status) }), "warning" );
            return;
        }
        const messageText = i18nString$w(UIStrings$L.liveEditCompileFailed, { PH1: exceptionDetails.text });
        this.uiSourceCode.addLineMessage("Error" , messageText, exceptionDetails.lineNumber, exceptionDetails.columnNumber);
        function getErrorText(status) {
            switch (status) {
                case "BlockedByActiveFunction" :
                    return 'Functions that are on the stack (currently being executed) can not be edited';
                case "BlockedByActiveGenerator" :
                    return 'Async functions/generators that are active can not be edited';
                case "BlockedByTopLevelEsModuleChange" :
                    return 'The top-level of ES modules can not be edited';
                case "CompileError" :
                case "Ok" :
                    throw new Error('Compile errors and Ok status must not be reported on the console');
            }
        }
    }
    async update() {
        const release = await this.#updateMutex.acquire();
        const diverged = this.isDiverged();
        if (diverged && !this.#hasDivergedFromVM) {
            await this.divergeFromVM();
        }
        else if (!diverged && this.#hasDivergedFromVM) {
            await this.mergeToVM();
        }
        release();
    }
    async divergeFromVM() {
        if (this.script) {
            this.#isDivergingFromVM = true;
            await this.#resourceScriptMapping.debuggerWorkspaceBinding.updateLocations(this.script);
            this.#isDivergingFromVM = undefined;
            this.#hasDivergedFromVM = true;
            this.dispatchEventToListeners("DidDivergeFromVM" );
        }
    }
    async mergeToVM() {
        if (this.script) {
            this.#hasDivergedFromVM = undefined;
            this.#isMergingToVM = true;
            await this.#resourceScriptMapping.debuggerWorkspaceBinding.updateLocations(this.script);
            this.#isMergingToVM = undefined;
            this.dispatchEventToListeners("DidMergeToVM" );
        }
    }
    hasDivergedFromVM() {
        return Boolean(this.#hasDivergedFromVM);
    }
    isDivergingFromVM() {
        return Boolean(this.#isDivergingFromVM);
    }
    isMergingToVM() {
        return Boolean(this.#isMergingToVM);
    }
    checkMapping() {
        if (!this.script || typeof this.#scriptSource !== 'undefined') {
            this.mappingCheckedForTest();
            return;
        }
        void this.script.requestContentData().then(content => {
            this.#scriptSource = ContentData.textOr(content, null);
            void this.update().then(() => this.mappingCheckedForTest());
        });
    }
    mappingCheckedForTest() {
    }
    dispose() {
        this.uiSourceCode.removeEventListener(Events$2.WorkingCopyChanged, this.workingCopyChanged, this);
        this.uiSourceCode.removeEventListener(Events$2.WorkingCopyCommitted, this.workingCopyCommitted, this);
    }
    addSourceMapURL(sourceMapURL) {
        if (!this.script) {
            return;
        }
        this.script.debuggerModel.setSourceMapURL(this.script, sourceMapURL);
    }
    addDebugInfoURL(debugInfoURL) {
        if (!this.script) {
            return;
        }
        const { pluginManager } = DebuggerWorkspaceBinding.instance();
        pluginManager.setDebugInfoURL(this.script, debugInfoURL);
    }
    hasSourceMapURL() {
        return Boolean(this.script?.sourceMapURL);
    }
    async missingSymbolFiles() {
        if (!this.script) {
            return null;
        }
        const { pluginManager } = this.#resourceScriptMapping.debuggerWorkspaceBinding;
        const sources = await pluginManager.getSourcesForScript(this.script);
        return sources && 'missingSymbolFiles' in sources ? sources.missingSymbolFiles : null;
    }
}

// Copyright 2014 The Chromium Authors
class DebuggerWorkspaceBinding {
    resourceMapping;
    #debuggerModelToData;
    #liveLocationPromises;
    pluginManager;
    ignoreListManager;
    workspace;
    constructor(resourceMapping, targetManager, ignoreListManager, workspace) {
        this.resourceMapping = resourceMapping;
        this.resourceMapping.debuggerWorkspaceBinding = this;
        this.ignoreListManager = ignoreListManager;
        this.workspace = workspace;
        this.#debuggerModelToData = new Map();
        targetManager.observeModels(DebuggerModel, this);
        this.ignoreListManager.addEventListener("IGNORED_SCRIPT_RANGES_UPDATED" , event => this.updateLocations(event.data));
        this.#liveLocationPromises = new Set();
        this.pluginManager = new DebuggerLanguagePluginManager(targetManager, resourceMapping.workspace, this);
    }
    setFunctionRanges(uiSourceCode, ranges) {
        for (const modelData of this.#debuggerModelToData.values()) {
            modelData.compilerMapping.setFunctionRanges(uiSourceCode, ranges);
        }
    }
    static instance(opts = { forceNew: null, resourceMapping: null, targetManager: null, ignoreListManager: null, workspace: null }) {
        const { forceNew, resourceMapping, targetManager, ignoreListManager, workspace } = opts;
        if (forceNew) {
            if (!resourceMapping || !targetManager || !ignoreListManager || !workspace) {
                throw new Error(`Unable to create DebuggerWorkspaceBinding: resourceMapping, targetManager and IgnoreLIstManager must be provided: ${new Error().stack}`);
            }
            globalInstance().set(DebuggerWorkspaceBinding, new DebuggerWorkspaceBinding(resourceMapping, targetManager, ignoreListManager, workspace));
        }
        return globalInstance().get(DebuggerWorkspaceBinding);
    }
    static removeInstance() {
        globalInstance().delete(DebuggerWorkspaceBinding);
    }
    async computeAutoStepRanges(mode, callFrame) {
        function contained(location, range) {
            const { start, end } = range;
            if (start.scriptId !== location.scriptId) {
                return false;
            }
            if (location.lineNumber < start.lineNumber || location.lineNumber > end.lineNumber) {
                return false;
            }
            if (location.lineNumber === start.lineNumber && location.columnNumber < start.columnNumber) {
                return false;
            }
            if (location.lineNumber === end.lineNumber && location.columnNumber >= end.columnNumber) {
                return false;
            }
            return true;
        }
        const rawLocation = callFrame.location();
        if (!rawLocation) {
            return [];
        }
        const pluginManager = this.pluginManager;
        let ranges = [];
        if (mode === "StepOut" ) {
            return await pluginManager.getInlinedFunctionRanges(rawLocation);
        }
        const uiLocation = await pluginManager.rawLocationToUILocation(rawLocation);
        if (uiLocation) {
            ranges = await pluginManager.uiLocationToRawLocationRanges(uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber) ||
                [];
            ranges = ranges.filter(range => contained(rawLocation, range));
            if (mode === "StepOver" ) {
                ranges = ranges.concat(await pluginManager.getInlinedCalleesRanges(rawLocation));
            }
            return ranges;
        }
        const compilerMapping = this.#debuggerModelToData.get(rawLocation.debuggerModel)?.compilerMapping;
        if (!compilerMapping) {
            return [];
        }
        ranges = compilerMapping.getLocationRangesForSameSourceLocation(rawLocation);
        ranges = ranges.filter(range => contained(rawLocation, range));
        return ranges;
    }
    modelAdded(debuggerModel) {
        debuggerModel.setBeforePausedCallback(this.shouldPause.bind(this));
        this.#debuggerModelToData.set(debuggerModel, new ModelData(debuggerModel, this));
        debuggerModel.setComputeAutoStepRangesCallback(this.computeAutoStepRanges.bind(this));
    }
    modelRemoved(debuggerModel) {
        debuggerModel.setComputeAutoStepRangesCallback(null);
        const modelData = this.#debuggerModelToData.get(debuggerModel);
        if (modelData) {
            modelData.dispose();
            this.#debuggerModelToData.delete(debuggerModel);
        }
    }
    async pendingLiveLocationChangesPromise() {
        await Promise.all(this.#liveLocationPromises);
    }
    recordLiveLocationChange(promise) {
        void promise.then(() => {
            this.#liveLocationPromises.delete(promise);
        });
        this.#liveLocationPromises.add(promise);
    }
    async updateLocations(script) {
        const stackTraceUpdatePromise = script.target()
            .model(StackTraceModel)
            ?.scriptInfoChanged(script, this.#translateRawFrames.bind(this));
        if (stackTraceUpdatePromise) {
            this.recordLiveLocationChange(stackTraceUpdatePromise);
        }
        const updatePromises = [stackTraceUpdatePromise];
        const modelData = this.#debuggerModelToData.get(script.debuggerModel);
        if (modelData) {
            const updatePromise = modelData.updateLocations(script);
            this.recordLiveLocationChange(updatePromise);
            updatePromises.push(updatePromise);
        }
        await Promise.all(updatePromises);
    }
    async createStackTraceFromProtocolRuntime(stackTrace, target) {
        const model = target.model(StackTraceModel);
        const stackTracePromise = model.createFromProtocolRuntime(stackTrace, this.#translateRawFrames.bind(this));
        this.recordLiveLocationChange(stackTracePromise);
        return await stackTracePromise;
    }
    async createStackTraceFromDebuggerPaused(pausedDetails, target) {
        const model = target.model(StackTraceModel);
        const stackTracePromise = model.createFromDebuggerPaused(pausedDetails, this.#translateRawFrames.bind(this));
        this.recordLiveLocationChange(stackTracePromise);
        return await stackTracePromise;
    }
    async createLiveLocation(rawLocation, updateDelegate, locationPool) {
        const modelData = this.#debuggerModelToData.get(rawLocation.debuggerModel);
        if (!modelData) {
            return null;
        }
        const liveLocationPromise = modelData.createLiveLocation(rawLocation, updateDelegate, locationPool);
        this.recordLiveLocationChange(liveLocationPromise);
        return await liveLocationPromise;
    }
    async createStackTraceTopFrameLiveLocation(rawLocations, updateDelegate, locationPool) {
        console.assert(rawLocations.length > 0);
        const locationPromise = StackTraceTopFrameLocation.createStackTraceTopFrameLocation(rawLocations, this, updateDelegate, locationPool);
        this.recordLiveLocationChange(locationPromise);
        return await locationPromise;
    }
    async rawLocationToUILocation(rawLocation) {
        const uiLocation = await this.pluginManager.rawLocationToUILocation(rawLocation);
        if (uiLocation) {
            return uiLocation;
        }
        const modelData = this.#debuggerModelToData.get(rawLocation.debuggerModel);
        return modelData ? modelData.rawLocationToUILocation(rawLocation) : null;
    }
    uiSourceCodeForSourceMapSourceURL(debuggerModel, url, isContentScript) {
        const modelData = this.#debuggerModelToData.get(debuggerModel);
        if (!modelData) {
            return null;
        }
        return modelData.compilerMapping.uiSourceCodeForURL(url, isContentScript);
    }
    async uiSourceCodeForSourceMapSourceURLPromise(debuggerModel, url, isContentScript) {
        const uiSourceCode = this.uiSourceCodeForSourceMapSourceURL(debuggerModel, url, isContentScript);
        return await (uiSourceCode || this.waitForUISourceCodeAdded(url, debuggerModel.target()));
    }
    async uiSourceCodeForDebuggerLanguagePluginSourceURLPromise(debuggerModel, url) {
        const uiSourceCode = this.pluginManager.uiSourceCodeForURL(debuggerModel, url);
        return await (uiSourceCode || this.waitForUISourceCodeAdded(url, debuggerModel.target()));
    }
    uiSourceCodeForScript(script) {
        const modelData = this.#debuggerModelToData.get(script.debuggerModel);
        if (!modelData) {
            return null;
        }
        return modelData.uiSourceCodeForScript(script);
    }
    waitForUISourceCodeAdded(url, target) {
        return new Promise(resolve => {
            const descriptor = this.workspace.addEventListener(Events$1.UISourceCodeAdded, event => {
                const uiSourceCode = event.data;
                if (uiSourceCode.url() === url && NetworkProject.targetForUISourceCode(uiSourceCode) === target) {
                    this.workspace.removeEventListener(Events$1.UISourceCodeAdded, descriptor.listener);
                    resolve(uiSourceCode);
                }
            });
        });
    }
    async uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber) {
        const locations = await this.pluginManager.uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber);
        if (locations) {
            return locations;
        }
        for (const modelData of this.#debuggerModelToData.values()) {
            const locations = modelData.uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber);
            if (locations.length) {
                return locations;
            }
        }
        return [];
    }
    async uiLocationRangeToRawLocationRanges(uiSourceCode, textRange) {
        const ranges = await this.pluginManager.uiLocationRangeToRawLocationRanges(uiSourceCode, textRange);
        if (ranges) {
            return ranges;
        }
        for (const modelData of this.#debuggerModelToData.values()) {
            const ranges = modelData.uiLocationRangeToRawLocationRanges(uiSourceCode, textRange);
            if (ranges) {
                return ranges;
            }
        }
        return [];
    }
    async functionBoundsAtRawLocation(rawLocation) {
        const modelData = this.#debuggerModelToData.get(rawLocation.debuggerModel);
        return modelData ? await modelData.functionBoundsAtRawLocation(rawLocation) : null;
    }
    async normalizeUILocation(uiLocation) {
        const rawLocations = await this.uiLocationToRawLocations(uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber);
        for (const location of rawLocations) {
            const uiLocationCandidate = await this.rawLocationToUILocation(location);
            if (uiLocationCandidate) {
                return uiLocationCandidate;
            }
        }
        return uiLocation;
    }
    async getMappedLines(uiSourceCode) {
        for (const modelData of this.#debuggerModelToData.values()) {
            const mappedLines = modelData.getMappedLines(uiSourceCode);
            if (mappedLines !== null) {
                return mappedLines;
            }
        }
        return await this.pluginManager.getMappedLines(uiSourceCode);
    }
    scriptFile(uiSourceCode, debuggerModel) {
        const modelData = this.#debuggerModelToData.get(debuggerModel);
        return modelData ? modelData.getResourceScriptMapping().scriptFile(uiSourceCode) : null;
    }
    scriptsForUISourceCode(uiSourceCode) {
        const scripts = new Set();
        this.pluginManager.scriptsForUISourceCode(uiSourceCode).forEach(script => scripts.add(script));
        for (const modelData of this.#debuggerModelToData.values()) {
            const resourceScriptFile = modelData.getResourceScriptMapping().scriptFile(uiSourceCode);
            if (resourceScriptFile?.script) {
                scripts.add(resourceScriptFile.script);
            }
            modelData.compilerMapping.scriptsForUISourceCode(uiSourceCode).forEach(script => scripts.add(script));
        }
        return [...scripts];
    }
    supportsConditionalBreakpoints(uiSourceCode) {
        const scripts = this.pluginManager.scriptsForUISourceCode(uiSourceCode);
        return scripts.every(script => script.isJavaScript());
    }
    resetForTest(target) {
        const debuggerModel = target.model(DebuggerModel);
        const modelData = this.#debuggerModelToData.get(debuggerModel);
        if (modelData) {
            modelData.getResourceScriptMapping().resetForTest();
        }
    }
    removeLiveLocation(location) {
        const modelData = this.#debuggerModelToData.get(location.rawLocation.debuggerModel);
        if (modelData) {
            modelData.disposeLocation(location);
        }
    }
    async shouldPause(debuggerPausedDetails, autoSteppingContext) {
        const { callFrames: [frame] } = debuggerPausedDetails;
        if (!frame) {
            return false;
        }
        const functionLocation = frame.functionLocation();
        if (!autoSteppingContext || debuggerPausedDetails.reason !== "step"  ||
            !functionLocation || !frame.script.isWasm() || !moduleSetting('wasm-auto-stepping').get() ||
            !this.pluginManager.hasPluginForScript(frame.script)) {
            return true;
        }
        const uiLocation = await this.pluginManager.rawLocationToUILocation(frame.location());
        if (uiLocation) {
            return true;
        }
        return autoSteppingContext.script() !== functionLocation.script() ||
            autoSteppingContext.columnNumber !== functionLocation.columnNumber ||
            autoSteppingContext.lineNumber !== functionLocation.lineNumber;
    }
    async #translateRawFrames(frames, target) {
        const rawFrames = frames.slice(0);
        const translatedFrames = [];
        while (rawFrames.length) {
            await this.#translateRawFramesStep(rawFrames, translatedFrames, target);
        }
        return translatedFrames;
    }
    async #translateRawFramesStep(rawFrames, translatedFrames, target) {
        if (await this.pluginManager.translateRawFramesStep(rawFrames, translatedFrames, target)) {
            return;
        }
        const modelData = this.#debuggerModelToData.get(target.model(DebuggerModel));
        if (modelData) {
            await modelData.translateRawFramesStep(rawFrames, translatedFrames);
            return;
        }
        const frame = rawFrames.shift();
        const { url, lineNumber, columnNumber, functionName } = frame;
        translatedFrames.push([{ url, line: lineNumber, column: columnNumber, name: functionName }]);
    }
}
class ModelData {
    #debuggerModel;
    #debuggerWorkspaceBinding;
    #defaultMapping;
    #resourceMapping;
    #resourceScriptMapping;
    compilerMapping;
    #locations;
    constructor(debuggerModel, debuggerWorkspaceBinding) {
        this.#debuggerModel = debuggerModel;
        this.#debuggerWorkspaceBinding = debuggerWorkspaceBinding;
        const { workspace } = debuggerWorkspaceBinding.resourceMapping;
        this.#defaultMapping = new DefaultScriptMapping(debuggerModel, workspace, debuggerWorkspaceBinding);
        this.#resourceMapping = debuggerWorkspaceBinding.resourceMapping;
        this.#resourceScriptMapping = new ResourceScriptMapping(debuggerModel, workspace, debuggerWorkspaceBinding);
        this.compilerMapping = new CompilerScriptMapping(debuggerModel, workspace, debuggerWorkspaceBinding);
        this.#locations = new Multimap();
    }
    async createLiveLocation(rawLocation, updateDelegate, locationPool) {
        console.assert(rawLocation.scriptId !== '');
        const scriptId = rawLocation.scriptId;
        const location = new Location(scriptId, rawLocation, this.#debuggerWorkspaceBinding, updateDelegate, locationPool);
        this.#locations.set(scriptId, location);
        await location.update();
        return location;
    }
    disposeLocation(location) {
        this.#locations.delete(location.scriptId, location);
    }
    async updateLocations(script) {
        const promises = [];
        for (const location of this.#locations.get(script.scriptId)) {
            promises.push(location.update());
        }
        await Promise.all(promises);
    }
    rawLocationToUILocation(rawLocation) {
        let uiLocation = this.compilerMapping.rawLocationToUILocation(rawLocation);
        uiLocation = uiLocation || this.#resourceScriptMapping.rawLocationToUILocation(rawLocation);
        uiLocation = uiLocation || this.#resourceMapping.jsLocationToUILocation(rawLocation);
        uiLocation = uiLocation || this.#defaultMapping.rawLocationToUILocation(rawLocation);
        return uiLocation;
    }
    uiSourceCodeForScript(script) {
        let uiSourceCode = null;
        uiSourceCode = uiSourceCode || this.#resourceScriptMapping.uiSourceCodeForScript(script);
        uiSourceCode = uiSourceCode || this.#resourceMapping.uiSourceCodeForScript(script);
        uiSourceCode = uiSourceCode || this.#defaultMapping.uiSourceCodeForScript(script);
        return uiSourceCode;
    }
    uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber = 0) {
        let locations = this.compilerMapping.uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber);
        locations = locations.length ?
            locations :
            this.#resourceScriptMapping.uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber);
        locations = locations.length ?
            locations :
            this.#resourceMapping.uiLocationToJSLocations(uiSourceCode, lineNumber, columnNumber);
        locations = locations.length ?
            locations :
            this.#defaultMapping.uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber);
        return locations;
    }
    uiLocationRangeToRawLocationRanges(uiSourceCode, textRange) {
        let ranges = this.compilerMapping.uiLocationRangeToRawLocationRanges(uiSourceCode, textRange);
        ranges ??= this.#resourceScriptMapping.uiLocationRangeToRawLocationRanges(uiSourceCode, textRange);
        ranges ??= this.#resourceMapping.uiLocationRangeToJSLocationRanges(uiSourceCode, textRange);
        ranges ??= this.#defaultMapping.uiLocationRangeToRawLocationRanges(uiSourceCode, textRange);
        return ranges;
    }
    async functionBoundsAtRawLocation(rawLocation) {
        let scope = null;
        scope = scope || await this.compilerMapping.functionBoundsAtRawLocation(rawLocation);
        scope = scope || await this.#resourceScriptMapping.functionBoundsAtRawLocation(rawLocation);
        scope = scope || await this.#resourceMapping.functionBoundsAtRawLocation(rawLocation);
        return scope;
    }
    async translateRawFramesStep(rawFrames, translatedFrames) {
        if (!await this.compilerMapping.translateRawFramesStep(rawFrames, translatedFrames)) {
            this.#defaultTranslateRawFramesStep(rawFrames, translatedFrames);
        }
    }
    #defaultTranslateRawFramesStep(rawFrames, translatedFrames) {
        const frame = rawFrames.shift();
        const { scriptId, url, lineNumber, columnNumber, functionName } = frame;
        const rawLocation = scriptId ? this.#debuggerModel.createRawLocationByScriptId(scriptId, lineNumber, columnNumber) :
            url ? this.#debuggerModel.createRawLocationByURL(url, lineNumber, columnNumber) :
                null;
        if (rawLocation) {
            const uiLocation = this.rawLocationToUILocation(rawLocation);
            if (uiLocation) {
                translatedFrames.push([{
                        uiSourceCode: uiLocation.uiSourceCode,
                        name: functionName,
                        line: uiLocation.lineNumber,
                        column: uiLocation.columnNumber ?? -1
                    }]);
                return;
            }
        }
        translatedFrames.push([{ url, line: lineNumber, column: columnNumber, name: functionName }]);
    }
    getMappedLines(uiSourceCode) {
        const mappedLines = this.compilerMapping.getMappedLines(uiSourceCode);
        return mappedLines;
    }
    dispose() {
        this.#debuggerModel.setBeforePausedCallback(null);
        this.compilerMapping.dispose();
        this.#resourceScriptMapping.dispose();
        this.#defaultMapping.dispose();
    }
    getResourceScriptMapping() {
        return this.#resourceScriptMapping;
    }
}
class Location extends LiveLocationWithPool {
    scriptId;
    rawLocation;
    #binding;
    constructor(scriptId, rawLocation, binding, updateDelegate, locationPool) {
        super(updateDelegate, locationPool);
        this.scriptId = scriptId;
        this.rawLocation = rawLocation;
        this.#binding = binding;
    }
    async uiLocation() {
        const debuggerModelLocation = this.rawLocation;
        return await this.#binding.rawLocationToUILocation(debuggerModelLocation);
    }
    dispose() {
        super.dispose();
        this.#binding.removeLiveLocation(this);
    }
}
class StackTraceTopFrameLocation extends LiveLocationWithPool {
    #updateScheduled;
    #current;
    #locations;
    constructor(updateDelegate, locationPool) {
        super(updateDelegate, locationPool);
        this.#updateScheduled = true;
        this.#current = null;
        this.#locations = null;
    }
    static async createStackTraceTopFrameLocation(rawLocations, binding, updateDelegate, locationPool) {
        const location = new StackTraceTopFrameLocation(updateDelegate, locationPool);
        const locationsPromises = rawLocations.map(rawLocation => binding.createLiveLocation(rawLocation, location.scheduleUpdate.bind(location), locationPool));
        location.#locations = ((await Promise.all(locationsPromises)).filter(l => !!l));
        await location.updateLocation();
        return location;
    }
    async uiLocation() {
        return this.#current ? await this.#current.uiLocation() : null;
    }
    dispose() {
        super.dispose();
        if (this.#locations) {
            for (const location of this.#locations) {
                location.dispose();
            }
        }
        this.#locations = null;
        this.#current = null;
    }
    async scheduleUpdate() {
        if (this.#updateScheduled) {
            return;
        }
        this.#updateScheduled = true;
        queueMicrotask(() => {
            void this.updateLocation();
        });
    }
    async updateLocation() {
        this.#updateScheduled = false;
        if (!this.#locations || this.#locations.length === 0) {
            return;
        }
        this.#current = this.#locations[0];
        for (const location of this.#locations) {
            const uiLocation = await location.uiLocation();
            if (!uiLocation?.isIgnoreListed()) {
                this.#current = location;
                break;
            }
        }
        void this.update();
    }
}

// Copyright 2012 The Chromium Authors
class PresentationSourceFrameMessageManager {
    #targetToMessageHelperMap = new WeakMap();
    constructor() {
        TargetManager.instance().observeModels(DebuggerModel, this);
        TargetManager.instance().observeModels(CSSModel, this);
    }
    modelAdded(model) {
        const target = model.target();
        const helper = this.#targetToMessageHelperMap.get(target) ?? new PresentationSourceFrameMessageHelper();
        if (model instanceof DebuggerModel) {
            helper.setDebuggerModel(model);
        }
        else {
            helper.setCSSModel(model);
        }
        this.#targetToMessageHelperMap.set(target, helper);
    }
    modelRemoved(model) {
        const target = model.target();
        const helper = this.#targetToMessageHelperMap.get(target);
        helper?.clear();
    }
    addMessage(message, source, target) {
        const helper = this.#targetToMessageHelperMap.get(target);
        void helper?.addMessage(message, source);
    }
    clear() {
        for (const target of TargetManager.instance().targets()) {
            const helper = this.#targetToMessageHelperMap.get(target);
            helper?.clear();
        }
    }
}
class PresentationSourceFrameMessageHelper {
    #debuggerModel;
    #cssModel;
    #presentationMessages = new Map();
    #locationPool;
    constructor() {
        this.#locationPool = new LiveLocationPool();
        WorkspaceImpl.instance().addEventListener(Events$1.UISourceCodeAdded, this.#uiSourceCodeAdded.bind(this));
    }
    setDebuggerModel(debuggerModel) {
        if (this.#debuggerModel) {
            throw new Error('Cannot set DebuggerModel twice');
        }
        this.#debuggerModel = debuggerModel;
        debuggerModel.addEventListener(Events$5.ParsedScriptSource, event => {
            queueMicrotask(() => {
                this.#parsedScriptSource(event);
            });
        });
        debuggerModel.addEventListener(Events$5.GlobalObjectCleared, this.#debuggerReset, this);
    }
    setCSSModel(cssModel) {
        if (this.#cssModel) {
            throw new Error('Cannot set CSSModel twice');
        }
        this.#cssModel = cssModel;
        cssModel.addEventListener(Events$a.StyleSheetAdded, event => queueMicrotask(() => this.#styleSheetAdded(event)));
    }
    async addMessage(message, source) {
        const presentation = new PresentationSourceFrameMessage(message, this.#locationPool);
        const location = this.#rawLocation(source) ?? this.#cssLocation(source) ?? this.#uiLocation(source);
        if (location) {
            await presentation.updateLocationSource(location);
        }
        if (source.url) {
            let messages = this.#presentationMessages.get(source.url);
            if (!messages) {
                messages = [];
                this.#presentationMessages.set(source.url, messages);
            }
            messages.push({ source, presentation });
        }
    }
    #uiLocation(source) {
        if (!source.url) {
            return null;
        }
        const uiSourceCode = WorkspaceImpl.instance().uiSourceCodeForURL(source.url);
        if (!uiSourceCode) {
            return null;
        }
        return new UILocation(uiSourceCode, source.line, source.column);
    }
    #cssLocation(source) {
        if (!this.#cssModel || !source.url) {
            return null;
        }
        const locations = this.#cssModel.createRawLocationsByURL(source.url, source.line, source.column);
        return locations[0] ?? null;
    }
    #rawLocation(source) {
        if (!this.#debuggerModel) {
            return null;
        }
        if (source.scriptId) {
            return this.#debuggerModel.createRawLocationByScriptId(source.scriptId, source.line, source.column);
        }
        const callFrame = source.stackTrace?.callFrames ? source.stackTrace.callFrames[0] : null;
        if (callFrame) {
            return this.#debuggerModel.createRawLocationByScriptId(callFrame.scriptId, callFrame.lineNumber, callFrame.columnNumber);
        }
        if (source.url) {
            return this.#debuggerModel.createRawLocationByURL(source.url, source.line, source.column);
        }
        return null;
    }
    #parsedScriptSource(event) {
        const script = event.data;
        const messages = this.#presentationMessages.get(script.sourceURL);
        const promises = [];
        for (const { presentation, source } of messages ?? []) {
            const rawLocation = this.#rawLocation(source);
            if (rawLocation && script.scriptId === rawLocation.scriptId) {
                promises.push(presentation.updateLocationSource(rawLocation));
            }
        }
        void Promise.all(promises).then(this.parsedScriptSourceForTest.bind(this));
    }
    parsedScriptSourceForTest() {
    }
    #uiSourceCodeAdded(event) {
        const uiSourceCode = event.data;
        const messages = this.#presentationMessages.get(uiSourceCode.url());
        const promises = [];
        for (const { presentation, source } of messages ?? []) {
            promises.push(presentation.updateLocationSource(new UILocation(uiSourceCode, source.line, source.column)));
        }
        void Promise.all(promises).then(this.uiSourceCodeAddedForTest.bind(this));
    }
    uiSourceCodeAddedForTest() {
    }
    #styleSheetAdded(event) {
        const header = event.data;
        const messages = this.#presentationMessages.get(header.sourceURL);
        const promises = [];
        for (const { source, presentation } of messages ?? []) {
            if (header.containsLocation(source.line, source.column)) {
                promises.push(presentation.updateLocationSource(new CSSLocation(header, source.line, source.column)));
            }
        }
        void Promise.all(promises).then(this.styleSheetAddedForTest.bind(this));
    }
    styleSheetAddedForTest() {
    }
    clear() {
        this.#debuggerReset();
    }
    #debuggerReset() {
        const presentations = Array.from(this.#presentationMessages.values()).flat();
        for (const { presentation } of presentations) {
            presentation.dispose();
        }
        this.#presentationMessages.clear();
        this.#locationPool.disposeAll();
    }
}
class FrozenLiveLocation extends LiveLocationWithPool {
    #uiLocation;
    constructor(uiLocation, updateDelegate, locationPool) {
        super(updateDelegate, locationPool);
        this.#uiLocation = uiLocation;
    }
    async uiLocation() {
        return this.#uiLocation;
    }
}
class PresentationSourceFrameMessage {
    #uiSourceCode;
    #liveLocation;
    #locationPool;
    #message;
    constructor(message, locationPool) {
        this.#message = message;
        this.#locationPool = locationPool;
    }
    async updateLocationSource(source) {
        if (source instanceof Location$1) {
            await DebuggerWorkspaceBinding.instance().createLiveLocation(source, this.#updateLocation.bind(this), this.#locationPool);
        }
        else if (source instanceof CSSLocation) {
            await CSSWorkspaceBinding.instance().createLiveLocation(source, this.#updateLocation.bind(this), this.#locationPool);
        }
        else if (source instanceof UILocation) {
            if (!this.#liveLocation) {
                this.#liveLocation = new FrozenLiveLocation(source, this.#updateLocation.bind(this), this.#locationPool);
                await this.#liveLocation.update();
            }
        }
    }
    async #updateLocation(liveLocation) {
        if (this.#uiSourceCode) {
            this.#uiSourceCode.removeMessage(this.#message);
        }
        if (liveLocation !== this.#liveLocation) {
            this.#uiSourceCode?.removeMessage(this.#message);
            this.#liveLocation?.dispose();
            this.#liveLocation = liveLocation;
        }
        const uiLocation = await liveLocation.uiLocation();
        if (!uiLocation) {
            return;
        }
        this.#message.range =
            TextRange.createFromLocation(uiLocation.lineNumber, uiLocation.columnNumber || 0);
        this.#uiSourceCode = uiLocation.uiSourceCode;
        this.#uiSourceCode.addMessage(this.#message);
    }
    dispose() {
        this.#uiSourceCode?.removeMessage(this.#message);
        this.#liveLocation?.dispose();
    }
}

// Copyright 2017 The Chromium Authors
const styleSheetRangeMap = new WeakMap();
const scriptRangeMap = new WeakMap();
const boundUISourceCodes = new WeakSet();
function computeScriptRange(script) {
    return new TextRange(script.lineOffset, script.columnOffset, script.endLine, script.endColumn);
}
function computeStyleSheetRange(header) {
    return new TextRange(header.startLine, header.startColumn, header.endLine, header.endColumn);
}
class ResourceMapping {
    workspace;
    #modelToInfo = new Map();
    #debuggerWorkspaceBinding = null;
    #cssWorkspaceBinding = null;
    constructor(targetManager, workspace) {
        this.workspace = workspace;
        targetManager.observeModels(ResourceTreeModel, this);
    }
    get debuggerWorkspaceBinding() {
        return this.#debuggerWorkspaceBinding;
    }
    set debuggerWorkspaceBinding(debuggerWorkspaceBinding) {
        if (this.#debuggerWorkspaceBinding) {
            throw new Error('DebuggerWorkspaceBinding already set');
        }
        this.#debuggerWorkspaceBinding = debuggerWorkspaceBinding;
    }
    get cssWorkspaceBinding() {
        return this.#cssWorkspaceBinding;
    }
    set cssWorkspaceBinding(cssWorkspaceBinding) {
        if (this.#cssWorkspaceBinding) {
            throw new Error('CSSWorkspaceBinding already set');
        }
        this.#cssWorkspaceBinding = cssWorkspaceBinding;
    }
    modelAdded(resourceTreeModel) {
        const info = new ModelInfo(this, resourceTreeModel);
        this.#modelToInfo.set(resourceTreeModel, info);
    }
    modelRemoved(resourceTreeModel) {
        const info = this.#modelToInfo.get(resourceTreeModel);
        if (info) {
            info.dispose();
            this.#modelToInfo.delete(resourceTreeModel);
        }
    }
    infoForTarget(target) {
        const resourceTreeModel = target.model(ResourceTreeModel);
        return resourceTreeModel ? this.#modelToInfo.get(resourceTreeModel) || null : null;
    }
    uiSourceCodeForScript(script) {
        const info = this.infoForTarget(script.debuggerModel.target());
        if (!info) {
            return null;
        }
        const project = info.getProject();
        const uiSourceCode = project.uiSourceCodeForURL(script.sourceURL);
        return uiSourceCode;
    }
    cssLocationToUILocation(cssLocation) {
        const header = cssLocation.header();
        if (!header) {
            return null;
        }
        const info = this.infoForTarget(cssLocation.cssModel().target());
        if (!info) {
            return null;
        }
        const uiSourceCode = info.getProject().uiSourceCodeForURL(cssLocation.url);
        if (!uiSourceCode) {
            return null;
        }
        const offset = styleSheetRangeMap.get(header) ?? computeStyleSheetRange(header);
        const lineNumber = cssLocation.lineNumber + offset.startLine - header.startLine;
        let columnNumber = cssLocation.columnNumber;
        if (cssLocation.lineNumber === header.startLine) {
            columnNumber += offset.startColumn - header.startColumn;
        }
        return uiSourceCode.uiLocation(lineNumber, columnNumber);
    }
    jsLocationToUILocation(jsLocation) {
        const script = jsLocation.script();
        if (!script) {
            return null;
        }
        const info = this.infoForTarget(jsLocation.debuggerModel.target());
        if (!info) {
            return null;
        }
        const embedderName = script.embedderName();
        if (!embedderName) {
            return null;
        }
        const uiSourceCode = info.getProject().uiSourceCodeForURL(embedderName);
        if (!uiSourceCode) {
            return null;
        }
        const { startLine, startColumn } = scriptRangeMap.get(script) ?? computeScriptRange(script);
        let { lineNumber, columnNumber } = jsLocation;
        if (lineNumber === script.lineOffset) {
            columnNumber += startColumn - script.columnOffset;
        }
        lineNumber += startLine - script.lineOffset;
        if (script.hasSourceURL) {
            if (lineNumber === 0) {
                columnNumber += script.columnOffset;
            }
            lineNumber += script.lineOffset;
        }
        return uiSourceCode.uiLocation(lineNumber, columnNumber);
    }
    uiLocationToJSLocations(uiSourceCode, lineNumber, columnNumber) {
        if (!boundUISourceCodes.has(uiSourceCode)) {
            return [];
        }
        const target = NetworkProject.targetForUISourceCode(uiSourceCode);
        if (!target) {
            return [];
        }
        const debuggerModel = target.model(DebuggerModel);
        if (!debuggerModel) {
            return [];
        }
        const locations = [];
        for (const script of debuggerModel.scripts()) {
            if (script.embedderName() !== uiSourceCode.url()) {
                continue;
            }
            const range = scriptRangeMap.get(script) ?? computeScriptRange(script);
            if (!range.containsLocation(lineNumber, columnNumber)) {
                continue;
            }
            let scriptLineNumber = lineNumber;
            let scriptColumnNumber = columnNumber;
            if (script.hasSourceURL) {
                scriptLineNumber -= range.startLine;
                if (scriptLineNumber === 0) {
                    scriptColumnNumber -= range.startColumn;
                }
            }
            locations.push(debuggerModel.createRawLocation(script, scriptLineNumber, scriptColumnNumber));
        }
        return locations;
    }
    uiLocationRangeToJSLocationRanges(uiSourceCode, textRange) {
        if (!boundUISourceCodes.has(uiSourceCode)) {
            return null;
        }
        const target = NetworkProject.targetForUISourceCode(uiSourceCode);
        if (!target) {
            return null;
        }
        const debuggerModel = target.model(DebuggerModel);
        if (!debuggerModel) {
            return null;
        }
        const ranges = [];
        for (const script of debuggerModel.scripts()) {
            if (script.embedderName() !== uiSourceCode.url()) {
                continue;
            }
            const scriptTextRange = scriptRangeMap.get(script) ?? computeScriptRange(script);
            const range = scriptTextRange.intersection(textRange);
            if (range.isEmpty()) {
                continue;
            }
            let { startLine, startColumn, endLine, endColumn } = range;
            if (script.hasSourceURL) {
                startLine -= range.startLine;
                if (startLine === 0) {
                    startColumn -= range.startColumn;
                }
                endLine -= range.startLine;
                if (endLine === 0) {
                    endColumn -= range.startColumn;
                }
            }
            const start = debuggerModel.createRawLocation(script, startLine, startColumn);
            const end = debuggerModel.createRawLocation(script, endLine, endColumn);
            ranges.push({ start, end });
        }
        return ranges;
    }
    getMappedLines(uiSourceCode) {
        if (!boundUISourceCodes.has(uiSourceCode)) {
            return null;
        }
        const target = NetworkProject.targetForUISourceCode(uiSourceCode);
        if (!target) {
            return null;
        }
        const debuggerModel = target.model(DebuggerModel);
        if (!debuggerModel) {
            return null;
        }
        const mappedLines = new Set();
        for (const script of debuggerModel.scripts()) {
            if (script.embedderName() !== uiSourceCode.url()) {
                continue;
            }
            const { startLine, endLine } = scriptRangeMap.get(script) ?? computeScriptRange(script);
            for (let line = startLine; line <= endLine; ++line) {
                mappedLines.add(line);
            }
        }
        return mappedLines;
    }
    uiLocationToCSSLocations(uiLocation) {
        if (!boundUISourceCodes.has(uiLocation.uiSourceCode)) {
            return [];
        }
        const target = NetworkProject.targetForUISourceCode(uiLocation.uiSourceCode);
        if (!target) {
            return [];
        }
        const cssModel = target.model(CSSModel);
        if (!cssModel) {
            return [];
        }
        return cssModel.createRawLocationsByURL(uiLocation.uiSourceCode.url(), uiLocation.lineNumber, uiLocation.columnNumber);
    }
    async functionBoundsAtRawLocation(rawLocation) {
        const script = rawLocation.script();
        if (!script) {
            return null;
        }
        const info = this.infoForTarget(script.debuggerModel.target());
        if (!info) {
            return null;
        }
        const embedderName = script.embedderName();
        if (!embedderName) {
            return null;
        }
        const uiSourceCode = info.getProject().uiSourceCodeForURL(embedderName);
        if (!uiSourceCode) {
            return null;
        }
        let { lineNumber, columnNumber } = rawLocation;
        lineNumber -= script.lineOffset;
        if (lineNumber === 0) {
            columnNumber -= script.columnOffset;
        }
        const scopeTreeAndText = script ? await scopeTreeForScript(script) : null;
        if (!scopeTreeAndText) {
            return null;
        }
        const offset = scopeTreeAndText.text.offsetFromPosition(lineNumber, columnNumber);
        const results = [];
        (function walk(nodes) {
            for (const node of nodes) {
                if (!(offset >= node.start && offset < node.end)) {
                    continue;
                }
                results.push(node);
                walk(node.children);
            }
        })([scopeTreeAndText.scopeTree]);
        const result = results.findLast(node => node.kind === 2  ||
            node.kind === 4 );
        if (!result) {
            return null;
        }
        const startPosition = scopeTreeAndText.text.positionFromOffset(result.start);
        const endPosition = scopeTreeAndText.text.positionFromOffset(result.end);
        startPosition.lineNumber += script.lineOffset;
        if (startPosition.lineNumber === script.lineOffset) {
            startPosition.columnNumber += script.columnOffset;
        }
        endPosition.lineNumber += script.lineOffset;
        if (endPosition.lineNumber === script.lineOffset) {
            endPosition.columnNumber += script.columnOffset;
        }
        const name = '';
        const range = new TextRange(startPosition.lineNumber, startPosition.columnNumber, endPosition.lineNumber, endPosition.columnNumber);
        return new UIFunctionBounds(uiSourceCode, range, name);
    }
    resetForTest(target) {
        const resourceTreeModel = target.model(ResourceTreeModel);
        const info = resourceTreeModel ? this.#modelToInfo.get(resourceTreeModel) : null;
        if (info) {
            info.resetForTest();
        }
    }
}
class ModelInfo {
    project;
    #bindings = new Map();
    #cssModel;
    #eventListeners;
    resourceMapping;
    constructor(resourceMapping, resourceTreeModel) {
        const target = resourceTreeModel.target();
        this.resourceMapping = resourceMapping;
        this.project = new ContentProviderBasedProject(resourceMapping.workspace, 'resources:' + target.id(), projectTypes.Network, '', false );
        NetworkProject.setTargetForProject(this.project, target);
        const cssModel = target.model(CSSModel);
        console.assert(Boolean(cssModel));
        this.#cssModel = cssModel;
        for (const frame of resourceTreeModel.frames()) {
            for (const resource of frame.getResourcesMap().values()) {
                this.addResource(resource);
            }
        }
        this.#eventListeners = [
            resourceTreeModel.addEventListener(Events$6.ResourceAdded, this.resourceAdded, this),
            resourceTreeModel.addEventListener(Events$6.FrameWillNavigate, this.frameWillNavigate, this),
            resourceTreeModel.addEventListener(Events$6.FrameDetached, this.frameDetached, this),
            this.#cssModel.addEventListener(Events$a.StyleSheetChanged, event => {
                void this.styleSheetChanged(event);
            }, this),
        ];
    }
    async styleSheetChanged(event) {
        const header = this.#cssModel.styleSheetHeaderForId(event.data.styleSheetId);
        if (!header || !header.isInline || (header.isInline && header.isMutable)) {
            return;
        }
        const binding = this.#bindings.get(header.resourceURL());
        if (!binding) {
            return;
        }
        await binding.styleSheetChanged(header, event.data.edit || null);
    }
    acceptsResource(resource) {
        const resourceType = resource.resourceType();
        if (resourceType !== resourceTypes.Image &&
            resourceType !== resourceTypes.Font &&
            resourceType !== resourceTypes.Document &&
            resourceType !== resourceTypes.Manifest &&
            resourceType !== resourceTypes.Fetch &&
            resourceType !== resourceTypes.XHR) {
            return false;
        }
        if (resourceType === resourceTypes.Image && resource.mimeType &&
            !resource.mimeType.startsWith('image')) {
            return false;
        }
        if (resourceType === resourceTypes.Font && resource.mimeType &&
            !resource.mimeType.includes('font')) {
            return false;
        }
        if ((resourceType === resourceTypes.Image ||
            resourceType === resourceTypes.Font) &&
            schemeIs(resource.contentURL(), 'data:')) {
            return false;
        }
        return true;
    }
    resourceAdded(event) {
        this.addResource(event.data);
    }
    addResource(resource) {
        if (!this.acceptsResource(resource)) {
            return;
        }
        let binding = this.#bindings.get(resource.url);
        if (!binding) {
            binding = new Binding(this, resource);
            this.#bindings.set(resource.url, binding);
        }
        else {
            binding.addResource(resource);
        }
    }
    removeFrameResources(frame) {
        for (const resource of frame.resources()) {
            if (!this.acceptsResource(resource)) {
                continue;
            }
            const binding = this.#bindings.get(resource.url);
            if (!binding) {
                continue;
            }
            if (binding.resources.size === 1) {
                binding.dispose();
                this.#bindings.delete(resource.url);
            }
            else {
                binding.removeResource(resource);
            }
        }
    }
    frameWillNavigate(event) {
        this.removeFrameResources(event.data);
    }
    frameDetached(event) {
        this.removeFrameResources(event.data.frame);
    }
    resetForTest() {
        for (const binding of this.#bindings.values()) {
            binding.dispose();
        }
        this.#bindings.clear();
    }
    dispose() {
        removeEventListeners(this.#eventListeners);
        for (const binding of this.#bindings.values()) {
            binding.dispose();
        }
        this.#bindings.clear();
        this.project.removeProject();
    }
    getProject() {
        return this.project;
    }
}
class Binding {
    resources;
    #project;
    #uiSourceCode;
    #edits = [];
    #debuggerWorkspaceBinding;
    #cssWorkspaceBinding;
    constructor(modelInfo, resource) {
        this.resources = new Set([resource]);
        this.#project = modelInfo.project;
        this.#debuggerWorkspaceBinding = modelInfo.resourceMapping.debuggerWorkspaceBinding;
        this.#cssWorkspaceBinding = modelInfo.resourceMapping.cssWorkspaceBinding;
        this.#uiSourceCode = this.#project.createUISourceCode(resource.url, resource.contentType());
        boundUISourceCodes.add(this.#uiSourceCode);
        if (resource.frameId) {
            NetworkProject.setInitialFrameAttribution(this.#uiSourceCode, resource.frameId);
        }
        this.#project.addUISourceCodeWithProvider(this.#uiSourceCode, this, resourceMetadata(resource), resource.mimeType);
        void Promise.all([
            ...this.inlineScripts().map(script => this.#debuggerWorkspaceBinding?.updateLocations(script)),
            ...this.inlineStyles().map(style => this.#cssWorkspaceBinding?.updateLocations(style)),
        ]);
    }
    inlineStyles() {
        const target = NetworkProject.targetForUISourceCode(this.#uiSourceCode);
        const stylesheets = [];
        if (!target) {
            return stylesheets;
        }
        const cssModel = target.model(CSSModel);
        if (cssModel) {
            for (const headerId of cssModel.getStyleSheetIdsForURL(this.#uiSourceCode.url())) {
                const header = cssModel.styleSheetHeaderForId(headerId);
                if (header) {
                    stylesheets.push(header);
                }
            }
        }
        return stylesheets;
    }
    inlineScripts() {
        const target = NetworkProject.targetForUISourceCode(this.#uiSourceCode);
        if (!target) {
            return [];
        }
        const debuggerModel = target.model(DebuggerModel);
        if (!debuggerModel) {
            return [];
        }
        return debuggerModel.scripts().filter(script => script.embedderName() === this.#uiSourceCode.url());
    }
    async styleSheetChanged(stylesheet, edit) {
        this.#edits.push({ stylesheet, edit });
        if (this.#edits.length > 1) {
            return;
        }
        const content = await this.#uiSourceCode.requestContentData();
        if (!ContentData.isError(content)) {
            await this.innerStyleSheetChanged(content.text);
        }
        this.#edits = [];
    }
    async innerStyleSheetChanged(content) {
        const scripts = this.inlineScripts();
        const styles = this.inlineStyles();
        let text = new Text(content);
        for (const data of this.#edits) {
            const edit = data.edit;
            if (!edit) {
                continue;
            }
            const stylesheet = data.stylesheet;
            const startLocation = styleSheetRangeMap.get(stylesheet) ?? computeStyleSheetRange(stylesheet);
            const oldRange = edit.oldRange.relativeFrom(startLocation.startLine, startLocation.startColumn);
            const newRange = edit.newRange.relativeFrom(startLocation.startLine, startLocation.startColumn);
            text = new Text(text.replaceRange(oldRange, edit.newText));
            const updatePromises = [];
            for (const script of scripts) {
                const range = scriptRangeMap.get(script) ?? computeScriptRange(script);
                if (!range.follows(oldRange)) {
                    continue;
                }
                scriptRangeMap.set(script, range.rebaseAfterTextEdit(oldRange, newRange));
                updatePromises.push(this.#debuggerWorkspaceBinding?.updateLocations(script));
            }
            for (const style of styles) {
                const range = styleSheetRangeMap.get(style) ?? computeStyleSheetRange(style);
                if (!range.follows(oldRange)) {
                    continue;
                }
                styleSheetRangeMap.set(style, range.rebaseAfterTextEdit(oldRange, newRange));
                updatePromises.push(this.#cssWorkspaceBinding?.updateLocations(style));
            }
            await Promise.all(updatePromises);
        }
        this.#uiSourceCode.addRevision(text.value());
    }
    addResource(resource) {
        this.resources.add(resource);
        if (resource.frameId) {
            NetworkProject.addFrameAttribution(this.#uiSourceCode, resource.frameId);
        }
    }
    removeResource(resource) {
        this.resources.delete(resource);
        if (resource.frameId) {
            NetworkProject.removeFrameAttribution(this.#uiSourceCode, resource.frameId);
        }
    }
    dispose() {
        this.#project.removeUISourceCode(this.#uiSourceCode.url());
        void Promise.all([
            ...this.inlineScripts().map(script => this.#debuggerWorkspaceBinding?.updateLocations(script)),
            ...this.inlineStyles().map(style => this.#cssWorkspaceBinding?.updateLocations(style)),
        ]);
    }
    firstResource() {
        console.assert(this.resources.size > 0);
        return this.resources.values().next().value;
    }
    contentURL() {
        return this.firstResource().contentURL();
    }
    contentType() {
        return this.firstResource().contentType();
    }
    requestContentData() {
        return this.firstResource().requestContentData();
    }
    searchInContent(query, caseSensitive, isRegex) {
        return this.firstResource().searchInContent(query, caseSensitive, isRegex);
    }
}

// Copyright 2025 The Chromium Authors
class Universe {
    context = new DevToolsContext();
    constructor(options) {
        const settings = Settings.instance({
            forceNew: true,
            ...options.settingsCreationOptions,
        });
        const targetManager = new TargetManager(this.context, options.overrideAutoStartModels);
        this.context.set(TargetManager, targetManager);
        const multitargetNetworkManager = new MultitargetNetworkManager(targetManager);
        this.context.set(MultitargetNetworkManager, multitargetNetworkManager);
        const pageResourceLoader = new PageResourceLoader(targetManager, settings, multitargetNetworkManager, null);
        this.context.set(PageResourceLoader, pageResourceLoader);
        const workspace = new WorkspaceImpl();
        this.context.set(WorkspaceImpl, workspace);
        const ignoreListManager = new IgnoreListManager(settings, targetManager);
        this.context.set(IgnoreListManager, ignoreListManager);
        const resourceMapping = new ResourceMapping(targetManager, workspace);
        const cssWorkspaceBinding = new CSSWorkspaceBinding(resourceMapping, targetManager);
        this.context.set(CSSWorkspaceBinding, cssWorkspaceBinding);
        const debuggerWorkspaceBinding = new DebuggerWorkspaceBinding(resourceMapping, targetManager, ignoreListManager, workspace);
        this.context.set(DebuggerWorkspaceBinding, debuggerWorkspaceBinding);
    }
}

var Universe$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Universe: Universe
});

// Copyright 2025 The Chromium Authors

var foundation = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Universe: Universe$1
});

// Copyright 2020 The Chromium Authors

var protocol = /*#__PURE__*/Object.freeze({
	__proto__: null
});

var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) => function __require() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var require_create_entity_finder_api = __commonJS({
    "package/lib/create-entity-finder-api.js"(exports$1, module) {
        var DOMAIN_IN_URL_REGEX = /:\/\/(\S*?)(:\d+)?(\/|$)/;
        var DOMAIN_CHARACTERS = /([a-z0-9.-]+\.[a-z0-9]+|localhost)/i;
        var IP_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
        var ROOT_DOMAIN_REGEX = /[^.]+\.([^.]+|(gov|com|co|ne)\.\w{2})$/i;
        function getDomainFromOriginOrURL(originOrURL) {
            if (typeof originOrURL !== "string")
                return null;
            if (originOrURL.length > 1e4 || originOrURL.startsWith("data:"))
                return null;
            if (DOMAIN_IN_URL_REGEX.test(originOrURL))
                return originOrURL.match(DOMAIN_IN_URL_REGEX)[1];
            if (DOMAIN_CHARACTERS.test(originOrURL))
                return originOrURL.match(DOMAIN_CHARACTERS)[0];
            return null;
        }
        function getRootDomain(originOrURL) {
            const domain = getDomainFromOriginOrURL(originOrURL);
            if (!domain)
                return null;
            if (IP_REGEX.test(domain))
                return domain;
            const match = domain.match(ROOT_DOMAIN_REGEX);
            return match && match[0] || domain;
        }
        function sliceSubdomainFromDomain(domain, rootDomain) {
            if (domain.length <= rootDomain.length)
                return domain;
            return domain.split(".").slice(1).join(".");
        }
        function getEntityInDataset(entityByDomain, entityBySubDomain, entityByRootDomain, originOrURL) {
            const domain = getDomainFromOriginOrURL(originOrURL);
            const rootDomain = getRootDomain(domain);
            if (!domain || !rootDomain)
                return void 0;
            if (entityByDomain.has(domain))
                return entityByDomain.get(domain);
            for (let subdomain = domain; subdomain.length > rootDomain.length; subdomain = sliceSubdomainFromDomain(subdomain, rootDomain)) {
                if (entityBySubDomain.has(subdomain))
                    return entityBySubDomain.get(subdomain);
            }
            if (entityByRootDomain.has(rootDomain))
                return entityByRootDomain.get(rootDomain);
            return void 0;
        }
        function getProductInDataset(entityByDomain, entityBySubDomain, entityByRootDomain, originOrURL) {
            const entity = getEntityInDataset(entityByDomain, entityBySubDomain, entityByRootDomain, originOrURL);
            const products = entity && entity.products;
            if (!products)
                return void 0;
            if (typeof originOrURL !== "string")
                return void 0;
            for (const product of products) {
                for (const pattern of product.urlPatterns) {
                    if (pattern instanceof RegExp && pattern.test(originOrURL))
                        return product;
                    if (typeof pattern === "string" && originOrURL.includes(pattern))
                        return product;
                }
            }
            return void 0;
        }
        function cloneEntities(entities) {
            return entities.map((entity_) => {
                const entity = {
                    company: entity_.name,
                    categories: [entity_.category],
                    ...entity_
                };
                const products = (entity_.products || []).map((product) => ({
                    company: entity.company,
                    category: entity.category,
                    categories: [entity.category],
                    facades: [],
                    ...product,
                    urlPatterns: (product.urlPatterns || []).map((s) => s.startsWith("REGEXP:") ? new RegExp(s.slice("REGEXP:".length)) : s)
                }));
                entity.products = products;
                return entity;
            });
        }
        function createAPIFromDataset(entities_) {
            const entities = cloneEntities(entities_);
            const entityByDomain =  new Map();
            const entityByRootDomain =  new Map();
            const entityBySubDomain =  new Map();
            for (const entity of entities) {
                entity.totalExecutionTime = Number(entity.totalExecutionTime) || 0;
                entity.totalOccurrences = Number(entity.totalOccurrences) || 0;
                entity.averageExecutionTime = entity.totalExecutionTime / entity.totalOccurrences;
                for (const domain of entity.domains) {
                    if (entityByDomain.has(domain)) {
                        const duplicate = entityByDomain.get(domain);
                        throw new Error(`Duplicate domain ${domain} (${entity.name} and ${duplicate.name})`);
                    }
                    entityByDomain.set(domain, entity);
                    const rootDomain = getRootDomain(domain);
                    if (domain.startsWith("*.")) {
                        const wildcardDomain = domain.slice(2);
                        if (wildcardDomain === rootDomain)
                            entityByRootDomain.set(rootDomain, entity);
                        else
                            entityBySubDomain.set(wildcardDomain, entity);
                    }
                }
            }
            for (const [rootDomain, entity] of entityByRootDomain.entries()) {
                if (!entity)
                    entityByRootDomain.delete(rootDomain);
            }
            const getEntity = getEntityInDataset.bind(null, entityByDomain, entityBySubDomain, entityByRootDomain);
            const getProduct = getProductInDataset.bind(null, entityByDomain, entityBySubDomain, entityByRootDomain);
            return { getEntity, getProduct, getRootDomain, entities };
        }
        module.exports = { createAPIFromDataset };
    }
});
var require_entities_nostats = __commonJS({
    "package/dist/entities-nostats.json"(exports$1, module) {
        module.exports = [{ name: "Google/Doubleclick Ads", company: "Google", homepage: "https://marketingplatform.google.com/about/enterprise/", category: "ad", domains: ["adservice.google.com", "adservice.google.com.au", "adservice.google.com.sg", "adservice.google.com.br", "adservice.google.com.ua", "adservice.google.co.uk", "adservice.google.co.jp", "adservice.google.co.in", "adservice.google.co.kr", "adservice.google.co.id", "adservice.google.co.nz", "adservice.google.ie", "adservice.google.se", "adservice.google.de", "adservice.google.ca", "adservice.google.be", "adservice.google.es", "adservice.google.ch", "adservice.google.fr", "adservice.google.nl", "*.googleadservices.com", "*.googlesyndication.com", "*.googletagservices.com", "*.2mdn.net", "*.doubleclick.net"] }, { name: "Facebook", homepage: "https://www.facebook.com", category: "social", domains: ["*.facebook.com", "*.atlassbx.com", "*.fbsbx.com", "fbcdn-photos-e-a.akamaihd.net", "*.facebook.net", "*.fbcdn.net"], products: [{ name: "Facebook Messenger Customer Chat", urlPatterns: ["REGEXP:connect\\.facebook\\.net\\/.*\\/sdk\\/xfbml\\.customerchat\\.js"], facades: [{ name: "React Live Chat Loader", repo: "https://github.com/calibreapp/react-live-chat-loader" }] }] }, { name: "Instagram", homepage: "https://www.instagram.com", category: "social", domains: ["*.cdninstagram.com", "*.instagram.com"] }, { name: "Google CDN", company: "Google", homepage: "https://developers.google.com/speed/libraries/", category: "cdn", domains: ["ajax.googleapis.com", "commondatastorage.googleapis.com", "www.gstatic.com", "ssl.gstatic.com"] }, { name: "Google Maps", company: "Google", homepage: "https://www.google.com/maps", category: "utility", domains: ["maps.google.com", "maps-api-ssl.google.com", "maps.googleapis.com", "mts.googleapis.com", "mt.googleapis.com", "mt0.googleapis.com", "mt1.googleapis.com", "mt2.googleapis.com", "mt3.googleapis.com", "khm0.googleapis.com", "khm1.googleapis.com", "khms.googleapis.com", "khms1.googleapis.com", "khms2.googleapis.com", "maps.gstatic.com"] }, { name: "Other Google APIs/SDKs", company: "Google", homepage: "https://developers.google.com/apis-explorer/#p/", category: "utility", domains: ["accounts.google.com", "apis.google.com", "calendar.google.com", "clients2.google.com", "cse.google.com", "news.google.com", "pay.google.com", "payments.google.com", "play.google.com", "smartlock.google.com", "www.google.com", "www.google.de", "www.google.co.jp", "www.google.com.au", "www.google.co.uk", "www.google.ie", "www.google.com.sg", "www.google.co.in", "www.google.com.br", "www.google.ca", "www.google.co.kr", "www.google.co.nz", "www.google.co.id", "www.google.fr", "www.google.be", "www.google.com.ua", "www.google.nl", "www.google.ru", "www.google.se", "www.googleapis.com", "imasdk.googleapis.com", "storage.googleapis.com", "translate.googleapis.com", "translate.google.com", "translate-pa.googleapis.com", "lh3.googleusercontent.com", "jnn-pa.googleapis.com", "csi.gstatic.com"] }, { name: "Firebase", homepage: "https://developers.google.com/apis-explorer/#p/", category: "utility", domains: ["firebasestorage.googleapis.com", "firestore.googleapis.com", "firebaseinstallations.googleapis.com", "firebase.googleapis.com", "firebaseremoteconfig.googleapis.com"] }, { name: "Google Analytics", company: "Google", homepage: "https://marketingplatform.google.com/about/analytics/", category: "analytics", domains: ["*.google-analytics.com", "*.urchin.com", "analytics.google.com"] }, { name: "Google Optimize", company: "Google", homepage: "https://marketingplatform.google.com/about/optimize/", category: "analytics", domains: ["www.googleoptimize.com"] }, { name: "Google AMP", company: "Google", homepage: "https://github.com/google/amp-client-id-library", category: "analytics", domains: ["ampcid.google.com"] }, { name: "Google Tag Manager", company: "Google", homepage: "https://marketingplatform.google.com/about/tag-manager/", category: "tag-manager", domains: ["*.googletagmanager.com"] }, { name: "Google Fonts", company: "Google", homepage: "https://fonts.google.com/", category: "cdn", domains: ["fonts.googleapis.com", "fonts.gstatic.com"] }, { name: "Adobe TypeKit", company: "Adobe", homepage: "https://fonts.adobe.com/", category: "cdn", domains: ["*.typekit.com", "*.typekit.net"] }, { name: "YouTube", homepage: "https://youtube.com", category: "video", domains: ["*.youtube.com", "*.ggpht.com", "*.youtube-nocookie.com", "*.ytimg.com"], products: [{ name: "YouTube Embedded Player", urlPatterns: ["youtube.com/embed/"], facades: [{ name: "Lite YouTube", repo: "https://github.com/paulirish/lite-youtube-embed" }, { name: "Ngx Lite Video", repo: "https://github.com/karim-mamdouh/ngx-lite-video" }] }] }, { name: "Twitter", homepage: "https://twitter.com", category: "social", domains: ["*.vine.co", "*.twimg.com", "*.twitpic.com", "platform.twitter.com", "syndication.twitter.com"] }, { name: "AddThis", homepage: "https://www.addthis.com/", category: "social", domains: ["*.addthis.com", "*.addthiscdn.com", "*.addthisedge.com"] }, { name: "AddToAny", homepage: "https://www.addtoany.com/", category: "social", domains: ["*.addtoany.com"] }, { name: "Akamai", homepage: "https://www.akamai.com/", category: "cdn", domains: ["23.62.3.183", "*.akamaitechnologies.com", "*.akamaitechnologies.fr", "*.akamai.net", "*.akamaiedge.net", "*.akamaihd.net", "*.akamaized.net", "*.edgefcs.net", "*.edgekey.net", "edgesuite.net", "*.srip.net"] }, { name: "Blogger", homepage: "https://www.blogger.com/", category: "hosting", domains: ["*.blogblog.com", "*.blogger.com", "*.blogspot.com", "images-blogger-opensocial.googleusercontent.com"] }, { name: "Gravatar", homepage: "https://en.gravatar.com/", category: "social", domains: ["*.gravatar.com"] }, { name: "Yandex Metrica", company: "Yandex", homepage: "https://metrica.yandex.com/about?", category: "analytics", domains: ["mc.yandex.ru", "mc.yandex.com", "d31j93rd8oukbv.cloudfront.net"] }, { name: "Hotjar", homepage: "https://www.hotjar.com/", category: "analytics", domains: ["*.hotjar.com", "*.hotjar.io"] }, { name: "Baidu Analytics", homepage: "https://tongji.baidu.com/web/welcome/login", category: "analytics", domains: ["hm.baidu.com", "hmcdn.baidu.com"] }, { name: "Insider", homepage: "", category: "analytics", domains: ["*.useinsider.com"] }, { name: "Adobe Experience Cloud", company: "Adobe", homepage: "", category: "analytics", domains: ["*.2o7.net", "du8783wkf05yr.cloudfront.net", "*.hitbox.com", "*.imageg.net", "*.nedstat.com", "*.omtrdc.net"] }, { name: "Adobe Tag Manager", company: "Adobe", homepage: "https://www.adobe.com/experience-platform/", category: "tag-manager", domains: ["*.adobedtm.com", "*.demdex.net", "*.everesttech.net", "sstats.adobe.com", "hbrt.adobe.com"] }, { name: "jQuery CDN", homepage: "https://code.jquery.com/", category: "cdn", domains: ["*.jquery.com"] }, { name: "Cloudflare CDN", homepage: "https://cdnjs.com/", category: "cdn", domains: ["cdnjs.cloudflare.com", "amp.cloudflare.com"] }, { name: "Cloudflare", homepage: "https://www.cloudflare.com/website-optimization/", category: "utility", domains: ["ajax.cloudflare.com", "*.nel.cloudflare.com", "static.cloudflareinsights.com"] }, { name: "WordPress", company: "Automattic", homepage: "https://wp.com/", category: "hosting", domains: ["*.wordpress.com", "s0.wp.com", "s2.wp.com", "*.w.org", "c0.wp.com", "s1.wp.com", "i0.wp.com", "i1.wp.com", "i2.wp.com", "widgets.wp.com"] }, { name: "WordPress Site Stats", company: "Automattic", homepage: "https://wp.com/", category: "analytics", domains: ["pixel.wp.com", "stats.wp.com"] }, { name: "Hatena Blog", homepage: "https://hatenablog.com/", category: "hosting", domains: ["*.st-hatena.com", "*.hatena.ne.jp"] }, { name: "Shopify", homepage: "https://www.shopify.com/", category: "hosting", domains: ["*.shopify.com", "*.shopifyapps.com", "*.shopifycdn.com", "*.shopifysvc.com"] }, { name: "Dealer", homepage: "https://www.dealer.com/", category: "hosting", domains: ["*.dealer.com"] }, { name: "PIXNET", homepage: "https://www.pixnet.net/", category: "social", domains: ["*.pixfs.net", "*.pixnet.net"] }, { name: "Moat", homepage: "https://moat.com/", category: "ad", domains: ["*.moatads.com", "*.moatpixel.com"] }, { name: "33 Across", homepage: "https://33across.com/", category: "ad", domains: ["*.33across.com"] }, { name: "OpenX", homepage: "https://www.openx.com/", category: "ad", domains: ["*.deliverimp.com", "*.openxadexchange.com", "*.servedbyopenx.com", "*.jump-time.net", "*.openx.net", "*.openxcdn.net"] }, { name: "Amazon Ads", homepage: "https://ad.amazon.com/", category: "ad", domains: ["*.amazon-adsystem.com"] }, { name: "Rubicon Project", homepage: "https://rubiconproject.com/", category: "ad", domains: ["*.rubiconproject.com", "*.chango.com", "*.fimserve.com"] }, { name: "The Trade Desk", homepage: "https://www.thetradedesk.com/", category: "ad", domains: ["*.adsrvr.org", "d1eoo1tco6rr5e.cloudfront.net"] }, { name: "Bidswitch", homepage: "https://www.bidswitch.com/", category: "ad", domains: ["*.bidswitch.net"] }, { name: "LiveRamp IdentityLink", homepage: "https://liveramp.com/discover-identitylink/", category: "analytics", domains: ["*.circulate.com", "*.rlcdn.com"] }, { name: "Drawbridge", homepage: "https://www.drawbridge.com/", category: "ad", domains: ["*.adsymptotic.com"] }, { name: "AOL / Oath / Verizon Media", homepage: "https://www.oath.com/", category: "ad", domains: ["*.advertising.com", "*.aol.com", "*.aolcdn.com", "*.blogsmithmedia.com", "*.oath.com", "*.aol.net", "*.tacoda.net", "*.aol.co.uk"] }, { name: "Xaxis", homepage: "https://www.xaxis.com/", category: "ad", domains: ["*.247realmedia.com", "*.mookie1.com", "*.gmads.net"] }, { name: "Freshdesk", company: "Freshworks", homepage: "https://freshdesk.com/", category: "customer-success", domains: ["d36mpcpuzc4ztk.cloudfront.net"] }, { name: "Help Scout", homepage: "https://www.helpscout.net/", category: "customer-success", domains: ["djtflbt20bdde.cloudfront.net", "*.helpscout.net"], products: [{ name: "Help Scout Beacon", urlPatterns: ["beacon-v2.helpscout.net"], facades: [{ name: "React Live Chat Loader", repo: "https://github.com/calibreapp/react-live-chat-loader" }] }] }, { name: "Alexa", homepage: "https://www.alexa.com/", category: "analytics", domains: ["*.alexametrics.com", "d31qbv1cthcecs.cloudfront.net"] }, { name: "OneSignal", homepage: "https://onesignal.com/", category: "utility", domains: ["*.onesignal.com"] }, { name: "Lucky Orange", homepage: "https://www.luckyorange.com/", category: "analytics", domains: ["*.luckyorange.com", "d10lpsik1i8c69.cloudfront.net", "*.luckyorange.net"] }, { name: "Crazy Egg", homepage: "https://www.crazyegg.com/", category: "analytics", domains: ["*.cetrk.com", "*.crazyegg.com", "dnn506yrbagrg.cloudfront.net"] }, { name: "Hello Bar", homepage: "https://www.hellobar.com/", category: "marketing", domains: ["*.hellobar.com"] }, { name: "Yandex Ads", company: "Yandex", homepage: "https://yandex.com/adv/", category: "ad", domains: ["an.yandex.ru"] }, { name: "Salesforce", homepage: "https://www.salesforce.com/products/marketing-cloud/", category: "analytics", domains: ["*.krxd.net"] }, { name: "Salesforce Commerce Cloud", homepage: "https://www.salesforce.com/products/commerce-cloud/overview/", category: "hosting", domains: ["*.cquotient.com", "*.demandware.net", "demandware.edgesuite.net"] }, { name: "Optimizely", homepage: "https://www.optimizely.com/", category: "analytics", domains: ["*.optimizely.com"] }, { name: "LiveChat", homepage: "https://www.livechat.com/", category: "customer-success", domains: ["*.livechatinc.com", "*.livechat.com", "*.livechat-static.com"] }, { name: "VK", homepage: "https://vk.com/", category: "social", domains: ["*.vk.com"] }, { name: "Tumblr", homepage: "https://tumblr.com/", category: "social", domains: ["*.tumblr.com"] }, { name: "Wistia", homepage: "https://wistia.com/", category: "video", domains: ["*.wistia.com", "embedwistia-a.akamaihd.net", "*.wistia.net"] }, { name: "Brightcove", homepage: "https://www.brightcove.com/en/", category: "video", domains: ["*.brightcove.com", "*.brightcove.net", "*.zencdn.net"] }, { name: "JSDelivr CDN", homepage: "https://www.jsdelivr.com/", category: "cdn", domains: ["*.jsdelivr.net"] }, { name: "Sumo", homepage: "https://sumo.com/", category: "marketing", domains: ["*.sumo.com", "*.sumome.com", "sumo.b-cdn.net"] }, { name: "Vimeo", homepage: "https://vimeo.com/", category: "video", domains: ["*.vimeo.com", "*.vimeocdn.com"], products: [{ name: "Vimeo Embedded Player", urlPatterns: ["player.vimeo.com/video/"], facades: [{ name: "Lite Vimeo", repo: "https://github.com/slightlyoff/lite-vimeo" }, { name: "Lite Vimeo Embed", repo: "https://github.com/luwes/lite-vimeo-embed" }, { name: "Ngx Lite Video", repo: "https://github.com/karim-mamdouh/ngx-lite-video" }] }] }, { name: "Disqus", homepage: "https://disqus.com/", category: "social", domains: ["*.disqus.com", "*.disquscdn.com"] }, { name: "Yandex APIs", company: "Yandex", homepage: "https://yandex.ru/", category: "utility", domains: ["api-maps.yandex.ru", "money.yandex.ru"] }, { name: "Yandex CDN", company: "Yandex", homepage: "https://yandex.ru/", category: "cdn", domains: ["*.yandex.st", "*.yastatic.net"] }, { name: "Integral Ad Science", homepage: "https://integralads.com/uk/", category: "ad", domains: ["*.adsafeprotected.com", "*.iasds01.com"] }, { name: "Tealium", homepage: "https://tealium.com/", category: "tag-manager", domains: ["*.aniview.com", "*.delvenetworks.com", "*.limelight.com", "*.tiqcdn.com", "*.llnwd.net", "*.tealiumiq.com"] }, { name: "Pubmatic", homepage: "https://pubmatic.com/", category: "ad", domains: ["*.pubmatic.com"] }, { name: "Olark", homepage: "https://www.olark.com/", category: "customer-success", domains: ["*.olark.com"] }, { name: "Tawk.to", homepage: "https://www.tawk.to/", category: "customer-success", domains: ["*.tawk.to"] }, { name: "OptinMonster", homepage: "https://optinmonster.com/", category: "marketing", domains: ["*.opmnstr.com", "*.optmnstr.com", "*.optmstr.com"] }, { name: "ZenDesk", homepage: "https://zendesk.com/", category: "customer-success", domains: ["*.zdassets.com", "*.zendesk.com", "*.zopim.com"] }, { name: "Pusher", homepage: "https://pusher.com/", category: "utility", domains: ["*.pusher.com", "*.pusherapp.com"] }, { name: "Drift", homepage: "https://www.drift.com/", category: "marketing", domains: ["*.drift.com", "*.driftt.com"], products: [{ name: "Drift Live Chat", urlPatterns: ["REGEXP:js\\.driftt\\.com\\/include\\/.*\\/.*\\.js"], facades: [{ name: "React Live Chat Loader", repo: "https://github.com/calibreapp/react-live-chat-loader" }] }] }, { name: "Sentry", homepage: "https://sentry.io/", category: "utility", domains: ["*.getsentry.com", "*.ravenjs.com", "*.sentry-cdn.com", "*.sentry.io"] }, { name: "Amazon Web Services", homepage: "https://aws.amazon.com/s3/", category: "other", domains: ["*.amazon.com", "*.amazonaws.com", "*.amazonwebapps.com", "*.amazonwebservices.com", "*.elasticbeanstalk.com", "*.images-amazon.com", "*.amazon.co.uk"] }, { name: "Amazon Pay", homepage: "https://pay.amazon.com", category: "utility", domains: ["payments.amazon.com", "*.payments-amazon.com"] }, { name: "Media.net", homepage: "https://www.media.net/", category: "ad", domains: ["*.media.net", "*.mnet-ad.net"] }, { name: "Yahoo!", homepage: "https://www.yahoo.com/", category: "ad", domains: ["*.bluelithium.com", "*.hostingprod.com", "*.lexity.com", "*.yahoo.com", "*.yahooapis.com", "*.yimg.com", "*.zenfs.com", "*.yahoo.net"] }, { name: "Adroll", homepage: "https://www.adroll.com/", category: "ad", domains: ["*.adroll.com"] }, { name: "Twitch", homepage: "https://twitch.tv/", category: "video", domains: ["*.twitch.tv"] }, { name: "Taboola", homepage: "https://www.taboola.com/", category: "ad", domains: ["*.taboola.com", "*.taboolasyndication.com"] }, { name: "Sizmek", homepage: "https://www.sizmek.com/", category: "ad", domains: ["*.serving-sys.com", "*.peer39.net"] }, { name: "Scorecard Research", homepage: "https://www.scorecardresearch.com/", category: "ad", domains: ["*.scorecardresearch.com"] }, { name: "Criteo", homepage: "https://www.criteo.com/", category: "ad", domains: ["*.criteo.com", "*.emailretargeting.com", "*.criteo.net"] }, { name: "Segment", homepage: "https://segment.com/", category: "analytics", domains: ["*.segment.com", "*.segment.io"] }, { name: "ShareThis", homepage: "https://www.sharethis.com/", category: "social", domains: ["*.sharethis.com"] }, { name: "Distil Networks", homepage: "https://www.distilnetworks.com/", category: "utility", domains: ["*.areyouahuman.com"] }, { name: "Connexity", homepage: "https://connexity.com/", category: "analytics", domains: ["*.connexity.net"] }, { name: "Popads", homepage: "https://www.popads.net/", category: "ad", domains: ["*.popads.net"] }, { name: "CreateJS CDN", homepage: "https://code.createjs.com/", category: "cdn", domains: ["*.createjs.com"] }, { name: "Squarespace", homepage: "https://www.squarespace.com/", category: "hosting", domains: ["*.squarespace.com"] }, { name: "Media Math", homepage: "https://www.mediamath.com/", category: "ad", domains: ["*.mathads.com", "*.mathtag.com"] }, { name: "Mixpanel", homepage: "https://mixpanel.com/", category: "analytics", domains: ["*.mixpanel.com", "*.mxpnl.com"] }, { name: "FontAwesome CDN", homepage: "https://fontawesome.com/", category: "cdn", domains: ["*.fontawesome.com"] }, { name: "Hubspot", homepage: "https://hubspot.com/", category: "marketing", domains: ["*.hs-scripts.com", "*.hubspot.com", "*.leadin.com", "*.hs-analytics.net", "*.hscollectedforms.net", "*.hscta.net", "*.hsforms.net", "*.hsleadflows.net", "*.hsstatic.net", "*.hubspot.net", "*.hsforms.com", "*.hs-banner.com", "*.hs-embed-reporting.com", "*.hs-growth-metrics.com", "*.hs-data.com", "*.hsadspixel.net", "*.hubapi.com"] }, { name: "Mailchimp", homepage: "https://mailchimp.com/", category: "marketing", domains: ["*.chimpstatic.com", "*.list-manage.com", "*.mailchimp.com"] }, { name: "MGID", homepage: "https://www.mgid.com/", category: "ad", domains: ["*.mgid.com", "*.dt07.net"] }, { name: "Stripe", homepage: "https://stripe.com", category: "utility", domains: ["*.stripe.com", "*.stripecdn.com", "*.stripe.network"] }, { name: "PayPal", homepage: "https://paypal.com", category: "utility", domains: ["*.paypal.com", "*.paypalobjects.com"] }, { name: "Market GID", homepage: "https://www.marketgid.com/", category: "ad", domains: ["*.marketgid.com"] }, { name: "Pinterest", homepage: "https://pinterest.com/", category: "social", domains: ["*.pinimg.com", "*.pinterest.com"] }, { name: "New Relic", homepage: "https://newrelic.com/", category: "utility", domains: ["*.newrelic.com", "*.nr-data.net"] }, { name: "AppDynamics", homepage: "https://www.appdynamics.com/", category: "utility", domains: ["*.appdynamics.com", "*.eum-appdynamics.com", "d3tjaysgumg9lf.cloudfront.net"] }, { name: "Parking Crew", homepage: "https://parkingcrew.net/", category: "other", domains: ["d1lxhc4jvstzrp.cloudfront.net", "*.parkingcrew.net"] }, { name: "WordAds", company: "Automattic", homepage: "https://wordads.co/", category: "ad", domains: ["*.pubmine.com"] }, { name: "AppNexus", homepage: "https://www.appnexus.com/", category: "ad", domains: ["*.adnxs.com", "*.ctasnet.com", "*.adrdgt.com"] }, { name: "Histats", homepage: "https://www.histats.com/", category: "analytics", domains: ["*.histats.com"] }, { name: "DoubleVerify", homepage: "https://www.doubleverify.com/", category: "ad", domains: ["*.doubleverify.com", "*.dvtps.com", "*.iqfp1.com"] }, { name: "Mediavine", homepage: "https://www.mediavine.com/", category: "ad", domains: ["*.mediavine.com"] }, { name: "Wix", homepage: "https://www.wix.com/", category: "hosting", domains: ["*.parastorage.com", "*.wix.com", "*.wixstatic.com", "*.wixapps.net"] }, { name: "Webflow", homepage: "https://webflow.com/", category: "hosting", domains: ["*.uploads-ssl.webflow.com", "*.assets-global.website-files.com", "*.assets.website-files.com"] }, { name: "Weebly", homepage: "https://www.weebly.com/", category: "hosting", domains: ["*.editmysite.com"] }, { name: "LinkedIn", homepage: "https://www.linkedin.com/", category: "social", domains: ["*.bizographics.com", "platform.linkedin.com", "*.slideshare.com", "*.slidesharecdn.com", "*.oribi.io"] }, { name: "LinkedIn Ads", category: "ad", domains: ["*.licdn.com", "*.ads.linkedin.com", "ads.linkedin.com", "www.linkedin.com"] }, { name: "Vox Media", homepage: "https://www.voxmedia.com/", category: "content", domains: ["*.vox-cdn.com", "*.voxmedia.com"] }, { name: "Hotmart", homepage: "https://www.hotmart.com/", category: "content", domains: ["*.hotmart.com"] }, { name: "SoundCloud", homepage: "https://www.soundcloud.com/", category: "content", domains: ["*.sndcdn.com", "*.soundcloud.com", "*.stratus.sc"] }, { name: "Spotify", homepage: "https://www.spotify.com/", category: "content", domains: ["*.scdn.co", "*.spotify.com"] }, { name: "AMP", homepage: "https://amp.dev/", category: "content", domains: ["*.ampproject.org"] }, { name: "Beeketing", homepage: "https://beeketing.com/", category: "marketing", domains: ["*.beeketing.com"] }, { name: "Albacross", homepage: "https://albacross.com/", category: "marketing", domains: ["*.albacross.com"] }, { name: "TrafficJunky", homepage: "https://www.trafficjunky.com/", category: "ad", domains: ["*.contentabc.com", "*.trafficjunky.net"] }, { name: "Bootstrap CDN", homepage: "https://www.bootstrapcdn.com/", category: "cdn", domains: ["*.bootstrapcdn.com"] }, { name: "Shareaholic", homepage: "https://www.shareaholic.com/", category: "social", domains: ["*.shareaholic.com", "dsms0mj1bbhn4.cloudfront.net"] }, { name: "Snowplow", homepage: "https://snowplowanalytics.com/", category: "analytics", domains: ["d32hwlnfiv2gyn.cloudfront.net"] }, { name: "RD Station", homepage: "https://www.rdstation.com/en/", category: "marketing", domains: ["d335luupugsy2.cloudfront.net"] }, { name: "Jivochat", homepage: "https://www.jivochat.com/", category: "customer-success", domains: ["*.jivosite.com"] }, { name: "Listrak", homepage: "https://www.listrak.com/", category: "marketing", domains: ["*.listrak.com", "*.listrakbi.com"] }, { name: "Ontame", homepage: "https://www.ontame.io", category: "analytics", domains: ["*.ontame.io"] }, { name: "Ipify", homepage: "https://www.ipify.org", category: "utility", domains: ["*.ipify.org"] }, { name: "Ensighten", homepage: "https://www.ensighten.com/", category: "tag-manager", domains: ["*.ensighten.com"] }, { name: "EpiServer", homepage: "https://www.episerver.com", category: "content", domains: ["*.episerver.net"] }, { name: "mPulse", homepage: "https://developer.akamai.com/akamai-mpulse", category: "analytics", domains: ["*.akstat.io", "*.go-mpulse.net", "*.mpulse.net", "*.mpstat.us"] }, { name: "Pingdom RUM", homepage: "https://www.pingdom.com/product/performance-monitoring/", category: "analytics", domains: ["*.pingdom.net"] }, { name: "SpeedCurve RUM", company: "SpeedCurve", homepage: "https://www.speedcurve.com/features/performance-monitoring/", category: "analytics", domains: ["*.speedcurve.com"] }, { name: "Radar", company: "Cedexis", homepage: "https://www.cedexis.com/radar/", category: "analytics", domains: ["*.cedexis-test.com", "*.cedexis.com", "*.cmdolb.com", "cedexis.leasewebcdn.com", "*.cedexis-radar.net", "*.cedexis.net", "cedexis-test01.insnw.net", "cedexisakamaitest.azureedge.net", "cedexispub.cdnetworks.net", "cs600.wac.alphacdn.net", "cs600.wpc.edgecastdns.net", "global2.cmdolb.com", "img-cedexis.mncdn.com", "a-cedexis.msedge.net", "zn3vgszfh.fastestcdn.net"] }, { name: "Byside", homepage: "https://byside.com", category: "analytics", domains: ["*.byside.com"] }, { name: "VWO", homepage: "https://vwo.com", category: "analytics", domains: ["*.vwo.com", "*.visualwebsiteoptimizer.com", "d5phz18u4wuww.cloudfront.net", "*.wingify.com"] }, { name: "Bing Ads", homepage: "https://bingads.microsoft.com", category: "ad", domains: ["*.bing.com", "*.microsoft.com", "*.msn.com", "*.s-msft.com", "*.s-msn.com", "*.msads.net", "*.msecnd.net"] }, { name: "GoSquared", homepage: "https://www.gosquared.com", category: "analytics", domains: ["*.gosquared.com", "d1l6p2sc9645hc.cloudfront.net"] }, { name: "Usabilla", homepage: "https://usabilla.com", category: "analytics", domains: ["*.usabilla.com", "d6tizftlrpuof.cloudfront.net"] }, { name: "Fastly Insights", homepage: "https://insights.fastlylabs.com", category: "analytics", domains: ["*.fastly-insights.com"] }, { name: "Visual IQ", homepage: "https://www.visualiq.com", category: "analytics", domains: ["*.myvisualiq.net"] }, { name: "Snapchat", homepage: "https://www.snapchat.com", category: "analytics", domains: ["*.snapchat.com", "*.sc-static.net"] }, { name: "Atlas Solutions", homepage: "https://atlassolutions.com", category: "analytics", domains: ["*.atdmt.com"] }, { name: "Quantcast", homepage: "https://www.quantcast.com", category: "analytics", domains: ["*.brtstats.com", "*.quantcount.com", "*.quantserve.com", "*.semantictec.com", "*.ntv.io"] }, { name: "Spiceworks", homepage: "https://www.spiceworks.com", category: "analytics", domains: ["*.spiceworks.com"] }, { name: "Marketo", homepage: "https://www.marketo.com", category: "analytics", domains: ["*.marketo.com", "*.mktoresp.com", "*.marketo.net"] }, { name: "Intercom", homepage: "https://www.intercom.com", category: "customer-success", domains: ["*.intercomcdn.com", "*.intercom.io"], products: [{ name: "Intercom Widget", urlPatterns: ["widget.intercom.io", "js.intercomcdn.com/shim.latest.js"], facades: [{ name: "React Live Chat Loader", repo: "https://github.com/calibreapp/react-live-chat-loader" }, { name: "Intercom Facade", repo: "https://github.com/danielbachhuber/intercom-facade/" }] }] }, { name: "Unpkg", homepage: "https://unpkg.com", category: "cdn", domains: ["*.unpkg.com", "*.npmcdn.com"] }, { name: "ReadSpeaker", homepage: "https://www.readspeaker.com", category: "other", domains: ["*.readspeaker.com"] }, { name: "Browsealoud", homepage: "https://www.texthelp.com/en-gb/products/browsealoud/", category: "other", domains: ["*.browsealoud.com", "*.texthelp.com"] }, { name: "15gifts", category: "customer-success", domains: ["*.15gifts.com", "*.primefuse.com"] }, { name: "1xRUN", category: "utility", domains: ["*.1xrun.com"] }, { name: "2AdPro Media Solutions", category: "ad", domains: ["*.2adpro.com"] }, { name: "301 Digital Media", category: "content", domains: ["*.301ads.com", "*.301network.com"] }, { name: "360 picnic platform", company: "MediaV", category: "ad", domains: ["*.mediav.com"] }, { name: "365 Media Group", category: "content", domains: ["*.365dm.com"] }, { name: "365 Tech Services", category: "hosting", domains: ["*.365webservices.co.uk"] }, { name: "3D Issue", category: "utility", domains: ["*.3dissue.com", "*.pressjack.com"] }, { name: "47Line Technologies", category: "other", domains: ["*.pejs.net"] }, { name: "4finance", category: "utility", domains: ["*.4finance.com"] }, { name: "5miles", category: "content", domains: ["*.5milesapp.com"] }, { name: "77Tool", company: "77Agency", category: "analytics", domains: ["*.77tracking.com"] }, { name: "9xb", category: "ad", domains: ["*.9xb.com"] }, { name: "@UK", category: "hosting", domains: ["*.uk-plc.net"] }, { name: "A Perfect Pocket", category: "hosting", domains: ["*.aperfectpocketdata.com"] }, { name: "A-FIS PTE", category: "analytics", domains: ["*.websta.me"] }, { name: "AB Tasty", homepage: "https://www.abtasty.com/", category: "analytics", domains: ["*.abtasty.com", "d1447tq2m68ekg.cloudfront.net"] }, { name: "ABA RESEARCH", category: "analytics", domains: ["*.abaresearch.uk", "qmodal.azurewebsites.net"] }, { name: "ADMIZED", category: "ad", domains: ["*.admized.com"] }, { name: "ADNOLOGIES", category: "ad", domains: ["*.heias.com"] }, { name: "ADventori", category: "ad", domains: ["*.adventori.com"] }, { name: "AI Media Group", category: "ad", domains: ["*.aimediagroup.com"] }, { name: "AIR.TV", category: "ad", domains: ["*.air.tv"] }, { name: "AKQA", category: "ad", domains: ["*.srtk.net"] }, { name: "AOL ad", company: "AOL", category: "ad", domains: ["*.atwola.com"] }, { name: "AOL On", company: "AOL", category: "content", domains: ["*.5min.com"] }, { name: "AOL Sponsored Listiings", company: "AOL", category: "ad", domains: ["*.adsonar.com"] }, { name: "APSIS Lead", company: "APSIS International AB", category: "ad", domains: ["*.prospecteye.com"] }, { name: "APSIS Profile Cloud", company: "APSIS", category: "analytics", domains: ["*.innomdc.com"] }, { name: "APSIS Forms", company: "APSIS", category: "other", domains: ["*.apsisforms.com"] }, { name: "ARENA", company: "Altitude", category: "ad", domains: ["*.altitude-arena.com"] }, { name: "ARM", category: "analytics", domains: ["*.tag4arm.com"] }, { name: "ASAPP", category: "other", domains: ["*.asapp.com"] }, { name: "ASP", category: "hosting", domains: ["*.goshowoff.com"] }, { name: "AT Internet", category: "analytics", domains: ["*.ati-host.net"] }, { name: "ATTRAQT", category: "utility", domains: ["*.attraqt.com", "*.locayta.com"] }, { name: "AVANSER", category: "analytics", domains: ["*.avanser.com.au"] }, { name: "AVG", company: "AVG Technologies", category: "utility", domains: ["*.avg.com"] }, { name: "AWeber", category: "ad", domains: ["*.aweber.com"] }, { name: "AXS", category: "content", domains: ["*.axs.com"] }, { name: "Accentuate", company: "Accentuate Digital", category: "utility", homepage: "https://www.accentuate.io/", domains: ["*.accentuate.io"] }, { name: "Accenture", category: "analytics", domains: ["*.tmvtp.com"] }, { name: "Accord Holdings", category: "ad", domains: ["*.agcdn.com"] }, { name: "Accordant Media", category: "ad", domains: ["*.a3cloud.net"] }, { name: "Account Kit", category: "other", domains: ["*.accountkit.com"] }, { name: "Accuen Media (Omnicom Media Group)", category: "content", domains: ["*.p-td.com"] }, { name: "Accuweather", category: "content", domains: ["*.accuweather.com"] }, { name: "Acquisio", category: "ad", domains: ["*.acq.io"] }, { name: "Act-On Software", category: "marketing", domains: ["*.actonsoftware.com"] }, { name: "ActBlue", category: "other", domains: ["*.actblue.com"] }, { name: "Active Agent", category: "ad", domains: ["*.active-agent.com"] }, { name: "ActiveCampaign", category: "ad", domains: ["*.trackcmp.net", "app-us1.com", "*.app-us1.com"] }, { name: "AcuityAds", category: "ad", domains: ["*.acuityplatform.com"] }, { name: "Acxiom", category: "ad", domains: ["*.acxiom-online.com", "*.acxiomapac.com", "*.delivery.net"] }, { name: "Ad4Screen", category: "ad", domains: ["*.a4.tl"] }, { name: "Ad6Media", category: "ad", domains: ["*.ad6media.fr"] }, { name: "AdCurve", category: "ad", domains: ["*.shop2market.com"] }, { name: "AdEasy", category: "ad", domains: ["*.adeasy.ru"] }, { name: "AdExtent", category: "ad", domains: ["*.adextent.com"] }, { name: "AdForge Edge", company: "AdForge", category: "ad", domains: ["*.adforgeinc.com"] }, { name: "AdGear", company: "Samsung Electronics", category: "ad", domains: ["*.adgear.com", "*.adgrx.com"] }, { name: "AdInMedia", category: "ad", domains: ["*.fastapi.net"] }, { name: "AdJug", category: "ad", domains: ["*.adjug.com"] }, { name: "AdMatic", category: "ad", domains: ["*.admatic.com.tr"] }, { name: "AdMedia", category: "ad", domains: ["*.admedia.com"] }, { name: "AdRecover", category: "ad", domains: ["*.adrecover.com"] }, { name: "AdRiver", category: "ad", domains: ["*.adriver.ru"] }, { name: "AdSniper", category: "ad", domains: ["*.adsniper.ru", "*.sniperlog.ru"] }, { name: "AdSpeed", category: "ad", domains: ["*.adspeed.net"] }, { name: "AdSpruce", category: "ad", domains: ["*.adspruce.com"] }, { name: "AdSupply", category: "ad", domains: ["*.doublepimp.com"] }, { name: "AdTheorent", category: "ad", domains: ["*.adentifi.com"] }, { name: "AdThink AudienceInsights", company: "AdThink Media", category: "analytics", domains: ["*.audienceinsights.net"] }, { name: "AdTrue", company: "FPT AdTrue", category: "ad", domains: ["*.adtrue.com"] }, { name: "AdYapper", category: "ad", domains: ["*.adyapper.com"] }, { name: "Adacado", category: "ad", domains: ["*.adacado.com"] }, { name: "Adap.tv", category: "ad", domains: ["*.adap.tv"] }, { name: "Adapt Services", category: "hosting", domains: ["*.adcmps.com"] }, { name: "Adaptive Web", category: "hosting", domains: ["*.adaptive.co.uk"] }, { name: "Adara Media", category: "ad", domains: ["*.yieldoptimizer.com"] }, { name: "Adblade", category: "ad", domains: ["*.adblade.com"] }, { name: "Adbrain", category: "ad", domains: ["*.adbrn.com"] }, { name: "AddEvent", category: "utility", domains: ["*.addevent.com"] }, { name: "AddShoppers", category: "social", domains: ["*.addshoppers.com", "d3rr3d0n31t48m.cloudfront.net", "*.shop.pe"] }, { name: "AddThisEvent", category: "hosting", domains: ["*.addthisevent.com"] }, { name: "Addoox MetaNetwork", company: "Addoox", category: "ad", domains: ["*.metanetwork.net"] }, { name: "Addvantage Media", category: "ad", domains: ["*.addvantagemedia.com", "*.simplytechnology.net"] }, { name: "AD EBis", category: "analytics", homepage: "https://www.ebis.ne.jp/", domains: ["*.ebis.ne.jp"] }, { name: "Adecs", category: "customer-success", domains: ["*.adecs.co.uk"] }, { name: "Adelphic", category: "ad", domains: ["*.ipredictive.com"] }, { name: "Adestra", category: "ad", domains: ["*.adestra.com", "*.msgfocus.com"] }, { name: "Adform", category: "ad", domains: ["*.adform.net", "*.adformdsp.net"] }, { name: "Adkontekst", category: "ad", domains: ["*.adkontekst.pl"] }, { name: "Adlead", category: "ad", domains: ["*.webelapp.com"] }, { name: "Adledge", category: "utility", domains: ["*.adledge.com"] }, { name: "Adloox", category: "ad", domains: ["*.adlooxtracking.com"] }, { name: "Adlux", category: "ad", domains: ["*.adlux.com"] }, { name: "Admedo", category: "ad", domains: ["*.a8723.com", "*.adizio.com", "*.admedo.com"] }, { name: "Admeta", company: "Wideorbit", category: "ad", domains: ["*.atemda.com"] }, { name: "Admetrics", company: "Next Tuesday", category: "analytics", domains: ["*.nt.vc"] }, { name: "Admiral", category: "ad", domains: ["*.unknowntray.com"] }, { name: "Admitad", category: "ad", domains: ["*.lenmit.com"] }, { name: "Admixer for Publishers", company: "Admixer", category: "ad", domains: ["*.admixer.net"] }, { name: "Adnium", category: "ad", domains: ["*.adnium.com"] }, { name: "Adnostic", company: "Dennis Publishing", category: "ad", domains: ["*.adnostic.co.uk"] }, { name: "Adobe Marketing Cloud", company: "Adobe Systems", category: "ad", domains: ["*.adobetag.com"] }, { name: "Adobe Scene7", company: "Adobe Systems", category: "content", domains: ["wwwimages.adobe.com", "*.scene7.com", "*.everestads.net", "*.everestjs.net"] }, { name: "Adobe Systems", category: "content", domains: ["adobe.com", "www.adobe.com"] }, { name: "Adobe Business Catalyst", homepage: "https://www.businesscatalyst.com/", category: "hosting", domains: ["*.businesscatalyst.com"] }, { name: "Adocean", company: "Gemius", category: "ad", domains: ["*.adocean.pl"] }, { name: "Adometry", company: "Google", category: "ad", domains: ["*.dmtry.com"] }, { name: "Adomik", category: "analytics", domains: ["*.adomik.com"] }, { name: "Adotmob", category: "ad", domains: ["*.adotmob.com"] }, { name: "Adrian Quevedo", category: "hosting", domains: ["*.adrianquevedo.com"] }, { name: "Adroit Digital Solutions", category: "ad", domains: ["*.imiclk.com", "*.abmr.net"] }, { name: "AdsNative", category: "ad", domains: ["*.adsnative.com"] }, { name: "AdsWizz", category: "ad", domains: ["*.adswizz.com"] }, { name: "Adscale", category: "ad", domains: ["*.adscale.de"] }, { name: "Adschoom", company: "JSWeb Production", category: "ad", domains: ["*.adschoom.com"] }, { name: "Adscience", category: "ad", domains: ["*.adscience.nl"] }, { name: "Adsiduous", category: "ad", domains: ["*.adsiduous.com"] }, { name: "Adsty", category: "ad", domains: ["*.adx1.com"] }, { name: "Adtech (AOL)", category: "ad", domains: ["*.adtechus.com"] }, { name: "Adtegrity", category: "ad", domains: ["*.adtpix.com"] }, { name: "Adthink", company: "Adthink Media", category: "ad", domains: ["*.adxcore.com", "*.dcoengine.com"] }, { name: "AdultWebmasterEmpire.Com", category: "ad", domains: ["*.awempire.com"] }, { name: "Adunity", category: "ad", domains: ["*.adunity.com"] }, { name: "Advance Magazine Group", category: "content", domains: ["*.condenastdigital.com", "*.condenet.com", "*.condenast.co.uk"] }, { name: "Adverline Board", company: "Adverline", category: "ad", domains: ["*.adverline.com", "*.adnext.fr"] }, { name: "AdvertServe", category: "ad", domains: ["*.advertserve.com"] }, { name: "Advolution", category: "utility", domains: ["*.advolution.de"] }, { name: "Adwise", category: "ad", domains: ["*.adwise.bg"] }, { name: "Adyen", category: "utility", domains: ["*.adyen.com"] }, { name: "Adyoulike", category: "ad", domains: ["*.adyoulike.com", "*.omnitagjs.com", "*.adyoulike.net"] }, { name: "Adzerk", category: "ad", domains: ["*.adzerk.net"] }, { name: "Adzip", company: "Adbox Digital", category: "ad", domains: ["*.adzip.co"] }, { name: "AerServ", category: "ad", domains: ["*.aerserv.com"] }, { name: "Affectv", category: "ad", domains: ["*.affectv.com", "*.affec.tv"] }, { name: "Affiliate Window", company: "Digital Window", category: "ad", domains: ["*.dwin1.com"] }, { name: "Affiliatly", category: "ad", domains: ["*.affiliatly.com"] }, { name: "Affino", category: "ad", domains: ["affino.com"] }, { name: "Affirm", category: "utility", domains: ["*.affirm.com"] }, { name: "Afterpay", company: "Block", category: "utility", homepage: "https://www.afterpay.com/", domains: ["*.afterpay.com"] }, { name: "Agenda Media", category: "ad", domains: ["*.agendamedia.co.uk"] }, { name: "Aggregate Knowledge", company: "Neustar", category: "ad", domains: ["*.agkn.com"] }, { name: "AgilOne", category: "marketing", domains: ["*.agilone.com"] }, { name: "Agility", category: "hosting", domains: ["*.agilitycms.com"] }, { name: "Ahalogy", category: "social", domains: ["*.ahalogy.com"] }, { name: "Aheadworks", category: "utility", domains: ["*.aheadworks.com"] }, { name: "AirPR", category: "analytics", domains: ["*.airpr.com"] }, { name: "Aira", category: "ad", domains: ["*.aira.net"] }, { name: "Airport Parking and Hotels", category: "content", domains: ["*.aph.com"] }, { name: "Akanoo", category: "analytics", domains: ["*.akanoo.com"] }, { name: "Alchemy", company: "AndBeyond.Media", category: "ad", domains: ["*.andbeyond.media"] }, { name: "AlephD", company: "AOL", category: "ad", domains: ["*.alephd.com"] }, { name: "AliveChat", company: "AYU Technology Solutions", category: "customer-success", domains: ["*.websitealive.com", "*.websitealive7.com"] }, { name: "All Access", category: "other", domains: ["*.allaccess.com.ph"] }, { name: "Alliance for Audited Media", category: "ad", domains: ["*.aamsitecertifier.com"] }, { name: "Allyde", category: "marketing", domains: ["*.mautic.com"] }, { name: "AlphaSSL", category: "utility", domains: ["*.alphassl.com"] }, { name: "Altitude", category: "ad", domains: ["*.altitudeplatform.com"] }, { name: "Altocloud", category: "analytics", domains: ["*.altocloud.com"] }, { name: "Amadeus", category: "content", domains: ["*.e-travel.com"] }, { name: "Amazon CloudFront", company: "Amazon", category: "utility", domains: ["cloudfront.net"] }, { name: "Ambassador", category: "ad", domains: ["*.getambassador.com"] }, { name: "Ambient", company: "Ericcson", category: "other", domains: ["*.adnetwork.vn", "*.ambientplatform.vn"] }, { name: "Amelia Communication", category: "hosting", domains: ["*.sara.media"] }, { name: "Amobee", category: "marketing", domains: ["*.amgdgt.com", "*.kontera.com"] }, { name: "Amplience", category: "marketing", domains: ["*.10cms.com", "*.amplience.com", "*.amplience.net", "*.bigcontent.io", "*.adis.ws"] }, { name: "Amplitude Mobile Analytics", company: "Amplitude", category: "analytics", domains: ["*.amplitude.com", "d24n15hnbwhuhn.cloudfront.net"] }, { name: "Anametrix", company: "Ensighten", category: "analytics", domains: ["*.anametrix.com"] }, { name: "Ancora Platform", company: "Ancora Media Solutions", category: "ad", domains: ["*.ancoraplatform.com"] }, { name: "Anedot", category: "other", domains: ["*.anedot.com"] }, { name: "AnimateJS", category: "utility", domains: ["*.animatedjs.com"] }, { name: "AnswerDash", category: "customer-success", domains: ["*.answerdash.com"] }, { name: "Answers", category: "analytics", domains: ["*.answcdn.com", "*.answers.com", "*.dsply.com"] }, { name: "Apester", category: "analytics", domains: ["*.apester.com", "*.qmerce.com"] }, { name: "Apligraf SmartWeb", company: "Apligraf", category: "utility", domains: ["*.apligraf.com.br"] }, { name: "Appier", category: "ad", domains: ["*.appier.net"] }, { name: "Appsolute", category: "utility", homepage: "https://appsolute.us/", domains: ["dropahint.love"] }, { name: "Apptus eSales", company: "Apptus", category: "analytics", domains: ["*.apptus.com"] }, { name: "Arbor", company: "LiveRamp", category: "other", domains: ["*.pippio.com"] }, { name: "Ardent Creative", category: "hosting", domains: ["*.ardentcreative.co.uk"] }, { name: "Arnold Clark Automobiles", category: "content", domains: ["*.arnoldclark.com"] }, { name: "Atom Content Marketing", category: "content", domains: ["*.atomvault.net"] }, { name: "Atom Data", category: "other", domains: ["*.atomdata.io"] }, { name: "Attribution", category: "ad", domains: ["*.attributionapp.com"] }, { name: "Audience 360", company: "Datapoint Media", category: "ad", domains: ["*.dpmsrv.com"] }, { name: "Audience Science", category: "ad", domains: ["*.revsci.net"] }, { name: "AudienceSearch", company: "Intimate Merger", category: "ad", domains: ["*.im-apps.net"] }, { name: "Auditorius", category: "ad", domains: ["*.audtd.com"] }, { name: "Augur", category: "analytics", domains: ["*.augur.io"] }, { name: "Auto Link Maker", company: "Apple", category: "ad", domains: ["*.apple.com"] }, { name: "Autopilot", category: "ad", domains: ["*.autopilothq.com"] }, { name: "Avail", company: "RichRelevance", category: "ad", domains: ["*.avail.net"] }, { name: "AvantLink", category: "ad", domains: ["*.avmws.com"] }, { name: "Avco Systems", category: "utility", domains: ["*.avcosystems.com"] }, { name: "Avid Media", category: "customer-success", domains: ["*.adspdbl.com", "*.metadsp.co.uk"] }, { name: "Avocet Systems", category: "ad", domains: ["*.avocet.io", "ads.avct.cloud"] }, { name: "Avora", category: "analytics", domains: ["*.truedash.com"] }, { name: "Azure Traffic Manager", company: "Microsoft", category: "other", domains: ["*.gateway.net", "*.trafficmanager.net"] }, { name: "Azure Web Services", company: "Microsoft", category: "cdn", domains: ["*.azurewebsites.net", "*.azureedge.net", "*.msedge.net", "*.windows.net"] }, { name: "BAM", category: "analytics", domains: ["*.bam-x.com"] }, { name: "Baifendian Technology", category: "marketing", domains: ["*.baifendian.com"] }, { name: "Bankrate", category: "utility", domains: ["*.bankrate.com"] }, { name: "BannerFlow", company: "Nordic Factory Solutions", category: "ad", domains: ["*.bannerflow.com"] }, { name: "Barclaycard SmartPay", company: "Barclaycard", category: "utility", domains: ["*.barclaycardsmartpay.com"] }, { name: "Barilliance", category: "analytics", domains: ["*.barilliance.net", "dn3y71tq7jf07.cloudfront.net"] }, { name: "Barnebys", category: "other", domains: ["*.barnebys.com"] }, { name: "Basis", company: "Basis Technologies", category: "ad", homepage: "https://basis.net/", domains: ["*.basis.net"] }, { name: "Batch Media", category: "ad", domains: ["*.t4ft.de"] }, { name: "Bauer Consumer Media", category: "content", domains: ["*.bauercdn.com", "*.greatmagazines.co.uk"] }, { name: "Baynote", category: "analytics", domains: ["*.baynote.net"] }, { name: "Bazaarvoice", category: "analytics", domains: ["*.bazaarvoice.com", "*.feedmagnet.com"] }, { name: "Beachfront Media", category: "ad", domains: ["*.bfmio.com"] }, { name: "BeamPulse", category: "analytics", domains: ["*.beampulse.com"] }, { name: "Beeswax", category: "ad", domains: ["*.bidr.io"] }, { name: "Beetailer", category: "social", domains: ["*.beetailer.com"] }, { name: "Best Of Media S.A.", category: "content", domains: ["*.servebom.com"] }, { name: "Bet365", category: "ad", domains: ["*.bet365affiliates.com"] }, { name: "Betfair", category: "other", domains: ["*.cdnbf.net"] }, { name: "Betgenius", company: "Genius Sports", category: "content", domains: ["*.connextra.com"] }, { name: "Better Banners", category: "ad", domains: ["*.betterbannerscloud.com"] }, { name: "Better Business Bureau", category: "analytics", domains: ["*.bbb.org"] }, { name: "Between Digital", category: "ad", domains: ["*.betweendigital.com"] }, { name: "BidTheatre", category: "ad", domains: ["*.bidtheatre.com"] }, { name: "Bidtellect", category: "ad", domains: ["*.bttrack.com"] }, { name: "Bigcommerce", category: "marketing", domains: ["*.bigcommerce.com"] }, { name: "BitGravity", company: "Tata Communications", category: "content", domains: ["*.bitgravity.com"] }, { name: "Bitly", category: "utility", domains: ["*.bitly.com", "*.lemde.fr", "*.bit.ly"] }, { name: "Bizible", category: "ad", domains: ["*.bizible.com", "*.bizibly.com"] }, { name: "Bizrate", category: "analytics", domains: ["*.bizrate.com"] }, { name: "BlastCasta", category: "social", domains: ["*.poweringnews.com"] }, { name: "Blindado", category: "utility", domains: ["*.siteblindado.com"] }, { name: "Blis", category: "ad", domains: ["*.blismedia.com"] }, { name: "Blogg.se", category: "hosting", domains: ["*.cdnme.se", "*.publishme.se"] }, { name: "BloomReach", category: "ad", domains: ["*.brcdn.com", "*.brsrvr.com", "*.brsvr.com"] }, { name: "Bloomberg", category: "content", domains: ["*.gotraffic.net"] }, { name: "Shop Logic", company: "BloomReach", category: "marketing", domains: ["*.goshoplogic.com"] }, { name: "Blue State Digital", category: "ad", domains: ["*.bsd.net"] }, { name: "Blue Triangle Technologies", category: "analytics", domains: ["*.btttag.com"] }, { name: "BlueCava", category: "ad", domains: ["*.bluecava.com"] }, { name: "BlueKai", company: "Oracle", category: "ad", domains: ["*.bkrtx.com", "*.bluekai.com"] }, { name: "Bluecore", category: "analytics", domains: ["*.bluecore.com"] }, { name: "Bluegg", category: "hosting", domains: ["d1va5oqn59yrvt.cloudfront.net"] }, { name: "Bold Commerce", category: "utility", domains: ["*.shappify-cdn.com", "*.shappify.com", "*.boldapps.net"] }, { name: "BoldChat", company: "LogMeIn", category: "customer-success", domains: ["*.boldchat.com"] }, { name: "Bombora", category: "ad", domains: ["*.mlno6.com"] }, { name: "Bonnier", category: "content", domains: ["*.bonniercorp.com"] }, { name: "Bookatable", category: "content", domains: ["*.bookatable.com", "*.livebookings.com"] }, { name: "Booking.com", category: "content", domains: ["*.bstatic.com"] }, { name: "Boomtrain", category: "ad", domains: ["*.boomtrain.com", "*.boomtrain.net"] }, { name: "BoostSuite", category: "ad", domains: ["*.poweredbyeden.com"] }, { name: "Boostable", category: "ad", domains: ["*.boostable.com"] }, { name: "Bootstrap Chinese network", category: "cdn", domains: ["*.bootcss.com"] }, { name: "Booxscale", category: "ad", domains: ["*.booxscale.com"] }, { name: "Borderfree", company: "pitney bowes", category: "utility", domains: ["*.borderfree.com", "*.fiftyone.com"] }, { name: "BowNow", category: "analytics", homepage: "https://bow-now.jp/", domains: ["*.bownow.jp"] }, { name: "Box", category: "hosting", domains: ["*.box.com"] }, { name: "Boxever", category: "analytics", domains: ["*.boxever.com"] }, { name: "Braintree Payments", company: "Paypal", category: "utility", domains: ["*.braintreegateway.com"] }, { name: "Branch Metrics", category: "ad", domains: ["*.branch.io", "*.app.link"] }, { name: "Brand Finance", category: "other", domains: ["*.brandirectory.com"] }, { name: "Brand View", category: "analytics", domains: ["*.brandview.com"] }, { name: "Brandscreen", category: "ad", domains: ["*.rtbidder.net"] }, { name: "BridgeTrack", company: "Sapient", category: "ad", domains: ["*.bridgetrack.com"] }, { name: "BrightRoll", company: "Yahoo!", category: "ad", domains: ["*.btrll.com"] }, { name: "BrightTag / Signal", company: "Signal", homepage: "https://www.signal.co", category: "tag-manager", domains: ["*.btstatic.com", "*.thebrighttag.com"] }, { name: "Brightcove ZenCoder", company: "Brightcove", category: "other", domains: ["*.zencoder.net"] }, { name: "Bronto Software", category: "marketing", domains: ["*.bm23.com", "*.bronto.com", "*.brontops.com"] }, { name: "Browser-Update.org", category: "other", domains: ["*.browser-update.org"] }, { name: "Buffer", category: "social", domains: ["*.bufferapp.com"] }, { name: "Bugsnag", category: "utility", domains: ["*.bugsnag.com", "d2wy8f7a9ursnm.cloudfront.net"] }, { name: "Burst Media", category: "ad", domains: ["*.burstnet.com", "*.1rx.io"] }, { name: "Burt", category: "analytics", domains: ["*.richmetrics.com", "*.burt.io"] }, { name: "Business Message", category: "ad", domains: ["*.message-business.com"] }, { name: "Business Week", company: "Bloomberg", category: "social", domains: ["*.bwbx.io"] }, { name: "Buto", company: "Big Button", category: "ad", domains: ["*.buto.tv"] }, { name: "Button", category: "ad", domains: ["*.btncdn.com"] }, { name: "BuySellAds", category: "ad", domains: ["*.buysellads.com", "*.buysellads.net"] }, { name: "BuySight (AOL)", category: "ad", domains: ["*.pulsemgr.com"] }, { name: "Buyapowa", category: "ad", domains: ["*.co-buying.com"] }, { name: "BuzzFeed", category: "social", domains: ["*.buzzfed.com", "*.buzzfeed.com"] }, { name: "C1X", category: "ad", domains: ["*.c1exchange.com"] }, { name: "C3 Metrics", category: "analytics", domains: ["*.c3tag.com"] }, { name: "CANDDi", company: "Campaign and Digital Intelligence", category: "ad", domains: ["*.canddi.com"] }, { name: "CCM benchmark Group", category: "social", domains: ["*.ccm2.net"] }, { name: "CD Networks", category: "utility", domains: ["*.gccdn.net"] }, { name: "CDN Planet", category: "analytics", domains: ["*.cdnplanet.com"] }, { name: "InAuth", category: "utility", homepage: "https://www.inauth.com/", domains: ["*.cdn-net.com"] }, { name: "CJ Affiliate", company: "Conversant", category: "ad", domains: ["*.cj.com", "*.dpbolvw.net"] }, { name: "CJ Affiliate by Conversant", company: "Conversant", category: "ad", domains: ["*.ftjcfx.com"] }, { name: "CNBC", category: "content", domains: ["*.cnbc.com"] }, { name: "CNET Content Solutions", company: "CBS Interactive", category: "content", domains: ["*.cnetcontent.com"] }, { name: "CPEx", category: "content", domains: ["*.cpex.cz"] }, { name: "CPXi", category: "ad", domains: ["*.cpxinteractive.com"] }, { name: "CUBED Attribution", company: "CUBED", category: "ad", domains: ["*.withcubed.com"] }, { name: "Cachefly", category: "utility", domains: ["*.cachefly.net"] }, { name: "Calendly", category: "other", domains: ["*.calendly.com"] }, { name: "CallRail", category: "analytics", domains: ["*.callrail.com"] }, { name: "CallTrackingMetrics", category: "analytics", domains: ["*.tctm.co"] }, { name: "Canned Banners", category: "ad", domains: ["*.cannedbanners.com"] }, { name: "Canopy Labs", category: "analytics", domains: ["*.canopylabs.com"] }, { name: "Capita", category: "utility", domains: ["*.crcom.co.uk"] }, { name: "Captify Media", category: "ad", domains: ["*.cpx.to"] }, { name: "Captiify", category: "ad", domains: ["*.captifymedia.com"] }, { name: "Captivate Ai", category: "ad", domains: ["*.captivate.ai"] }, { name: "Captora", category: "marketing", domains: ["*.captora.com"] }, { name: "Carcloud", category: "other", domains: ["*.carcloud.co.uk"] }, { name: "Cardlytics", category: "ad", domains: ["*.cardlytics.com"] }, { name: "Cardosa Enterprises", category: "analytics", domains: ["*.y-track.com"] }, { name: "Caspian Media", category: "ad", domains: ["*.caspianmedia.com"] }, { name: "Cast", category: "utility", domains: ["*.cast.rocks"] }, { name: "Catch", category: "other", domains: ["*.getcatch.com"] }, { name: "Cavisson", category: "analytics", domains: ["*.cavisson.com"] }, { name: "Cedato", category: "ad", domains: ["*.algovid.com", "*.vdoserv.com"] }, { name: "Celebrus Technologies", category: "analytics", domains: ["*.celebrus.com"] }, { name: "Celtra", category: "ad", domains: ["*.celtra.com"] }, { name: "Centro", category: "ad", domains: ["*.brand-server.com"] }, { name: "Ceros", category: "other", domains: ["ceros.com", "view.ceros.com"] }, { name: "Ceros Analytics", company: "Ceros", category: "analytics", domains: ["api.ceros.com"] }, { name: "Certona", category: "analytics", domains: ["*.certona.net"] }, { name: "Certum", category: "utility", domains: ["*.ocsp-certum.com", "*.certum.pl"] }, { name: "Cgrdirect", category: "other", domains: ["*.cgrdirect.co.uk"] }, { name: "Channel 5 Media", category: "ad", domains: ["*.five.tv"] }, { name: "Channel.me", category: "customer-success", domains: ["*.channel.me"] }, { name: "ChannelAdvisor", category: "ad", domains: ["*.channeladvisor.com", "*.searchmarketing.com"] }, { name: "ChannelApe", company: "ChannelApe", category: "other", homepage: "https://www.channelape.com/", domains: ["*.channelape.com"] }, { name: "Chargeads Oscar", company: "Chargeads", category: "ad", domains: ["*.chargeads.com"] }, { name: "Charities Aid Foundation", category: "utility", domains: ["*.cafonline.org"] }, { name: "Chartbeat", category: "analytics", domains: ["*.chartbeat.com", "*.chartbeat.net"] }, { name: "Cheapflights Media", company: "Momondo", category: "content", domains: ["*.momondo.net"] }, { name: "CheckM8", category: "ad", domains: ["*.checkm8.com"] }, { name: "CheckRate", company: "FreeStart", category: "utility", domains: ["*.checkrate.co.uk"] }, { name: "Checkfront", category: "other", domains: ["*.checkfront.com", "dcg3jth5savst.cloudfront.net"] }, { name: "CheetahMail", company: "Experian", category: "ad", domains: ["*.chtah.com"] }, { name: "Chitika", category: "ad", domains: ["*.chitika.net"] }, { name: "ChoiceStream", category: "ad", domains: ["*.choicestream.com"] }, { name: "Cint", category: "social", domains: ["*.cint.com"] }, { name: "Civic", category: "hosting", domains: ["*.civiccomputing.com"] }, { name: "ClearRise", category: "customer-success", domains: ["*.clearrise.com"] }, { name: "Clearstream", category: "ad", domains: ["*.clrstm.com"] }, { name: "Clerk.io ApS", category: "analytics", domains: ["*.clerk.io"] }, { name: "CleverDATA", category: "ad", domains: ["*.1dmp.io"] }, { name: "CleverTap", category: "analytics", domains: ["d2r1yp2w7bby2u.cloudfront.net"] }, { name: "Click Density", category: "analytics", domains: ["*.clickdensity.com"] }, { name: "Click4Assistance", category: "customer-success", domains: ["*.click4assistance.co.uk"] }, { name: "ClickDesk", category: "customer-success", domains: ["*.clickdesk.com", "d1gwclp1pmzk26.cloudfront.net"] }, { name: "ClickDimensions", category: "ad", domains: ["*.clickdimensions.com"] }, { name: "Clickadu (Winner Solutions)", category: "ad", domains: ["*.clickadu.com"] }, { name: "Clickagy Audience Lab", company: "Clickagy", category: "ad", domains: ["*.clickagy.com"] }, { name: "Clickio", category: "ad", domains: [] }, { name: "Clicktale", category: "analytics", domains: ["*.cdngc.net", "*.clicktale.net"] }, { name: "Clicktripz", category: "content", domains: ["*.clicktripz.com"] }, { name: "Clik.com Websites", category: "content", domains: ["*.clikpic.com"] }, { name: "Cloud Technologies", category: "ad", domains: ["*.behavioralengine.com", "*.behavioralmailing.com"] }, { name: "Cloud-A", category: "other", domains: ["*.bulkstorage.ca"] }, { name: "Cloud.typography", company: "Hoefler &amp; Co", category: "cdn", domains: ["*.typography.com"] }, { name: "CloudSponge", category: "ad", domains: ["*.cloudsponge.com"] }, { name: "CloudVPS", category: "other", domains: ["*.adoftheyear.com", "*.objectstore.eu"] }, { name: "Cloudinary", category: "content", domains: ["*.cloudinary.com"] }, { name: "Cloudqp", company: "Cloudwp", category: "other", domains: ["*.cloudwp.io"] }, { name: "Cludo", category: "utility", domains: ["*.cludo.com"] }, { name: "Cognesia", category: "marketing", domains: ["*.intelli-direct.com"] }, { name: "CogoCast", company: "Cogo Labs", category: "ad", domains: ["*.cogocast.net"] }, { name: "Colbenson", category: "utility", domains: ["*.colbenson.com"] }, { name: "Collective", category: "ad", domains: ["*.collective-media.net"] }, { name: "Com Laude", category: "other", domains: ["*.gdimg.net"] }, { name: "Comm100", category: "customer-success", domains: ["*.comm100.com"] }, { name: "CommerceHub", category: "marketing", domains: ["*.mercent.com"] }, { name: "Commission Factory", category: "ad", domains: ["*.cfjump.com"] }, { name: "Communicator", category: "ad", domains: ["*.communicatorcorp.com", "*.communicatoremail.com"] }, { name: "Comodo", category: "utility", domains: ["*.comodo.com", "*.trust-provider.com", "*.trustlogo.com", "*.usertrust.com", "*.comodo.net"] }, { name: "Comodo Certificate Authority", company: "Comodo", category: "utility", domains: ["crt.comodoca.com", "*.comodoca4.com", "ocsp.comodoca.com", "ocsp.usertrust.com", "crt.usertrust.com"] }, { name: "Compete", company: "Millwood Brown Digital", category: "analytics", domains: ["*.c-col.com", "*.compete.com"] }, { name: "Compuware", category: "analytics", domains: ["*.axf8.net"] }, { name: "Conductrics", category: "analytics", domains: ["*.conductrics.com"] }, { name: "Confirmit", category: "analytics", domains: ["*.confirmit.com"] }, { name: "Connatix", category: "ad", domains: ["*.connatix.com"] }, { name: "Connect Events", category: "hosting", domains: ["*.connectevents.com.au"] }, { name: "Constant Contact", category: "ad", domains: ["*.ctctcdn.com"] }, { name: "Constructor.io", category: "utility", domains: ["*.cnstrc.com"] }, { name: "Contabo", category: "hosting", domains: ["185.2.100.179"] }, { name: "Content Media Corporation", category: "content", domains: ["*.contentmedia.eu"] }, { name: "ContentSquare", category: "analytics", domains: ["d1m6l9dfulcyw7.cloudfront.net", "*.content-square.net", "*.contentsquare.net"] }, { name: "ContextWeb", category: "ad", domains: ["*.contextweb.com"] }, { name: "Continental Exchange Solutions", category: "utility", domains: ["*.hifx.com"] }, { name: "Converge-Digital", category: "ad", domains: ["*.converge-digital.com"] }, { name: "Conversant", category: "analytics", domains: ["*.dotomi.com", "*.dtmpub.com", "*.emjcd.com", "mediaplex.com", "*.tqlkg.com", "*.fastclick.net"] }, { name: "Conversant Ad Server", company: "Conversant", category: "ad", domains: ["adfarm.mediaplex.com", "*.mediaplex.com"] }, { name: "Conversant Tag Manager", company: "Conversant", category: "tag-manager", domains: ["*.mplxtms.com"] }, { name: "Conversio", category: "ad", domains: ["*.conversio.com"] }, { name: "Conversion Labs", category: "ad", domains: ["*.net.pl"] }, { name: "Conversion Logic", category: "ad", domains: ["*.conversionlogic.net"] }, { name: "Convert Insights", category: "analytics", domains: ["*.convertexperiments.com"] }, { name: "ConvertMedia", category: "ad", domains: ["*.admailtiser.com", "*.basebanner.com", "*.cmbestsrv.com", "*.vidfuture.com", "*.zorosrv.com"] }, { name: "Convertro", category: "ad", domains: ["*.convertro.com"] }, { name: "Conviva", category: "content", domains: ["*.conviva.com"] }, { name: "Cookie Reports", category: "utility", domains: ["*.cookiereports.com"] }, { name: "Cookie-Script.com", category: "utility", domains: ["*.cookie-script.com"] }, { name: "CookieQ", company: "Baycloud Systems", category: "utility", domains: ["*.cookieq.com"] }, { name: "CoolaData", category: "analytics", domains: ["*.cooladata.com"] }, { name: "CopperEgg", category: "analytics", domains: ["*.copperegg.com", "d2vig74li2resi.cloudfront.net"] }, { name: "Council ad Network", category: "ad", domains: ["*.counciladvertising.net"] }, { name: "Covert Pics", category: "content", domains: ["*.covet.pics"] }, { name: "Cox Digital Solutions", category: "ad", domains: ["*.afy11.net"] }, { name: "Creafi Online Media", category: "ad", domains: ["*.creafi-online-media.com"] }, { name: "Creators", category: "content", domains: ["*.creators.co"] }, { name: "Crimson Hexagon Analytics", company: "Crimson Hexagon", category: "analytics", domains: ["*.hexagon-analytics.com"] }, { name: "Crimtan", category: "ad", domains: ["*.ctnsnet.com"] }, { name: "Cross Pixel Media", category: "ad", domains: ["*.crsspxl.com"] }, { name: "Crosswise", category: "ad", domains: ["*.univide.com"] }, { name: "Crowd Control", company: "Lotame", category: "ad", domains: ["*.crwdcntrl.net"] }, { name: "Crowd Ignite", category: "ad", domains: ["*.crowdignite.com"] }, { name: "CrowdTwist", category: "ad", domains: ["*.crowdtwist.com"] }, { name: "Crowdskout", category: "ad", domains: ["*.crowdskout.com"] }, { name: "Crowdynews", category: "social", domains: ["*.breakingburner.com"] }, { name: "Curalate", category: "marketing", domains: ["*.curalate.com", "d116tqlcqfmz3v.cloudfront.net"] }, { name: "Customer Acquisition Cloud", company: "[24]7", category: "ad", domains: ["*.campanja.com"] }, { name: "Customer.io", category: "ad", domains: ["*.customer.io"] }, { name: "Custora", category: "analytics", domains: ["*.custora.com"] }, { name: "Cxense", category: "ad", domains: ["*.cxense.com", "*.cxpublic.com", "*.emediate.dk", "*.emediate.eu"] }, { name: "CyberKnight", company: "Namogoo", category: "utility", domains: ["*.namogoo.com"] }, { name: "CyberSource (Visa)", category: "utility", domains: ["*.authorize.net"] }, { name: "Cybernet Quest", category: "analytics", domains: ["*.cqcounter.com"] }, { name: "D.A. Consortium", category: "ad", domains: ["*.eff1.net"] }, { name: "D4t4 Solutions", category: "analytics", domains: ["*.u5e.com"] }, { name: "DCSL Software", category: "hosting", domains: ["*.dcslsoftware.com"] }, { name: "DMG Media", category: "content", domains: ["*.mol.im", "*.and.co.uk", "*.anm.co.uk", "*.dailymail.co.uk"] }, { name: "DTSCOUT", category: "ad", domains: ["*.dtscout.com"] }, { name: "Dailykarma", category: "utility", homepage: "https://www.dailykarma.com/", domains: ["*.dailykarma.io"] }, { name: "Dailymotion", category: "content", domains: ["*.dailymotion.com", "*.dmxleo.com", "*.dm.gg", "*.pxlad.io", "*.dmcdn.net", "*.sublimevideo.net"] }, { name: "Dash Hudson", company: "Dash Hudson", category: "content", domains: ["*.dashhudson.com"] }, { name: "Datacamp", category: "utility", domains: ["*.cdn77.org"] }, { name: "Datalicious", category: "tag-manager", domains: ["*.supert.ag", "*.optimahub.com"] }, { name: "Datalogix", category: "ad", domains: ["*.nexac.com"] }, { name: "Datawrapper", category: "utility", domains: ["*.datawrapper.de", "*.dwcdn.net"] }, { name: "Dataxu", category: "marketing", domains: ["*.w55c.net"] }, { name: "DatoCMS", homepage: "https://www.datocms.com/", category: "content", domains: ["*.datocms-assets.com"] }, { name: "Datonics", category: "ad", domains: ["*.pro-market.net"] }, { name: "Dealtime", category: "content", domains: ["*.dealtime.com"] }, { name: "Debenhams Geo Location", company: "Debenhams", category: "utility", domains: ["176.74.183.134"] }, { name: "Decibel Insight", category: "analytics", domains: ["*.decibelinsight.net"] }, { name: "Deep Forest Media", company: "Rakuten", category: "ad", domains: ["*.dpclk.com"] }, { name: "DeepIntent", category: "ad", domains: ["*.deepintent.com"] }, { name: "Delicious Media", category: "social", domains: ["*.delicious.com"] }, { name: "Delineo", category: "ad", domains: ["*.delineo.com"] }, { name: "Delta Projects AB", category: "ad", domains: ["*.de17a.com"] }, { name: "Demand Media", category: "content", domains: ["*.dmtracker.com"] }, { name: "DemandBase", category: "marketing", domains: ["*.demandbase.com"] }, { name: "DemandJump", category: "analytics", domains: ["*.demandjump.com"] }, { name: "Dennis Publishing", category: "content", domains: ["*.alphr.com"] }, { name: "Devatics", category: "analytics", domains: ["*.devatics.com", "*.devatics.io"] }, { name: "Developer Media", category: "ad", domains: ["*.developermedia.com"] }, { name: "DialogTech", category: "ad", domains: ["*.dialogtech.com"] }, { name: "DialogTech SourceTrak", company: "DialogTech", category: "ad", domains: ["d31y97ze264gaa.cloudfront.net"] }, { name: "DigiCert", category: "utility", domains: ["*.digicert.com"] }, { name: "Digioh", category: "ad", domains: ["*.lightboxcdn.com"] }, { name: "Digital Look", category: "content", domains: ["*.digitallook.com"] }, { name: "Digital Media Exchange", company: "NDN", category: "content", domains: ["*.newsinc.com"] }, { name: "Digital Millennium Copyright Act Services", category: "utility", domains: ["*.dmca.com"] }, { name: "Digital Ocean", category: "other", domains: ["95.85.62.56"] }, { name: "Digital Remedy", category: "ad", domains: ["*.consumedmedia.com"] }, { name: "Digital Window", category: "ad", domains: ["*.awin1.com", "*.zenaps.com"] }, { name: "DigitalScirocco", category: "analytics", domains: ["*.digitalscirocco.net"] }, { name: "Digitial Point", category: "utility", domains: ["*.dpstatic.com"] }, { name: "Diligent (Adnetik)", category: "ad", domains: ["*.wtp101.com"] }, { name: "Directed Edge", category: "social", domains: ["*.directededge.com"] }, { name: "Distribute Travel", category: "ad", domains: ["*.dtrck.net"] }, { name: "District M", category: "ad", domains: ["*.districtm.io"] }, { name: "DistroScale", category: "ad", domains: ["*.jsrdn.com"] }, { name: "Divido", category: "utility", domains: ["*.divido.com"] }, { name: "Dow Jones", category: "content", domains: ["*.dowjones.com", "*.dowjoneson.com"] }, { name: "Drifty Co", category: "utility", domains: ["*.onicframework.com"] }, { name: "Drip", company: "The Numa Group", category: "ad", domains: ["*.getdrip.com"] }, { name: "Dropbox", category: "utility", domains: ["*.dropboxusercontent.com"] }, { name: "Dyn Real User Monitoring", company: "Dyn", category: "analytics", domains: ["*.jisusaiche.biz", "*.dynapis.com", "*.jisusaiche.com", "*.dynapis.info"] }, { name: "DynAdmic", category: "ad", domains: ["*.dyntrk.com"] }, { name: "Dynamic Converter", category: "utility", domains: ["*.dynamicconverter.com"] }, { name: "Dynamic Dummy Image Generator", company: "Open Source", category: "utility", domains: ["*.dummyimage.com"] }, { name: "Dynamic Logic", category: "ad", domains: ["*.dl-rms.com", "*.questionmarket.com"] }, { name: "Dynamic Yield", category: "customer-success", domains: ["*.dynamicyield.com"] }, { name: "Dynatrace", category: "analytics", domains: ["*.ruxit.com", "js-cdn.dynatrace.com"] }, { name: "ec-concier", homepage: "https://ec-concier.com/", category: "marketing", domains: ["*.ec-concier.com"] }, { name: "ECT News Network", category: "content", domains: ["*.ectnews.com"] }, { name: "ELITechGroup", category: "analytics", domains: ["*.elitechnology.com"] }, { name: "EMAP", category: "content", domains: ["*.emap.com"] }, { name: "EMedia Solutions", category: "ad", domains: ["*.e-shots.eu"] }, { name: "EQ works", category: "ad", domains: ["*.eqads.com"] }, { name: "ESV Digital", category: "analytics", domains: ["*.esearchvision.com"] }, { name: "Ebiquity", category: "analytics", domains: ["*.ebiquitymedia.com"] }, { name: "Eco Rebates", category: "ad", domains: ["*.ecorebates.com"] }, { name: "Ecwid", category: "hosting", domains: ["*.ecwid.com", "*.shopsettings.com", "d3fi9i0jj23cau.cloudfront.net", "d3j0zfs7paavns.cloudfront.net"] }, { name: "Edge Web Fonts", company: "Adobe Systems", category: "cdn", domains: ["*.edgefonts.net"] }, { name: "Edition Digital", category: "ad", domains: ["*.editiondigital.com"] }, { name: "Edot Web Technologies", category: "hosting", domains: ["*.edot.co.za"] }, { name: "Effective Measure", category: "ad", domains: ["*.effectivemeasure.net"] }, { name: "Effiliation sa", category: "ad", domains: ["*.effiliation.com"] }, { name: "Ekm Systems", category: "analytics", domains: ["*.ekmsecure.com", "*.ekmpinpoint.co.uk"] }, { name: "Elastera", category: "hosting", domains: ["*.elastera.net"] }, { name: "Elastic Ad", category: "ad", domains: ["*.elasticad.net"] }, { name: "Elastic Load Balancing", company: "Amazon Web Services", category: "hosting", domains: ["*.105app.com"] }, { name: "Elecard StreamEye", company: "Elecard", category: "other", domains: ["*.streameye.net"] }, { name: "Elevate", company: "Elevate Technology Solutions", category: "utility", domains: ["*.elevaate.technology"] }, { name: "Elicit", category: "utility", domains: ["*.elicitapp.com"] }, { name: "Elogia", category: "ad", domains: ["*.elogia.net"] }, { name: "Email Attitude", company: "1000mercis", category: "ad", domains: ["*.email-attitude.com"] }, { name: "EmailCenter", category: "ad", domains: ["*.emailcenteruk.com"] }, { name: "Embedly", category: "content", domains: ["*.embedly.com", "*.embed.ly"] }, { name: "EmpathyBroker Site Search", company: "EmpathyBroker", category: "utility", domains: ["*.empathybroker.com"] }, { name: "Enfusen", category: "analytics", domains: ["*.enfusen.com"] }, { name: "Engadget", company: "Engadget (AOL)", category: "content", domains: ["*.gdgt.com"] }, { name: "Engagio", category: "marketing", domains: ["*.engagio.com"] }, { name: "Ensighten Manage", company: "Ensighten", category: "tag-manager", domains: ["*.levexis.com"] }, { name: "EntityLink", category: "other", domains: ["*.entitytag.co.uk"] }, { name: "Entrust Datacard", category: "utility", domains: ["*.entrust.com", "*.entrust.net"] }, { name: "Equiniti", category: "utility", domains: ["*.equiniti.com"] }, { name: "Errorception", category: "utility", domains: ["*.errorception.com"] }, { name: "Esri ArcGIS", company: "Esri", category: "utility", domains: ["*.arcgis.com", "*.arcgisonline.com"] }, { name: "Ethnio", category: "analytics", domains: ["*.ethn.io"] }, { name: "Eulerian Technologies", category: "ad", domains: ["*.eolcdn.com"] }, { name: "Euroland", category: "utility", domains: ["*.euroland.com"] }, { name: "European Interactive Digital ad Alli", category: "utility", domains: ["*.edaa.eu"] }, { name: "Eventbrite", category: "hosting", domains: ["*.evbuc.com", "*.eventbrite.co.uk"] }, { name: "Everflow", category: "analytics", domains: ["*.tp88trk.com"] }, { name: "Evergage", category: "analytics", domains: ["*.evergage.com", "*.evgnet.com"] }, { name: "Everquote", category: "content", domains: ["*.evq1.com"] }, { name: "Everyday Health", category: "ad", domains: ["*.agoramedia.com"] }, { name: "Evidon", category: "analytics", domains: ["*.evidon.com"] }, { name: "Evolve Media", category: "content", domains: ["*.evolvemediallc.com"] }, { name: "Exactag", category: "ad", domains: ["*.exactag.com"] }, { name: "ExoClick", category: "ad", domains: ["*.exoclick.com"] }, { name: "Expedia", category: "content", domains: ["*.travel-assets.com", "*.trvl-media.com", "*.trvl-px.com", "*.uciservice.com"] }, { name: "Expedia Australia", company: "Expedia", category: "content", domains: ["*.expedia.com.au"] }, { name: "Expedia Canada", company: "Expedia", category: "content", domains: ["*.expedia.ca"] }, { name: "Expedia France", company: "Expedia", category: "content", domains: ["*.expedia.fr"] }, { name: "Expedia Germany", company: "Expedia", category: "content", domains: ["*.expedia.de"] }, { name: "Expedia Italy", company: "Expedia", category: "content", domains: ["*.expedia.it"] }, { name: "Expedia Japan", company: "Expedia", category: "content", domains: ["*.expedia.co.jp"] }, { name: "Expedia USA", company: "Expedia", category: "content", domains: ["*.expedia.com"] }, { name: "Expedia United Kingdom", company: "Expedia", category: "content", domains: ["*.expedia.co.uk"] }, { name: "Experian", category: "utility", domains: ["*.audienceiq.com", "*.experian.com", "*.experianmarketingservices.digital"] }, { name: "Experian Cross-Channel Marketing Platform", company: "Experian", category: "marketing", domains: ["*.eccmp.com", "*.ccmp.eu"] }, { name: "Exponea", category: "analytics", domains: ["*.exponea.com"] }, { name: "Exponential Interactive", category: "ad", domains: ["*.exponential.com"] }, { name: "Extensis WebInk", category: "cdn", domains: ["*.webink.com"] }, { name: "Extole", category: "ad", domains: ["*.extole.com", "*.extole.io"] }, { name: "Ey-Seren", category: "analytics", domains: ["*.webabacus.com"] }, { name: "EyeView", category: "ad", domains: ["*.eyeviewads.com"] }, { name: "Eyeota", category: "ad", domains: ["*.eyeota.net"] }, { name: "Ezakus Pretargeting", company: "Ezakus", category: "ad", domains: ["*.ezakus.net"] }, { name: "Ezoic", category: "analytics", domains: ["*.ezoic.net"] }, { name: "FLXone", company: "Teradata", category: "ad", domains: ["*.pangolin.blue", "*.flx1.com", "d2hlpp31teaww3.cloudfront.net", "*.flxpxl.com"] }, { name: "Fairfax Media", category: "content", domains: ["ads.fairfax.com.au", "resources.fairfax.com.au"] }, { name: "Fairfax Media Analtics", company: "Fairfax Media", category: "analytics", domains: ["analytics.fairfax.com.au"] }, { name: "Falk Technologies", category: "ad", domains: ["*.angsrvr.com"] }, { name: "Fanplayr", category: "analytics", domains: ["*.fanplayr.com", "d38nbbai6u794i.cloudfront.net"] }, { name: "Fast Thinking", company: "NE Marketing", category: "marketing", domains: ["*.fast-thinking.co.uk"] }, { name: "Fastest Forward", category: "analytics", domains: ["*.gaug.es"] }, { name: "Fastly", category: "utility", domains: ["*.fastly.net"] }, { name: "Feedbackify", company: "InsideMetrics", category: "analytics", domains: ["*.feedbackify.com"] }, { name: "Feefo.com", company: "Feefo", category: "analytics", domains: ["*.feefo.com"] }, { name: "Fidelity Media", category: "ad", domains: ["*.fidelity-media.com"] }, { name: "Filestack", category: "content", domains: ["*.filepicker.io"] }, { name: "Finsbury Media", category: "ad", domains: ["*.finsburymedia.com"] }, { name: "Firepush", category: "utility", domains: ["*.firepush.io"] }, { name: "FirstImpression", category: "ad", domains: ["*.firstimpression.io"] }, { name: "Fit Analytics", category: "other", domains: ["*.fitanalytics.com"] }, { name: "Fits Me", category: "analytics", domains: ["*.fits.me"] }, { name: "Fivetran", category: "analytics", domains: ["*.fivetran.com"] }, { name: "FlexShopper", category: "utility", domains: ["*.flexshopper.com"] }, { name: "Flickr", category: "content", domains: ["*.flickr.com", "*.staticflickr.com"] }, { name: "Flipboard", category: "social", domains: ["*.flipboard.com"] }, { name: "Flipdesk", category: "customer-success", homepage: "https://flipdesk.jp/", domains: ["*.flipdesk.jp"] }, { name: "Flipp", category: "analytics", domains: ["*.wishabi.com", "d2e0sxz09bo7k2.cloudfront.net", "*.wishabi.net"] }, { name: "Flite", category: "ad", domains: ["*.flite.com"] }, { name: "Flixmedia", category: "analytics", domains: ["*.flix360.com", "*.flixcar.com", "*.flixfacts.com", "*.flixsyndication.net", "*.flixfacts.co.uk"] }, { name: "Flockler", category: "ad", domains: ["*.flockler.com"] }, { name: "Flowplayer", category: "content", domains: ["*.flowplayer.org"] }, { name: "Flowzymes Ky", category: "cdn", domains: ["*.jquerytools.org"] }, { name: "Fomo", category: "ad", domains: ["*.notifyapp.io"] }, { name: "Fonecall", category: "analytics", domains: ["*.web-call-analytics.com"] }, { name: "Fontdeck", category: "cdn", domains: ["*.fontdeck.com"] }, { name: "Foodity Technologies", category: "ad", domains: ["*.foodity.com"] }, { name: "Force24", category: "ad", domains: ["*.force24.co.uk"] }, { name: "ForeSee", company: "Answers", category: "analytics", domains: ["*.4seeresults.com", "*.answerscloud.com", "*.foresee.com", "*.foreseeresults.com"] }, { name: "Forensiq", category: "utility", domains: ["*.fqtag.com"] }, { name: "Fort Awesome", category: "cdn", domains: ["*.fortawesome.com"] }, { name: "Forter", category: "utility", domains: ["*.forter.com"] }, { name: "Forward Internet Group", category: "hosting", domains: ["*.f3d.io"] }, { name: "Forward3D", category: "ad", domains: ["*.forward3d.com"] }, { name: "Fospha", category: "analytics", domains: ["*.fospha.com"] }, { name: "Foursixty", category: "customer-success", domains: ["*.foursixty.com"] }, { name: "FoxyCart", category: "utility", domains: ["*.foxycart.com"] }, { name: "Fraudlogix", category: "utility", domains: ["*.yabidos.com"] }, { name: "FreakOut", category: "ad", domains: ["*.fout.jp"] }, { name: "Freespee", category: "customer-success", domains: ["*.freespee.com"] }, { name: "Freetobook", category: "content", domains: ["*.freetobook.com"] }, { name: "Fresh 8 Gaming", category: "ad", domains: ["*.fresh8.co"] }, { name: "Fresh Relevance", category: "analytics", domains: ["*.freshrelevance.com", "*.cloudfront.ne", "d1y9qtn9cuc3xw.cloudfront.net", "d81mfvml8p5ml.cloudfront.net", "dkpklk99llpj0.cloudfront.net"] }, { name: "Friendbuy", category: "ad", domains: ["*.friendbuy.com", "djnf6e5yyirys.cloudfront.net"] }, { name: "Frienefit", category: "ad", domains: ["*.frienefit.com"] }, { name: "FuelX", category: "ad", domains: ["*.fuelx.com"] }, { name: "Full Circle Studies", category: "analytics", domains: ["*.securestudies.com"] }, { name: "FullStory", category: "analytics", domains: ["*.fullstory.com"] }, { name: "Fyber", category: "ad", domains: ["*.fyber.com"] }, { name: "G-Forces Web Management", category: "hosting", domains: ["*.gforcesinternal.co.uk"] }, { name: "G4 Native", company: "Gravity4", category: "ad", domains: ["*.triggit.com"] }, { name: "GET ME IN!  (TicketMaster)", category: "content", domains: ["*.getmein.com"] }, { name: "GIPHY", category: "content", domains: ["*.giphy.com"] }, { name: "GainCloud", company: "GainCloud Systems", category: "other", domains: ["*.egaincloud.net"] }, { name: "Gath Adams", category: "content", domains: ["*.iwantthatflight.com.au"] }, { name: "Gecko Tribe", category: "social", domains: ["*.geckotribe.com"] }, { name: "Gemius", category: "ad", domains: ["*.gemius.pl"] }, { name: "Genesis Media", category: "ad", domains: ["*.bzgint.com", "*.genesismedia.com", "*.genesismediaus.com"] }, { name: "Genie Ventures", category: "ad", domains: ["*.genieventures.co.uk"] }, { name: "Geniee", category: "ad", domains: ["*.href.asia", "*.genieessp.jp", "*.genieesspv.jp", "*.gssprt.jp"] }, { name: "Geniuslink", category: "analytics", domains: ["*.geni.us"] }, { name: "GeoRiot", category: "other", domains: ["*.georiot.com"] }, { name: "GeoTrust", category: "utility", domains: ["*.geotrust.com"] }, { name: "Geoplugin", category: "utility", domains: ["*.geoplugin.com", "*.geoplugin.net"] }, { name: "Georeferencer", company: "Klokan Technologies", category: "utility", domains: ["*.georeferencer.com"] }, { name: "GetIntent RTBSuite", company: "GetIntent", category: "ad", domains: ["*.adhigh.net"] }, { name: "GetResponse", category: "ad", domains: ["*.getresponse.com"] }, { name: "GetSiteControl", company: "GetWebCraft", category: "utility", domains: ["*.getsitecontrol.com"] }, { name: "GetSocial", category: "social", domains: ["*.getsocial.io"] }, { name: "Getty Images", category: "content", domains: ["*.gettyimages.com", "*.gettyimages.co.uk"] }, { name: "Gfycat", company: "Gycat", category: "utility", domains: ["*.gfycat.com"] }, { name: "Ghostery Enterprise", company: "Ghostery", category: "marketing", domains: ["*.betrad.com"] }, { name: "Giant Media", category: "ad", domains: ["*.videostat.com"] }, { name: "Gigya", category: "analytics", domains: ["*.gigya.com"] }, { name: "GitHub", category: "utility", domains: ["*.github.com", "*.githubusercontent.com", "*.github.io", "*.rawgit.com"] }, { name: "Gladly", company: "Gladly", homepage: "https://www.gladly.com/", category: "customer-success", domains: ["*.gladly.com"] }, { name: "Glassdoor", category: "content", domains: ["*.glassdoor.com"] }, { name: "Gleam", category: "marketing", domains: ["*.gleam.io"] }, { name: "Global Digital Markets", category: "ad", domains: ["*.gdmdigital.com"] }, { name: "Global-e", category: "hosting", domains: ["*.global-e.com"] }, { name: "GlobalSign", category: "utility", domains: ["*.globalsign.com", "*.globalsign.net"] }, { name: "GlobalWebIndex", category: "analytics", domains: ["*.globalwebindex.net"] }, { name: "Globase International", category: "ad", domains: ["*.globase.com"] }, { name: "GoDataFeed", category: "other", domains: ["*.godatafeed.com"] }, { name: "Google APIs", company: "Google", category: "utility", domains: ["googleapis.com"] }, { name: "Google Ad Block Detection", company: "Google", category: "ad", domains: ["*.0emn.com", "*.0fmm.com"] }, { name: "Google Analytics Experiments", company: "Google", category: "analytics", domains: ["*.gexperiments1.com"] }, { name: "Google DoubleClick Ad Exchange", company: "Google", category: "ad", domains: ["*.admeld.com"] }, { name: "Google IPV6 Metrics", company: "Google", category: "analytics", domains: ["*.ipv6test.net"] }, { name: "Google Plus", company: "Google", category: "social", domains: ["plus.google.com"] }, { name: "Google Trusted Stores", company: "Google", category: "utility", domains: ["*.googlecommerce.com"] }, { name: "Google Video", company: "Google", category: "content", domains: ["*.googlevideo.com"] }, { name: "Google reCAPTCHA", company: "Google", category: "utility", domains: ["*.recaptcha.net"] }, { name: "GovMetric", company: "ROL Solutions", category: "analytics", domains: ["*.govmetric.com"] }, { name: "Granify", category: "analytics", domains: ["*.granify.com"] }, { name: "Grapeshot", category: "ad", domains: ["*.gscontxt.net", "*.grapeshot.co.uk"] }, { name: "Gravity (AOL)", category: "analytics", domains: ["*.grvcdn.com"] }, { name: "Groovy Gecko", category: "content", domains: ["*.ggwebcast.com", "*.groovygecko.net"] }, { name: "GroupM", category: "ad", domains: ["*.qservz.com"] }, { name: "Guardian Media", category: "ad", domains: ["*.theguardian.com", "*.guardian.co.uk"] }, { name: "GumGum", category: "ad", domains: ["*.gumgum.com"] }, { name: "Gumtree", category: "content", domains: ["*.gumtree.com"] }, { name: "H264 Codec", company: "Cisco", category: "other", domains: ["*.openh264.org"] }, { name: "HERE", category: "analytics", domains: ["*.medio.com"] }, { name: "HP Optimost", company: "Hewlett-Packard Development Company", category: "marketing", domains: ["*.hp.com", "d2uncb19xzxhzx.cloudfront.net"] }, { name: "Has Offers", company: "TUNE", category: "ad", domains: ["*.go2cloud.org"] }, { name: "Hawk Search", category: "utility", domains: ["*.hawksearch.com"] }, { name: "Haymarket Media Group", category: "content", domains: ["*.brandrepublic.com", "*.hbpl.co.uk"] }, { name: "Heap", category: "analytics", domains: ["*.heapanalytics.com"] }, { name: "Hearst Communications", category: "content", domains: ["*.h-cdn.co", "*.hearstdigital.com", "*.hearstlabs.com", "*.hearst.io", "*.cdnds.net"] }, { name: "Heatmap", category: "analytics", domains: ["*.heatmap.it"] }, { name: "Heroku", category: "other", domains: ["*.herokuapp.com"] }, { name: "Hexton", category: "utility", domains: ["*.hextom.com"] }, { name: "Hibernia Networks", category: "utility", domains: ["*.hiberniacdn.com"] }, { name: "High Impact Media", category: "ad", domains: ["*.reactx.com"] }, { name: "Highcharts", category: "utility", domains: ["*.highcharts.com"] }, { name: "Highwinds", category: "utility", domains: ["*.hwcdn.net"] }, { name: "HitsLink", category: "analytics", domains: ["*.hitslink.com"] }, { name: "Hola Networks", category: "other", domains: ["*.h-cdn.com"] }, { name: "Hootsuite", category: "analytics", domains: ["*.hootsuite.com"] }, { name: "HotUKDeals", category: "analytics", domains: ["*.hotukdeals.com"] }, { name: "HotWords", company: "Media Response Group", category: "ad", domains: ["*.hotwords.com.br"] }, { name: "HotelsCombined", category: "content", domains: ["*.datahc.com"] }, { name: "Hoverr", category: "ad", domains: ["*.hoverr.media"] }, { name: "Hull.js", category: "utility", domains: ["*.hull.io", "*.hullapp.io"] }, { name: "Hupso Website Analyzer", company: "Hupso", category: "analytics", domains: ["*.hupso.com"] }, { name: "I-Behavior", company: "WPP", category: "ad", domains: ["*.ib-ibi.com"] }, { name: "i-mobile", company: "i-mobile", category: "ad", domains: ["*.i-mobile.co.jp"] }, { name: "IBM Digital Analytics", company: "IBM", category: "analytics", domains: ["*.cmcore.com", "coremetrics.com", "data.coremetrics.com", "data.de.coremetrics.com", "libs.de.coremetrics.com", "tmscdn.de.coremetrics.com", "iocdn.coremetrics.com", "libs.coremetrics.com", "tmscdn.coremetrics.com", "*.s81c.com", "*.unica.com", "*.coremetrics.eu"] }, { name: "IBM Digital Data Exchange", company: "IBM", category: "tag-manager", domains: ["tagmanager.coremetrics.com"] }, { name: "IBM Tealeaf", company: "IBM", category: "analytics", domains: ["*.ibmcloud.com"] }, { name: "IBM Acoustic Campaign", company: "IBM", category: "analytics", domains: ["www.sc.pages01.net", "www.sc.pages02.net", "www.sc.pages03.net", "www.sc.pages04.net", "www.sc.pages05.net", "www.sc.pages06.net", "www.sc.pages07.net", "www.sc.pages08.net", "www.sc.pages09.net", "www.sc.pagesA.net"] }, { name: "ICF Technology", category: "content", domains: ["*.camads.net"] }, { name: "IFDNRG", category: "hosting", domains: ["*.ifdnrg.com"] }, { name: "IMRG", category: "analytics", domains: ["*.peermap.com", "*.imrg.org"] }, { name: "IPONWEB", category: "ad", domains: ["*.company-target.com", "*.liadm.com", "*.iponweb.net", "*.p161.net"] }, { name: "IQ Mobile", category: "utility", domains: ["*.iqm.cc"] }, { name: "IS Group", category: "hosting", domains: ["*.creative-serving.com"] }, { name: "IT Dienstleistungen Tim Prinzkosky", category: "utility", domains: ["*.flaticons.net"] }, { name: "IXI Digital", company: "Equifax", category: "ad", domains: ["*.ixiaa.com"] }, { name: "IcoMoon", category: "cdn", domains: ["d19ayerf5ehaab.cloudfront.net", "d1azc1qln24ryf.cloudfront.net"] }, { name: "IdenTrust", category: "utility", domains: ["*.identrust.com"] }, { name: "Ido", category: "customer-success", domains: ["*.idio.co"] }, { name: "Ignition One", category: "marketing", domains: ["*.searchignite.com"] }, { name: "ImageShack", category: "content", domains: ["*.yfrog.com"] }, { name: "Imagen Studio", category: "utility", domains: ["*.telephonesky.com"] }, { name: "Imagini Holdings", category: "ad", domains: ["*.vdna-assets.com"] }, { name: "Img Safe", category: "content", domains: ["*.imgsafe.org"] }, { name: "Imgur", category: "utility", domains: ["*.imgur.com"] }, { name: "Impact Radius", category: "ad", domains: ["*.impactradius-event.com", "*.impactradius-go.com", "*.7eer.net", "d3cxv97fi8q177.cloudfront.net", "*.evyy.net", "*.ojrq.net", "utt.impactcdn.com", "*.sjv.io"] }, { name: "Improve Digital", category: "ad", domains: ["*.360yield.com"] }, { name: "Improvely", category: "analytics", domains: ["*.iljmp.com"] }, { name: "InMobi", category: "ad", domains: ["*.inmobi.com"] }, { name: "InSkin Media", category: "ad", domains: ["*.inskinad.com", "*.inskinmedia.com"] }, { name: "Inbenta", category: "customer-success", domains: ["*.inbenta.com"] }, { name: "Incisive Media", category: "content", domains: ["*.incisivemedia.com"] }, { name: "Indeed", category: "content", domains: ["*.indeed.com"] }, { name: "Index Exchange", company: "WPP", category: "ad", domains: ["*.casalemedia.com", "*.indexww.com"] }, { name: "Indoona", category: "other", domains: ["*.indoona.com"] }, { name: "Infectious Media", category: "ad", domains: ["*.impdesk.com", "*.impressiondesk.com", "*.inmz.net"] }, { name: "Inference Mobile", category: "ad", domains: ["*.inferencemobile.com"] }, { name: "Infinity Tracking", category: "analytics", domains: ["*.infinity-tracking.net"] }, { name: "Infoline", category: "analytics", domains: ["*.ioam.de"] }, { name: "Infolinks", category: "ad", domains: ["*.infolinks.com"] }, { name: "Infopark", category: "hosting", domains: ["*.scrvt.com"] }, { name: "Infusionsoft", category: "ad", domains: ["*.infusionsoft.com"] }, { name: "Ink", category: "ad", domains: ["*.inktad.com"] }, { name: "Inktel Contact Center Solutions", company: "Inktel", category: "customer-success", domains: ["*.inktel.com"] }, { name: "Inneractive", category: "ad", domains: ["*.inner-active.mobi"] }, { name: "Innovid", category: "ad", homepage: "https://www.innovid.com/", domains: ["*.innovid.com"] }, { name: "Insight Express", category: "analytics", domains: ["*.insightexpressai.com"] }, { name: "Insipio", category: "other", domains: ["*.insipio.com"] }, { name: "Inspectlet", category: "analytics", domains: ["*.inspectlet.com"] }, { name: "Instansive", category: "utility", domains: ["*.instansive.com"] }, { name: "Instart", homepage: "https://www.instart.com/", category: "utility", domains: ["*.insnw.net"] }, { name: "Instembedder", category: "content", domains: ["*.instaembedder.com"] }, { name: "Instinctive", category: "ad", domains: ["*.instinctiveads.com"] }, { name: "Intelligent Reach", category: "ad", domains: ["*.ist-track.com"] }, { name: "Intent HQ", category: "analytics", domains: ["*.intenthq.com"] }, { name: "Intent IQ", category: "ad", domains: ["*.intentiq.com"] }, { name: "Intercept Interactive", category: "ad", domains: ["*.undertone.com"] }, { name: "Interest Graph", company: "AOL", category: "ad", domains: ["*.gravity.com"] }, { name: "Internet Brands", category: "content", domains: ["*.ibpxl.com"] }, { name: "Interpublic Group", category: "ad", domains: ["*.mbww.com"] }, { name: "Interstate", category: "analytics", domains: ["*.interstateanalytics.com"] }, { name: "Interview", category: "analytics", domains: ["*.efm.me"] }, { name: "Intilery", category: "customer-success", domains: ["*.intilery-analytics.com"] }, { name: "Investis", category: "utility", domains: ["*.investis.com"] }, { name: "Investis Flife", category: "hosting", domains: ["*.quartalflife.com"] }, { name: "Invodo", category: "ad", domains: ["*.invodo.com"] }, { name: "iSite", category: "analytics", domains: ["*.isitetv.com"] }, { name: "Issue", category: "content", domains: ["*.issue.by"] }, { name: "J.D. Williams & Co", category: "content", domains: ["*.drct2u.com"] }, { name: "Janrain", category: "analytics", domains: ["*.janrain.com", "*.janrainbackplane.com", "*.rpxnow.com", "d3hmp0045zy3cs.cloudfront.net"] }, { name: "Jellyfish", category: "ad", domains: ["*.jellyfish.net"] }, { name: "JetStream", category: "content", domains: ["*.xlcdn.com"] }, { name: "JingDong", category: "content", domains: ["*.3.com", "*.jd.com"] }, { name: "Jivox", category: "ad", domains: ["*.jivox.com"] }, { name: "Jobvite", category: "content", domains: ["*.jobvite.com"] }, { name: "Johnston Press", category: "content", domains: ["*.johnstonpress.co.uk", "*.jpress.co.uk"] }, { name: "Join the Dots (Research)", category: "social", domains: ["*.jtdiscuss.com"] }, { name: "JotForm", category: "utility", domains: ["*.jotformpro.com"] }, { name: "JuicyAds", category: "ad", domains: ["*.juicyads.com"] }, { name: "JustPremium", category: "ad", domains: ["*.net.net"] }, { name: "JustPremium Ads", company: "JustPremium", category: "ad", domains: ["*.justpremium.com"] }, { name: "JustUno", category: "ad", domains: ["*.justuno.com", "d2j3qa5nc37287.cloudfront.net"] }, { name: "KINX (Korea Internet Neutral eXchange)", category: "other", domains: ["*.kinxcdn.com"] }, { name: "KISSmetrics", category: "analytics", domains: ["*.kissmetrics.com", "doug1izaerwt3.cloudfront.net", "dsyszv14g9ymi.cloudfront.net"] }, { name: "Kaizen Platform", category: "analytics", domains: ["*.kaizenplatform.net"] }, { name: "Kakao", category: "social", domains: ["*.daum.net", "*.daumcdn.net"] }, { name: "Kaltura Video Platform", company: "Kaltura", category: "content", domains: ["*.kaltura.com"] }, { name: "Kameleoon", homepage: "https://www.kameleoon.com/", category: "analytics", domains: ["*.kameleoon.com", "*.kameleoon.eu", "*.kameleoon.io"] }, { name: "Kampyle", category: "analytics", domains: ["*.kampyle.com"] }, { name: "Kantar", category: "analytics", domains: ["*.sesamestats.com"] }, { name: "Kargo", category: "marketing", domains: ["*.kargo.com"] }, { name: "KARTE", company: "Plaid", homepage: "https://karte.io/", category: "marketing", domains: ["*.karte.io"] }, { name: "Kauli", category: "ad", domains: ["*.kau.li"] }, { name: "Keen", company: "Keen", homepage: "https://keen.io/", category: "analytics", domains: ["*.keen.io", "d26b395fwzu5fz.cloudfront.net"] }, { name: "Kelkoo", category: "hosting", domains: ["*.kelkoo.com"] }, { name: "Kenshoo", category: "marketing", domains: ["*.xg4ken.com"] }, { name: "Key CDN", category: "utility", domains: ["*.kxcdn.com"] }, { name: "Keynote", company: "Dynatrace", category: "analytics", domains: ["*.keynote.com"] }, { name: "Keywee", category: "ad", domains: ["*.keywee.co"] }, { name: "Kiosked", category: "ad", domains: ["*.kiosked.com"] }, { name: "Klarna", category: "utility", domains: ["*.klarna.com"] }, { name: "Klaviyo", category: "ad", domains: ["*.klaviyo.com"] }, { name: "Klevu Search", company: "Klevu", category: "utility", domains: ["*.klevu.com"] }, { name: "Klick2Contact", category: "customer-success", domains: ["*.klick2contact.com"] }, { name: "Knight Lab", company: "Northwestern University", category: "utility", domains: ["*.knightlab.com"] }, { name: "Kodajo", category: "other", domains: ["*.kodajo.com"] }, { name: "Komoona", category: "ad", domains: ["*.komoona.com"] }, { name: "Korrelate", company: "JD Power", category: "analytics", domains: ["*.korrelate.net"] }, { name: "LKQD", category: "ad", domains: ["*.lkqd.net"] }, { name: "Layer0", category: "cdn", domains: ["*.layer0.co"] }, { name: "Layershift", category: "hosting", domains: ["109.109.138.174"] }, { name: "Lead Forensics", category: "ad", domains: ["*.200summit.com", "*.baw5tracker.com", "*.business-path-55.com", "*.bux1le001.com", "*.central-core-7.com", "*.direct-azr-78.com", "*.explore-123.com", "*.forensics1000.com", "*.gldsta-02-or.com", "*.green-bloc9.com", "*.lansrv040.com", "*.lead-123.com", "*.leadforensics.com", "*.mavic852.com", "*.mon-com-net.com", "*.peak-ip-54.com", "*.snta0034.com", "*.svr-prc-01.com", "*.syntace-094.com", "*.tghbn12.com", "*.trail-web.com", "*.web-01-gbl.com", "*.web-cntr-07.com", "*.trackdiscovery.net"] }, { name: "Lead Intelligence", company: "Magnetise Solutions", category: "ad", domains: ["*.leadintelligence.co.uk"] }, { name: "LeadLander", category: "analytics", domains: ["*.formalyzer.com", "*.trackalyzer.com"] }, { name: "Leaflet", category: "utility", domains: ["*.leafletjs.com"] }, { name: "LeasdBoxer", company: "LeadBoxer", category: "ad", domains: ["*.leadboxer.com"] }, { name: "LeaseWeb", homepage: "https://www.leaseweb.com/", category: "cdn", domains: ["*.lswcdn.net", "*.leasewebcdn.com"] }, { name: "Leboncoin", category: "content", domains: ["*.leboncoin.fr"] }, { name: "Lengow", category: "hosting", domains: ["*.lengow.com"] }, { name: "Lessbuttons", category: "social", domains: ["*.lessbuttons.com"] }, { name: "Letter Press", category: "ad", domains: ["*.getletterpress.com"] }, { name: "Level 3 Communications", category: "utility", domains: ["footprint.net"] }, { name: "Level3", category: "other", domains: ["secure.footprint.net"] }, { name: "Lifestreet Media", category: "social", domains: ["*.lfstmedia.com"] }, { name: "LiftSuggest", category: "analytics", domains: ["d2blwevgjs7yom.cloudfront.net"] }, { name: "Ligatus", category: "ad", domains: ["*.ligadx.com"] }, { name: "LightStep", category: "analytics", domains: ["*.lightstep.com"] }, { name: "LightWidget", category: "utility", domains: ["*.lightwidget.com"] }, { name: "Likelihood", company: "LIkeihood", category: "hosting", domains: ["*.likelihood.com"] }, { name: "LikeShop", company: "Dash Hudson", category: "content", domains: ["likeshop.me"] }, { name: "LINE Corporation", category: "ad", domains: ["*.line-scdn.net", "*.line.me"] }, { name: "Linkcious", category: "analytics", domains: ["*.linkcious.com"] }, { name: "Linking Mobile", category: "ad", domains: ["*.linkingmobile.com"] }, { name: "LittleData", category: "analytics", homepage: "https://www.littledata.io/", domains: ["*.littledata.io"] }, { name: "LiveBurst", category: "ad", domains: ["*.liveburst.com"] }, { name: "LiveClicker", category: "ad", domains: ["*.liveclicker.net"] }, { name: "LiveHelpNow", category: "customer-success", domains: ["*.livehelpnow.net"] }, { name: "LiveInternet", category: "analytics", domains: ["*.yadro.ru"] }, { name: "LiveJournal", category: "social", domains: ["*.livejournal.com", "*.livejournal.net"] }, { name: "LivePerson", category: "customer-success", homepage: "https://www.liveperson.com/", domains: ["*.liveperson.com", "*.look.io", "*.liveperson.net", "*.lpsnmedia.net"] }, { name: "LiveRail", company: "Facebook", category: "ad", domains: ["*.liverail.com", "*.lrcdn.net"] }, { name: "LiveTex", category: "customer-success", domains: ["*.livetex.ru"] }, { name: "Livefyre", category: "content", domains: ["*.fyre.co", "*.livefyre.com"] }, { name: "Living Map Company", category: "utility", domains: ["*.livingmap.com"] }, { name: "Local World", category: "content", domains: ["*.thelocalpeople.co.uk"] }, { name: "LockerDome", category: "analytics", domains: ["*.lockerdome.com"] }, { name: "Logentries", company: "Rapid", category: "utility", domains: ["*.logentries.com"] }, { name: "Logicalis", category: "analytics", domains: ["*.trovus.co.uk"] }, { name: "LoginRadius", company: "LoginRadius", homepage: "https://www.loginradius.com/", category: "ad", domains: ["*.loginradius.com", "*.lrcontent.com"] }, { name: "LongTail Ad Solutions", category: "ad", domains: ["*.jwpcdn.com", "*.jwplatform.com", "*.jwplayer.com", "*.jwpltx.com", "*.jwpsrv.com", "*.longtailvideo.com"] }, { name: "Loop Commerce", category: "other", domains: ["*.loopassets.net"] }, { name: "Loop11", category: "analytics", domains: ["*.loop11.com"] }, { name: "LoopMe", category: "ad", domains: ["*.loopme.biz", "*.loopme.com", "*.vntsm.com", "*.loopme.me"] }, { name: "Looper", category: "content", domains: ["*.looper.com"] }, { name: "Loyalty Point", category: "ad", domains: ["*.loyaltypoint.pl"] }, { name: "LoyaltyLion", category: "ad", domains: ["*.loyaltylion.com", "*.loyaltylion.net", "dg1f2pfrgjxdq.cloudfront.net"] }, { name: "Luma Tag", category: "analytics", domains: ["*.lumatag.co.uk"] }, { name: "Lumesse", category: "content", domains: ["*.recruitmentplatform.com"] }, { name: "Luminate", category: "ad", domains: ["*.luminate.com"] }, { name: "Lynchpin Analytics", category: "analytics", domains: ["*.lypn.net"] }, { name: "Lyris", category: "ad", domains: ["*.clicktracks.com"] }, { name: "Lytics", category: "ad", domains: ["*.lytics.io"] }, { name: "MEC WebTrack", company: "MEC", category: "ad", domains: ["*.e-webtrack.net"] }, { name: "MECLABS Institute", category: "analytics", domains: ["*.meclabs.com", "*.meclabsdata.com"] }, { name: "MLveda", category: "utility", domains: ["*.mlveda.com"] }, { name: "Macromill", company: "Macromill", category: "analytics", homepage: "https://group.macromill.com/", domains: ["*.macromill.com"] }, { name: "Macropod BugHerd", company: "Macropod", category: "utility", domains: ["*.bugherd.com"] }, { name: "Madison Logic", category: "marketing", domains: ["*.ml314.com"] }, { name: "Madmetrics", company: "Keyade", category: "analytics", domains: ["*.keyade.com"] }, { name: "Magnetic", category: "ad", domains: ["*.domdex.com", "d3ezl4ajpp2zy8.cloudfront.net"] }, { name: "Magnetic Platform", company: "Magnetic", category: "ad", domains: ["*.magnetic.is"] }, { name: "MailMunch", category: "ad", domains: ["*.mailmunch.co"] }, { name: "MailPlus", category: "ad", domains: ["*.mailplus.nl"] }, { name: "Mapbox", category: "utility", domains: ["*.mapbox.com"] }, { name: "Maptive", category: "utility", domains: ["*.maptive.com"] }, { name: "Marcaria.com", category: "other", domains: ["*.gooo.al"] }, { name: "Marchex", category: "analytics", domains: ["*.voicestar.com", "*.marchex.io"] }, { name: "Mark and Mini", category: "ad", domains: ["*.markandmini.com"] }, { name: "Marker", category: "utility", domains: ["*.marker.io"] }, { name: "Marketing Dashboards", company: "GroupM", category: "analytics", domains: ["*.m-decision.com"] }, { name: "Marketizator", category: "analytics", domains: ["*.marketizator.com"] }, { name: "Marketplace Web Service", company: "Amazon", category: "other", domains: ["*.ssl-images-amazon.com"] }, { name: "Mashable", category: "social", domains: ["*.mshcdn.com"] }, { name: "MatchWork", category: "utility", domains: ["*.matchwork.com"] }, { name: "MathJax", category: "utility", domains: ["*.mathjax.org"] }, { name: "Mather Economics", category: "analytics", domains: ["*.matheranalytics.com"] }, { name: "MaxCDN Enterprise", company: "MaxCDN", category: "utility", domains: ["*.netdna-cdn.com", "*.netdna-ssl.com"] }, { name: "MaxMind", category: "utility", domains: ["*.maxmind.com"] }, { name: "MaxPoint Interactive", category: "ad", domains: ["*.mxptint.net"] }, { name: "Maxsi", category: "analytics", domains: ["*.evisitanalyst.com"] }, { name: "Maxymiser", category: "analytics", domains: ["*.maxymiser.net, maxymiser.hs.llnwd.net"] }, { name: "McAffee", category: "utility", domains: ["*.mcafeesecure.com", "*.scanalert.com"] }, { name: "Measured", category: "analytics", domains: ["*.measured.com"], homepage: "https://www.measured.com/" }, { name: "Media IQ", category: "analytics", domains: ["*.mediaiqdigital.com"] }, { name: "Media Management Technologies", category: "ad", domains: ["*.speedshiftmedia.com"] }, { name: "Media Temple", category: "hosting", domains: ["*.goodlayers2.com"] }, { name: "Mediabong", category: "ad", domains: ["*.mediabong.net"] }, { name: "Mediahawk", category: "analytics", domains: ["*.mediahawk.co.uk"] }, { name: "Mediahub", category: "ad", domains: ["*.hubverifyandoptimize.com", "*.projectwatchtower.com"] }, { name: "Mediasyndicator", category: "ad", domains: ["*.creativesyndicator.com"] }, { name: "Medium", category: "content", domains: ["*.medium.com"] }, { name: "Meetrics", category: "ad", domains: ["*.de.com", "*.meetrics.net", "*.mxcdn.net"] }, { name: "Mega", company: "Mega Information Technology", category: "other", domains: ["*.mgcdn.com"] }, { name: "Melt", category: "ad", domains: ["*.meltdsp.com", "*.mesp.com"] }, { name: "Meltwater Group", category: "customer-success", domains: ["*.meltwaternews.com"] }, { name: "Meme", category: "ad", domains: ["*.viewwonder.com"] }, { name: "MentAd", category: "ad", domains: ["*.mentad.com"] }, { name: "Mention Me", category: "ad", domains: ["*.mention-me.com"] }, { name: "Merchant Equipment Store", category: "utility", domains: ["*.merchantequip.com"] }, { name: "Merchenta", category: "customer-success", domains: ["*.merchenta.com"] }, { name: "Merkle Digital Data Exchange", company: "Merkle", category: "ad", domains: ["*.brilig.com"] }, { name: "Merkle Paid Search", company: "Merkle", category: "ad", domains: ["*.rkdms.com"] }, { name: "Met Office", category: "content", domains: ["*.metoffice.gov.uk"] }, { name: "Meta Broadcast", category: "social", domains: ["*.metabroadcast.com"] }, { name: "Michael Associates", category: "ad", domains: ["*.checktestsite.com"] }, { name: "Michelin", category: "content", domains: ["*.viamichelin.com"] }, { name: "Microad", category: "ad", domains: ["*.microad.jp"] }, { name: "Microsoft Certificate Services", company: "Microsoft", category: "utility", domains: ["*.msocsp.com"] }, { name: "Microsoft Hosted Libs", company: "Microsoft", category: "cdn", domains: ["*.aspnetcdn.com"] }, { name: "Microsoft XBox Live", company: "Microsoft", category: "marketing", domains: ["*.xboxlive.com"] }, { name: "Mightypop", category: "ad", domains: ["*.mightypop.ca"] }, { name: "Mika Tuupola", category: "utility", domains: ["*.appelsiini.net"] }, { name: "Millennial Media", category: "ad", domains: ["*.jumptap.com"] }, { name: "Mirror Image Internet", category: "utility", domains: ["*.miisolutions.net"] }, { name: "Mobify", category: "utility", domains: ["*.mobify.com", "*.mobify.net"] }, { name: "Mobile Nations", category: "social", domains: ["*.mobilenations.com"] }, { name: "Mobivate", category: "ad", domains: ["*.mobivatebulksms.com"] }, { name: "Momondo", category: "content", domains: ["*.momondo.dk"] }, { name: "Momondo Group", category: "content", domains: ["*.momondogrouo.com", "*.momondogroup.com"] }, { name: "Monarch Ads", category: "ad", domains: ["*.monarchads.com"] }, { name: "Monetate", category: "analytics", domains: ["*.monetate.net"] }, { name: "MonetizeMore", category: "ad", domains: ["*.m2.ai"] }, { name: "Monitor", company: "Econda", category: "analytics", domains: ["*.econda-monitor.de"] }, { name: "Monkey Frog Media", category: "content", domains: ["*.monkeyfrogmedia.com"] }, { name: "Monotype", category: "cdn", domains: ["*.fonts.com", "*.fonts.net"] }, { name: "Moore-Wilson", category: "ad", domains: ["*.mwdev.co.uk"] }, { name: "Moovweb", category: "utility", domains: ["*.moovweb.net"] }, { name: "Mopinion", category: "analytics", domains: ["*.mopinion.com"] }, { name: "MotionPoint", category: "other", domains: ["*.convertlanguage.com"] }, { name: "Mouse3K", category: "analytics", domains: ["*.mouse3k.com"] }, { name: "MouseStats", category: "analytics", domains: ["*.mousestats.com"] }, { name: "Mouseflow", homepage: "https://mouseflow.com/", category: "analytics", domains: ["*.mouseflow.com"] }, { name: "Movable Ink", category: "analytics", domains: ["*.micpn.com"] }, { name: "MovingIMAGE24", category: "content", domains: ["*.edge-cdn.net"] }, { name: "Moxielinks", category: "ad", domains: ["*.moxielinks.com"] }, { name: "Moz Recommended Companies", company: "Moz", category: "analytics", domains: ["d2eeipcrcdle6.cloudfront.net"] }, { name: "Mozilla", category: "utility", domains: ["*.mozilla.org"] }, { name: "Multiview", category: "content", domains: ["*.multiview.com", "*.track-mv.com"] }, { name: "Mux", category: "analytics", domains: ["*.litix.io"] }, { name: "MyAds", company: "MyBuys", category: "analytics", domains: ["*.veruta.com"] }, { name: "MyBuys", category: "analytics", domains: ["*.mybuys.com"] }, { name: "MyFonts", category: "cdn", domains: ["*.myfonts.net"] }, { name: "MyRegistry", category: "other", domains: ["*.myregistry.com"] }, { name: "MySpace", company: "Specific Media", category: "social", domains: ["*.myspace.com"] }, { name: "Mynewsdesk", category: "utility", domains: ["*.mynewsdesk.com"] }, { name: "NAVIS", category: "content", domains: ["*.navistechnologies.info"] }, { name: "NCC Group Real User Monitoring", company: "NCC Group", category: "analytics", domains: ["*.nccgroup-webperf.com"] }, { name: "NEORY Marketing Cloud", company: "NEORY", category: "marketing", domains: ["*.ad-srv.net"] }, { name: "Nanigans", category: "ad", domains: ["*.nanigans.com"] }, { name: "Nano Interactive", category: "ad", domains: ["*.audiencemanager.de"] }, { name: "Nanorep", company: "Nanorep Technologies", category: "customer-success", domains: ["*.nanorep.com"] }, { name: "Narrative", category: "ad", domains: ["*.narrative.io"] }, { name: "Native Ads", category: "ad", domains: ["*.nativeads.com"] }, { name: "Nativo", category: "ad", domains: ["*.postrelease.com"] }, { name: "Navegg", category: "ad", domains: ["*.navdmp.com"] }, { name: "NaviStone", category: "ad", domains: ["*.murdoog.com"] }, { name: "Naytev", category: "analytics", domains: ["*.naytev.com"] }, { name: "Needle", category: "analytics", domains: ["*.needle.com"] }, { name: "Neiman Marcus", category: "content", domains: ["*.ctscdn.com"] }, { name: "Nend", category: "ad", domains: ["*.nend.net"] }, { name: "Neodata", category: "ad", domains: ["*.neodatagroup.com"] }, { name: "Net Applications", category: "analytics", domains: ["*.hitsprocessor.com"] }, { name: "Net Reviews", category: "analytics", domains: ["*.avis-verifies.com"] }, { name: "NetAffiliation", company: "Kwanco", category: "ad", domains: ["*.metaffiliation.com"] }, { name: "NetDirector", company: "G-Forces Web Management", category: "other", domains: ["*.netdirector.co.uk"] }, { name: "NetFlix", category: "content", domains: ["*.nflxext.com", "*.nflximg.net"] }, { name: "Nielsen NetRatings SiteCensus", company: "The Nielsen Company", homepage: "http://www.nielsen-online.com/intlpage.html", category: "analytics", domains: ["*.imrworldwide.com"] }, { name: "NetSeer", category: "ad", domains: ["*.netseer.com", "*.ns-cdn.com"] }, { name: "NetShelter", company: "Ziff Davis Tech", category: "ad", domains: ["*.netshelter.net"] }, { name: "Netmining", company: "Ignition One", category: "ad", domains: ["*.netmng.com"] }, { name: "Netop", category: "customer-success", domains: ["*.netop.com"] }, { name: "Network Solutions", category: "utility", domains: ["*.netsolssl.com", "*.networksolutions.com"] }, { name: "Neustar AdAdvisor", company: "Neustar", category: "ad", domains: ["*.adadvisor.net"] }, { name: "New Approach Media", category: "ad", domains: ["*.newapproachmedia.co.uk"] }, { name: "NewShareCounts", category: "social", domains: ["*.newsharecounts.com"] }, { name: "News", category: "social", domains: ["*.news.com.au", "*.newsanalytics.com.au", "*.newsapi.com.au", "*.newscdn.com.au", "*.newsdata.com.au", "*.newsdiscover.com.au", "*.news-static.com"] }, { name: "Newsquest", category: "content", domains: ["*.newsquestdigital.co.uk"] }, { name: "Newzulu", category: "content", domains: ["*.filemobile.com", "*.projects.fm"] }, { name: "Nexcess.Net", category: "hosting", domains: ["*.nexcesscdn.net"] }, { name: "Nexstar Media Group", category: "ad", domains: ["*.yashi.com"] }, { name: "NextPerf", company: "Rakuten Marketing", category: "ad", domains: ["*.nxtck.com"] }, { name: "Nine.com.au", company: "Nine Digital", category: "content", domains: ["*.9msn.com.au"] }, { name: "NitroSell", category: "hosting", domains: ["*.nitrosell.com"] }, { name: "Nochex", category: "utility", domains: ["*.nochex.com"] }, { name: "Northern &amp; Shell Media Group", category: "content", domains: ["*.northernandshell.co.uk"] }, { name: "Nosto", category: "analytics", domains: ["*.nosto.com"] }, { name: "Now Interact", category: "analytics", domains: ["*.nowinteract.com"] }, { name: "Numberly", company: "1000mercis", category: "ad", domains: ["*.mmtro.com", "*.nzaza.com"] }, { name: "NyaConcepts", category: "analytics", domains: ["*.xclusive.ly"] }, { name: "O2", category: "other", domains: ["*.o2.co.uk"] }, { name: "GoDaddy", homepage: "https://www.godaddy.com/", category: "utility", domains: ["*.godaddy.com", "*.wsimg.com"] }, { name: "ObjectPlanet", category: "analytics", domains: ["*.easypolls.net"] }, { name: "OhMyAd", category: "ad", domains: ["*.ohmyad.co"] }, { name: "Okas Concepts", category: "utility", domains: ["*.okasconcepts.com"] }, { name: "Okta", category: "analytics", domains: ["*.okta.com"] }, { name: "Olapic", category: "content", domains: ["*.photorank.me"] }, { name: "Ometria", category: "analytics", domains: ["*.ometria.com"] }, { name: "Omniconvert", category: "analytics", domains: ["*.omniconvert.com", "d2tgfbvjf3q6hn.cloudfront.net", "d3vbj265bmdenw.cloudfront.net"] }, { name: "Omniroot", company: "Verizon", category: "utility", domains: ["*.omniroot.com"] }, { name: "OnAudience", company: "Cloud Technologies", category: "ad", domains: ["*.onaudience.com"] }, { name: "OnScroll", category: "ad", domains: ["*.onscroll.com"] }, { name: "OnState", category: "ad", domains: ["*.onstate.co.uk"] }, { name: "OnYourMap", category: "utility", domains: ["*.onyourmap.com"] }, { name: "One by AOL", company: "AOL", category: "ad", domains: ["*.adtechjp.com", "*.adtech.de"] }, { name: "One by AOL:Mobile", company: "AOL", category: "ad", domains: ["*.nexage.com"] }, { name: "OneAll", category: "analytics", domains: ["*.oneall.com"] }, { name: "OneSoon", category: "analytics", domains: ["*.adalyser.com"] }, { name: "OneTag", category: "ad", domains: ["*.onetag-sys.com"] }, { name: "Onet", category: "ad", domains: ["*.onet.pl"] }, { name: "Online Rewards", company: "Mastercard", category: "ad", domains: ["*.loyaltygateway.com"] }, { name: "Online republic", category: "content", domains: ["*.imallcdn.net"] }, { name: "Ooyala", category: "ad", domains: ["*.ooyala.com"] }, { name: "OpenTable", company: "Priceline Group", category: "content", domains: ["*.opentable.com", "*.opentable.co.uk", "*.toptable.co.uk"] }, { name: "OpenX Ad Exchange", company: "OpenX Technologies", category: "ad", domains: ["*.liftdna.com"] }, { name: "Opinion Stage", category: "analytics", domains: ["*.opinionstage.com"] }, { name: "OpinionBar", category: "analytics", domains: ["*.opinionbar.com"] }, { name: "Opta", company: "Perform Group", category: "content", domains: ["*.opta.net"] }, { name: "OptiMonk", category: "ad", domains: ["*.optimonk.com"] }, { name: "Optilead", category: "analytics", domains: ["*.dyn-img.com", "*.leadcall.co.uk", "*.optilead.co.uk"] }, { name: "Optimatic", category: "ad", domains: ["*.optimatic.com"] }, { name: "Optimise Media Group", category: "utility", domains: ["*.omguk.com"] }, { name: "Optimost", company: "OpenText", category: "ad", domains: ["*.optimost.com"] }, { name: "Optimove", company: "Mobius Solutions", category: "analytics", domains: ["*.optimove.net"] }, { name: "Optorb", category: "ad", domains: ["*.optorb.com"] }, { name: "Oracle", category: "marketing", domains: ["*.custhelp.com", "*.eloqua.com", "*.en25.com", "*.estara.com", "*.instantservice.com"] }, { name: "Oracle Recommendations On Demand", company: "Oracle", category: "analytics", domains: ["*.atgsvcs.com"] }, { name: "Oracle Responsys", company: "Oracle", category: "marketing", domains: ["*.adrsp.net", "*.responsys.net"] }, { name: "Order Security-VOID", company: "Order Security", category: "analytics", domains: ["*.order-security.com"] }, { name: "Oriel", category: "ad", domains: ["*.oriel.io"] }, { name: "Outbrain", homepage: "https://www.outbrain.com/", category: "ad", domains: ["*.outbrain.com", "*.outbrainimg.com", "*.visualrevenue.com"] }, { name: "OverStream", company: "Coull", category: "ad", domains: ["*.coull.com"] }, { name: "Overdrive", category: "content", domains: ["*.contentreserve.com"] }, { name: "Overstock", category: "utility", domains: ["*.ostkcdn.com"] }, { name: "OwnerIQ", category: "ad", domains: ["*.owneriq.net"] }, { name: "OzCart", category: "utility", domains: ["*.ozcart.com.au"] }, { name: "Ozone Media", category: "ad", domains: ["*.adadyn.com"] }, { name: "Loqate", company: "Loqate", category: "other", domains: ["*.pcapredict.com", "*.postcodeanywhere.co.uk"] }, { name: "PEER 1 Hosting", category: "hosting", domains: ["*.peer1.com"] }, { name: "PERFORM", category: "content", domains: ["*.performgroup.com"] }, { name: "PICnet", category: "hosting", domains: ["*.nonprofitsoapbox.com"] }, { name: "Pacnet", company: "Telstra", category: "other", domains: ["*.cdndelivery.net"] }, { name: "Pagefair", category: "ad", domains: ["*.pagefair.com", "*.pagefair.net"] }, { name: "Pagely", category: "other", domains: ["*.optnmstr.com"] }, { name: "Pagesuite", category: "ad", domains: ["*.pagesuite-professional.co.uk"] }, { name: "Pardot", category: "marketing", domains: ["*.pardot.com"] }, { name: "Parse.ly", category: "analytics", domains: ["*.parsely.com", "d1z2jf7jlzjs58.cloudfront.net"] }, { name: "Pay per Click", company: "Eysys", category: "ad", domains: ["*.eysys.com"] }, { name: "PayPal Ads", category: "ad", domains: ["*.where.com"] }, { name: "Peaks & Pies", category: "analytics", domains: ["*.bunchbox.co"] }, { name: "PebblePost", category: "ad", domains: ["*.pbbl.co"] }, { name: "Peerius", category: "analytics", domains: ["*.peerius.com"] }, { name: "Peermap", company: "IMRG", category: "analytics", domains: ["peermapcontent.affino.com"] }, { name: "Penske Media", category: "content", domains: ["*.pmc.com"] }, { name: "Penton", category: "utility", domains: ["*.pisces-penton.com"] }, { name: "Pepper", category: "ad", domains: ["*.peppercorp.com"] }, { name: "Perfect Audience", company: "Marin Software", category: "ad", domains: ["*.prfct.co", "*.marinsm.com", "*.perfectaudience.com"] }, { name: "Perfect Market", category: "ad", domains: ["*.perfectmarket.com"] }, { name: "Perfect Privacy", category: "other", domains: ["*.suitesmart.com"] }, { name: "Perform Group", category: "content", domains: ["*.performfeeds.com", "*.premiumtv.co.uk"] }, { name: "Performio", category: "ad", domains: ["*.performax.cz"] }, { name: "PerimeterX Bot Defender", company: "PerimeterX", category: "utility", domains: ["*.perimeterx.net", "*.pxi.pub"] }, { name: "Periscope", category: "content", domains: ["*.periscope.tv"] }, { name: "Permutive", category: "ad", domains: ["*.permutive.com", "d3alqb8vzo7fun.cloudfront.net"] }, { name: "Petametrics", category: "analytics", domains: ["*.petametrics.com"] }, { name: "PhotoBucket", category: "content", domains: ["*.photobucket.com"] }, { name: "Picreel", category: "analytics", domains: ["*.pcrl.co", "*.picreel.com"] }, { name: "Pictela (AOL)", category: "analytics", domains: ["*.pictela.net"] }, { name: "PistonHeads", category: "social", domains: ["*.pistonheads.com"] }, { name: "Piwik", category: "analytics", domains: ["*.drtvtracker.com", "*.piwikpro.com", "*.raac33.net"] }, { name: "Pixalate", category: "utility", domains: ["*.adrta.com"] }, { name: "Pixlee", category: "social", domains: ["*.pixlee.com"] }, { name: "Placed", category: "analytics", domains: ["*.placed.com"] }, { name: "Planning-inc", category: "analytics", domains: ["*.planning-inc.co.uk"] }, { name: "PlayAd Media Group", category: "ad", domains: ["*.youplay.se"] }, { name: "Playbuzz", category: "hosting", domains: ["*.playbuzz.com"] }, { name: "Pleenq", category: "ad", domains: ["*.pleenq.com"] }, { name: "Plentific", category: "content", domains: ["*.plentific.com"] }, { name: "PluginDetect", category: "other", domains: ["dtlilztwypawv.cloudfront.net"] }, { name: "Po.st", company: "RadiumOne", category: "utility", domains: ["*.po.st"] }, { name: "Pointpin", category: "utility", domains: ["*.pointp.in"] }, { name: "Pointroll (Garnett)", category: "ad", domains: ["*.pointroll.com"] }, { name: "Polar", homepage: "https://polar.me/", category: "ad", domains: ["*.polarmobile.ca", "*.mediaeverywhere.com", "*.mediavoice.com", "*.plrsrvcs.com", "*.polarcdn-engine.com", "*.polarcdn-meraxes.com", "*.polarcdn-pentos.com", "*.polarcdn-static.com", "*.polarcdn-terrax.com", "*.polarcdn.com", "*.polarmobile.com", "*.poweredbypolar.com", "*.mediaconductor.me", "*.polaracademy.me"] }, { name: "PollDaddy (Automattic)", category: "ad", domains: ["static.polldaddy.com", "*.poll.fm"] }, { name: "Polldaddy", company: "Automattic", category: "analytics", domains: ["polldaddy.com", "*.polldaddy.com"] }, { name: "Polyfill service", company: "Polyfill.io", category: "other", domains: ["*.polyfill.io"] }, { name: "MegaPopAds", category: "ad", domains: ["*.megapopads.com"] }, { name: "Populis", category: "ad", domains: ["*.populisengage.com"] }, { name: "Postimage.org", category: "content", domains: ["*.postimg.org"] }, { name: "PowerFront", category: "hosting", domains: ["*.inside-graph.com"] }, { name: "PowerReviews", category: "analytics", domains: ["*.powerreviews.com"] }, { name: "Powerlinks.com", category: "ad", domains: ["*.powerlinks.com"] }, { name: "Press+", category: "ad", domains: ["*.pipol.com", "*.ppjol.com", "*.ppjol.net"] }, { name: "PressArea", category: "utility", domains: ["*.pressarea.com"] }, { name: "Pretio Interactive", category: "ad", domains: ["*.pretio.in"] }, { name: "Prezi", category: "utility", domains: ["*.prezi.com"] }, { name: "PriceGrabber", category: "content", domains: ["*.pgcdn.com", "*.pricegrabber.com"] }, { name: "PriceRunner", category: "content", domains: ["*.pricerunner.com"] }, { name: "PrintFriendly", category: "utility", domains: ["*.printfriendly.com"] }, { name: "Privy", category: "ad", domains: ["*.privy.com", "*.privymktg.com"] }, { name: "Proclivity Media", category: "analytics", domains: ["*.pswec.com"] }, { name: "Profitshare", category: "ad", domains: ["*.profitshare.ro"] }, { name: "Programattik", category: "ad", domains: ["*.programattik.com"] }, { name: "Proper Media", category: "content", domains: ["*.proper.io"] }, { name: "Property Week", category: "content", domains: ["*.propertyweek.com"] }, { name: "Provide Support", category: "customer-success", domains: ["*.providesupport.com"] }, { name: "Proweb Uk", category: "hosting", domains: ["*.proweb.net"] }, { name: "Proximic (ComScore)", category: "ad", domains: ["*.proximic.com"] }, { name: "Psyma", category: "ad", domains: ["*.psyma.com"] }, { name: "PubFactory", company: "Safari Books Online", category: "content", domains: ["*.pubfactory.com"] }, { name: "PubNation", category: "ad", domains: ["*.pubnation.com"] }, { name: "Publicidad.net", category: "ad", domains: ["*.publicidad.tv"] }, { name: "PublishThis", company: "Ultra Unlimited", category: "ad", domains: ["*.publishthis.com"] }, { name: "Pulse Insights", category: "analytics", domains: ["*.pulseinsights.com"] }, { name: "Pulsepoint", category: "marketing", domains: ["*.displaymarketplace.com"] }, { name: "Purch", category: "ad", domains: ["*.bestofmedia.com", "*.purch.com"] }, { name: "Pure Chat", category: "customer-success", domains: ["*.purechat.com"] }, { name: "PushCrew", category: "ad", domains: ["*.pushcrew.com"] }, { name: "Q1Media", category: "ad", domains: ["*.q1media.com", "*.q1mediahydraplatform.com"] }, { name: "Qbase Software Development", category: "hosting", domains: ["*.smartwebportal.co.uk"] }, { name: "Qeryz", category: "analytics", domains: ["*.qeryz.com"] }, { name: "Qode Interactive", category: "hosting", domains: ["*.qodeinteractive.com"] }, { name: "Qrius", category: "social", domains: ["*.qrius.me"] }, { name: "Qualaroo", category: "analytics", domains: ["*.qualaroo.com"] }, { name: "Qualtrics", category: "analytics", domains: ["*.qualtrics.com"] }, { name: "Qubit", company: "Qubit", category: "analytics", domains: ["*.qubit.com", "*.qutics.com", "d3c3cq33003psk.cloudfront.net", "*.goqubit.com", "*.qubitproducts.com"] }, { name: "Qubit Deliver", company: "Qubit", category: "analytics", domains: ["d1m54pdnjzjnhe.cloudfront.net", "d22rutvoghj3db.cloudfront.net", "dd6zx4ibq538k.cloudfront.net"] }, { name: "QuestionPro", category: "analytics", domains: ["*.questionpro.com"] }, { name: "Queue-it", category: "other", domains: ["*.queue-it.net"] }, { name: "QuinStreet", category: "ad", domains: ["*.Quinstreet.com", "*.b2btechleadform.com", "*.qnsr.com", "*.qsstats.com"] }, { name: "QuoVadis", category: "utility", domains: ["*.quovadisglobal.com"] }, { name: "Qzzr", category: "analytics", domains: ["*.movementventures.com", "*.qzzr.com"] }, { name: "RapidAPI", category: "utility", domains: ["*.rapidapi.com"] }, { name: "RCS Media Group", category: "ad", domains: ["*.rcsadv.it"] }, { name: "REVIVVE", category: "ad", domains: ["*.revivve.com"] }, { name: "RSSinclude", category: "social", domains: ["*.rssinclude.com"] }, { name: "RTB House AdPilot", company: "RTB House", category: "ad", domains: ["*.erne.co", "*.creativecdn.com"] }, { name: "RTB Media", category: "ad", domains: ["*.rtb-media.me"] }, { name: "RUN", category: "ad", domains: ["*.runadtag.com", "*.rundsp.com"] }, { name: "Rackspace", category: "hosting", domains: ["*.rackcdn.com", "*.rackspacecloud.com", "*.raxcdn.com", "*.websitetestlink.com"] }, { name: "RadiumOne", category: "ad", domains: ["*.gwallet.com", "*.r1-cdn.net"] }, { name: "Rakuten DC Storm", company: "Rakuten", category: "analytics", domains: ["*.dc-storm.com", "*.h4k5.com", "*.stormiq.com"] }, { name: "Rakuten LinkShare", company: "Rakuten", category: "ad", domains: ["*.linksynergy.com"] }, { name: "Rakuten Marketing", company: "Rakuten", category: "ad", domains: ["*.rakuten-static.com", "*.rmtag.com", "tag.rmp.rakuten.com"] }, { name: "Rakuten MediaForge", company: "Rakuten", category: "ad", domains: ["*.mediaforge.com"] }, { name: "Rambler", company: "Rambler & Co", category: "utility", domains: ["*.rambler.ru"] }, { name: "Ranker", category: "content", domains: ["*.ranker.com", "*.rnkr-static.com"] }, { name: "Ravelin", category: "utility", domains: ["*.ravelin.com"] }, { name: "Raygun", category: "utility", domains: ["*.raygun.io", "*.rapidzebra.io"] }, { name: "ReCollect", category: "utility", domains: ["*.recollect.net"] }, { name: "ReSRC", category: "utility", domains: ["*.resrc.it"] }, { name: "ReTargeter", category: "ad", domains: ["*.retargeter.com"] }, { name: "Reach Group", category: "ad", domains: ["*.redintelligence.net"] }, { name: "ReachDynamics", category: "ad", domains: ["*.rdcdn.com"] }, { name: "ReachForce", category: "ad", domains: ["*.reachforce.com"] }, { name: "ReachLocal", category: "ad", domains: ["*.rtrk.co.nz"] }, { name: "ReachMee", category: "content", domains: ["*.reachmee.com"] }, { name: "Reactful", category: "analytics", domains: ["*.reactful.com"] }, { name: "Realtime", company: "internet business technologies", category: "utility", domains: ["*.realtime.co"] }, { name: "Realtime Media (Brian Communications)", category: "ad", domains: ["*.rtm.com"] }, { name: "Realtime Targeting", category: "ad", domains: ["*.idtargeting.com"] }, { name: "Realytics", category: "analytics", domains: ["dcniko1cv0rz.cloudfront.net", "*.realytics.net"] }, { name: "RebelMouse", category: "ad", domains: ["*.rebelmouse.com", "*.rbl.ms"] }, { name: "Receiptful", category: "utility", domains: ["*.receiptful.com"] }, { name: "Recite Me", category: "other", domains: ["*.reciteme.com"] }, { name: "RecoBell", category: "analytics", domains: ["*.recobell.io"] }, { name: "Recommend", category: "analytics", domains: ["*.recommend.pro"] }, { name: "Red Eye International", category: "ad", domains: ["*.pajmc.com"] }, { name: "Redfish Group", category: "ad", domains: ["*.wmps.com"] }, { name: "Reevoo", category: "analytics", domains: ["*.reevoo.com"] }, { name: "Refersion", category: "ad", domains: ["*.refersion.com"] }, { name: "Refined Ads", category: "ad", domains: ["*.refinedads.com"] }, { name: "Reflektion", category: "analytics", domains: ["*.reflektion.com", "d26opx5dl8t69i.cloudfront.net"] }, { name: "Reflow", company: "Scenestealer", category: "ad", domains: ["*.reflow.tv"] }, { name: "Reklama", category: "ad", domains: ["*.o2.pl", "*.wp.pl"] }, { name: "Relevad ReleStar", company: "Relevad", category: "ad", domains: ["*.relestar.com"] }, { name: "Remarketing Pixel", company: "Adsterra Network", category: "ad", domains: ["*.datadbs.com", "*.remarketingpixel.com"] }, { name: "Remintrex", company: "SmartUp Venture", category: "ad", domains: ["*.remintrex.com"] }, { name: "Republer", category: "ad", domains: ["*.republer.com"] }, { name: "Research Now", category: "analytics", domains: ["*.researchgnow.com", "*.researchnow.com"] }, { name: "Research Online", company: "Skills Development Scotland", category: "content", domains: ["*.researchonline.org.uk"] }, { name: "Resonance Insights", category: "analytics", domains: ["*.res-x.com"] }, { name: "Resonate Networks", category: "analytics", domains: ["*.reson8.com"] }, { name: "Response Team", category: "ad", domains: ["*.i-transactads.com"] }, { name: "ResponseTap", category: "analytics", domains: ["*.adinsight.com", "*.responsetap.com"] }, { name: "ResponsiveVoice", category: "other", domains: ["*.responsivevoice.org"] }, { name: "Retention Science", category: "ad", domains: ["*.retentionscience.com", "d1stxfv94hrhia.cloudfront.net"] }, { name: "Revcontent", category: "content", domains: ["*.revcontent.com"] }, { name: "Revee", category: "ad", domains: ["*.revee.com"] }, { name: "Revenue Conduit", category: "utility", domains: ["*.revenueconduit.com"] }, { name: "RevenueMantra", category: "ad", domains: ["*.revenuemantra.com"] }, { name: "Reviews.co.uk", category: "analytics", domains: ["*.reviews.co.uk"] }, { name: "Reviews.io", category: "analytics", domains: ["*.reviews.io"] }, { name: "Revolver Maps", category: "analytics", domains: ["*.revolvermaps.com"] }, { name: "Revv", category: "utility", domains: ["*.revv.co"] }, { name: "RichRelevance", category: "analytics", domains: ["*.richrelevance.com"] }, { name: "RightNow Service Cloud", company: "Oracle", category: "customer-success", domains: ["*.rightnowtech.com", "*.rnengage.com"] }, { name: "Rightster", category: "ad", domains: ["*.ads-creativesyndicator.com"] }, { name: "Riskified", category: "utility", domains: ["*.riskified.com"] }, { name: "Rockerbox", category: "analytics", homepage: "https://www.rockerbox.com/", domains: ["getrockerbox.com"] }, { name: "Rocket Fuel", category: "ad", domains: ["*.rfihub.com", "*.ru4.com", "*.rfihub.net", "*.ad1x.com"] }, { name: "Rollbar", category: "utility", domains: ["*.rollbar.com", "d37gvrvc0wt4s1.cloudfront.net"] }, { name: "RomanCart", category: "utility", domains: ["*.romancart.com"] }, { name: "Rondavu", category: "ad", domains: ["*.rondavu.com"] }, { name: "Roomkey", category: "content", domains: ["*.roomkey.com"] }, { name: "Roost", category: "utility", domains: ["*.goroost.com"] }, { name: "Roxot", category: "ad", domains: ["*.rxthdr.com"] }, { name: "Roxr Software", category: "analytics", domains: ["*.getclicky.com"] }, { name: "Rtoaster", company: "Brainpad", homepage: "https://www.brainpad.co.jp/rtoaster/", category: "marketing", domains: ["*.rtoaster.jp"] }, { name: "Rubikloud.com", category: "analytics", domains: ["*.rubikloud.com"] }, { name: "Ruler Analytics", company: "Ruler", category: "analytics", domains: ["*.nyltx.com", "*.ruleranalytics.com"] }, { name: "Runner", company: "Rambler & Co", category: "content", domains: ["*.begun.ru"] }, { name: "S4M", category: "ad", domains: ["*.sam4m.com"] }, { name: "SAP Hybris Marketing Convert", company: "SAP", category: "ad", domains: ["*.seewhy.com"] }, { name: "SAS Institute", category: "ad", domains: ["*.aimatch.com", "*.sas.com"] }, { name: "SATORI", homepage: "https://satori.marketing/", category: "marketing", domains: ["satori.segs.jp"] }, { name: "SC ShopMania Net SRL", category: "content", domains: ["*.shopmania.com"] }, { name: "SDL Media Manager", company: "SDL", category: "other", domains: ["*.sdlmedia.com"] }, { name: "SFR", category: "other", domains: ["*.sfr.fr"] }, { name: "SLI Systems", category: "utility", domains: ["*.resultslist.com", "*.resultspage.com", "*.sli-spark.com"] }, { name: "SMARTASSISTANT", company: "Smart Information Systems", category: "customer-success", domains: ["*.smartassistant.com"] }, { name: "SMARTSTREAM.TV", category: "ad", domains: ["*.smartstream.tv"] }, { name: "SPX", company: "Smaato", category: "ad", domains: ["*.smaato.net"] }, { name: "Sabio", category: "customer-success", domains: ["*.sabio.co.uk"] }, { name: "Sailthru", category: "analytics", domains: ["*.sail-horizon.com", "*.sail-personalize.com", "*.sail-track.com"] }, { name: "Sailthru Sightlines", company: "Sailthru", category: "marketing", domains: ["*.sailthru.com"] }, { name: "Sajari Pty", category: "utility", domains: ["*.sajari.com"] }, { name: "SaleCycle", category: "ad", domains: ["*.salecycle.com", "d16fk4ms6rqz1v.cloudfront.net", "d22j4fzzszoii2.cloudfront.net", "d30ke5tqu2tkyx.cloudfront.net", "dn1i8v75r669j.cloudfront.net"] }, { name: "Salesforce Live Agent", company: "Salesforce.com", category: "customer-success", domains: ["*.salesforceliveagent.com"] }, { name: "Salesforce.com", category: "ad", domains: ["*.force.com", "*.salesforce.com"] }, { name: "Samba TV", company: "Samba", category: "content", domains: ["*.samba.tv"] }, { name: "Samplicio.us", category: "analytics", domains: ["*.samplicio.us"] }, { name: "Say Media", category: "ad", domains: ["*.saymedia.com"] }, { name: "Scenario", category: "analytics", domains: ["*.getscenario.com"] }, { name: "Schuh (image shard)", company: "Schuh", category: "other", domains: ["d2ob0iztsaxy5v.cloudfront.net"] }, { name: "Science Rockstars", category: "analytics", domains: ["*.persuasionapi.com"] }, { name: "ScientiaMobile", category: "analytics", domains: ["*.wurflcloud.com", "*.wurfl.io"] }, { name: "Scoota", category: "ad", domains: ["*.rockabox.co", "*.scoota.co", "d31i2625d5nv27.cloudfront.net", "dyjnzf8evxrp2.cloudfront.net"] }, { name: "ScribbleLive", category: "ad", domains: ["*.scribblelive.com"] }, { name: "SearchForce", category: "ad", domains: ["*.searchforce.net"] }, { name: "SearchSpring", category: "utility", domains: ["*.searchspring.net"] }, { name: "Searchanise", category: "analytics", domains: ["*.searchanise.com"] }, { name: "Sears Holdings", category: "content", domains: ["*.shld.net"] }, { name: "Secomapp", category: "utility", domains: ["*.secomapp.com"] }, { name: "SecuredVisit", company: "4Cite Marketing", category: "ad", domains: ["*.securedvisit.com"] }, { name: "SecurityMetrics", category: "utility", domains: ["*.securitymetrics.com"] }, { name: "Segmento", category: "ad", domains: ["*.rutarget.ru"] }, { name: "Segmint", category: "analytics", domains: ["*.segmint.net"] }, { name: "Sekindo", category: "content", domains: ["*.sekindo.com"] }, { name: "Seldon", category: "analytics", domains: ["*.rummblelabs.com"] }, { name: "SelectMedia International", category: "content", domains: ["*.selectmedia.asia"] }, { name: "Selligent", category: "ad", domains: ["*.emsecure.net", "*.slgnt.eu", "targetemsecure.blob.core.windows.net"] }, { name: "Sellpoints", category: "analytics", domains: ["*.sellpoints.com"] }, { name: "Semantics3", category: "analytics", domains: ["*.hits.io"] }, { name: "Semasio", category: "analytics", domains: ["*.semasio.net"] }, { name: "Semcasting Site Visitor Attribution", company: "Semcasting", category: "ad", domains: ["*.smartzonessva.com"] }, { name: "Sentifi", category: "social", domains: ["*.sentifi.com"] }, { name: "ServMetric", category: "analytics", domains: ["*.servmetric.com"] }, { name: "ServiceSource International", category: "marketing", domains: ["*.scoutanalytics.net"] }, { name: "ServiceTick", category: "analytics", domains: ["*.servicetick.com"] }, { name: "Servo", company: "Xervo", category: "hosting", domains: ["*.onmodulus.net"] }, { name: "SessionCam", company: "ServiceTick", category: "analytics", domains: ["*.sessioncam.com", "d2oh4tlt9mrke9.cloudfront.net"] }, { name: "Seznam", category: "utility", domains: ["*.imedia.cz"] }, { name: "Sharethrough", category: "ad", domains: ["*.sharethrough.com"] }, { name: "SharpSpring", category: "marketing", domains: ["*.sharpspring.com", "*.marketingautomation.services"] }, { name: "ShopRunner", category: "content", domains: ["*.shoprunner.com", "*.s-9.us"] }, { name: "ShopStorm", category: "utility", domains: ["*.shopstorm.com"] }, { name: "Shopatron", category: "hosting", domains: ["*.shopatron.com"] }, { name: "Shopgate", category: "utility", domains: ["*.shopgate.com"] }, { name: "ShopiMind", company: "ShopIMind", category: "ad", domains: ["*.shopimind.com"] }, { name: "Shopkeeper Tools", category: "utility", domains: ["*.shopkeepertools.com"] }, { name: "Sidecar", category: "other", domains: ["*.getsidecar.com", "d3v27wwd40f0xu.cloudfront.net"] }, { name: "Sidereel", category: "analytics", domains: ["*.sidereel.com"] }, { name: "Sift Science", category: "utility", domains: ["*.siftscience.com"] }, { name: "Signal", category: "tag-manager", domains: ["*.sitetagger.co.uk"] }, { name: "Signyfyd", category: "utility", domains: ["*.signifyd.com"] }, { name: "Silktide", category: "hosting", domains: ["*.silktide.com"] }, { name: "Silverpop", company: "IBM", category: "ad", domains: ["*.mkt912.com", "*.mkt922.com", "*.mkt932.com", "*.mkt941.com", "*.mkt51.net", "*.mkt61.net", "*.pages01.net", "*.pages02.net", "*.pages03.net", "*.pages04.net", "*.pages05.net"] }, { name: "Simplaex", category: "marketing", domains: ["*.simplaex.net"] }, { name: "SimpleReach", category: "analytics", domains: ["*.simplereach.com", "d8rk54i4mohrb.cloudfront.net"] }, { name: "Simplestream", category: "content", domains: ["*.simplestream.com"] }, { name: "Simpli.fi", category: "ad", domains: ["*.simpli.fi"] }, { name: "Simplicity Marketing", category: "ad", domains: ["*.flashtalking.com"] }, { name: "SinnerSchrader Deutschland", category: "ad", domains: ["*.s2Betrieb.de"] }, { name: "Sirv", category: "other", domains: ["*.sirv.com"] }, { name: "Site Meter", category: "analytics", domains: ["*.sitemeter.com"] }, { name: "Site24x7 Real User Monitoring", company: "Site24x7", category: "analytics", domains: ["*.site24x7rum.com"] }, { name: "SiteGainer", category: "analytics", domains: ["*.sitegainer.com", "d191y0yd6d0jy4.cloudfront.net"] }, { name: "SiteScout", company: "Centro", category: "ad", domains: ["*.pixel.ad", "*.sitescout.com"] }, { name: "Siteimprove", category: "utility", domains: ["*.siteimprove.com", "*.siteimproveanalytics.com"] }, { name: "Six Degrees Group", category: "hosting", domains: ["*.fstech.co.uk"] }, { name: "Skimbit", category: "ad", domains: ["*.redirectingat.com", "*.skimresources.com", "*.skimresources.net"] }, { name: "Skimlinks", category: "ad", domains: ["*.skimlinks.com"] }, { name: "SkyGlue Technology", category: "analytics", domains: ["*.skyglue.com"] }, { name: "SkyScanner", category: "content", domains: ["*.skyscanner.net"] }, { name: "Skybet", company: "Bonne Terre t/a Sky Vegas (Sky)", category: "other", domains: ["*.skybet.com"] }, { name: "Skype", category: "other", domains: ["*.skype.com"] }, { name: "Slate Group", category: "content", domains: ["*.cdnslate.com"] }, { name: "SlimCut Media Outstream", company: "SlimCut Media", category: "ad", domains: ["*.freeskreen.com"] }, { name: "Smart Insight Tracking", company: "Emarsys", category: "analytics", domains: ["*.scarabresearch.com"] }, { name: "Smart AdServer", category: "ad", domains: ["*.01net.com", "*.sascdn.com", "*.sasqos.com", "*.smartadserver.com"] }, { name: "SmartFocus", category: "analytics", domains: ["*.emv2.com", "*.emv3.com", "*.predictiveintent.com", "*.smartfocus.com", "*.themessagecloud.com"] }, { name: "Smarter Click", category: "ad", domains: ["*.smct.co", "*.smarterclick.co.uk"] }, { name: "SmarterHQ", category: "analytics", domains: ["*.smarterhq.io", "d1n00d49gkbray.cloudfront.net", "*.smarterremarketer.net"] }, { name: "Smarttools", category: "customer-success", domains: ["*.smartertrack.com"] }, { name: "Smartzer", category: "ad", domains: ["*.smartzer.com"] }, { name: "Snack Media", category: "content", domains: ["*.snack-media.com"] }, { name: "Snacktools", category: "ad", domains: ["*.bannersnack.com"] }, { name: "SnapEngage", category: "customer-success", domains: ["*.snapengage.com"] }, { name: "SnapWidget", category: "content", domains: ["*.snapwidget.com"] }, { name: "Soasta", category: "analytics", domains: ["*.lognormal.net"] }, { name: "SociableLabs", category: "ad", domains: ["*.sociablelabs.net", "*.sociablelabs.com"] }, { name: "Social Annex", category: "customer-success", domains: ["*.socialannex.com"] }, { name: "SocialShopWave", category: "social", domains: ["*.socialshopwave.com"] }, { name: "Socialphotos", category: "social", domains: ["*.slpht.com"] }, { name: "Sociomantic Labs", company: "DunnHumby", category: "ad", domains: ["*.sociomantic.com"] }, { name: "SodaHead", category: "analytics", domains: ["*.sodahead.com"] }, { name: "Softwebzone", category: "hosting", domains: ["*.softwebzone.com"] }, { name: "Sojern", category: "marketing", domains: ["*.sojern.com"] }, { name: "Sokrati", category: "marketing", domains: ["*.sokrati.com"] }, { name: "Sonobi", category: "ad", domains: ["*.sonobi.com"] }, { name: "Sooqr Search", company: "Sooqr", category: "utility", domains: ["*.sooqr.com"] }, { name: "Sophus3", category: "analytics", domains: ["*.s3ae.com", "*.sophus3.com"] }, { name: "Sorenson Media", category: "content", domains: ["*.sorensonmedia.com"] }, { name: "Sortable", category: "ad", domains: ["*.deployads.com"] }, { name: "Sotic", category: "hosting", domains: ["*.sotic.net", "*.soticservers.net"] }, { name: "Soundest", category: "ad", domains: ["*.soundestlink.com", "*.soundest.net"] }, { name: "Sourcepoint", category: "ad", domains: ["*.decenthat.com", "*.fallingfalcon.com", "*.summerhamster.com", "d2lv4zbk7v5f93.cloudfront.net", "d3qxwzhswv93jk.cloudfront.net"] }, { name: "SourceKnowledge", homepage: "https://www.sourceknowledge.com", category: "ad", domains: ["*.provenpixel.com"] }, { name: "SpaceNet", category: "hosting", domains: ["*.nmm.de"] }, { name: "Sparkflow", company: "Intercept Interactive", category: "ad", domains: ["*.sparkflow.net"] }, { name: "Specific Media", category: "ad", domains: ["*.specificmedia.com", "*.adviva.net", "*.specificclick.net"] }, { name: "Spicy", company: "Data-Centric Alliance", category: "ad", domains: ["*.sspicy.ru"] }, { name: "Spoke", category: "customer-success", domains: ["*.121d8.com"] }, { name: "Spongecell", category: "ad", domains: ["*.spongecell.com"] }, { name: "Spot.IM", category: "social", domains: ["*.spot.im", "*.spotim.market"] }, { name: "SpotXchange", category: "ad", domains: ["*.spotxcdn.com", "*.spotxchange.com", "*.spotx.tv"] }, { name: "SpringServer", category: "ad", domains: ["*.springserve.com"] }, { name: "Spylight", category: "other", domains: ["*.spylight.com"] }, { name: "SreamAMG", company: "StreamAMG", category: "other", domains: ["*.streamamg.com"] }, { name: "StackAdapt", category: "ad", domains: ["*.stackadapt.com"] }, { name: "StackExchange", category: "social", domains: ["*.sstatic.net"] }, { name: "Stackla PTY", category: "social", domains: ["*.stackla.com"] }, { name: "Stailamedia", category: "ad", domains: ["*.stailamedia.com"] }, { name: "Stamped.io", category: "analytics", domains: ["*.stamped.io"] }, { name: "Starfield Services Root Certificate Authority", company: "Starfield Technologies", category: "utility", domains: ["*.starfieldtech.com", "ss2.us", "*.ss2.us"] }, { name: "Starfield Technologies", category: "utility", domains: ["*.websiteprotection.com"] }, { name: "StatCounter", category: "analytics", domains: ["*.statcounter.com"] }, { name: "Statful", category: "analytics", domains: ["*.statful.com"] }, { name: "Steelhouse", category: "ad", domains: ["*.steelhousemedia.com"] }, { name: "Steepto", category: "ad", domains: ["*.steepto.com"] }, { name: "StellaService", category: "analytics", domains: ["*.stellaservice.com"] }, { name: "StickyADS.tv", category: "ad", domains: ["*.stickyadstv.com"] }, { name: "STINGRAY", company: "FlexOne", category: "ad", domains: ["*.impact-ad.jp"] }, { name: "Storify", company: "Adobe Systems", category: "social", domains: ["*.storify.com"] }, { name: "Storm Tag Manager", company: "Rakuten", category: "tag-manager", domains: ["*.stormcontainertag.com"] }, { name: "Storygize", category: "ad", domains: ["*.storygize.net"] }, { name: "Strands", category: "utility", domains: ["*.strands.com"] }, { name: "StreamRail", category: "ad", domains: ["*.streamrail.com", "*.streamrail.net"] }, { name: "StrikeAd", category: "ad", domains: ["*.strikead.com"] }, { name: "Struq", company: "Quantcast", category: "ad", domains: ["*.struq.com"] }, { name: "Str\xC3\xB6er Digital Media", category: "ad", domains: ["*.stroeerdigitalmedia.de"] }, { name: "StumbleUpon", category: "content", domains: ["*.stumble-upon.com", "*.stumbleupon.com"] }, { name: "Sub2 Technologies", category: "analytics", domains: ["*.sub2tech.com"] }, { name: "SublimeSkinz", category: "ad", domains: ["*.ayads.co"] }, { name: "Sumo Logic", category: "utility", domains: ["*.sumologic.com"] }, { name: "Sunday Times Driving", category: "content", domains: ["*.driving.co.uk"] }, { name: "SundaySky", category: "ad", domains: ["*.sundaysky.com", "dds6m601du5ji.cloudfront.net"] }, { name: "Sunrise Integration", category: "utility", domains: ["*.sunriseintegration.com"] }, { name: "Supertool Network Technology", category: "analytics", domains: ["*.miaozhen.com"] }, { name: "Survata", category: "analytics", domains: ["*.survata.com"] }, { name: "SurveyGizmo", category: "analytics", domains: ["*.surveygizmo.eu"] }, { name: "SurveyMonkey", category: "analytics", domains: ["*.surveymonkey.com"] }, { name: "Survicate", category: "analytics", domains: ["*.survicate.com"] }, { name: "Sweet Tooth", category: "ad", domains: ["*.sweettooth.io"] }, { name: "Swiftype", category: "utility", domains: ["*.swiftype.com", "*.swiftypecdn.com"] }, { name: "Switch Concepts", category: "ad", domains: ["*.switchadhub.com"] }, { name: "SwitchAds", company: "Switch Concepts", category: "ad", domains: ["*.switchads.com"] }, { name: "Swogo", category: "analytics", domains: ["*.xsellapp.com"] }, { name: "Swoop", category: "ad", domains: ["*.swoop.com"] }, { name: "Symantec", category: "utility", domains: ["*.norton.com", "*.symantec.com", "*.symcb.com", "*.symcd.com"] }, { name: "Syncapse", category: "social", domains: ["*.clickable.net"] }, { name: "Synergetic", category: "ad", domains: ["*.synergetic.ag"] }, { name: "Synthetix", category: "customer-success", domains: ["*.syn-finity.com", "*.synthetix-ec1.com", "*.synthetix.com"] }, { name: "Syte", category: "other", domains: ["*.syteapi.com"] }, { name: "TINT", category: "content", domains: ["*.71n7.com", "d33w9bm0n1egwm.cloudfront.net", "d36hc0p18k1aoc.cloudfront.net", "d3l7tj34e9fc43.cloudfront.net"] }, { name: "TNS (Kantar Group)", category: "analytics", domains: ["*.tns-counter.ru"] }, { name: "TRUSTe", category: "utility", domains: ["*.truste.com"] }, { name: "TV Genius", company: "Ericcson Media Services", category: "content", domains: ["*.tvgenius.net"] }, { name: "TVSquared", category: "ad", domains: ["*.tvsquared.com"] }, { name: "TVTY", category: "ad", domains: ["*.distribeo.com", "*.ogigl.com"] }, { name: "Tactics bvba", category: "hosting", domains: ["*.influid.co"] }, { name: "Tag Inspector", company: "InfoTrust", category: "analytics", domains: ["d22xmn10vbouk4.cloudfront.net"] }, { name: "TagCommander", category: "tag-manager", domains: ["*.commander1.com", "*.tagcommander.com"] }, { name: "Tagboard", category: "social", domains: ["*.tagboard.com"] }, { name: "Taggstar", company: "Taggstar UK", category: "ad", domains: ["*.taggstar.com"] }, { name: "Tail Target", company: "Tail", category: "ad", domains: ["*.tailtarget.com"] }, { name: "Tailored", category: "other", domains: ["d24qm7bu56swjs.cloudfront.net", "dw3vahmen1rfy.cloudfront.net", "*.tailored.to"] }, { name: "Taleo Enterprise Cloud Service", company: "Oracle", category: "content", domains: ["*.taleo.net"] }, { name: "Talkable", category: "ad", domains: ["*.talkable.com", "d2jjzw81hqbuqv.cloudfront.net"] }, { name: "TapSense", category: "ad", domains: ["*.tapsense.com"] }, { name: "Tapad", category: "ad", domains: ["*.tapad.com"] }, { name: "Teads", category: "ad", domains: ["*.teads.tv"] }, { name: "Team Internet Tonic", company: "Team Internet", category: "ad", domains: ["*.dntrax.com"] }, { name: "TechTarget", category: "content", domains: ["*.techtarget.com", "*.ttgtmedia.com"] }, { name: "Technorati", company: "Synacor", category: "ad", domains: ["*.technoratimedia.com"] }, { name: "Teedhaze", category: "content", domains: ["*.fuel451.com"] }, { name: "Tell Apart", category: "analytics", domains: ["*.tellapart.com", "*.tellaparts.com"] }, { name: "Tencent", category: "content", domains: ["*.qq.com", "*.ywxi.net"] }, { name: "Thanx Media", category: "utility", domains: ["*.hawksearch.info"] }, { name: "Thawte", category: "utility", domains: ["*.thawte.com"] }, { name: "Thesis", category: "analytics", homepage: "https://www.thesistesting.com/", domains: ["*.ttsep.com"] }, { name: "The AA", category: "ad", domains: ["*.adstheaa.com"] }, { name: "The ADEX", category: "ad", domains: ["*.theadex.com"] }, { name: "The Best Day", category: "social", domains: ["*.thebestday.com"] }, { name: "The Filter", company: "Exabre", category: "analytics", domains: ["*.thefilter.com"] }, { name: "The Guardian", category: "analytics", domains: ["*.ophan.co.uk"] }, { name: "The Hut Group", category: "content", domains: ["*.thcdn.com"] }, { name: "The Numa Group", category: "other", domains: ["*.hittail.com"] }, { name: "The Publisher Desk", category: "ad", domains: ["*.206ads.com", "*.publisherdesk.com"] }, { name: "The Sydney Morning Herald", company: "Fairfax Media", category: "content", domains: ["*.smh.com.au"] }, { name: "The Wall Street Jounal", category: "content", domains: ["*.wsj.net"] }, { name: "The Wall Street Journal", category: "content", domains: ["*.marketwatch.com"] }, { name: "TheFind", category: "content", domains: ["*.thefind.com"] }, { name: "Thinglink", category: "utility", domains: ["*.thinglink.com"] }, { name: "Thirdpresence", category: "ad", domains: ["*.thirdpresence.com"] }, { name: "ThreatMetrix", category: "utility", domains: ["*.online-metrix.net"] }, { name: "Throtle", homepage: "https://throtle.io/", category: "analytics", domains: ["*.thrtle.com", "*.v12group.com"] }, { name: "TicketMaster", category: "content", domains: ["*.t-x.io", "*.tmcs.net"] }, { name: "TikTok", company: "ByteDance Ltd", homepage: "https://www.tiktok.com/en/", category: "social", domains: ["*.tiktok.com", "*.ipstatp.com"] }, { name: "Tidio Live Chat", company: "Tidio", homepage: "https://www.tidiochat.com/en/", category: "customer-success", domains: ["*.tidiochat.com"] }, { name: "Tiledesk Live Chat", company: "Tiledesk SRL", homepage: "https://www.tiledesk.com/", category: "customer-success", domains: ["*.tiledesk.com"] }, { name: "Time", category: "content", domains: ["*.timeinc.net"] }, { name: "Time2Perf", category: "ad", domains: ["*.time2perf.com"] }, { name: "TinyURL", category: "utility", domains: ["*.tinyurl.com"] }, { name: "Tivo", category: "analytics", domains: ["*.rovicorp.com"] }, { name: "Tom&Co", category: "hosting", domains: ["*.tomandco.uk"] }, { name: "Toms Native Ads", company: "Purch", category: "ad", domains: ["*.natoms.com"] }, { name: "ToneMedia", category: "ad", domains: ["*.clickfuse.com"] }, { name: "Tonic", company: "Team Internet", category: "ad", domains: ["*.dntx.com"] }, { name: "Touch Commerce", category: "customer-success", domains: ["*.inq.com", "*.touchcommerce.com"] }, { name: "ToutApp", category: "ad", domains: ["*.toutapp.com"] }, { name: "TraceView", company: "Solarwinds", category: "analytics", domains: ["*.tracelytics.com", "d2gfdmu30u15x7.cloudfront.net"] }, { name: "TrackJS", category: "analytics", domains: ["*.trackjs.com", "d2zah9y47r7bi2.cloudfront.net"] }, { name: "Tradedoubler", category: "ad", domains: ["*.pvnsolutions.com", "*.tradedoubler.com"] }, { name: "Tradelab", category: "ad", domains: ["*.tradelab.fr"] }, { name: "TrafficFactory", category: "ad", domains: ["*.trafficfactory.biz"] }, { name: "TrafficHunt", category: "ad", domains: ["*.traffichunt.com"] }, { name: "TrafficStars", category: "ad", domains: ["*.trafficstars.com", "*.tsyndicate.com"] }, { name: "Transifex", category: "utility", domains: ["*.transifex.com"] }, { name: "Travelex", category: "utility", domains: ["*.travelex.net", "*.travelex.co.uk"] }, { name: "Travelocity Canada", company: "Travelocity", category: "content", domains: ["*.travelocity.ca"] }, { name: "Travelocity USA", company: "Travelocity", category: "content", domains: ["*.travelocity.com"] }, { name: "Travelzoo", category: "content", domains: ["*.travelzoo.com"] }, { name: "Treasure Data", category: "analytics", domains: ["*.treasuredata.com"] }, { name: "Tremor Video", category: "ad", domains: ["*.tremorhub.com", "*.videohub.tv"] }, { name: "Trialfire", category: "analytics", domains: ["*.trialfire.com"] }, { name: "Tribal Fusion", company: "Exponential Interactive", category: "ad", domains: ["*.tribalfusion.com"] }, { name: "Triblio", category: "marketing", domains: ["*.tribl.io"] }, { name: "Triggered Messaging", company: "Fresh Relevance", category: "ad", domains: ["*.triggeredmessaging.com"] }, { name: "Trinity Mirror", category: "content", domains: ["*.mirror.co.uk"] }, { name: "Trinity Mirror Digital Media", category: "social", domains: ["*.tm-aws.com", "*.icnetwork.co.uk"] }, { name: "TripAdvisor", category: "content", domains: ["*.jscache.com", "*.tacdn.com", "*.tamgrt.com", "*.tripadvisor.com", "*.viator.com", "*.tripadvisor.co.uk"] }, { name: "TripleLift", category: "ad", domains: ["*.3lift.com"] }, { name: "Tru Optik", category: "ad", domains: ["*.truoptik.com"] }, { name: "TruConversion", category: "analytics", domains: ["*.truconversion.com"] }, { name: "Trueffect", category: "marketing", domains: ["*.adlegend.com"] }, { name: "Truefit", category: "analytics", domains: ["*.truefitcorp.com"] }, { name: "Trust Guard", category: "utility", domains: ["*.trust-guard.com"] }, { name: "Trust Pilot", category: "analytics", domains: ["*.trustpilot.com"] }, { name: "Amazon Trust Services", company: "Amazon", category: "utility", domains: ["*.amazontrust.com", "o.ss2.us"] }, { name: "Google Trust Services", company: "Google", category: "utility", domains: ["*.pki.goog"] }, { name: "Let's Encrypt", homepage: "https://letsencrypt.org/", category: "utility", domains: ["*.letsencrypt.org"] }, { name: "TrustX", category: "ad", domains: ["*.trustx.org"] }, { name: "Trusted Shops", category: "utility", domains: ["*.trustedshops.com"] }, { name: "Trustev", company: "TransUnion", category: "utility", domains: ["*.trustev.com"] }, { name: "Trustwave", category: "utility", domains: ["*.trustwave.com"] }, { name: "Tryzens TradeState", company: "Tryzens", category: "analytics", domains: ["*.tryzens-analytics.com"] }, { name: "TubeMogul", category: "ad", domains: ["*.tubemogul.com"] }, { name: "Turn", category: "ad", domains: ["*.turn.com"] }, { name: "Tutorialize", category: "customer-success", domains: ["*.tutorialize.me"] }, { name: "Twenga", category: "content", domains: ["*.twenga.fr", "*.c4tw.net", "*.twenga.co.uk"] }, { name: "Twitframe", company: "Superblock", category: "utility", domains: ["*.twitframe.com"] }, { name: "Twitter Online Conversion Tracking", company: "Twitter", category: "ad", domains: ["*.ads-twitter.com", "analytics.twitter.com"] }, { name: "Twitter Short URL", company: "Twitter", category: "social", domains: ["*.t.co"] }, { name: "Twyn Group", category: "ad", domains: ["*.twyn.com"] }, { name: "Tynt", company: "33 Across", category: "ad", domains: ["*.tynt.com"] }, { name: "Typepad", category: "hosting", domains: ["*.typepad.com"] }, { name: "TyrbooBytes", category: "utility", domains: ["*.turbobytes.net"] }, { name: "UPS i-parcel", company: "UPS", category: "other", domains: ["*.i-parcel.com"] }, { name: "US Media Consulting", category: "ad", domains: ["*.mediade.sk"] }, { name: "Ubertags", category: "tag-manager", domains: ["*.ubertags.com"] }, { name: "Umbel", category: "analytics", domains: ["*.umbel.com"] }, { name: "Unanimis", company: "Switch", category: "ad", domains: ["*.unanimis.co.uk"] }, { name: "Unbounce", category: "ad", domains: ["*.ubembed.com", "*.unbounce.com", "d2xxq4ijfwetlm.cloudfront.net", "d9hhrg4mnvzow.cloudfront.net"] }, { name: "Underdog Media", category: "ad", domains: ["*.underdog.media", "*.udmserve.net"] }, { name: "Understand Digital", category: "ad", domains: ["*.redirecting2.net"] }, { name: "Undertone", company: "Perion", category: "ad", domains: ["*.legolas-media.com"] }, { name: "Unidays", category: "ad", domains: ["*.myunidays.com", "*.unidays.world"] }, { name: "Uniqodo", category: "ad", domains: ["*.uniqodo.com"] }, { name: "Unite", category: "ad", domains: ["*.uadx.com"] }, { name: "United Card Services", category: "utility", domains: ["*.ucs.su"] }, { name: "United Internet", category: "hosting", domains: ["*.uicdn.com"] }, { name: "United Internet Media", category: "ad", domains: ["*.ui-portal.de"] }, { name: "United Internet Media AG", category: "hosting", domains: ["*.tifbs.net", "*.uicdn.net", "*.uimserv.net"] }, { name: "Unknown", category: "other", domains: [] }, { name: "Unruly Media", category: "ad", domains: ["*.unrulymedia.com"] }, { name: "UpBuild", category: "ad", domains: ["*.upbuild.io"] }, { name: "UpSellit", category: "analytics", domains: ["*.upsellit.com"] }, { name: "Upland Software", category: "hosting", domains: ["*.clickability.com"] }, { name: "Airship", category: "marketing", domains: ["*.urbanairship.com", "*.aswpsdkus.com"] }, { name: "UsabilityTools", category: "analytics", domains: ["*.usabilitytools.com"] }, { name: "Usablenet.net", category: "utility", domains: ["*.usablenet.net"] }, { name: "Use It Better", category: "analytics", domains: ["*.useitbetter.com"] }, { name: "User Replay", category: "analytics", domains: ["*.userreplay.net"] }, { name: "UserReport", category: "analytics", domains: ["*.userreport.com"] }, { name: "Userneeds", category: "analytics", domains: ["*.userneeds.dk"] }, { name: "Userzoom", category: "analytics", domains: ["*.userzoom.com"] }, { name: "V12 Retail Finance", category: "utility", domains: ["*.v12finance.com"] }, { name: "Vacaciones eDreams", category: "content", domains: ["*.odistatic.net"] }, { name: "Varick Media Management", category: "ad", domains: ["*.vmmpxl.com"] }, { name: "Vdopia Chocolate", company: "Vdopia", category: "ad", domains: ["*.vdopia.com"] }, { name: "Ve", company: "Ve", homepage: "https://www.ve.com/", category: "marketing", domains: ["*.veinteractive.com", "*.ve.com"] }, { name: "Ve Interactive", company: "Ve", category: "ad", domains: ["*.vepxl1.net", "*.adgenie.co.uk"] }, { name: "Vee24", category: "customer-success", domains: ["*.vee24.com"] }, { name: "Veeseo", category: "content", domains: ["*.veeseo.com"] }, { name: "Venatus Media", category: "marketing", domains: ["*.alcvid.com", "*.venatusmedia.com"] }, { name: "Veoxa", category: "ad", domains: ["*.veoxa.com"] }, { name: "Vergic AB", category: "customer-success", domains: ["*.psplugin.com"] }, { name: "Vergic Engage Platform", company: "Vergic", category: "customer-success", domains: ["*.vergic.com"] }, { name: "Verisign (Symantec)", category: "utility", domains: ["*.verisign.com"] }, { name: "Verizon", category: "utility", domains: ["*.public-trust.com"] }, { name: "Verizon Digital Media CDN", homepage: "https://www.verizondigitalmedia.com/", category: "cdn", domains: ["*.edgecastcdn.net", "*.edgecastdns.net"] }, { name: "Verizon Uplynk", company: "Verizon", category: "content", domains: ["*.uplynk.com"] }, { name: "Vero", company: "Semblance", category: "ad", domains: ["*.getvero.com", "d3qxef4rp70elm.cloudfront.net"] }, { name: "VertaMedia", category: "ad", domains: ["*.vertamedia.com"] }, { name: "Vertical Mass", category: "ad", domains: ["*.vmweb.net"] }, { name: "Vestorly", category: "ad", domains: ["*.oodalab.com"] }, { name: "Vextras", category: "other", domains: ["*.vextras.com"] }, { name: "Viacom", category: "content", domains: ["*.mtvnservices.com"] }, { name: "Vibrant Media", category: "ad", domains: ["*.intellitxt.com", "*.picadmedia.com"] }, { name: "VidPulse", category: "analytics", domains: ["*.vidpulse.com"] }, { name: "Video Media Groep", category: "ad", domains: ["*.vmg.host", "*.inpagevideo.nl"] }, { name: "VideoHub", company: "Tremor Video", category: "ad", domains: ["*.scanscout.com"] }, { name: "Videology", category: "ad", domains: ["*.tidaltv.com"] }, { name: "Vidible", category: "ad", domains: ["*.vidible.tv"] }, { name: "VigLink", category: "ad", domains: ["*.viglink.com"] }, { name: "Vindico", company: "Viant", category: "ad", domains: ["*.vindicosuite.com"] }, { name: "Viocorp International", category: "content", domains: ["*.vioapi.com"] }, { name: "ViralNinjas", category: "ad", domains: ["*.viralninjas.com"] }, { name: "Virool", category: "ad", domains: ["*.virool.com"] }, { name: "Virtual Earth", company: "Microsoft", category: "utility", domains: ["*.virtualearth.net"] }, { name: "Visely", company: "Visely", category: "other", homepage: "https://visely.io/", domains: ["*.visely.io"] }, { name: "VisScore", category: "analytics", domains: ["*.visscore.com", "d2hkbi3gan6yg6.cloudfront.net"] }, { name: "Visible Measures", category: "ad", domains: ["*.visiblemeasures.com"] }, { name: "Visual Studio", company: "Microsoft", category: "utility", domains: ["*.visualstudio.com"] }, { name: "VisualDNA", category: "ad", domains: ["*.visualdna.com"] }, { name: "VisualVisitor", category: "ad", domains: ["*.id-visitors.com"] }, { name: "Vivocha S.p.A", category: "customer-success", domains: ["*.vivocha.com"] }, { name: "Vizu (Nielsen)", category: "analytics", domains: ["*.vizu.com"] }, { name: "Vizury", category: "ad", domains: ["*.vizury.com"] }, { name: "VoiceFive", category: "analytics", domains: ["*.voicefive.com"] }, { name: "Volvelle", company: "Optomaton", category: "ad", domains: ["*.volvelle.tech"] }, { name: "VouchedFor", category: "analytics", domains: ["*.vouchedfor.co.uk"] }, { name: "WARPCACHE", category: "utility", domains: ["*.warpcache.net"] }, { name: "WISHLIST", company: "Shopapps", category: "social", domains: ["*.shopapps.in"] }, { name: "WP Engine", category: "hosting", domains: ["*.wpengine.com"] }, { name: "WalkMe", category: "customer-success", domains: ["*.walkme.com"] }, { name: "Watching That", category: "other", domains: ["*.watchingthat.com"] }, { name: "Wayfair", category: "analytics", domains: ["*.wayfair.com"] }, { name: "Web CEO", category: "other", domains: ["*.websiteceo.com"] }, { name: "Web Dissector", company: "Beijing Gridsum Technologies", category: "analytics", domains: ["*.gridsumdissector.com", "*.webdissector.com"] }, { name: "Web Forensics", category: "analytics", domains: ["*.webforensics.co.uk"] }, { name: "Web Security and Performance", company: "NCC Group", category: "utility", domains: ["*.nccgroup.trust"] }, { name: "WebEngage", category: "customer-success", domains: ["*.webengage.co", "*.webengage.com", "d23nd6ymopvz52.cloudfront.net", "d3701cc9l7v9a6.cloudfront.net"] }, { name: "WebInsight", company: "dotMailer", category: "analytics", domains: ["*.trackedlink.net", "*.trackedweb.net"] }, { name: "WebPageOne Solutions", category: "other", domains: ["*.webpageone.com"] }, { name: "WebSpectator", category: "ad", domains: ["*.webspectator.com"] }, { name: "WebTuna", company: "Application Performance", category: "analytics", domains: ["*.webtuna.com"] }, { name: "WebVideoCore", company: "StreamingVideoProvider", category: "content", domains: ["*.webvideocore.net"] }, { name: "WebWombat", category: "utility", domains: ["*.ic.com.au"] }, { name: "Webcollage", category: "customer-success", domains: ["*.webcollage.net"] }, { name: "Webcore", category: "ad", domains: ["*.onefeed.co.uk"] }, { name: "Webkul", company: "Webkul Software", category: "utility", domains: ["*.webkul.com"] }, { name: "Webmarked", category: "utility", domains: ["*.webmarked.net"] }, { name: "Weborama", category: "ad", domains: ["*.weborama.com", "*.weborama.fr"] }, { name: "WebpageFX", category: "ad", domains: ["*.leadmanagerfx.com"] }, { name: "Webphone", company: "IP WEB SERVICES", category: "customer-success", domains: ["*.webphone.net"] }, { name: "Webselect selectcommerce", company: "Webselect Internet", category: "hosting", domains: ["*.webselect.net"] }, { name: "Webthinking", category: "hosting", domains: ["*.webthinking.co.uk"] }, { name: "Webtrekk", category: "analytics", domains: ["*.wbtrk.net", "*.webtrekk-asia.net", "*.webtrekk.net", "*.wt-eu02.net", "*.wt-safetag.com"] }, { name: "Webtrends", category: "analytics", domains: ["*.webtrends.com", "*.webtrendslive.com", "d1q62gfb8siqnm.cloudfront.net"] }, { name: "Webtype", category: "cdn", domains: ["*.webtype.com"] }, { name: "White Ops", category: "utility", domains: ["*.acexedge.com", "*.tagsrvcs.com"] }, { name: "Whitespace", category: "ad", domains: ["*.whitespacers.com"] }, { name: "WhosOn Live Chat Software", category: "customer-success", domains: ["*.whoson.com"] }, { name: "Wibbitz", category: "other", domains: ["*.wibbitz.com"] }, { name: "Wide Area Communications", category: "hosting", domains: ["*.widearea.co.uk"] }, { name: "WideOrbit", category: "marketing", domains: ["*.admaym.com"] }, { name: "William Reed", category: "content", domains: ["*.wrbm.com"] }, { name: "WillyFogg.com", category: "content", domains: ["*.willyfogg.com"] }, { name: "Windows", company: "Microsoft", category: "utility", domains: ["*.windowsupdate.com"] }, { name: "WisePops", category: "utility", domains: ["*.wisepops.com"] }, { name: "Wishlist King", company: "Appmate", category: "other", homepage: "https://appmate.io/", domains: ["*.appmate.io"] }, { name: "Wishpond Technologies", category: "marketing", domains: ["*.wishpond.com", "*.wishpond.net"] }, { name: "WizRocket Technologies", category: "analytics", domains: ["*.wzrkt.com"] }, { name: "Woopra", category: "analytics", domains: ["*.woopra.com"] }, { name: "Woosmap", category: "utility", domains: ["*.woosmap.com"] }, { name: "WorkCast", category: "hosting", domains: ["*.workcast.net"] }, { name: "World News Media", category: "content", domains: ["*.wnmedia.co.uk"] }, { name: "Worldpay", category: "utility", domains: ["*.worldpay.com"] }, { name: "Wow Analytics", category: "analytics", domains: ["*.wowanalytics.co.uk"] }, { name: "Wowcher", category: "ad", domains: ["*.wowcher.co.uk"] }, { name: "Wufoo", category: "utility", domains: ["*.wufoo.com"] }, { name: "Wunderkind", category: "marketing", homepage: "https://www.wunderkind.co/", domains: ["*.bounceexchange.com", "*.bouncex.net", "*.wknd.ai", "*.cdnbasket.net", "*.cdnwidget.com"] }, { name: "Wyng", category: "ad", domains: ["*.offerpop.com"] }, { name: "XMLSHOP", category: "hosting", domains: ["*.xmlshop.biz"] }, { name: "XiTi", company: "AT Internet", category: "analytics", domains: ["*.xiti.com", "*.aticdn.net"], homepage: "https://www.atinternet.com/en/" }, { name: "YUDU", category: "content", domains: ["*.yudu.com"] }, { name: "Yahoo! Ad Exchange", company: "Yahoo!", category: "ad", domains: ["*.yieldmanager.com", "*.browsiprod.com"] }, { name: "Yahoo! JAPAN Ads", company: "Yahoo! JAPAN", category: "ad", homepage: "https://marketing.yahoo.co.jp/service/yahooads/", domains: ["yads.c.yimg.jp", "s.yimg.jp", "b92.yahoo.co.jp"] }, { name: "Yahoo! Tag Manager", company: "Yahoo! JAPAN", category: "tag-manager", homepage: "https://marketing.yahoo.co.jp/service/tagmanager/", domains: ["*.yjtag.jp"] }, { name: "Yahoo! Small Business", company: "Yahoo!", category: "hosting", domains: ["*.aabacosmallbusiness.com"] }, { name: "Yellow Robot", category: "ad", domains: ["*.backinstock.org"] }, { name: "YieldPartners", category: "ad", domains: ["*.yieldpartners.com"] }, { name: "Yieldbot", category: "ad", domains: ["*.yldbt.com"] }, { name: "Yieldify", category: "ad", domains: ["*.yieldify.com", "*.yieldifylabs.com", "d33wq5gej88ld6.cloudfront.net", "dwmvwp56lzq5t.cloudfront.net"] }, { name: "Yieldlab", category: "ad", domains: ["*.yieldlab.net"] }, { name: "Yieldmo", category: "ad", domains: ["*.yieldmo.com"] }, { name: "Yieldr", category: "ad", domains: ["*.254a.com"] }, { name: "Yo", category: "utility", domains: ["*.yopify.com"] }, { name: "YoYo", category: "utility", domains: ["*.goadservices.com"] }, { name: "Yotpo", homepage: "https://www.yotpo.com/", category: "marketing", domains: ["*.yotpo.com", "*.swellrewards.com"] }, { name: "Yottaa", category: "hosting", domains: ["*.yottaa.com", "*.yottaa.net"] }, { name: "YourAmigo", category: "utility", domains: ["*.youramigo.com"] }, { name: "YuMe", category: "ad", domains: ["*.yume.com", "*.yumenetworks.com"] }, { name: "Yummley", category: "other", domains: ["*.yummly.com"] }, { name: "ZEDO", category: "ad", domains: ["*.zedo.com"] }, { name: "Zafu", category: "analytics", domains: ["*.zafu.com"] }, { name: "Zaius", category: "ad", domains: ["*.zaius.com"] }, { name: "Zamplus ad", category: "ad", domains: ["*.zampda.net"] }, { name: "Zanox", category: "ad", domains: ["*.zanox.com", "*.zanox.ws"] }, { name: "Zapper", category: "utility", domains: ["*.zapper.com"] }, { name: "Zarget", category: "analytics", domains: ["*.zarget.com"] }, { name: "Zemanta", category: "ad", domains: ["*.zemanta.com"] }, { name: "Zen Internet", category: "other", domains: ["*.zyen.com"] }, { name: "Zenovia Digital Exchange", category: "ad", domains: ["*.rhythmxchange.com", "*.zenoviaexchange.com"] }, { name: "ZergNet", category: "content", domains: ["*.zergnet.com"] }, { name: "Zerogrey", category: "hosting", domains: ["*.zerogrey.com"] }, { name: "Ziff Davis Tech", category: "ad", domains: ["*.adziff.com", "*.zdbb.net"] }, { name: "Zmags", category: "marketing", domains: ["*.zmags.com"] }, { name: "Zolando", category: "content", domains: ["*.ztat.net"] }, { name: "Zoover", category: "analytics", domains: ["*.zoover.nl", "*.zoover.co.uk"] }, { name: "Zopim", category: "customer-success", domains: ["*.zopim.io"] }, { name: "[24]7", category: "customer-success", domains: ["*.247-inc.net", "*.247inc.net", "d1af033869koo7.cloudfront.net"] }, { name: "adKernel", category: "ad", domains: ["*.adkernel.com"] }, { name: "adMarketplace", company: "AMPexchange", category: "ad", domains: ["*.ampxchange.com", "*.admarketplace.net"] }, { name: "addtocalendar", category: "utility", domains: ["*.addtocalendar.com"] }, { name: "adnanny", category: "ad", domains: ["*.adserver01.de"] }, { name: "affilinet", category: "ad", domains: ["*.reussissonsensemble.fr", "*.successfultogether.co.uk"] }, { name: "audioBoom", category: "social", domains: ["*.audioboom.com", "*.audioboo.fm"] }, { name: "bPay by Barclaycard", company: "Barclays Bank", category: "utility", domains: ["*.bpay.co.uk"] }, { name: "bRealTime", category: "ad", domains: ["*.brealtime.com"] }, { name: "bd4travel", category: "analytics", domains: ["*.bd4travel.com"] }, { name: "bizinformation-VOID", company: "bizinformation", category: "analytics", domains: ["*.bizinformation.org"] }, { name: "carrot", category: "social", domains: ["*.sharebutton.co"] }, { name: "cloudIQ", category: "analytics", domains: ["*.cloud-iq.com"] }, { name: "comScore", category: "analytics", domains: ["*.adxpose.com", "*.comscore.com", "*.sitestat.com", "*.zqtk.net"] }, { name: "content.ad", category: "ad", domains: ["*.content.ad"] }, { name: "d3 Media", company: "d3 Technologies", category: "other", domains: ["*.d3sv.net"] }, { name: "dexiMEDIA", category: "ad", domains: ["*.deximedia.com"] }, { name: "dianomi", category: "ad", domains: ["*.dianomi.com", "*.dianomioffers.co.uk"] }, { name: "donReach", category: "social", domains: ["*.donreach.com"] }, { name: "dotMailer", category: "ad", domains: ["*.dmtrk.com", "*.dotmailer.com", "*.emlfiles.com"] }, { name: "dotMailer Surveys", company: "dotMailer", category: "analytics", domains: ["*.dotmailer-surveys.com"] }, { name: "dstillery", category: "ad", domains: ["*.dstillery.com", "*.media6degrees.com"] }, { name: "eBay", category: "ad", domains: ["*.ebay.com", "*.ebayimg.com", "*.fetchback.com"] }, { name: "eBay Enterprise", category: "hosting", domains: ["*.csdata1.com", "*.gsipartners.com"] }, { name: "eBuzzing", company: "Teads Managed Services", category: "ad", domains: ["*.ebz.io"] }, { name: "eDigital Research", category: "customer-success", domains: ["*.edigitalresearch.com", "*.edigitalsurvey.com", "*.edrcdn.com", "*.ecustomeropinions.com"] }, { name: "eGain", category: "analytics", domains: ["*.analytics-egain.com", "*.egain.com"] }, { name: "eHost", category: "hosting", domains: ["*.ehosts.net"] }, { name: "eKomi", category: "analytics", domains: ["*.ekomi.com", "*.ekomi.de"] }, { name: "eWAY", company: "Web Active Pty", category: "utility", domains: ["*.eway.com.au"] }, { name: "eXTReMe digital", category: "analytics", domains: ["*.extreme-dm.com"] }, { name: "eXelate", category: "ad", domains: ["*.exelator.com"] }, { name: "ecommercefeed.net", category: "marketing", domains: ["*.ecommercefeed.net"] }, { name: "engage:BDR", category: "ad", domains: ["*.bnmla.com", "*.ebdr3.com"] }, { name: "epago", category: "ad", domains: ["*.adaos-ads.net"] }, { name: "epoq internet services", category: "analytics", domains: ["*.epoq.de"] }, { name: "etouches", category: "hosting", domains: ["*.etouches.com"] }, { name: "etracker", category: "analytics", domains: ["*.etracker.com", "*.etracker.de"] }, { name: "everestads.com", category: "content", domains: ["*.verestads.net"] }, { name: "exebid.DCA", company: "Data-Centric Alliance", category: "ad", domains: ["*.exe.bid"] }, { name: "eyeReturn Marketing", category: "marketing", domains: ["*.eyereturn.com"] }, { name: "feedoptimise", category: "hosting", domains: ["*.feedoptimise.com", "d1w78njrm56n7g.cloudfront.net"] }, { name: "fifty-five", category: "ad", domains: ["*.55labs.com"] }, { name: "fluct", category: "ad", domains: ["*.adingo.jp"] }, { name: "freegeoip.net", company: "(community-funded)", category: "utility", domains: ["*.freegeoip.net"] }, { name: "freewheel.tv", category: "content", domains: ["*.fwmrm.net"] }, { name: "gnatta", category: "customer-success", domains: ["*.gnatta.com"] }, { name: "home.pl", category: "hosting", domains: ["*.nscontext.eu"] }, { name: "hyfn", category: "ad", domains: ["*.hyfn.com"] }, { name: "iAdvize SAS", category: "customer-success", domains: ["*.iadvize.com"] }, { name: "iBillboard", category: "ad", domains: ["*.ibillboard.com"] }, { name: "iCrossing", category: "ad", domains: ["*.ic-live.com"] }, { name: "iFactory", company: "RDW Group", category: "hosting", domains: ["*.ifactory.com"] }, { name: "iGoDigital", category: "analytics", domains: ["*.igodigital.com"] }, { name: "iJento", company: "Fopsha", category: "ad", domains: ["*.ijento.com"] }, { name: "iPage", category: "hosting", domains: ["*.ipage.com"] }, { name: "iPerceptions", category: "customer-success", domains: ["*.iperceptions.com"] }, { name: "iTunes", company: "Apple", category: "content", domains: ["*.mzstatic.com"] }, { name: "imgix", company: "Zebrafish Labs", category: "utility", domains: ["*.imgix.net"] }, { name: "infogr.am", category: "utility", domains: ["*.infogr.am", "*.jifo.co"] }, { name: "iotec", category: "analytics", domains: ["*.dsp.io"] }, { name: "iovation", category: "utility", domains: ["*.iesnare.com"] }, { name: "ipinfo.io", category: "utility", domains: ["*.ipinfo.io"] }, { name: "issuu", category: "content", domains: ["*.issuu.com", "*.isu.pub"] }, { name: "iubenda", category: "utility", domains: ["*.iubenda.com"] }, { name: "j2 Cloud Services", category: "ad", domains: ["*.campaigner.com"] }, { name: "jsonip.com", category: "analytics", domains: ["*.jsonip.com"] }, { name: "linkpulse", category: "analytics", domains: ["*.lp4.io"] }, { name: "loGo_net", category: "analytics", domains: ["*.logo-net.co.uk"] }, { name: "mainADV", category: "ad", domains: ["*.httptrack.com", "*.solocpm.com"] }, { name: "mbr targeting", category: "ad", domains: ["*.m6r.eu"] }, { name: "media.ventive", category: "ad", domains: ["*.contentspread.net"] }, { name: "metrigo", category: "ad", domains: ["*.metrigo.com"] }, { name: "minicabit.com", category: "content", domains: ["*.minicabit.com"] }, { name: "mobiManage", category: "hosting", domains: ["*.mobimanage.com"] }, { name: "moving-pictures", category: "other", domains: ["*.moving-pictures.biz", "*.v6-moving-pictures.com", "*.vtstat.com", "*.moving-pictures.de"] }, { name: "my6sense", category: "ad", domains: ["*.mynativeplatform.com"] }, { name: "myThings", category: "ad", domains: ["*.mythings.com", "*.mythingsmedia.net"] }, { name: "mymovies", category: "content", domains: ["*.mymovies.net"] }, { name: "nRelate-VOID", company: "nRelate", category: "content", domains: ["*.nrelate.com"] }, { name: "nToklo", category: "analytics", domains: ["*.ntoklo.com"] }, { name: "neXeps", category: "ad", domains: ["*.nexeps.com"] }, { name: "ninemsn Pty.", category: "utility", domains: ["*.ninemsn.com.au"] }, { name: "nugg.ad", category: "ad", domains: ["*.nuggad.net"] }, { name: "numero interactive", company: "numero", category: "ad", domains: ["*.numerointeractive.com"] }, { name: "optMD", company: "Optimax Media Delivery", category: "ad", domains: ["*.optmd.com"] }, { name: "otracking.com", category: "analytics", domains: ["*.otracking.com"] }, { name: "paysafecard", company: "Paysafe Group", category: "utility", domains: ["*.paysafecard.com"] }, { name: "piano", category: "ad", domains: ["*.npttech.com", "*.tinypass.com"] }, { name: "piclike", category: "ad", domains: ["*.piclike.us"] }, { name: "placehold.it", category: "utility", domains: ["*.placehold.it"] }, { name: "plista", category: "ad", domains: ["*.plista.com"] }, { name: "prebid.org", category: "utility", domains: ["*.prebid.org"] }, { name: "reEmbed", category: "other", domains: ["*.reembed.com"] }, { name: "reddit", category: "social", domains: ["*.reddit.com", "*.redditstatic.com"] }, { name: "rewardStyle.com", category: "ad", domains: ["*.rewardstyle.com"] }, { name: "rss2json", category: "utility", domains: ["*.rss2json.com"] }, { name: "sage Pay", company: "Sage Pay Europe", category: "utility", domains: ["*.sagepay.com"] }, { name: "section.io", category: "utility", domains: ["*.squixa.net"] }, { name: "smartclip", category: "ad", domains: ["*.smartclip.net"] }, { name: "sovrn", category: "ad", domains: ["*.lijit.com"] }, { name: "stackpile.io", company: "StackPile", category: "tag-manager", domains: ["*.stackpile.io"] }, { name: "template-help.com", category: "hosting", domains: ["*.template-help.com"] }, { name: "test", company: "test only", category: "other", domains: ["*.testtesttest.com"] }, { name: "trueAnthem", category: "social", domains: ["*.tru.am"] }, { name: "tweetmeme-VOID", company: "tweetmeme", category: "analytics", domains: ["*.tweetmeme.com"] }, { name: "uLogin", category: "other", domains: ["*.ulogin.ru"] }, { name: "uLogix", category: "ad", domains: ["*.ulogix.ru"] }, { name: "ucfunnel ucX", company: "ucfunnel", category: "ad", domains: ["*.aralego.com"] }, { name: "up-value", category: "ad", domains: ["*.up-value.de"] }, { name: "wywy", category: "ad", domains: ["*.wywy.com", "*.wywyuserservice.com"] }, { name: "CDK Dealer Management", company: "CDK Global", homepage: "https://www.cdkglobal.com/us", category: "hosting", domains: ["*.assets-cdk.com"] }, { name: "fam", company: "Fing Co Ltd.", homepage: "http://admin.fam-ad.com/report/", category: "ad", domains: ["*.fam-ad.com"] }, { name: "zypmedia", category: "ad", domains: ["*.extend.tv"] }, { name: "codigo", homepage: "https://www.codigo.se", category: "analytics", domains: ["*.codigo.se"] }, { name: "Playground", homepage: "https://playground.xyz", category: "ad", domains: ["*.playground.xyz"] }, { name: "RAM", homepage: "https://www2.rampanel.com/", category: "analytics", domains: ["*.rampanel.com"] }, { name: "Adition", homepage: "https://www.adition.com", category: "ad", domains: ["*.adition.com"] }, { name: "Widespace", homepage: "https://www.widespace.com", category: "ad", domains: ["*.widespace.com"] }, { name: "Colpirio", homepage: "https://www.widespace.com", category: "analytics", domains: ["*.colpirio.com"] }, { name: "Brandmetrics", homepage: "https://www.brandmetrics.com", category: "analytics", domains: ["*.brandmetrics.com"] }, { name: "EasyAd", homepage: "https://web.easy-ads.com/", category: "ad", domains: ["*.easy-ads.com"] }, { name: "Glimr", homepage: "https://glimr.io/", category: "analytics", domains: ["*.glimr.io"] }, { name: "Webtreck", homepage: "https://www.webtrekk.com/en/home/", category: "analytics", domains: ["*.wcfbc.net"] }, { name: "DigiTrust", homepage: "http://www.digitru.st/", category: "analytics", domains: ["*.digitru.st"] }, { name: "Kantar Sifo", homepage: "https://www.kantarsifo.se", category: "analytics", domains: ["*.research-int.se"] }, { name: "Concert", homepage: "https://concert.io/", category: "ad", domains: ["*.concert.io"] }, { name: "Emerse", homepage: "https://www.emerse.com/", category: "ad", domains: ["*.emerse.com"] }, { name: "Iterate", homepage: "https://iteratehq.com/", category: "analytics", domains: ["*.iteratehq.com"] }, { name: "Cookiebot", homepage: "https://www.cookiebot.com/", category: "utility", domains: ["*.cookiebot.com"] }, { name: "Netlify", homepage: "https://www.netlify.com/", category: "utility", domains: ["*.netlify.com", "*.netlifyusercontent.com"] }, { name: "Scroll", homepage: "https://scroll.com/", category: "utility", domains: ["*.scroll.com"] }, { name: "Consumable", homepage: "https://consumable.com/", category: "ad", domains: ["*.serverbid.com"] }, { name: "DMD Marketing", homepage: "https://www.dmdconnects.com/", category: "ad", domains: ["*.medtargetsystem.com"] }, { name: "Catchpoint", homepage: "https://www.catchpoint.com/", category: "analytics", domains: ["*.3gl.net", "*.3genlabs.net"] }, { name: "Terminus", homepage: "https://terminus.com/", category: "ad", domains: ["*.terminus.services"] }, { name: "Acceptable Ads", homepage: "https://acceptableads.com/", category: "ad", domains: ["*.aaxads.com", "*.aaxdetect.com"] }, { name: "ClearBrain", homepage: "https://www.clearbrain.com/", category: "analytics", domains: ["*.clearbrain.com"] }, { name: "Optanon", homepage: "https://www.cookielaw.org/", category: "consent-provider", domains: ["*.onetrust.com", "*.cookielaw.org"] }, { name: "TrustArc", homepage: "https://www.trustarc.com/", category: "utility", domains: ["*.trustarc.com"] }, { name: "iSpot.tv", homepage: "https://www.ispot.tv/", category: "ad", domains: ["*.ispot.tv"] }, { name: "RevJet", homepage: "https://www.revjet.com/", category: "ad", domains: ["*.revjet.com"] }, { name: "atlasRTX", homepage: "https://www.atlasrtx.com/", category: "customer-success", domains: ["*.atlasrtx.com"] }, { name: "ContactAtOnce", homepage: "https://www.contactatonce.com/", category: "customer-success", domains: ["*.contactatonce.com"] }, { name: "Algolia", homepage: "https://www.algolia.com/", category: "utility", domains: ["*.algolianet.com", "*.algolia.net", "*.algolia.io"] }, { name: "EMX Digital", homepage: "https://emxdigital.com", category: "ad", domains: ["*.emxdgt.com"] }, { name: "Moxie", homepage: "https://www.gomoxie.com/", category: "utility", domains: ["*.gomoxie.solutions"] }, { name: "Scripps Network Digital", homepage: "https://www.scrippsnetworksdigital.com/", category: "ad", domains: ["*.snidigital.com"] }, { name: "TurnTo", homepage: "https://www.turntonetworks.com/", category: "utility", domains: ["*.turnto.com"] }, { name: "Quantum Metric", homepage: "https://www.quantummetric.com/", category: "analytics", domains: ["*.quantummetric.com"] }, { name: "Carbon Ads", homepage: "https://www.carbonads.net/", category: "ad", domains: ["*.carbonads.net", "*.carbonads.com"] }, { name: "Ably", homepage: "https://www.ably.io/", category: "utility", domains: ["*.ably.io"] }, { name: "Sectigo", homepage: "https://sectigo.com/", category: "utility", domains: ["*.sectigo.com"] }, { name: "Specless", homepage: "https://gospecless.com/", category: "ad", domains: ["*.specless.tech"] }, { name: "Loggly", homepage: "https://www.loggly.com/", category: "analytics", domains: ["*.loggly.com", "d9jmv9u00p0mv.cloudfront.net"] }, { name: "Intent Media", homepage: "https://intent.com/", category: "ad", domains: ["*.intentmedia.net"] }, { name: "Supership", homepage: "https://supership.jp/", category: "ad", domains: ["*.socdm.com"] }, { name: "F@N Communications", homepage: "https://www.fancs.com/", category: "ad", domains: ["*.ladsp.com"] }, { name: "Vidyard", homepage: "https://www.vidyard.com/", category: "utility", domains: ["*.vidyard.com"] }, { name: "RapidSSL", homepage: "https://www.rapidssl.com/", category: "utility", domains: ["*.rapidssl.com"] }, { name: "Coherent Path", homepage: "https://coherentpath.com/", category: "utility", domains: ["*.coherentpath.com"] }, { name: "Attentive", homepage: "https://attentivemobile.com/", category: "ad", domains: ["*.attn.tv", "*.attentivemobile.com"] }, { name: "emetriq", homepage: "https://www.emetriq.com/", category: "ad", domains: ["*.emetriq.de", "*.xplosion.de"] }, { name: "Bonzai", homepage: "https://www.bonzai.co/", category: "ad", domains: ["*.bonzai.co"] }, { name: "Freshchat", homepage: "https://www.freshworks.com/live-chat-software/", category: "customer-success", domains: ["*.freshchat.com", "*.freshworksapi.com"], products: [{ name: "Freshdesk Messaging", urlPatterns: ["wchat.freshchat.com"], facades: [{ name: "Freshdesk Messaging (formerly Freshchat) Facade", repo: "https://github.com/coliff/freshdesk-messaging-facade/" }] }] }, { name: "Contentful", homepage: "https://www.contentful.com/", category: "utility", domains: ["*.contentful.com"] }, { name: "PureCars", homepage: "https://www.purecars.com/", category: "marketing", domains: ["*.purecars.com"] }, { name: "Tray Commerce", homepage: "https://www.tray.com.br/", category: "marketing", domains: ["*.tcdn.com.br"] }, { name: "AdScore", homepage: "https://www.adscore.com/", category: "ad", domains: ["*.adsco.re"] }, { name: "WebsiteBuilder.com", homepage: "https://www.websitebuilder.com", category: "hosting", domains: ["*.mywebsitebuilder.com"] }, { name: "mParticle", homepage: "https://www.mparticle.com/", category: "utility", domains: ["*.mparticle.com"] }, { name: "Ada", homepage: "https://www.ada.support/", category: "customer-success", domains: ["*.ada.support"] }, { name: "Quora Ads", homepage: "https://www.quora.com/business/", category: "ad", domains: ["*.quora.com"] }, { name: "Auth0", homepage: "https://auth0.com/", category: "utility", domains: ["*.auth0.com"] }, { name: "Bridgewell DSP", homepage: "https://www.bridgewell.com/", category: "ad", domains: ["*.scupio.com"] }, { name: "Wicked Reports", homepage: "https://www.wickedreports.com/", category: "marketing", domains: ["*.wickedreports.com"] }, { name: "Jaywing", homepage: "https://jaywing.com/", category: "marketing", domains: ["*.jaywing.com"] }, { name: "Holimetrix", homepage: "https://u360.d-bi.fr/", category: "marketing", domains: ["*.d-bi.fr"] }, { name: "iZooto", homepage: "https://www.izooto.com", category: "marketing", domains: ["*.izooto.com"] }, { name: "Ordergroove", homepage: "https://www.ordergroove.com/", category: "marketing", domains: ["*.ordergroove.com"] }, { name: "PageSense", homepage: "https://www.zoho.com/pagesense/", category: "analytics", domains: ["*.pagesense.io"] }, { name: "Vizzit", homepage: "https://www.vizzit.se", category: "analytics", domains: ["*.vizzit.se"] }, { name: "Click Guardian", homepage: "https://www.clickguardian.co.uk/", category: "ad", domains: ["*.clickguardian.app", "*.clickguardian.co.uk"] }, { name: "Smartsupp", company: "Smartsupp.com", homepage: "https://www.smartsupp.com", category: "customer-success", domains: ["*.smartsuppchat.com", "*.smartsupp.com", "smartsupp-widget-161959.c.cdn77.org", "*.smartsuppcdn.com"] }, { name: "Smartlook", company: "Smartsupp.com", homepage: "https://www.smartlook.com/", category: "analytics", domains: ["*.smartlook.com"] }, { name: "Luigis Box", company: "Luigis Box", homepage: "https://www.luigisbox.com/", category: "utility", domains: ["*.luigisbox.com"] }, { name: "Targito", company: "VIVmail.cz", homepage: "https://www.targito.com", category: "marketing", domains: ["*.targito.com"] }, { name: "Foxentry", company: "AVANTRO", homepage: "https://foxentry.cz/", category: "utility", domains: ["*.foxentry.cz"] }, { name: "Pendo", homepage: "https://www.pendo.io", category: "analytics", domains: ["*.pendo.io"] }, { name: "Braze", homepage: "https://www.braze.com", category: "analytics", domains: ["*.appboycdn.com"] }, { name: "Usersnap", homepage: "https://usersnap.com", category: "customer-success", domains: ["*.usersnap.com"] }, { name: "Rewardful", homepage: "https://www.getrewardful.com", category: "analytics", domains: ["*.wdfl.co"] }, { name: "Launch Darkly", homepage: "https://launchdarkly.com", category: "utility", domains: ["*.launchdarkly.com"] }, { name: "Statuspage", company: "Atlassian", homepage: "https://www.statuspage.io", category: "utility", domains: ["*.statuspage.io"] }, { name: "HyperInzerce", homepage: "https://hyperinzerce.cz", category: "ad", domains: ["*.hyperinzerce.cz"] }, { name: "POWr", homepage: "https://www.powr.io", category: "utility", domains: ["*.powr.io"] }, { name: "Coral", company: "Coral", homepage: "https://coralproject.net", category: "content", domains: ["*.coral.coralproject.net"] }, { name: "Bolt", homepage: "https://www.bolt.com/", category: "utility", domains: ["*.bolt.com"] }, { name: "Judge.me", homepage: "https://judge.me/", category: "marketing", domains: ["*.judge.me"] }, { name: "Tilda", homepage: "https://tilda.cc/", category: "hosting", domains: ["*.tildacdn.com"] }, { name: "SalesLoft", homepage: "https://salesloft.com/", category: "marketing", domains: ["*.salesloft.com"] }, { name: "Accessibe Accessibility Overlay", company: "Accessibe", homepage: "https://accessibe.com/", category: "utility", domains: ["*.accessibe.com", "*.acsbapp.com", "*.acsbap.com"] }, { name: "Builder", homepage: "https://www.builder.io/", category: "hosting", domains: ["*.builder.io"] }, { name: "Pepperjam", homepage: "https://www.pepperjam.com/", category: "marketing", domains: ["*.pepperjam.com", "*.affiliatetechnology.com"] }, { name: "Reach", homepage: "https://withreach.com/", category: "utility", domains: ["*.gointerpay.net"] }, { name: "Chameleon", homepage: "https://www.trychameleon.com/", category: "marketing", domains: ["*.trychameleon.com"] }, { name: "Matomo", company: "InnoCraft", homepage: "https://matomo.org/", category: "analytics", domains: ["*.matomo.cloud"] }, { name: "Segmanta", homepage: "https://segmanta.com/", category: "marketing", domains: ["*.segmanta.com"] }, { name: "Podsights", homepage: "https://podsights.com/", category: "marketing", domains: ["*.pdst.fm", "us-central1-adaptive-growth.cloudfunctions.net"] }, { name: "Chatwoot", homepage: "https://www.chatwoot.com/", category: "customer-success", domains: ["*.chatwoot.com"] }, { name: "Crisp", homepage: "https://crisp.chat/", category: "customer-success", domains: ["*.crisp.chat"] }, { name: "Admiral CMP", homepage: "https://www.getadmiral.com", category: "consent-provider", domains: ["admiral.mgr.consensu.org", "*.admiral.mgr.consensu.org"] }, { name: "Adnuntius CMP", homepage: "https://adnuntius.com", category: "consent-provider", domains: ["adnuntiusconsent.mgr.consensu.org", "*.adnuntiusconsent.mgr.consensu.org"] }, { name: "Clickio CMP", homepage: "https://clickio.com", category: "consent-provider", domains: ["clickio.mgr.consensu.org", "*.clickio.mgr.consensu.org"] }, { name: "AppConsent CMP", homepage: "https://appconsent.io/en", category: "consent-provider", domains: ["appconsent.mgr.consensu.org", "*.appconsent.mgr.consensu.org"] }, { name: "DMG Media CMP", homepage: "https://www.dmgmedia.co.uk", category: "consent-provider", domains: ["dmgmedia.mgr.consensu.org", "*.dmgmedia.mgr.consensu.org"] }, { name: "Axel Springer CMP", homepage: "https://www.axelspringer.com", category: "consent-provider", domains: ["axelspringer.mgr.consensu.org", "*.axelspringer.mgr.consensu.org"] }, { name: "Bedrock CMP", homepage: "https://www.bedrockstreaming.com", category: "consent-provider", domains: ["bedrock.mgr.consensu.org", "*.bedrock.mgr.consensu.org"] }, { name: "BMIND CMP", homepage: "https://www.bmind.es", category: "consent-provider", domains: ["bmind.mgr.consensu.org", "*.bmind.mgr.consensu.org"] }, { name: "Borlabs CMP", homepage: "https://borlabs.io", category: "consent-provider", domains: ["borlabs.mgr.consensu.org", "*.borlabs.mgr.consensu.org"] }, { name: "Civic CMP", homepage: "https://www.civicuk.com", category: "consent-provider", domains: ["cookiecontrol.mgr.consensu.org", "*.cookiecontrol.mgr.consensu.org"] }, { name: "Commanders Act CMP", homepage: "https://www.commandersact.com", category: "consent-provider", domains: ["commandersact.mgr.consensu.org", "*.commandersact.mgr.consensu.org"] }, { name: "Complianz CMP", homepage: "https://complianz.io/", category: "consent-provider", domains: ["complianz.mgr.consensu.org", "*.complianz.mgr.consensu.org"] }, { name: "Consent Desk CMP", homepage: "https://www.consentdesk.com/", category: "consent-provider", domains: ["consentdesk.mgr.consensu.org", "*.consentdesk.mgr.consensu.org"] }, { name: "Consent Manager CMP", homepage: "https://consentmanager.net", category: "consent-provider", domains: ["consentmanager.mgr.consensu.org", "*.consentmanager.mgr.consensu.org"] }, { name: "Conversant CMP", homepage: "https://www.conversantmedia.eu/", category: "consent-provider", domains: ["conversant.mgr.consensu.org", "*.conversant.mgr.consensu.org"] }, { name: "Cookie Information CMP", homepage: "https://www.cookieinformation.com/", category: "consent-provider", domains: ["cookieinformation.mgr.consensu.org", "*.cookieinformation.mgr.consensu.org"] }, { name: "Cookiebot CMP", homepage: "https://www.cookiebot.com", category: "consent-provider", domains: ["cookiebot.mgr.consensu.org", "*.cookiebot.mgr.consensu.org"] }, { name: "Truendo CMP", homepage: "https://truendo.com/", category: "consent-provider", domains: ["truendo.mgr.consensu.org", "*.truendo.mgr.consensu.org"] }, { name: "Dentsu CMP", homepage: "https://www.dentsuaegisnetwork.de/", category: "consent-provider", domains: ["dan.mgr.consensu.org", "*.dan.mgr.consensu.org"] }, { name: "Didomi CMP", homepage: "https://www.didomi.io/en/", category: "consent-provider", domains: ["didomi.mgr.consensu.org", "*.didomi.mgr.consensu.org"] }, { name: "Ensighten CMP", homepage: "https://www.ensighten.com/", category: "consent-provider", domains: ["ensighten.mgr.consensu.org", "*.ensighten.mgr.consensu.org"] }, { name: "Evidon CMP", homepage: "https://evidon.com", category: "consent-provider", domains: ["evidon.mgr.consensu.org", "*.evidon.mgr.consensu.org"] }, { name: "Ezoic CMP", homepage: "https://www.ezoic.com/", category: "consent-provider", domains: ["ezoic.mgr.consensu.org", "*.ezoic.mgr.consensu.org"] }, { name: "Gemius CMP", homepage: "https://www.gemius.com", category: "consent-provider", domains: ["gemius.mgr.consensu.org", "*.gemius.mgr.consensu.org"] }, { name: "NitroPay CMP", homepage: "https://nitropay.com/", category: "consent-provider", domains: ["nitropay.mgr.consensu.org", "*.nitropay.mgr.consensu.org"] }, { name: "Google FundingChoices", homepage: "https://fundingchoices.google.com/start/", category: "consent-provider", domains: ["fundingchoices.mgr.consensu.org", "*.fundingchoices.mgr.consensu.org", "fundingchoicesmessages.google.com", "*.fundingchoicesmessages.google.com"] }, { name: "Gravito CMP", homepage: "https://www.gravito.net/", category: "consent-provider", domains: ["gravito.mgr.consensu.org", "*.gravito.mgr.consensu.org"] }, { name: "ID Ward CMP", homepage: "https://id-ward.com/enterprise", category: "consent-provider", domains: ["idward.mgr.consensu.org", "*.idward.mgr.consensu.org"] }, { name: "iubenda CMP", homepage: "https://www.iubenda.com", category: "consent-provider", domains: ["iubenda.mgr.consensu.org", "*.iubenda.mgr.consensu.org"] }, { name: "Jump CMP", homepage: "https://jumpgroup.it/", category: "consent-provider", domains: ["avacy.mgr.consensu.org", "*.avacy.mgr.consensu.org"] }, { name: "LiveRamp CMP", homepage: "https://liveramp.com/", category: "consent-provider", domains: ["faktor.mgr.consensu.org", "*.faktor.mgr.consensu.org"] }, { name: "Madvertise CMP", homepage: "https://madvertise.com/en/", category: "consent-provider", domains: ["madvertise.mgr.consensu.org", "*.madvertise.mgr.consensu.org"] }, { name: "Mairdumont Netletic CMP", homepage: "https://www.mairdumont-netletix.com/", category: "consent-provider", domains: ["mdnxmp.mgr.consensu.org", "*.mdnxmp.mgr.consensu.org"] }, { name: "Marfeel CMP", homepage: "https://www.marfeel.com/", category: "consent-provider", domains: ["marfeel.mgr.consensu.org", "*.marfeel.mgr.consensu.org"] }, { name: "Mediavine CMP", homepage: "https://www.mediavine.com/", category: "consent-provider", domains: ["mediavine.mgr.consensu.org", "*.mediavine.mgr.consensu.org"] }, { name: "ConsentServe CMP", homepage: "https://www.consentserve.com/", category: "consent-provider", domains: ["consentserve.mgr.consensu.org", "*.consentserve.mgr.consensu.org"] }, { name: "Next14 CMP", homepage: "https://www.next14.com/", category: "consent-provider", domains: ["next14.mgr.consensu.org", "*.next14.mgr.consensu.org"] }, { name: "AdRoll CMP", homepage: "https://www.adroll.com/", category: "consent-provider", domains: ["adroll.mgr.consensu.org", "*.adroll.mgr.consensu.org"] }, { name: "Ogury CMP", homepage: "https://www.ogury.com/", category: "consent-provider", domains: ["ogury.mgr.consensu.org", "*.ogury.mgr.consensu.org"] }, { name: "OneTag CMP", homepage: "https://onetag.net", category: "consent-provider", domains: ["onetag.mgr.consensu.org", "*.onetag.mgr.consensu.org"] }, { name: "OneTrust CMP", homepage: "https://onetrust.com", category: "consent-provider", domains: ["onetrust.mgr.consensu.org", "*.onetrust.mgr.consensu.org"] }, { name: "optAd360 CMP", homepage: "https://www.optad360.com/", category: "consent-provider", domains: ["optad360.mgr.consensu.org", "*.optad360.mgr.consensu.org"] }, { name: "Osano CMP", homepage: "https://www.osano.com", category: "consent-provider", domains: ["osano.mgr.consensu.org", "*.osano.mgr.consensu.org"] }, { name: "Playwire CMP", homepage: "https://www.playwire.com", category: "consent-provider", domains: ["playwire.mgr.consensu.org", "*.playwire.mgr.consensu.org"] }, { name: "Pulselive CMP", homepage: "https://www.pulselive.com", category: "consent-provider", domains: ["pulselive.mgr.consensu.org", "*.pulselive.mgr.consensu.org"] }, { name: "Quantcast Choice", homepage: "https://quantcast.com", category: "consent-provider", domains: ["quantcast.mgr.consensu.org", "*.quantcast.mgr.consensu.org"] }, { name: "RCS Pubblicita CMP", homepage: "http://www.rcspubblicita.it/site/home.html", category: "consent-provider", domains: ["rcsmediagroup.mgr.consensu.org", "*.rcsmediagroup.mgr.consensu.org"] }, { name: "Rich Audience CMP", homepage: "https://richaudience.com", category: "consent-provider", domains: ["richaudience.mgr.consensu.org", "*.richaudience.mgr.consensu.org"] }, { name: "Ringier Axel Springer CMP", homepage: "https://www.ringieraxelspringer.pl/en/home/", category: "consent-provider", domains: ["rasp.mgr.consensu.org", "*.rasp.mgr.consensu.org"] }, { name: "Secure Privacy CMP", homepage: "https://secureprivacy.ai/", category: "consent-provider", domains: ["secureprivacy.mgr.consensu.org", "*.secureprivacy.mgr.consensu.org"] }, { name: "Securiti CMP", homepage: "https://securiti.ai/", category: "consent-provider", domains: ["securiti.mgr.consensu.org", "*.securiti.mgr.consensu.org"] }, { name: "Seznam.cz CMP", homepage: "https://www.seznam.cz/", category: "consent-provider", domains: ["seznam.mgr.consensu.org", "*.seznam.mgr.consensu.org"] }, { name: "ShareThis CMP", homepage: "https://sharethis.com", category: "consent-provider", domains: ["sharethis.mgr.consensu.org", "*.sharethis.mgr.consensu.org"] }, { name: "ShinyStat CMP", homepage: "https://www.shinystat.com", category: "consent-provider", domains: ["shinystat.mgr.consensu.org", "*.shinystat.mgr.consensu.org"] }, { name: "Sibbo CMP", homepage: "https://sibboventures.com/en/", category: "consent-provider", domains: ["sibboventures.mgr.consensu.org", "*.sibboventures.mgr.consensu.org"] }, { name: "Singlespot CMP", homepage: "https://www.singlespot.com/en", category: "consent-provider", domains: ["singlespot.mgr.consensu.org", "*.singlespot.mgr.consensu.org"] }, { name: "Sirdata CMP", homepage: "https://www.sirdata.com", category: "consent-provider", domains: ["sddan.mgr.consensu.org", "*.sddan.mgr.consensu.org"] }, { name: "Snigel CMP", homepage: "https://snigel.com", category: "consent-provider", domains: ["snigelweb.mgr.consensu.org", "*.snigelweb.mgr.consensu.org"] }, { name: "Sourcepoint CMP", homepage: "https://sourcepoint.com", category: "consent-provider", domains: ["sourcepoint.mgr.consensu.org", "*.sourcepoint.mgr.consensu.org"] }, { name: "Pubtech CMP", homepage: "https://www.pubtech.ai/", category: "consent-provider", domains: ["pubtech.mgr.consensu.org", "*.pubtech.mgr.consensu.org"] }, { name: "AdMetrics Pro CMP", homepage: "https://admetricspro.com", category: "consent-provider", domains: ["cmp.mgr.consensu.org", "*.cmp.mgr.consensu.org"] }, { name: "Traffective CMP", homepage: "https://traffective.com", category: "consent-provider", domains: ["traffective.mgr.consensu.org", "*.traffective.mgr.consensu.org"] }, { name: "UniConsent CMP", homepage: "https://www.uniconsent.com", category: "consent-provider", domains: ["uniconsent.mgr.consensu.org", "*.uniconsent.mgr.consensu.org", "cmp.uniconsent.com", "*.uniconsent.com"] }, { name: "TrustArc CMP", homepage: "https://trustarc.com/", category: "consent-provider", domains: ["trustarc.mgr.consensu.org", "*.trustarc.mgr.consensu.org"] }, { name: "Usercentrics CMP", homepage: "https://usercentrics.com", category: "consent-provider", domains: ["usercentrics.mgr.consensu.org", "*.usercentrics.mgr.consensu.org", "*.usercentrics.eu", "*.services.usercentrics.eu"] }, { name: "WebAds CMP", homepage: "https://www.webads.nl/", category: "consent-provider", domains: ["webads.mgr.consensu.org", "*.webads.mgr.consensu.org"] }, { name: "Trustcommander", company: "Commandersact", homepage: "https://www.commandersact.com", category: "consent-provider", domains: ["*.trustcommander.net"] }, { name: "Hubvisor", homepage: "https://www.hubvisor.io", category: "ad", domains: ["*.hubvisor.io"] }, { name: "Castle", homepage: "https://castle.io", category: "utility", domains: ["*.castle.io", "d2t77mnxyo7adj.cloudfront.net"] }, { name: "Wigzo", homepage: "https://www.wigzo.com/", category: "marketing", domains: ["*.wigzo.com", "*.wigzopush.com"] }, { name: "Convertful", homepage: "https://convertful.com/", category: "marketing", domains: ["*.convertful.com"] }, { name: "OpenLink", company: "MediaWallah", homepage: "https://www.mediawallah.com/", category: "ad", domains: ["*.mediawallahscript.com"] }, { name: "TPMN", company: "TPMN", homepage: "http://tpmn.io/", category: "ad", domains: ["*.tpmn.co.kr"] }, { name: "HERO", company: "Klarna", homepage: "https://www.usehero.com/", category: "customer-success", domains: ["*.usehero.com"] }, { name: "Zync", company: "Zeta Global", homepage: "https://zetaglobal.com/", category: "marketing", domains: ["*.rezync.com"] }, { name: "AdFuel Video", company: "AdFuel", homepage: "https://goadfuel.com/", category: "ad", domains: ["*.videoplayerhub.com"] }, { name: "Prefix Box AI Search", company: "Prefix Box", homepage: "https://www.prefixbox.com/", category: "utility", domains: ["*.prefixbox.com"] }, { name: "SpeedSize Service Worker", company: "SpeedSize", homepage: "https://speedsize.com/", category: "utility", domains: ["di6367dava8ow.cloudfront.net", "d2d22nphq0yz8t.cloudfront.net"] }, { name: "Vonage Video API", company: "Vonage", homepage: "https://www.vonage.com/communications-apis/video/", category: "video", domains: ["*.opentok.com"] }, { name: "Checkout.com", company: "Checkout.com", homepage: "https://www.checkout.com", category: "utility", domains: ["*.checkout.com"] }, { name: "Noibu", company: "Noibu", homepage: "https://www.noibu.com", category: "utility", domains: ["*.noibu.com"] }, { name: "Clarity", company: "Microsoft", homepage: "https://clarity.microsoft.com/", category: "utility", domains: ["*.clarity.ms"] }, { name: "goinstore", company: "Emplifi", homepage: "https://goinstore.com/", category: "customer-success", domains: ["*.goinstore.com"] }, { name: "SegmentStream", company: "SegmentStream", homepage: "https://segmentstream.com/", category: "marketing", domains: ["*.segmentstream.com"] }, { name: "Amazon Associates", company: "Amazon", homepage: "https://affiliate-program.amazon.co.uk/", category: "marketing", domains: ["*.associates-amazon.com"] }, { name: "DotMetrics", company: "Ipsos", homepage: "https://www.dotmetrics.net/", category: "analytics", domains: ["*.dotmetrics.net"] }, { name: "Truffle Bid", company: "Truffle", homepage: "https://truffle.bid/", category: "ad", domains: ["*.truffle.bid"] }, { name: "Hybrid", company: "Hybrid", homepage: "https://hybrid.ai/", category: "ad", domains: ["*.hybrid.ai"] }, { name: "AdMan Media", company: "AdMan", homepage: "https://admanmedia.com/", category: "video", domains: ["*.admanmedia.com"] }, { name: "ID5 Identity Cloud", company: "ID5", homepage: "https://id5.io/", category: "ad", domains: ["id5-sync.com", "*.id5-sync.com"] }, { name: "Audience Rate", company: "Audience Rate Limited", homepage: "https://www.audiencerate.com/", category: "ad", domains: ["*.audrte.com"] }, { name: "Seedtag", company: "Seedtag Advertising", homepage: "https://www.seedtag.com/", category: "ad", domains: ["*.seedtag.com"] }, { name: "IVI", company: "IVI Technologies", homepage: "http://ivitechnologies.com/", category: "ad", domains: ["*.ivitrack.com"] }, { name: "Sportradar", company: "Sportradar", homepage: "https://www.sportradar.com/", category: "ad", domains: ["*.sportradarserving.com"] }, { name: "ZEOTAP", company: "ZEOTAP", homepage: "https://zeotap.com/", category: "ad", domains: ["*.zeotap.com"] }, { name: "Web Content Assessor", company: "TMT Digital", homepage: "https://mediatrust.com/", category: "ad", domains: ["*.webcontentassessor.com"] }, { name: "Genie", company: "Media Force", homepage: "https://hellogenie.com/", category: "ad", domains: ["*.mfadsrvr.com"] }, { name: "mediarithmics", company: "mediarithmics", homepage: "https://www.mediarithmics.com/", category: "ad", domains: ["*.mediarithmics.com"] }, { name: "Ozone Project", company: "The Ozone Project", homepage: "https://www.ozoneproject.com/", category: "ad", domains: ["*.the-ozone-project.com"] }, { name: "FiftyAurora", company: "Fifty", homepage: "https://fifty.io/", category: "ad", domains: ["*.fiftyt.com"] }, { name: "smadex", company: "entravision", homepage: "https://smadex.com/", category: "ad", domains: ["*.smadex.com"] }, { name: "AWX", company: "Trinity Mirror", category: "ad", domains: ["*.tm-awx.com"] }, { name: "XPO", company: "Knorex", category: "ad", homepage: "https://www.knorex.com/", domains: ["*.brand-display.com"] }, { name: "Viafoura", company: "Viafoura", category: "ad", homepage: "https://viafoura.com/", domains: ["*.viafoura.co", "*.viafoura.net"] }, { name: "Adnami", company: "Adnami", category: "ad", homepage: "https://www.adnami.io/", domains: ["*.adnami.io"] }, { name: "LiveRamp Privacy Manager", company: "LiveRamp", category: "ad", homepage: "https://liveramp.com/privacy-legal-compliance/", domains: ["*.privacymanager.io"] }, { name: "Onfocus", company: "Onfocus SAS", category: "ad", domains: ["*.4dex.io"] }, { name: "viewTag", company: "Advanced Store", category: "ad", domains: ["*.ad4m.at"] }, { name: "MRP Prelytics", company: "Market Resource Partners", category: "ad", homepage: "https://www.mrpfd.com/", domains: ["*.mrpdata.net"] }, { name: "iPROM", company: "iPROM", category: "ad", homepage: "https://iprom.eu/", domains: ["*.iprom.net"] }, { name: "Plausible", company: "Plausible", homepage: "https://plausible.io/", category: "analytics", domains: ["*.plausible.io"] }, { name: "Micro Analytics", company: "Micro Analytics", homepage: "https://microanalytics.io/", category: "analytics", domains: ["padmin.microanalytics.io", "www.microanalytics.io", "dev.microanalytics.io", "status.microanalytics.io"] }, { name: "Scale8", company: "Scale8", homepage: "https://scale8.com/", category: "analytics", domains: ["www.scale8.com", "api-dev.scale8.com", "cdn.scale8.com", "ui.scale8.com"] }, { name: "Cabin", company: "Cabin", homepage: "https://withcabin.com/", category: "analytics", domains: ["*.withcabin.com"] }, { name: "Appcues", company: "Appcues", homepage: "https://www.appcues.com/", category: "analytics", domains: ["*.appcues.com"] }, { name: "Fathom Analytics", company: "Fathom", homepage: "https://usefathom.com/", category: "analytics", domains: ["*.usefathom.com"] }, { name: "Clearbit", company: "Clearbit", homepage: "https://clearbit.com/", category: "analytics", domains: ["*.clearbitjs.com", "*.clearbitscripts.com", "*.clearbit.com"] }, { name: "G2", company: "G2", homepage: "https://www.g2.com/", category: "utility", domains: ["*.g2.com", "*.g2crowd.com"] }, { name: "Navu", company: "Navu", homepage: "https://navu.co/", category: "ad", domains: ["*.navu.co"] }, { name: "InZynk", company: "InZynk", homepage: "https://inzynk.com/", category: "ad", domains: ["*.inzynk.com", "*.inzynk.io"] }, { name: "Integrate", company: "Integrate", homepage: "https://www.integrate.com/", category: "ad", domains: ["*.integrate.com", "*.listenloop.com"] }, { name: "Ad Lightning", company: "Boltive", homepage: "https://www.adlightning.com/", category: "ad", domains: ["*.adlightning.com"] }, { name: "GeoEdge", company: "GeoEdge", homepage: "https://www.geoedge.com/", category: "ad", domains: ["*.geoedge.com", "*.geoedge.be"] }, { name: "Doofinder", company: "Doofinder", homepage: "https://www.doofinder.com/", category: "utility", domains: ["cdn.doofinder.com"] }, { name: "Revlifter", company: "Revlifter", homepage: "https://www.revlifter.com/", category: "utility", domains: ["assets.revlifter.com"] }, { name: "Didomi", company: "Didomi", homepage: "https://www.didomi.io/", category: "consent-provider", domains: ["sdk.privacy-center.org", "api.privacy-center.org"] }, { name: "Pubperf Analytics", company: "Pubperf", homepage: "https://www.pubperf.com/", category: "analytics", domains: ["*.pubperf.com"] }];
    }
});
var require_nostats = __commonJS({
    "package/lib/subsets/nostats.js"(exports$1, module) {
        var { createAPIFromDataset } = require_create_entity_finder_api();
        var entities = require_entities_nostats();
        module.exports = createAPIFromDataset(entities);
    }
});
var require_nostats_subset = __commonJS({
    "package/nostats-subset.js"(exports$1, module) {
        module.exports = require_nostats();
    }
});
var nostatsSubset = require_nostats_subset();

// Copyright 2023 The Chromium Authors
const defaults = () => ({
    includeRuntimeCallStats: false,
    showAllEvents: false,
    debugMode: false,
    maxInvalidationEventsPerEvent: 20,
    enableAnimationsFrameHandler: false,
});
function configToCacheKey(config) {
    return JSON.stringify(config);
}

var Configuration = /*#__PURE__*/Object.freeze({
	__proto__: null,
	configToCacheKey: configToCacheKey,
	defaults: defaults
});

// Copyright 2024 The Chromium Authors
const extensionPalette = [
    'primary',
    'primary-light',
    'primary-dark',
    'secondary',
    'secondary-light',
    'secondary-dark',
    'tertiary',
    'tertiary-light',
    'tertiary-dark',
    'error',
    'warning',
];
function isExtensionPayloadMarker(payload) {
    return payload.dataType === 'marker';
}
function isExtensionEntryObj(payload) {
    const hasTrack = 'track' in payload && Boolean(payload.track);
    const validEntryType = payload.dataType === 'track-entry' || payload.dataType === undefined;
    return validEntryType && hasTrack;
}
function isConsoleTimestampPayloadTrackEntry(payload) {
    return payload.url !== undefined && payload.description !== undefined;
}
function isValidExtensionPayload(payload) {
    return isExtensionPayloadMarker(payload) || isExtensionEntryObj(payload) ||
        isConsoleTimestampPayloadTrackEntry(payload);
}
function isSyntheticExtensionEntry(entry) {
    return entry.cat === 'devtools.extension';
}

var Extensions$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	extensionPalette: extensionPalette,
	isConsoleTimestampPayloadTrackEntry: isConsoleTimestampPayloadTrackEntry,
	isExtensionEntryObj: isExtensionEntryObj,
	isExtensionPayloadMarker: isExtensionPayloadMarker,
	isSyntheticExtensionEntry: isSyntheticExtensionEntry,
	isValidExtensionPayload: isValidExtensionPayload
});

// Copyright 2023 The Chromium Authors
function isTimeRangeAnnotation(annotation) {
    return annotation.type === 'TIME_RANGE';
}
function isEntryLabelAnnotation(annotation) {
    return annotation.type === 'ENTRY_LABEL';
}
function isEntriesLinkAnnotation(annotation) {
    return annotation.type === 'ENTRIES_LINK';
}
function traceEventKeyToValues(key) {
    const parts = key.split('-');
    const type = parts[0];
    switch (type) {
        case "p" :
            if (parts.length !== 5 ||
                !(parts.every((part, i) => i === 0 || typeof part === 'number' || !isNaN(parseInt(part, 10))))) {
                throw new Error(`Invalid ProfileCallKey: ${key}`);
            }
            return {
                type: parts[0],
                processID: parseInt(parts[1], 10),
                threadID: parseInt(parts[2], 10),
                sampleIndex: parseInt(parts[3], 10),
                protocol: parseInt(parts[4], 10),
            };
        case "r" :
            if (parts.length !== 2 || !(typeof parts[1] === 'number' || !isNaN(parseInt(parts[1], 10)))) {
                throw new Error(`Invalid RawEvent Key: ${key}`);
            }
            return {
                type: parts[0],
                rawIndex: parseInt(parts[1], 10),
            };
        case "s" :
            if (parts.length !== 2 || !(typeof parts[1] === 'number' || !isNaN(parseInt(parts[1], 10)))) {
                throw new Error(`Invalid SyntheticEvent Key: ${key}`);
            }
            return {
                type: parts[0],
                rawIndex: parseInt(parts[1], 10),
            };
        case "l" : {
            if (parts.length !== 2 || Number.isNaN(parseInt(parts[1], 10))) {
                throw new Error(`Invalid LegacyTimelineFrame Key: ${key}`);
            }
            return {
                type,
                rawIndex: parseInt(parts[1], 10),
            };
        }
        default:
            throw new Error(`Unknown trace event key: ${key}`);
    }
}

var File$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	isEntriesLinkAnnotation: isEntriesLinkAnnotation,
	isEntryLabelAnnotation: isEntryLabelAnnotation,
	isTimeRangeAnnotation: isTimeRangeAnnotation,
	traceEventKeyToValues: traceEventKeyToValues
});

// Copyright 2025 The Chromium Authors

var Overlays = /*#__PURE__*/Object.freeze({
	__proto__: null
});

// Copyright 2022 The Chromium Authors
function Micro(value) {
    return value;
}
function Milli(value) {
    return value;
}
function Seconds(value) {
    return value;
}

var Timing$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Micro: Micro,
	Milli: Milli,
	Seconds: Seconds
});

// Copyright 2022 The Chromium Authors
function isNestableAsyncPhase(phase) {
    return phase === "b"  || phase === "e"  ||
        phase === "n" ;
}
function isPhaseAsync(phase) {
    return isNestableAsyncPhase(phase) || phase === "S"  || phase === "T"  ||
        phase === "F"  || phase === "p" ;
}
function isFlowPhase(phase) {
    return phase === "s"  || phase === "t"  || phase === "f" ;
}
function objectIsEvent(obj) {
    return 'cat' in obj && 'name' in obj && 'ts' in obj;
}
function objectIsCallFrame(object) {
    return ('functionName' in object && typeof object.functionName === 'string') &&
        ('scriptId' in object && (typeof object.scriptId === 'string' || typeof object.scriptId === 'number')) &&
        ('columnNumber' in object && typeof object.columnNumber === 'number') &&
        ('lineNumber' in object && typeof object.lineNumber === 'number') &&
        ('url' in object && typeof object.url === 'string');
}
const VALID_PROFILE_SOURCES = ['Inspector', 'SelfProfiling', 'Internal'];
function isRunTask(event) {
    return event.name === "RunTask"  && event.ph === "X" ;
}
function isAuctionWorkletRunningInProcess(event) {
    return event.name === 'AuctionWorkletRunningInProcess';
}
function isAuctionWorkletDoneWithProcess(event) {
    return event.name === 'AuctionWorkletDoneWithProcess';
}
function isLegacyScreenshot(event) {
    return event.name === "Screenshot"  && 'id' in event;
}
function isLegacySyntheticScreenshot(event) {
    return event.name === "Screenshot"  && 'dataUri' in (event.args ?? {});
}
function isScreenshot(event) {
    return event.name === "Screenshot"  && 'source_id' in (event.args ?? {});
}
function isSoftNavigationStart(event) {
    return event.name === "SoftNavigationStart" ;
}
const markerTypeGuards = [
    isMarkDOMContent,
    isMarkLoad,
    isFirstPaint,
    isFirstContentfulPaint,
    isAnyLargestContentfulPaintCandidate,
    isNavigationStart,
    isSoftNavigationStart,
];
const MarkerName = [
    "MarkDOMContent" ,
    "MarkLoad" ,
    "firstPaint" ,
    "firstContentfulPaint" ,
    "largestContentfulPaint::Candidate" ,
    "largestContentfulPaint::CandidateForSoftNavigation" ,
    "navigationStart" ,
    "SoftNavigationStart" ,
];
function isMarkerEvent(event) {
    if (event.ph === "I"  || "n" ) {
        return markerTypeGuards.some(fn => fn(event));
    }
}
const pageLoadEventTypeGuards = [
    ...markerTypeGuards,
    isInteractiveTime,
];
function eventIsPageLoadEvent(event) {
    if (event.ph === "I"  || "n" ) {
        return pageLoadEventTypeGuards.some(fn => fn(event));
    }
}
function isTracingSessionIdForWorker(event) {
    return event.name === 'TracingSessionIdForWorker';
}
const NO_NAVIGATION = 'NO_NAVIGATION';
function isScheduleStyleInvalidationTracking(event) {
    return event.name === "ScheduleStyleInvalidationTracking" ;
}
function isStyleRecalcInvalidationTracking(event) {
    return event.name === "StyleRecalcInvalidationTracking" ;
}
function isStyleInvalidatorInvalidationTracking(event) {
    return event.name === "StyleInvalidatorInvalidationTracking" ;
}
function isBeginCommitCompositorFrame(event) {
    return event.name === "BeginCommitCompositorFrame" ;
}
function isParseMetaViewport(event) {
    return event.name === "ParseMetaViewport" ;
}
function isLinkPreconnect(event) {
    return event.name === "LinkPreconnect" ;
}
function isScheduleStyleRecalculation(event) {
    return event.name === "ScheduleStyleRecalculation" ;
}
function isRenderFrameImplCreateChildFrame(event) {
    return event.name === "RenderFrameImpl::createChildFrame" ;
}
function isLayoutImageUnsized(event) {
    return event.name === "LayoutImageUnsized" ;
}
function isPairableAsyncBegin(e) {
    return e.ph === "b" ;
}
function isPairableAsyncEnd(e) {
    return e.ph === "e" ;
}
function isPairableAsyncInstant(e) {
    return e.ph === "n" ;
}
function isAnimationFrameAsyncStart(data) {
    return data.name === "AnimationFrame"  && data.ph === "b" ;
}
function isAnimationFrameAsyncEnd(data) {
    return data.name === "AnimationFrame"  && data.ph === "e" ;
}
function isAnimationFramePresentation(data) {
    return data.name === "AnimationFrame::Presentation" ;
}
function isPipelineReporter(event) {
    return event.name === "PipelineReporter" ;
}
function isSyntheticBased(event) {
    return 'rawSourceEvent' in event;
}
function isJSSample(event) {
    return event.name === "JSSample" ;
}
function isSyntheticInteraction(event) {
    return Boolean('interactionId' in event && event.args?.data && 'beginEvent' in event.args.data && 'endEvent' in event.args.data);
}
function isDrawFrame(event) {
    return event.name === "DrawFrame"  && event.ph === "I" ;
}
function isBeginFrame(event) {
    return Boolean(event.name === "BeginFrame"  && event.args && 'frameSeqId' in event.args);
}
function isDroppedFrame(event) {
    return Boolean(event.name === "DroppedFrame"  && event.args && 'frameSeqId' in event.args);
}
function isRequestMainThreadFrame(event) {
    return event.name === "RequestMainThreadFrame" ;
}
function isBeginMainThreadFrame(event) {
    return event.name === "BeginMainThreadFrame" ;
}
function isNeedsBeginFrameChanged(event) {
    return event.name === "NeedsBeginFrameChanged" ;
}
function isCommit(event) {
    return Boolean(event.name === "Commit"  && event.args && 'frameSeqId' in event.args);
}
function isRasterTask(event) {
    return event.name === "RasterTask" ;
}
function isCompositeLayers(event) {
    return event.name === "CompositeLayers" ;
}
function isActivateLayerTree(event) {
    return event.name === "ActivateLayerTree" ;
}
function isInvalidationTracking(event) {
    return isScheduleStyleInvalidationTracking(event) || isStyleRecalcInvalidationTracking(event) ||
        isStyleInvalidatorInvalidationTracking(event) || isLayoutInvalidationTracking(event);
}
function isDrawLazyPixelRef(event) {
    return event.name === "Draw LazyPixelRef" ;
}
function isDecodeLazyPixelRef(event) {
    return event.name === "Decode LazyPixelRef" ;
}
function isDecodeImage(event) {
    return event.name === "Decode Image" ;
}
var SelectorTimingsKey;
(function (SelectorTimingsKey) {
    SelectorTimingsKey["Elapsed"] = "elapsed (us)";
    SelectorTimingsKey["RejectPercentage"] = "reject_percentage";
    SelectorTimingsKey["FastRejectCount"] = "fast_reject_count";
    SelectorTimingsKey["MatchAttempts"] = "match_attempts";
    SelectorTimingsKey["MatchCount"] = "match_count";
    SelectorTimingsKey["Selector"] = "selector";
    SelectorTimingsKey["StyleSheetId"] = "style_sheet_id";
    SelectorTimingsKey["InvalidationCount"] = "invalidation_count";
})(SelectorTimingsKey || (SelectorTimingsKey = {}));
function isSelectorStats(event) {
    return event.name === "SelectorStats" ;
}
function isRecalcStyle(event) {
    return event.name === "UpdateLayoutTree" ;
}
function isLayout(event) {
    return event.name === "Layout"  && Boolean(event.args && 'beginData' in event.args);
}
function isInvalidateLayout(event) {
    return event.name === "InvalidateLayout" ;
}
function isDebuggerAsyncTaskScheduled(event) {
    return event.name === "v8::Debugger::AsyncTaskScheduled" ;
}
function isDebuggerAsyncTaskRun(event) {
    return event.name === "v8::Debugger::AsyncTaskRun" ;
}
function ProfileID(value) {
    return value;
}
function CallFrameID(value) {
    return value;
}
function SampleIndex(value) {
    return value;
}
function ProcessID(value) {
    return value;
}
function ThreadID(value) {
    return value;
}
function WorkerId(value) {
    return value;
}
function isComplete(event) {
    return event.ph === "X" ;
}
function isBegin(event) {
    return event.ph === "B" ;
}
function isEnd(event) {
    return event.ph === "E" ;
}
function isDispatch(event) {
    return event.name === 'EventDispatch' && event.ph === "X" ;
}
function isInstant(event) {
    return event.ph === "I" ;
}
function isRendererEvent(event) {
    return isInstant(event) || isComplete(event);
}
function isFireIdleCallback(event) {
    return event.name === 'FireIdleCallback' && event.ph === "X" ;
}
function isSchedulePostMessage(event) {
    return event.name === "SchedulePostMessage" ;
}
function isHandlePostMessage(event) {
    return event.name === "HandlePostMessage"  && event.ph === "X" ;
}
function isUpdateCounters(event) {
    return event.name === 'UpdateCounters';
}
function isDOMStats(event) {
    return event.name === 'DOMStats';
}
function isThreadName(event) {
    return event.name === "thread_name" ;
}
function isProcessName(event) {
    return event.name === 'process_name';
}
function isTracingStartedInBrowser(event) {
    return event.name === "TracingStartedInBrowser" ;
}
function isFrameCommittedInBrowser(event) {
    return event.name === 'FrameCommittedInBrowser';
}
function isCommitLoad(event) {
    return event.name === 'CommitLoad';
}
function isAnimation(event) {
    return event.name === 'Animation' && event.cat.includes('devtools.timeline');
}
function isSyntheticAnimation(event) {
    if (event.name !== 'Animation' || !event.cat.includes('devtools.timeline')) {
        return false;
    }
    const data = event.args?.data;
    if (!data) {
        return false;
    }
    return 'beginEvent' in data && 'endEvent' in data;
}
function isLayoutShift(event) {
    return event.name === "LayoutShift" ;
}
function isLayoutInvalidationTracking(event) {
    return event.name === "LayoutInvalidationTracking" ;
}
function isFirstContentfulPaint(event) {
    return event.name === "firstContentfulPaint" ;
}
function isAnyLargestContentfulPaintCandidate(event) {
    return event.name === "largestContentfulPaint::Candidate"  || event.name === "largestContentfulPaint::CandidateForSoftNavigation" ;
}
function isSoftLargestContentfulPaintCandidate(event) {
    return event.name === "largestContentfulPaint::CandidateForSoftNavigation" ;
}
function isLargestImagePaintCandidate(event) {
    return event.name === 'LargestImagePaint::Candidate';
}
function isLargestTextPaintCandidate(event) {
    return event.name === 'LargestTextPaint::Candidate';
}
function isMarkLoad(event) {
    return event.name === "MarkLoad" ;
}
function isFirstPaint(event) {
    return event.name === "firstPaint" ;
}
function isMarkDOMContent(event) {
    return event.name === "MarkDOMContent" ;
}
function isInteractiveTime(event) {
    return event.name === 'InteractiveTime';
}
function isEventTiming(event) {
    return event.name === "EventTiming" ;
}
function isEventTimingEnd(event) {
    return isEventTiming(event) && event.ph === "e" ;
}
function isEventTimingStart(event) {
    return isEventTiming(event) && event.ph === "b" ;
}
function isGPUTask(event) {
    return event.name === 'GPUTask';
}
function isProfile(event) {
    return event.name === "Profile" ;
}
function isSyntheticCpuProfile(event) {
    return event.name === "CpuProfile"  && event.ph === "X" ;
}
function isProfileChunk(event) {
    return event.name === "ProfileChunk" ;
}
function isResourceChangePriority(event) {
    return event.name === 'ResourceChangePriority';
}
function isResourceSendRequest(event) {
    return event.name === 'ResourceSendRequest';
}
function isResourceReceiveResponse(event) {
    return event.name === 'ResourceReceiveResponse';
}
function isResourceMarkAsCached(event) {
    return event.name === 'ResourceMarkAsCached';
}
function isResourceFinish(event) {
    return event.name === 'ResourceFinish';
}
function isResourceWillSendRequest(event) {
    return event.name === 'ResourceWillSendRequest';
}
function isResourceReceivedData(event) {
    return event.name === 'ResourceReceivedData';
}
function isReceivedDataEvent(event) {
    return event.name === 'ResourceReceivedData' || event.name === 'ResourceFinish' ||
        event.name === 'ResourceReceiveResponse';
}
function isSyntheticNetworkRequest(event) {
    return event.name === "SyntheticNetworkRequest" ;
}
function isSyntheticWebSocketConnection(event) {
    return event.name === 'SyntheticWebSocketConnection';
}
function isNetworkTrackEntry(event) {
    return isSyntheticNetworkRequest(event) || isSyntheticWebSocketConnection(event) || isWebSocketTraceEvent(event);
}
function isPrePaint(event) {
    return event.name === 'PrePaint';
}
function isNavigationStart(event) {
    return event.name === "navigationStart"  && event.args?.data?.documentLoaderURL !== '';
}
function isDidCommitSameDocumentNavigation(event) {
    return event.name === 'RenderFrameHostImpl::DidCommitSameDocumentNavigation' && event.ph === "X" ;
}
function isMainFrameViewport(event) {
    return event.name === 'PaintTimingVisualizer::Viewport';
}
function isSyntheticUserTiming(event) {
    if (event.cat !== 'blink.user_timing') {
        return false;
    }
    const data = event.args?.data;
    if (!data) {
        return false;
    }
    return 'beginEvent' in data && 'endEvent' in data;
}
function isSyntheticConsoleTiming(event) {
    if (event.cat !== 'blink.console') {
        return false;
    }
    const data = event.args?.data;
    if (!data) {
        return false;
    }
    return 'beginEvent' in data && 'endEvent' in data;
}
function isUserTiming(event) {
    return event.cat === 'blink.user_timing';
}
function isDomLoading(event) {
    return event.name === "domLoading" ;
}
function isBeginRemoteFontLoad(event) {
    return event.name === "BeginRemoteFontLoad" ;
}
function isRemoteFontLoaded(event) {
    return event.name === "RemoteFontLoaded" ;
}
function isPerformanceMeasure(event) {
    return isUserTiming(event) && isPhaseAsync(event.ph);
}
function isPerformanceMeasureBegin(event) {
    return isPerformanceMeasure(event) && event.ph === "b" ;
}
function isPerformanceMark(event) {
    return isUserTiming(event) && (event.ph === "R"  || event.ph === "I" );
}
function isConsoleTime(event) {
    return event.cat === 'blink.console' && isPhaseAsync(event.ph);
}
function isConsoleTimeStamp(event) {
    return event.ph === "I"  && event.name === "TimeStamp" ;
}
function isUserTimingMeasure(event) {
    return event.name === "UserTiming::Measure" ;
}
function isParseHTML(event) {
    return event.name === 'ParseHTML';
}
function isSyntheticLayoutShift(event) {
    return event.name === "SyntheticLayoutShift" ;
}
function isSyntheticLayoutShiftCluster(event) {
    return event.name === "SyntheticLayoutShiftCluster" ;
}
function isProfileCall(event) {
    return 'callFrame' in event;
}
function isPaint(event) {
    return event.name === "Paint" ;
}
function isPaintImage(event) {
    return event.name === "PaintImage"  && event.ph === "X" ;
}
function isScrollLayer(event) {
    return event.name === "ScrollLayer"  && event.ph === "X" ;
}
function isSetLayerId(event) {
    return event.name === "SetLayerTreeId" ;
}
function isUpdateLayer(event) {
    return event.name === "UpdateLayer" ;
}
function isDisplayListItemListSnapshot(event) {
    return event.name === "cc::DisplayItemList" ;
}
function isLayerTreeHostImplSnapshot(event) {
    return event.name === "cc::LayerTreeHostImpl" ;
}
function isFireAnimationFrame(event) {
    return event.name === "FireAnimationFrame"  && event.ph === "X" ;
}
function isTimerInstall(event) {
    return event.name === "TimerInstall" ;
}
function isTimerFire(event) {
    return event.name === "TimerFire"  && event.ph === "X" ;
}
function isRequestIdleCallback(event) {
    return event.name === "RequestIdleCallback" ;
}
function isWebSocketCreate(event) {
    return event.name === "WebSocketCreate" ;
}
function isWebSocketInfo(event) {
    return event.name === "WebSocketSendHandshakeRequest"  ||
        event.name === "WebSocketReceiveHandshakeResponse"  || event.name === "WebSocketDestroy" ;
}
function isWebSocketTransfer(event) {
    return event.name === "WebSocketSend"  || event.name === "WebSocketReceive" ;
}
function isWebSocketSendHandshakeRequest(event) {
    return event.name === "WebSocketSendHandshakeRequest" ;
}
function isWebSocketReceiveHandshakeResponse(event) {
    return event.name === "WebSocketReceiveHandshakeResponse" ;
}
function isWebSocketDestroy(event) {
    return event.name === "WebSocketDestroy" ;
}
function isWebSocketTraceEvent(event) {
    return isWebSocketCreate(event) || isWebSocketInfo(event) || isWebSocketTransfer(event);
}
function isWebSocketEvent(event) {
    return isWebSocketTraceEvent(event) || isSyntheticWebSocketConnection(event);
}
function isV8Compile(event) {
    return event.name === "v8.compile"  && event.ph === "X" ;
}
function isFunctionCall(event) {
    return event.name === "FunctionCall"  && event.ph === "X" ;
}
function isSchedulePostTaskCallback(event) {
    return event.name === "SchedulePostTaskCallback" ;
}
function isRunPostTaskCallback(event) {
    return event.name === "RunPostTaskCallback"  && event.ph === "X" ;
}
function isAbortPostTaskCallback(event) {
    return event.name === "AbortPostTaskCallback"  && event.ph === "X" ;
}
function isJSInvocationEvent(event) {
    switch (event.name) {
        case "RunMicrotasks" :
        case "FunctionCall" :
        case "EvaluateScript" :
        case "v8.evaluateModule" :
        case "EventDispatch" :
        case "V8.Execute" :
        case "V8Console::runTask" :
            return true;
    }
    if (event.name.startsWith('v8') || event.name.startsWith('V8')) {
        return true;
    }
    if (isConsoleRunTask(event)) {
        return true;
    }
    return false;
}
function isConsoleRunTask(event) {
    return event.name === "V8Console::runTask" ;
}
function isFlowPhaseEvent(event) {
    return event.ph === "s"  || event.ph === "t"  || event.ph === "f" ;
}
function isParseAuthorStyleSheetEvent(event) {
    return event.name === "ParseAuthorStyleSheet"  && event.ph === "X" ;
}
const Categories = {
    Console: 'blink.console',
    UserTiming: 'blink.user_timing',
    Loading: 'loading',
};
function isLegacyTimelineFrame(data) {
    return 'idle' in data && typeof data.idle === 'boolean';
}
function isRundownScriptCompiled(event) {
    return event.cat === 'disabled-by-default-devtools.target-rundown';
}
function isRundownScript(event) {
    return event.cat === 'disabled-by-default-devtools.v8-source-rundown' && event.name === 'ScriptCatchup';
}
function isRundownScriptSource(event) {
    return event.cat === 'disabled-by-default-devtools.v8-source-rundown-sources' && event.name === 'ScriptCatchup';
}
function isRundownScriptSourceLarge(event) {
    return event.cat === 'disabled-by-default-devtools.v8-source-rundown-sources' && event.name === 'LargeScriptCatchup';
}
function isAnyScriptSourceEvent(event) {
    return event.cat === 'disabled-by-default-devtools.v8-source-rundown-sources';
}
function isPreloadRenderBlockingStatusChangeEvent(event) {
    return event.name === "PreloadRenderBlockingStatusChange" ;
}

var TraceEvents = /*#__PURE__*/Object.freeze({
	__proto__: null,
	CallFrameID: CallFrameID,
	Categories: Categories,
	MarkerName: MarkerName,
	NO_NAVIGATION: NO_NAVIGATION,
	ProcessID: ProcessID,
	ProfileID: ProfileID,
	SampleIndex: SampleIndex,
	get SelectorTimingsKey () { return SelectorTimingsKey; },
	ThreadID: ThreadID,
	VALID_PROFILE_SOURCES: VALID_PROFILE_SOURCES,
	WorkerId: WorkerId,
	eventIsPageLoadEvent: eventIsPageLoadEvent,
	isAbortPostTaskCallback: isAbortPostTaskCallback,
	isActivateLayerTree: isActivateLayerTree,
	isAnimation: isAnimation,
	isAnimationFrameAsyncEnd: isAnimationFrameAsyncEnd,
	isAnimationFrameAsyncStart: isAnimationFrameAsyncStart,
	isAnimationFramePresentation: isAnimationFramePresentation,
	isAnyLargestContentfulPaintCandidate: isAnyLargestContentfulPaintCandidate,
	isAnyScriptSourceEvent: isAnyScriptSourceEvent,
	isAuctionWorkletDoneWithProcess: isAuctionWorkletDoneWithProcess,
	isAuctionWorkletRunningInProcess: isAuctionWorkletRunningInProcess,
	isBegin: isBegin,
	isBeginCommitCompositorFrame: isBeginCommitCompositorFrame,
	isBeginFrame: isBeginFrame,
	isBeginMainThreadFrame: isBeginMainThreadFrame,
	isBeginRemoteFontLoad: isBeginRemoteFontLoad,
	isCommit: isCommit,
	isCommitLoad: isCommitLoad,
	isComplete: isComplete,
	isCompositeLayers: isCompositeLayers,
	isConsoleRunTask: isConsoleRunTask,
	isConsoleTime: isConsoleTime,
	isConsoleTimeStamp: isConsoleTimeStamp,
	isDOMStats: isDOMStats,
	isDebuggerAsyncTaskRun: isDebuggerAsyncTaskRun,
	isDebuggerAsyncTaskScheduled: isDebuggerAsyncTaskScheduled,
	isDecodeImage: isDecodeImage,
	isDecodeLazyPixelRef: isDecodeLazyPixelRef,
	isDidCommitSameDocumentNavigation: isDidCommitSameDocumentNavigation,
	isDispatch: isDispatch,
	isDisplayListItemListSnapshot: isDisplayListItemListSnapshot,
	isDomLoading: isDomLoading,
	isDrawFrame: isDrawFrame,
	isDrawLazyPixelRef: isDrawLazyPixelRef,
	isDroppedFrame: isDroppedFrame,
	isEnd: isEnd,
	isEventTiming: isEventTiming,
	isEventTimingEnd: isEventTimingEnd,
	isEventTimingStart: isEventTimingStart,
	isFireAnimationFrame: isFireAnimationFrame,
	isFireIdleCallback: isFireIdleCallback,
	isFirstContentfulPaint: isFirstContentfulPaint,
	isFirstPaint: isFirstPaint,
	isFlowPhase: isFlowPhase,
	isFlowPhaseEvent: isFlowPhaseEvent,
	isFrameCommittedInBrowser: isFrameCommittedInBrowser,
	isFunctionCall: isFunctionCall,
	isGPUTask: isGPUTask,
	isHandlePostMessage: isHandlePostMessage,
	isInstant: isInstant,
	isInteractiveTime: isInteractiveTime,
	isInvalidateLayout: isInvalidateLayout,
	isInvalidationTracking: isInvalidationTracking,
	isJSInvocationEvent: isJSInvocationEvent,
	isJSSample: isJSSample,
	isLargestImagePaintCandidate: isLargestImagePaintCandidate,
	isLargestTextPaintCandidate: isLargestTextPaintCandidate,
	isLayerTreeHostImplSnapshot: isLayerTreeHostImplSnapshot,
	isLayout: isLayout,
	isLayoutImageUnsized: isLayoutImageUnsized,
	isLayoutInvalidationTracking: isLayoutInvalidationTracking,
	isLayoutShift: isLayoutShift,
	isLegacyScreenshot: isLegacyScreenshot,
	isLegacySyntheticScreenshot: isLegacySyntheticScreenshot,
	isLegacyTimelineFrame: isLegacyTimelineFrame,
	isLinkPreconnect: isLinkPreconnect,
	isMainFrameViewport: isMainFrameViewport,
	isMarkDOMContent: isMarkDOMContent,
	isMarkLoad: isMarkLoad,
	isMarkerEvent: isMarkerEvent,
	isNavigationStart: isNavigationStart,
	isNeedsBeginFrameChanged: isNeedsBeginFrameChanged,
	isNestableAsyncPhase: isNestableAsyncPhase,
	isNetworkTrackEntry: isNetworkTrackEntry,
	isPaint: isPaint,
	isPaintImage: isPaintImage,
	isPairableAsyncBegin: isPairableAsyncBegin,
	isPairableAsyncEnd: isPairableAsyncEnd,
	isPairableAsyncInstant: isPairableAsyncInstant,
	isParseAuthorStyleSheetEvent: isParseAuthorStyleSheetEvent,
	isParseHTML: isParseHTML,
	isParseMetaViewport: isParseMetaViewport,
	isPerformanceMark: isPerformanceMark,
	isPerformanceMeasure: isPerformanceMeasure,
	isPerformanceMeasureBegin: isPerformanceMeasureBegin,
	isPhaseAsync: isPhaseAsync,
	isPipelineReporter: isPipelineReporter,
	isPrePaint: isPrePaint,
	isPreloadRenderBlockingStatusChangeEvent: isPreloadRenderBlockingStatusChangeEvent,
	isProcessName: isProcessName,
	isProfile: isProfile,
	isProfileCall: isProfileCall,
	isProfileChunk: isProfileChunk,
	isRasterTask: isRasterTask,
	isRecalcStyle: isRecalcStyle,
	isReceivedDataEvent: isReceivedDataEvent,
	isRemoteFontLoaded: isRemoteFontLoaded,
	isRenderFrameImplCreateChildFrame: isRenderFrameImplCreateChildFrame,
	isRendererEvent: isRendererEvent,
	isRequestIdleCallback: isRequestIdleCallback,
	isRequestMainThreadFrame: isRequestMainThreadFrame,
	isResourceChangePriority: isResourceChangePriority,
	isResourceFinish: isResourceFinish,
	isResourceMarkAsCached: isResourceMarkAsCached,
	isResourceReceiveResponse: isResourceReceiveResponse,
	isResourceReceivedData: isResourceReceivedData,
	isResourceSendRequest: isResourceSendRequest,
	isResourceWillSendRequest: isResourceWillSendRequest,
	isRunPostTaskCallback: isRunPostTaskCallback,
	isRunTask: isRunTask,
	isRundownScript: isRundownScript,
	isRundownScriptCompiled: isRundownScriptCompiled,
	isRundownScriptSource: isRundownScriptSource,
	isRundownScriptSourceLarge: isRundownScriptSourceLarge,
	isSchedulePostMessage: isSchedulePostMessage,
	isSchedulePostTaskCallback: isSchedulePostTaskCallback,
	isScheduleStyleInvalidationTracking: isScheduleStyleInvalidationTracking,
	isScheduleStyleRecalculation: isScheduleStyleRecalculation,
	isScreenshot: isScreenshot,
	isScrollLayer: isScrollLayer,
	isSelectorStats: isSelectorStats,
	isSetLayerId: isSetLayerId,
	isSoftLargestContentfulPaintCandidate: isSoftLargestContentfulPaintCandidate,
	isSoftNavigationStart: isSoftNavigationStart,
	isStyleInvalidatorInvalidationTracking: isStyleInvalidatorInvalidationTracking,
	isStyleRecalcInvalidationTracking: isStyleRecalcInvalidationTracking,
	isSyntheticAnimation: isSyntheticAnimation,
	isSyntheticBased: isSyntheticBased,
	isSyntheticConsoleTiming: isSyntheticConsoleTiming,
	isSyntheticCpuProfile: isSyntheticCpuProfile,
	isSyntheticInteraction: isSyntheticInteraction,
	isSyntheticLayoutShift: isSyntheticLayoutShift,
	isSyntheticLayoutShiftCluster: isSyntheticLayoutShiftCluster,
	isSyntheticNetworkRequest: isSyntheticNetworkRequest,
	isSyntheticUserTiming: isSyntheticUserTiming,
	isSyntheticWebSocketConnection: isSyntheticWebSocketConnection,
	isThreadName: isThreadName,
	isTimerFire: isTimerFire,
	isTimerInstall: isTimerInstall,
	isTracingSessionIdForWorker: isTracingSessionIdForWorker,
	isTracingStartedInBrowser: isTracingStartedInBrowser,
	isUpdateCounters: isUpdateCounters,
	isUpdateLayer: isUpdateLayer,
	isUserTiming: isUserTiming,
	isUserTimingMeasure: isUserTimingMeasure,
	isV8Compile: isV8Compile,
	isWebSocketCreate: isWebSocketCreate,
	isWebSocketDestroy: isWebSocketDestroy,
	isWebSocketEvent: isWebSocketEvent,
	isWebSocketInfo: isWebSocketInfo,
	isWebSocketReceiveHandshakeResponse: isWebSocketReceiveHandshakeResponse,
	isWebSocketSendHandshakeRequest: isWebSocketSendHandshakeRequest,
	isWebSocketTraceEvent: isWebSocketTraceEvent,
	isWebSocketTransfer: isWebSocketTransfer,
	objectIsCallFrame: objectIsCallFrame,
	objectIsEvent: objectIsEvent
});

// Copyright 2022 The Chromium Authors

var types$3 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Configuration: Configuration,
	Events: TraceEvents,
	Extensions: Extensions$1,
	File: File$1,
	Overlays: Overlays,
	Timing: Timing$1
});

// Copyright 2024 The Chromium Authors
function getEntityForEvent(event, entityMappings) {
    const url = getNonResolvedURL(event);
    if (!url) {
        return;
    }
    return getEntityForUrl(url, entityMappings);
}
function getEntityForUrl(url, entityMappings) {
    const cachedByUrl = entityMappings.entityByUrlCache.get(url);
    if (cachedByUrl) {
        return cachedByUrl;
    }
    const entity = nostatsSubset.getEntity(url) ?? makeUpEntity(entityMappings.createdEntityCache, url);
    if (entity) {
        entityMappings.entityByUrlCache.set(url, entity);
    }
    return entity;
}
function getNonResolvedURL(entry, handlerData) {
    if (isProfileCall(entry)) {
        return entry.callFrame.url;
    }
    if (isSyntheticNetworkRequest(entry)) {
        return entry.args.data.url;
    }
    if (isParseAuthorStyleSheetEvent(entry) && entry.args) {
        return entry.args.data.stylesheetUrl;
    }
    if (entry.args?.data?.stackTrace && entry.args.data.stackTrace.length > 0) {
        return entry.args.data.stackTrace[0].url;
    }
    if (isParseHTML(entry)) {
        return entry.args.beginData.url;
    }
    if (handlerData) {
        if (isDecodeImage(entry)) {
            const paintEvent = handlerData.ImagePainting.paintImageForEvent.get(entry);
            return paintEvent ? getNonResolvedURL(paintEvent, handlerData) : null;
        }
        if (isDrawLazyPixelRef(entry) && entry.args?.LazyPixelRef) {
            const paintEvent = handlerData.ImagePainting.paintImageByDrawLazyPixelRef.get(entry.args.LazyPixelRef);
            return paintEvent ? getNonResolvedURL(paintEvent, handlerData) : null;
        }
    }
    if (entry.args?.data?.url) {
        return entry.args.data.url;
    }
    const requestId = entry.args?.data?.requestId;
    if (handlerData && requestId) {
        const url = handlerData.NetworkRequests.byId.get(requestId)?.args.data.url;
        if (url) {
            return url;
        }
    }
    return null;
}
function makeUpEntity(entityCache, url) {
    if (url.startsWith('chrome-extension:')) {
        return makeUpChromeExtensionEntity(entityCache, url);
    }
    if (!url.startsWith('http')) {
        return;
    }
    const rootDomain = nostatsSubset.getRootDomain(url);
    if (!rootDomain) {
        return;
    }
    if (entityCache.has(rootDomain)) {
        return entityCache.get(rootDomain);
    }
    const unrecognizedEntity = {
        name: rootDomain,
        company: rootDomain,
        category: '',
        categories: [],
        domains: [rootDomain],
        averageExecutionTime: 0,
        totalExecutionTime: 0,
        totalOccurrences: 0,
        isUnrecognized: true,
    };
    entityCache.set(rootDomain, unrecognizedEntity);
    return unrecognizedEntity;
}
function getChromeExtensionOrigin(url) {
    return url.protocol + '//' + url.host;
}
function makeUpChromeExtensionEntity(entityCache, url, extensionName) {
    const parsedUrl = new URL(url);
    const origin = getChromeExtensionOrigin(parsedUrl);
    const host = new URL(origin).host;
    const name = extensionName || host;
    const cachedEntity = entityCache.get(origin);
    if (cachedEntity) {
        return cachedEntity;
    }
    const chromeExtensionEntity = {
        name,
        company: name,
        category: 'Chrome Extension',
        homepage: 'https://chromewebstore.google.com/detail/' + host,
        categories: [],
        domains: [origin],
        averageExecutionTime: 0,
        totalExecutionTime: 0,
        totalOccurrences: 0,
    };
    entityCache.set(origin, chromeExtensionEntity);
    return chromeExtensionEntity;
}
function addEventToEntityMapping(event, entityMappings) {
    if (entityMappings.entityByEvent.has(event)) {
        return;
    }
    const entity = getEntityForEvent(event, entityMappings);
    if (!entity) {
        return;
    }
    const mappedEvents = entityMappings.eventsByEntity.get(entity);
    if (mappedEvents) {
        mappedEvents.push(event);
    }
    else {
        entityMappings.eventsByEntity.set(entity, [event]);
    }
    entityMappings.entityByEvent.set(event, entity);
}
function addNetworkRequestToEntityMapping(networkRequest, entityMappings, requestTraceEvents) {
    const entity = getEntityForEvent(networkRequest, entityMappings);
    if (!entity) {
        return;
    }
    const eventsToMap = [networkRequest, ...Object.values(requestTraceEvents).flat()];
    const mappedEvents = entityMappings.eventsByEntity.get(entity);
    if (mappedEvents) {
        mappedEvents.push(...eventsToMap);
    }
    else {
        entityMappings.eventsByEntity.set(entity, eventsToMap);
    }
    for (const evt of eventsToMap) {
        entityMappings.entityByEvent.set(evt, entity);
    }
}

var helpers$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	addEventToEntityMapping: addEventToEntityMapping,
	addNetworkRequestToEntityMapping: addNetworkRequestToEntityMapping,
	getEntityForEvent: getEntityForEvent,
	getEntityForUrl: getEntityForUrl,
	getNonResolvedURL: getNonResolvedURL,
	makeUpEntity: makeUpEntity
});

// Copyright 2024 The Chromium Authors
let activeManager = null;
class SyntheticEventsManager {
    #syntheticTraces = [];
    #rawTraceEvents = [];
    static activate(manager) {
        activeManager = manager;
    }
    static createAndActivate(rawEvents) {
        const manager = new SyntheticEventsManager(rawEvents);
        SyntheticEventsManager.activate(manager);
        return manager;
    }
    static getActiveManager() {
        if (!activeManager) {
            throw new Error('Attempted to get a SyntheticEventsManager without initializing');
        }
        return activeManager;
    }
    static reset() {
        activeManager = null;
    }
    static registerSyntheticEvent(syntheticEvent) {
        try {
            return SyntheticEventsManager.getActiveManager().#registerSyntheticEvent(syntheticEvent);
        }
        catch {
            return syntheticEvent;
        }
    }
    constructor(rawEvents) {
        this.#rawTraceEvents = rawEvents;
    }
    #registerSyntheticEvent(syntheticEvent) {
        const rawIndex = this.#rawTraceEvents.indexOf(syntheticEvent.rawSourceEvent);
        if (rawIndex < 0) {
            throw new Error('Attempted to register a synthetic event paired to an unknown raw event.');
        }
        const eventAsSynthetic = syntheticEvent;
        this.#syntheticTraces[rawIndex] = eventAsSynthetic;
        return eventAsSynthetic;
    }
    syntheticEventForRawEventIndex(rawEventIndex) {
        const syntheticEvent = this.#syntheticTraces.at(rawEventIndex);
        if (!syntheticEvent) {
            throw new Error(`Attempted to get a synthetic event from an unknown raw event index: ${rawEventIndex}`);
        }
        return syntheticEvent;
    }
    getSyntheticTraces() {
        return this.#syntheticTraces;
    }
    getRawTraceEvents() {
        return this.#rawTraceEvents;
    }
}

var SyntheticEvents = /*#__PURE__*/Object.freeze({
	__proto__: null,
	SyntheticEventsManager: SyntheticEventsManager
});

// Copyright 2022 The Chromium Authors
const milliToMicro = (value) => Micro(value * 1000);
const secondsToMilli = (value) => Milli(value * 1000);
const secondsToMicro = (value) => milliToMicro(secondsToMilli(value));
const microToMilli = (value) => Milli(value / 1000);
const microToSeconds = (value) => Seconds(value / 1000 / 1000);
function timeStampForEventAdjustedByClosestNavigation(event, traceBounds, navigationsByNavigationId, softNavigationsById, navigationsByFrameId) {
    let eventTimeStamp = event.ts - traceBounds.min;
    if (event.name === "largestContentfulPaint::CandidateForSoftNavigation"  &&
        event.args?.data?.performanceTimelineNavigationId) {
        const navigationForEvent = softNavigationsById.get(event.args.data.performanceTimelineNavigationId);
        if (navigationForEvent) {
            eventTimeStamp = event.ts - navigationForEvent.ts;
        }
    }
    else if (event.args?.data?.navigationId) {
        const navigationForEvent = navigationsByNavigationId.get(event.args.data.navigationId);
        if (navigationForEvent) {
            eventTimeStamp = event.ts - navigationForEvent.ts;
        }
    }
    else if (event.args?.data?.frame) {
        const navigationForEvent = getNavigationForTraceEvent(event, event.args.data.frame, navigationsByFrameId);
        if (navigationForEvent) {
            eventTimeStamp = event.ts - navigationForEvent.ts;
        }
    }
    return Micro(eventTimeStamp);
}
function expandWindowByPercentOrToOneMillisecond(annotationWindow, maxTraceWindow, percentage) {
    let newMin = annotationWindow.min - annotationWindow.range * (percentage / 100) / 2;
    let newMax = annotationWindow.max + annotationWindow.range * (percentage / 100) / 2;
    if (newMax - newMin < 1_000) {
        const rangeMiddle = (annotationWindow.min + annotationWindow.max) / 2;
        newMin = rangeMiddle - 500;
        newMax = rangeMiddle + 500;
    }
    newMin = Math.max(newMin, maxTraceWindow.min);
    newMax = Math.min(newMax, maxTraceWindow.max);
    const expandedWindow = {
        min: Micro(newMin),
        max: Micro(newMax),
        range: Micro(newMax - newMin),
    };
    return expandedWindow;
}
function eventTimingsMicroSeconds(event) {
    return {
        startTime: event.ts,
        endTime: (event.ts + (event.dur ?? 0)),
        duration: (event.dur || 0),
    };
}
function eventTimingsMilliSeconds(event) {
    return {
        startTime: (event.ts / 1000),
        endTime: (event.ts + (event.dur ?? 0)) / 1000,
        duration: (event.dur || 0) / 1000,
    };
}
function traceWindowMilliSeconds(bounds) {
    return {
        min: microToMilli(bounds.min),
        max: microToMilli(bounds.max),
        range: microToMilli(bounds.range),
    };
}
function traceWindowMicroSecondsToMilliSeconds(bounds) {
    return {
        min: microToMilli(bounds.min),
        max: microToMilli(bounds.max),
        range: microToMilli(bounds.range),
    };
}
function traceWindowFromMilliSeconds(min, max) {
    const traceWindow = {
        min: milliToMicro(min),
        max: milliToMicro(max),
        range: Micro(milliToMicro(max) - milliToMicro(min)),
    };
    return traceWindow;
}
function traceWindowFromMicroSeconds(min, max) {
    const traceWindow = {
        min,
        max,
        range: (max - min),
    };
    return traceWindow;
}
function traceWindowFromEvent(event) {
    return {
        min: event.ts,
        max: event.ts + (event.dur ?? 0),
        range: event.dur ?? 0,
    };
}
function traceWindowFromOverlay(overlay) {
    switch (overlay.type) {
        case 'ENTRY_LABEL':
        case 'ENTRY_OUTLINE':
        case 'ENTRY_SELECTED': {
            return traceWindowFromEvent(overlay.entry);
        }
        case 'TIMESPAN_BREAKDOWN': {
            const windows = overlay.sections.map(s => s.bounds);
            if (overlay.entry) {
                windows.push(traceWindowFromEvent(overlay.entry));
            }
            return combineTraceWindowsMicro(windows);
        }
        case 'CANDY_STRIPED_TIME_RANGE':
        case 'TIME_RANGE': {
            return structuredClone(overlay.bounds);
        }
        case 'ENTRIES_LINK': {
            const from = traceWindowFromEvent(overlay.entryFrom);
            if (!overlay.entryTo) {
                return from;
            }
            const to = traceWindowFromEvent(overlay.entryTo);
            return combineTraceWindowsMicro([from, to]);
        }
        case 'TIMESTAMP_MARKER':
            return traceWindowFromMicroSeconds(overlay.timestamp, overlay.timestamp);
        case 'TIMINGS_MARKER':
            return traceWindowFromMicroSeconds(overlay.adjustedTimestamp, overlay.adjustedTimestamp);
        case 'BOTTOM_INFO_BAR':
            return null;
        default:
            assertNever(overlay, `Unexpected overlay ${overlay}`);
    }
}
function combineTraceWindowsMicro(windows) {
    if (!windows.length) {
        return null;
    }
    const result = structuredClone(windows[0]);
    for (const bounds of windows.slice(1)) {
        result.min = Math.min(result.min, bounds.min);
        result.max = Math.max(result.max, bounds.max);
    }
    result.range = result.max - result.min;
    return result;
}
function boundsIncludeTimeRange(data) {
    const { min: visibleMin, max: visibleMax } = data.bounds;
    const { min: rangeMin, max: rangeMax } = data.timeRange;
    return visibleMin <= rangeMax && visibleMax >= rangeMin;
}
function eventIsInBounds(event, bounds) {
    const startTime = event.ts;
    return startTime <= bounds.max && bounds.min < (startTime + (event.dur ?? 0));
}
function timestampIsInBounds(bounds, timestamp) {
    return timestamp >= bounds.min && timestamp <= bounds.max;
}
function windowFitsInsideBounds(data) {
    return data.window.min >= data.bounds.min && data.window.max <= data.bounds.max;
}
function windowsEqual(w1, w2) {
    return w1.min === w2.min && w1.max === w2.max;
}

var Timing = /*#__PURE__*/Object.freeze({
	__proto__: null,
	boundsIncludeTimeRange: boundsIncludeTimeRange,
	combineTraceWindowsMicro: combineTraceWindowsMicro,
	eventIsInBounds: eventIsInBounds,
	eventTimingsMicroSeconds: eventTimingsMicroSeconds,
	eventTimingsMilliSeconds: eventTimingsMilliSeconds,
	expandWindowByPercentOrToOneMillisecond: expandWindowByPercentOrToOneMillisecond,
	microToMilli: microToMilli,
	microToSeconds: microToSeconds,
	milliToMicro: milliToMicro,
	secondsToMicro: secondsToMicro,
	secondsToMilli: secondsToMilli,
	timeStampForEventAdjustedByClosestNavigation: timeStampForEventAdjustedByClosestNavigation,
	timestampIsInBounds: timestampIsInBounds,
	traceWindowFromEvent: traceWindowFromEvent,
	traceWindowFromMicroSeconds: traceWindowFromMicroSeconds,
	traceWindowFromMilliSeconds: traceWindowFromMilliSeconds,
	traceWindowFromOverlay: traceWindowFromOverlay,
	traceWindowMicroSecondsToMilliSeconds: traceWindowMicroSecondsToMilliSeconds,
	traceWindowMilliSeconds: traceWindowMilliSeconds,
	windowFitsInsideBounds: windowFitsInsideBounds,
	windowsEqual: windowsEqual
});

// Copyright 2022 The Chromium Authors
function stackTraceInEvent(event) {
    if (event.args?.data?.stackTrace) {
        return event.args.data.stackTrace;
    }
    if (event.args?.stackTrace) {
        return event.args.stackTrace;
    }
    if (isRecalcStyle(event)) {
        return event.args.beginData?.stackTrace || null;
    }
    if (isLayout(event)) {
        return event.args.beginData.stackTrace ?? null;
    }
    if (isFunctionCall(event)) {
        const data = event.args.data;
        if (!data) {
            return null;
        }
        const { columnNumber, lineNumber, url, scriptId, functionName } = data;
        if (lineNumber === undefined || functionName === undefined || columnNumber === undefined ||
            scriptId === undefined || url === undefined) {
            return null;
        }
        return [{ columnNumber, lineNumber, url, scriptId, functionName }];
    }
    if (isProfileCall(event)) {
        const callFrame = event.callFrame;
        if (!callFrame) {
            return null;
        }
        const { columnNumber, lineNumber, url, scriptId, functionName } = callFrame;
        if (lineNumber === undefined || functionName === undefined || columnNumber === undefined ||
            scriptId === undefined || url === undefined) {
            return null;
        }
        return [{ columnNumber, lineNumber, url, scriptId, functionName }];
    }
    return null;
}
function extractOriginFromTrace(firstNavigationURL) {
    const url = ParsedURL.fromString(firstNavigationURL);
    if (url) {
        if (url.host.startsWith('www.')) {
            return url.host.slice(4);
        }
        return url.host;
    }
    return null;
}
function addEventToProcessThread(event, eventsInProcessThread) {
    const { tid, pid } = event;
    let eventsInThread = eventsInProcessThread.get(pid);
    if (!eventsInThread) {
        eventsInThread = new Map();
    }
    let events = eventsInThread.get(tid);
    if (!events) {
        events = [];
    }
    events.push(event);
    eventsInThread.set(event.tid, events);
    eventsInProcessThread.set(event.pid, eventsInThread);
}
function compareBeginAndEnd(aBeginTime, bBeginTime, aEndTime, bEndTime) {
    if (aBeginTime < bBeginTime) {
        return -1;
    }
    if (aBeginTime > bBeginTime) {
        return 1;
    }
    if (aEndTime > bEndTime) {
        return -1;
    }
    if (aEndTime < bEndTime) {
        return 1;
    }
    return 0;
}
function eventTimeComparator(a, b) {
    const aBeginTime = a.ts;
    const bBeginTime = b.ts;
    const aDuration = a.dur ?? 0;
    const bDuration = b.dur ?? 0;
    const aEndTime = aBeginTime + aDuration;
    const bEndTime = bBeginTime + bDuration;
    const timeDifference = compareBeginAndEnd(aBeginTime, bBeginTime, aEndTime, bEndTime);
    if (timeDifference) {
        return timeDifference;
    }
    if (isProfileCall(a) && !isProfileCall(b)) {
        return -1;
    }
    if (isProfileCall(b) && !isProfileCall(a)) {
        return 1;
    }
    return 0;
}
function sortTraceEventsInPlace(events) {
    events.sort(eventTimeComparator);
}
function mergeEventsInOrder(eventsArray1, eventsArray2) {
    const result = [];
    let i = 0;
    let j = 0;
    while (i < eventsArray1.length && j < eventsArray2.length) {
        const event1 = eventsArray1[i];
        const event2 = eventsArray2[j];
        const compareValue = eventTimeComparator(event1, event2);
        if (compareValue <= 0) {
            result.push(event1);
            i++;
        }
        if (compareValue === 1) {
            result.push(event2);
            j++;
        }
    }
    while (i < eventsArray1.length) {
        result.push(eventsArray1[i++]);
    }
    while (j < eventsArray2.length) {
        result.push(eventsArray2[j++]);
    }
    return result;
}
function parseDevtoolsDetails(timingDetail, key) {
    try {
        const detailObj = JSON.parse(timingDetail);
        if (!(key in detailObj)) {
            return null;
        }
        if (!isValidExtensionPayload(detailObj[key])) {
            return null;
        }
        return detailObj[key];
    }
    catch {
        return null;
    }
}
function getNavigationForTraceEvent(event, eventFrameId, navigationsByFrameId) {
    const navigations = navigationsByFrameId.get(eventFrameId);
    if (!navigations || eventFrameId === '') {
        return null;
    }
    const eventNavigationIndex = nearestIndexFromEnd(navigations, navigation => navigation.ts <= event.ts);
    if (eventNavigationIndex === null) {
        return null;
    }
    return navigations[eventNavigationIndex];
}
function extractId(event) {
    return event.id ?? event.id2?.global ?? event.id2?.local;
}
function activeURLForFrameAtTime(frameId, time, rendererProcessesByFrame) {
    const processData = rendererProcessesByFrame.get(frameId);
    if (!processData) {
        return null;
    }
    for (const processes of processData.values()) {
        for (const processInfo of processes) {
            if (processInfo.window.min > time || processInfo.window.max < time) {
                continue;
            }
            return processInfo.frame.url;
        }
    }
    return null;
}
function makeProfileCall(node, profileId, sampleIndex, ts, pid, tid) {
    return {
        cat: '',
        name: 'ProfileCall',
        nodeId: node.id,
        args: {},
        ph: "X" ,
        pid,
        tid,
        ts,
        dur: Micro(0),
        callFrame: node.callFrame,
        sampleIndex,
        profileId,
    };
}
function matchEvents(unpairedEvents) {
    sortTraceEventsInPlace(unpairedEvents);
    const matches = [];
    const beginEventsById = new Map();
    const instantEventsById = new Map();
    for (const event of unpairedEvents) {
        const id = getSyntheticId(event);
        if (id === undefined) {
            continue;
        }
        if (isPairableAsyncBegin(event)) {
            const existingEvents = beginEventsById.get(id) ?? [];
            existingEvents.push(event);
            beginEventsById.set(id, existingEvents);
        }
        else if (isPairableAsyncInstant(event)) {
            const existingEvents = instantEventsById.get(id) ?? [];
            existingEvents.push(event);
            instantEventsById.set(id, existingEvents);
        }
        else if (isPairableAsyncEnd(event)) {
            const beginEventsWithMatchingId = beginEventsById.get(id) ?? [];
            const beginEvent = beginEventsWithMatchingId.pop();
            if (!beginEvent) {
                continue;
            }
            const instantEventsWithMatchingId = instantEventsById.get(id) ?? [];
            const instantEventsForThisGroup = [];
            while (instantEventsWithMatchingId.length > 0) {
                if (instantEventsWithMatchingId[0].ts >= beginEvent.ts) {
                    const event = instantEventsWithMatchingId.pop();
                    if (event) {
                        instantEventsForThisGroup.push(event);
                    }
                }
                else {
                    break;
                }
            }
            const matchingGroup = {
                begin: beginEvent,
                end: event,
                instant: instantEventsForThisGroup,
                syntheticId: id,
            };
            matches.push(matchingGroup);
        }
    }
    for (const [id, beginEvents] of beginEventsById) {
        const beginEvent = beginEvents.pop();
        if (!beginEvent) {
            continue;
        }
        const matchingInstantEvents = instantEventsById.get(id);
        if (matchingInstantEvents?.length) {
            matches.push({
                syntheticId: id,
                begin: beginEvent,
                end: null,
                instant: matchingInstantEvents,
            });
        }
    }
    return matches;
}
function getSyntheticId(event) {
    const id = extractId(event);
    return id && `${event.cat}:${id}:${event.name}`;
}
function createSortedSyntheticEvents(matchedPairs) {
    const syntheticEvents = [];
    for (const eventsTriplet of matchedPairs) {
        const id = eventsTriplet.syntheticId;
        const beginEvent = eventsTriplet.begin;
        const endEvent = eventsTriplet.end;
        const instantEvents = eventsTriplet.instant;
        if (!beginEvent || !(endEvent || instantEvents)) {
            continue;
        }
        const triplet = { beginEvent, endEvent, instantEvents };
        function eventsArePairable(data) {
            const instantEventsMatch = data.instantEvents ? data.instantEvents.some(e => id === getSyntheticId(e)) : false;
            const endEventMatch = data.endEvent ? id === getSyntheticId(data.endEvent) : false;
            return Boolean(id) && (instantEventsMatch || endEventMatch);
        }
        if (!eventsArePairable(triplet)) {
            continue;
        }
        const targetEvent = endEvent || beginEvent;
        const event = SyntheticEventsManager.registerSyntheticEvent({
            rawSourceEvent: triplet.beginEvent,
            cat: targetEvent.cat,
            ph: targetEvent.ph,
            pid: targetEvent.pid,
            tid: targetEvent.tid,
            id,
            name: beginEvent.name,
            dur: Micro(targetEvent.ts - beginEvent.ts),
            ts: beginEvent.ts,
            args: {
                data: triplet,
            },
        });
        if (event.dur < 0) {
            continue;
        }
        syntheticEvents.push(event);
    }
    sortTraceEventsInPlace(syntheticEvents);
    return syntheticEvents;
}
function createMatchedSortedSyntheticEvents(unpairedAsyncEvents) {
    const matchedPairs = matchEvents(unpairedAsyncEvents);
    const syntheticEvents = createSortedSyntheticEvents(matchedPairs);
    return syntheticEvents;
}
function getZeroIndexedLineAndColumnForEvent(event) {
    const numbers = getRawLineAndColumnNumbersForEvent(event);
    const { lineNumber, columnNumber } = numbers;
    switch (event.name) {
        case "FunctionCall" :
        case "EvaluateScript" :
        case "v8.compile" :
        case "v8.produceCache" : {
            return {
                lineNumber: typeof lineNumber === 'number' ? lineNumber - 1 : undefined,
                columnNumber: typeof columnNumber === 'number' ? columnNumber - 1 : undefined,
            };
        }
        case "ProfileCall" : {
            const callFrame = event.callFrame;
            return {
                lineNumber: typeof lineNumber === 'number' ? callFrame.lineNumber - 1 : undefined,
                columnNumber: typeof columnNumber === 'number' ? callFrame.columnNumber - 1 : undefined,
            };
        }
        default: {
            return numbers;
        }
    }
}
function getZeroIndexedStackTraceInEventPayload(event) {
    const stack = stackTraceInEvent(event);
    if (!stack) {
        return null;
    }
    switch (event.name) {
        case "ScheduleStyleRecalculation" :
        case "InvalidateLayout" :
        case "FunctionCall" :
        case "Layout" :
        case "UpdateLayoutTree" : {
            return stack.map(makeZeroBasedCallFrame);
        }
        default: {
            if (isUserTiming(event) || isSyntheticExtensionEntry(event)) {
                return stack.map(makeZeroBasedCallFrame);
            }
            return stack;
        }
    }
}
function getStackTraceTopCallFrameInEventPayload(event) {
    const stack = stackTraceInEvent(event);
    if (!stack || stack.length === 0) {
        return null;
    }
    switch (event.name) {
        case "ScheduleStyleRecalculation" :
        case "InvalidateLayout" :
        case "FunctionCall" :
        case "Layout" :
        case "UpdateLayoutTree" : {
            return makeZeroBasedCallFrame(stack[0]);
        }
        default: {
            if (isUserTiming(event) || isSyntheticExtensionEntry(event)) {
                return makeZeroBasedCallFrame(stack[0]);
            }
            return stack[0];
        }
    }
}
function rawCallFrameForEntry(entry) {
    if (isProfileCall(entry)) {
        return entry.callFrame;
    }
    const topCallFrame = getStackTraceTopCallFrameInEventPayload(entry);
    if (topCallFrame) {
        return topCallFrame;
    }
    return null;
}
function makeZeroBasedCallFrame(callFrame) {
    const normalizedCallFrame = { ...callFrame };
    normalizedCallFrame.lineNumber = callFrame.lineNumber && callFrame.lineNumber - 1;
    normalizedCallFrame.columnNumber = callFrame.columnNumber && callFrame.columnNumber - 1;
    return normalizedCallFrame;
}
function getRawLineAndColumnNumbersForEvent(event) {
    if (!event.args?.data) {
        return {};
    }
    let lineNumber = undefined;
    let columnNumber = undefined;
    if ('lineNumber' in event.args.data && typeof event.args.data.lineNumber === 'number') {
        lineNumber = event.args.data.lineNumber;
    }
    if ('columnNumber' in event.args.data && typeof event.args.data.columnNumber === 'number') {
        columnNumber = event.args.data.columnNumber;
    }
    return { lineNumber, columnNumber };
}
function frameIDForEvent(event) {
    if (event.args && 'beginData' in event.args && typeof event.args.beginData === 'object' &&
        event.args.beginData !== null && 'frame' in event.args.beginData &&
        typeof event.args.beginData.frame === 'string') {
        return event.args.beginData.frame;
    }
    if (event.args?.data?.frame) {
        return event.args.data.frame;
    }
    return null;
}
const DevToolsTimelineEventCategory = 'disabled-by-default-devtools.timeline';
function isTopLevelEvent(event) {
    return event.cat.includes(DevToolsTimelineEventCategory) && event.name === "RunTask" ;
}
function isExtensionUrl(url) {
    return url.startsWith('extensions:') || url.startsWith('chrome-extension:');
}
function topLevelEventIndexEndingAfter(events, time) {
    let index = upperBound(events, time, (time, event) => time - event.ts) - 1;
    while (index > 0 && !isTopLevelEvent(events[index])) {
        index--;
    }
    return Math.max(index, 0);
}
function findRecalcStyleEvents(events, startTime, endTime) {
    const foundEvents = [];
    const startEventIndex = topLevelEventIndexEndingAfter(events, startTime);
    for (let i = startEventIndex; i < events.length; i++) {
        const event = events[i];
        if (!isRecalcStyle(event)) {
            continue;
        }
        if (event.ts >= (endTime || Infinity)) {
            continue;
        }
        foundEvents.push(event);
    }
    return foundEvents;
}
function findNextEventAfterTimestamp(candidates, ts) {
    const index = nearestIndexFromBeginning(candidates, candidate => ts < candidate.ts);
    return index === null ? null : candidates[index];
}
function findPreviousEventBeforeTimestamp(candidates, ts) {
    const index = nearestIndexFromEnd(candidates, candidate => candidate.ts < ts);
    return index === null ? null : candidates[index];
}
function forEachEvent(events, config) {
    const globalStartTime = config.startTime ?? Micro(0);
    const globalEndTime = config.endTime || Micro(Infinity);
    const ignoreAsyncEvents = config.ignoreAsyncEvents === false ? false : true;
    const stack = [];
    const startEventIndex = topLevelEventIndexEndingAfter(events, globalStartTime);
    for (let i = startEventIndex; i < events.length; i++) {
        const currentEvent = events[i];
        const currentEventTimings = eventTimingsMicroSeconds(currentEvent);
        if (currentEventTimings.endTime < globalStartTime) {
            continue;
        }
        if (currentEventTimings.startTime > globalEndTime) {
            break;
        }
        const isIgnoredAsyncEvent = ignoreAsyncEvents && isPhaseAsync(currentEvent.ph);
        if (isIgnoredAsyncEvent || isFlowPhase(currentEvent.ph)) {
            continue;
        }
        let lastEventOnStack = stack.at(-1);
        let lastEventEndTime = lastEventOnStack ? eventTimingsMicroSeconds(lastEventOnStack).endTime : null;
        while (lastEventOnStack && lastEventEndTime && lastEventEndTime <= currentEventTimings.startTime) {
            stack.pop();
            config.onEndEvent(lastEventOnStack);
            lastEventOnStack = stack.at(-1);
            lastEventEndTime = lastEventOnStack ? eventTimingsMicroSeconds(lastEventOnStack).endTime : null;
        }
        if (config.eventFilter && !config.eventFilter(currentEvent)) {
            continue;
        }
        if (currentEventTimings.duration) {
            config.onStartEvent(currentEvent);
            stack.push(currentEvent);
        }
        else if (config.onInstantEvent) {
            config.onInstantEvent(currentEvent);
        }
    }
    while (stack.length) {
        const last = stack.pop();
        if (last) {
            config.onEndEvent(last);
        }
    }
}
const parsedCategories = new Map();
function eventHasCategory(event, category) {
    let parsedCategoriesForEvent = parsedCategories.get(event.cat);
    if (!parsedCategoriesForEvent) {
        parsedCategoriesForEvent = new Set(event.cat.split(',') || []);
    }
    return parsedCategoriesForEvent.has(category);
}
function isMatchingCallFrame(eventFrame, nodeFrame) {
    return eventFrame.columnNumber === nodeFrame.columnNumber && eventFrame.lineNumber === nodeFrame.lineNumber &&
        String(eventFrame.scriptId) === nodeFrame.scriptId && eventFrame.url === nodeFrame.url &&
        eventFrame.functionName === nodeFrame.functionName;
}
function eventContainsTimestamp(event, ts) {
    return event.ts <= ts && event.ts + (event.dur || 0) >= ts;
}
function extractSampleTraceId(event) {
    if (!event.args) {
        return null;
    }
    if ('beginData' in event.args) {
        const beginData = event.args['beginData'];
        return beginData.sampleTraceId ?? null;
    }
    return event.args?.sampleTraceId ?? event.args?.data?.sampleTraceId ?? null;
}
const VISIBLE_TRACE_EVENT_TYPES = new Set([
    "AbortPostTaskCallback" ,
    "Animation" ,
    "AsyncTask" ,
    "v8.deserializeOnBackground" ,
    "v8.produceModuleCache" ,
    "v8.produceCache" ,
    "CancelAnimationFrame" ,
    "CancelIdleCallback" ,
    "Commit" ,
    "V8.CompileCode" ,
    "V8.CompileModule" ,
    "v8.compile" ,
    "CompositeLayers" ,
    "ComputeIntersections" ,
    "ConsoleTime" ,
    "CppGC.IncrementalSweep" ,
    "DoDecryptReply" ,
    "DoDecrypt" ,
    "DoDigestReply" ,
    "DoDigest" ,
    "DoEncryptReply" ,
    "DoEncrypt" ,
    "DoSignReply" ,
    "DoSign" ,
    "DoVerifyReply" ,
    "DoVerify" ,
    "Decode Image" ,
    "EmbedderCallback" ,
    "v8.evaluateModule" ,
    "EvaluateScript" ,
    "EventDispatch" ,
    "EventTiming" ,
    "V8.FinalizeDeserialization" ,
    "FireAnimationFrame" ,
    "FireIdleCallback" ,
    "FunctionCall" ,
    "BlinkGC.AtomicPhase" ,
    "GCEvent" ,
    "GPUTask" ,
    "HandlePostMessage" ,
    "HitTest" ,
    "JSSample" ,
    "Layerize" ,
    "Layout" ,
    "MajorGC" ,
    "MinorGC" ,
    "V8.OptimizeCode" ,
    "PaintSetup" ,
    "Paint" ,
    "ParseAuthorStyleSheet" ,
    "ParseHTML" ,
    "PrePaint" ,
    "ProfileCall" ,
    "Program" ,
    "RasterTask" ,
    "RequestAnimationFrame" ,
    "RequestIdleCallback" ,
    "ResourceFinish" ,
    "ResourceReceivedData" ,
    "ResourceReceiveResponse" ,
    "ResourceSendRequest" ,
    "ResourceWillSendRequest" ,
    "RunMicrotasks" ,
    "RunPostTaskCallback" ,
    "RunTask" ,
    "SchedulePostMessage" ,
    "SchedulePostTaskCallback" ,
    "ScheduleStyleRecalculation" ,
    "ScrollLayer" ,
    "CpuProfiler::StartProfiling" ,
    "v8.parseOnBackgroundParsing" ,
    "v8.parseOnBackgroundWaiting" ,
    "v8.parseOnBackground" ,
    "SyntheticLayoutShiftCluster" ,
    "SyntheticLayoutShift" ,
    "TimeStamp" ,
    "TimerFire" ,
    "TimerInstall" ,
    "TimerRemove" ,
    "UpdateLayerTree" ,
    "UpdateLayoutTree" ,
    "UserTiming" ,
    "V8Console::runTask" ,
    "v8.wasm.cachedModule" ,
    "v8.wasm.compiledModule" ,
    "v8.wasm.moduleCacheHit" ,
    "v8.wasm.moduleCacheInvalid" ,
    "v8.wasm.streamFromResponseCallback" ,
    "WebSocketCreate" ,
    "WebSocketDestroy" ,
    "WebSocketReceiveHandshakeResponse" ,
    "WebSocketReceive" ,
    "WebSocketSendHandshakeRequest" ,
    "WebSocketSend" ,
    "XHRLoad" ,
    "XHRReadyStateChange" ,
]);

var Trace = /*#__PURE__*/Object.freeze({
	__proto__: null,
	VISIBLE_TRACE_EVENT_TYPES: VISIBLE_TRACE_EVENT_TYPES,
	activeURLForFrameAtTime: activeURLForFrameAtTime,
	addEventToProcessThread: addEventToProcessThread,
	compareBeginAndEnd: compareBeginAndEnd,
	createMatchedSortedSyntheticEvents: createMatchedSortedSyntheticEvents,
	eventContainsTimestamp: eventContainsTimestamp,
	eventHasCategory: eventHasCategory,
	eventTimeComparator: eventTimeComparator,
	extractId: extractId,
	extractOriginFromTrace: extractOriginFromTrace,
	extractSampleTraceId: extractSampleTraceId,
	findNextEventAfterTimestamp: findNextEventAfterTimestamp,
	findPreviousEventBeforeTimestamp: findPreviousEventBeforeTimestamp,
	findRecalcStyleEvents: findRecalcStyleEvents,
	forEachEvent: forEachEvent,
	frameIDForEvent: frameIDForEvent,
	getNavigationForTraceEvent: getNavigationForTraceEvent,
	getStackTraceTopCallFrameInEventPayload: getStackTraceTopCallFrameInEventPayload,
	getSyntheticId: getSyntheticId,
	getZeroIndexedLineAndColumnForEvent: getZeroIndexedLineAndColumnForEvent,
	getZeroIndexedStackTraceInEventPayload: getZeroIndexedStackTraceInEventPayload,
	isExtensionUrl: isExtensionUrl,
	isMatchingCallFrame: isMatchingCallFrame,
	isTopLevelEvent: isTopLevelEvent,
	makeProfileCall: makeProfileCall,
	makeZeroBasedCallFrame: makeZeroBasedCallFrame,
	mergeEventsInOrder: mergeEventsInOrder,
	parseDevtoolsDetails: parseDevtoolsDetails,
	rawCallFrameForEntry: rawCallFrameForEntry,
	sortTraceEventsInPlace: sortTraceEventsInPlace,
	stackTraceInEvent: stackTraceInEvent
});

// Copyright 2023 The Chromium Authors
let nodeIdCount = 0;
const makeTraceEntryNodeId = () => (++nodeIdCount);
const makeEmptyTraceEntryTree = () => ({
    roots: new Set(),
    maxDepth: 0,
});
const makeEmptyTraceEntryNode = (entry, id) => ({
    entry,
    id,
    parent: null,
    children: [],
    depth: 0,
});
function treify(entries, options) {
    const entryToNode = new Map();
    const stack = [];
    nodeIdCount = -1;
    const tree = makeEmptyTraceEntryTree();
    for (let i = 0; i < entries.length; i++) {
        const event = entries[i];
        if (options && !options.filter.has(event.name)) {
            continue;
        }
        const duration = event.dur || 0;
        const nodeId = makeTraceEntryNodeId();
        const node = makeEmptyTraceEntryNode(event, nodeId);
        if (stack.length === 0) {
            tree.roots.add(node);
            node.selfTime = Micro(duration);
            stack.push(node);
            tree.maxDepth = Math.max(tree.maxDepth, stack.length);
            entryToNode.set(event, node);
            continue;
        }
        const parentNode = stack.at(-1);
        if (parentNode === undefined) {
            throw new Error('Impossible: no parent node found in the stack');
        }
        const parentEvent = parentNode.entry;
        const begin = event.ts;
        const parentBegin = parentEvent.ts;
        const parentDuration = parentEvent.dur || 0;
        const end = begin + duration;
        const parentEnd = parentBegin + parentDuration;
        const startsBeforeParent = begin < parentBegin;
        if (startsBeforeParent) {
            throw new Error('Impossible: current event starts before the parent event');
        }
        const startsAfterParent = begin >= parentEnd;
        if (startsAfterParent) {
            stack.pop();
            i--;
            nodeIdCount--;
            continue;
        }
        const endsAfterParent = end > parentEnd;
        if (endsAfterParent) {
            continue;
        }
        node.depth = stack.length;
        node.parent = parentNode;
        parentNode.children.push(node);
        node.selfTime = Micro(duration);
        if (parentNode.selfTime !== undefined) {
            parentNode.selfTime = Micro(parentNode.selfTime - (event.dur || 0));
        }
        stack.push(node);
        tree.maxDepth = Math.max(tree.maxDepth, stack.length);
        entryToNode.set(event, node);
    }
    return { tree, entryToNode };
}
function walkTreeFromEntry(entryToNode, rootEntry, onEntryStart, onEntryEnd) {
    const startNode = entryToNode.get(rootEntry);
    if (!startNode) {
        return;
    }
    walkTreeByNode(entryToNode, startNode, onEntryStart, onEntryEnd);
}
function walkEntireTree(entryToNode, tree, onEntryStart, onEntryEnd, traceWindowToInclude, minDuration) {
    for (const rootNode of tree.roots) {
        walkTreeByNode(entryToNode, rootNode, onEntryStart, onEntryEnd, traceWindowToInclude, minDuration);
    }
}
function walkTreeByNode(entryToNode, rootNode, onEntryStart, onEntryEnd, traceWindowToInclude, minDuration) {
    if (traceWindowToInclude && !treeNodeIsInWindow(rootNode, traceWindowToInclude)) {
        return;
    }
    if (typeof minDuration !== 'undefined') {
        const duration = Micro(rootNode.entry.ts + Micro(rootNode.entry.dur ?? 0));
        if (duration < minDuration) {
            return;
        }
    }
    onEntryStart(rootNode.entry);
    for (const child of rootNode.children) {
        walkTreeByNode(entryToNode, child, onEntryStart, onEntryEnd, traceWindowToInclude, minDuration);
    }
    onEntryEnd(rootNode.entry);
}
function treeNodeIsInWindow(node, traceWindow) {
    return eventIsInBounds(node.entry, traceWindow);
}
function canBuildTreesFromEvents(events) {
    const stack = [];
    for (const event of events) {
        const startTime = event.ts;
        const endTime = event.ts + (event.dur ?? 0);
        let parent = stack.at(-1);
        if (parent === undefined) {
            stack.push(event);
            continue;
        }
        let parentEndTime = parent.ts + (parent.dur ?? 0);
        while (stack.length && startTime >= parentEndTime) {
            stack.pop();
            parent = stack.at(-1);
            if (parent === undefined) {
                break;
            }
            parentEndTime = parent.ts + (parent.dur ?? 0);
        }
        if (stack.length && endTime > parentEndTime) {
            return false;
        }
        stack.push(event);
    }
    return true;
}

var TreeHelpers = /*#__PURE__*/Object.freeze({
	__proto__: null,
	canBuildTreesFromEvents: canBuildTreesFromEvents,
	makeEmptyTraceEntryNode: makeEmptyTraceEntryNode,
	makeEmptyTraceEntryTree: makeEmptyTraceEntryTree,
	makeTraceEntryNodeId: makeTraceEntryNodeId,
	treify: treify,
	walkEntireTree: walkEntireTree,
	walkTreeFromEntry: walkTreeFromEntry
});

// Copyright 2024 The Chromium Authors
function buildTrackDataFromExtensionEntries(extensionEntries, extensionTrackData, entryToNode) {
    const dataByTrack = new Map();
    for (const entry of extensionEntries) {
        const key = entry.devtoolsObj.trackGroup || `track-name-${entry.devtoolsObj.track}`;
        const batchedData = getWithDefault(dataByTrack, key, () => ({
            name: entry.devtoolsObj.trackGroup || entry.devtoolsObj.track,
            isTrackGroup: Boolean(entry.devtoolsObj.trackGroup),
            entriesByTrack: { [entry.devtoolsObj.track]: [] },
        }));
        if (!batchedData.entriesByTrack[entry.devtoolsObj.track]) {
            batchedData.entriesByTrack[entry.devtoolsObj.track] = [];
        }
        const entriesInTrack = batchedData.entriesByTrack[entry.devtoolsObj.track];
        entriesInTrack.push(entry);
    }
    for (const trackData of dataByTrack.values()) {
        for (const entries of Object.values(trackData.entriesByTrack)) {
            sortTraceEventsInPlace(entries);
            if (canBuildTreesFromEvents(entries)) {
                for (const [entry, node] of treify(entries).entryToNode) {
                    entryToNode.set(entry, node);
                }
            }
        }
        extensionTrackData.push(trackData);
    }
    return { extensionTrackData, entryToNode };
}

var Extensions = /*#__PURE__*/Object.freeze({
	__proto__: null,
	buildTrackDataFromExtensionEntries: buildTrackDataFromExtensionEntries
});

const NON_RENDER_BLOCKING_VALUES = new Set([
    'non_blocking',
    'dynamically_injected_non_blocking',
    'potentially_blocking',
]);
function isSyntheticNetworkRequestEventRenderBlocking(event) {
    return !NON_RENDER_BLOCKING_VALUES.has(event.args.data.renderBlocking);
}
const HIGH_NETWORK_PRIORITIES = new Set([
    "VeryHigh" ,
    "High" ,
    "Medium" ,
]);
function isSyntheticNetworkRequestHighPriority(event) {
    return HIGH_NETWORK_PRIORITIES.has(event.args.data.priority);
}
const CACHEABLE_STATUS_CODES = new Set([200, 203, 206]);
const STATIC_RESOURCE_TYPES = new Set([
    "Font" ,
    "Image" ,
    "Media" ,
    "Script" ,
    "Stylesheet" ,
]);
const NON_NETWORK_SCHEMES$1 = [
    'blob',
    'data',
    'intent',
    'file',
    'filesystem',
    'chrome-extension',
];
function parseCacheControl(header) {
    if (!header) {
        return null;
    }
    const directives = header.split(',').map(directive => directive.trim());
    const cacheControlOptions = {};
    for (const directive of directives) {
        const [key, value] = directive.split('=').map(part => part.trim());
        switch (key) {
            case 'max-age': {
                const maxAge = parseInt(value, 10);
                if (!isNaN(maxAge)) {
                    cacheControlOptions['max-age'] = maxAge;
                }
                break;
            }
            case 'no-cache':
                cacheControlOptions['no-cache'] = true;
                break;
            case 'no-store':
                cacheControlOptions['no-store'] = true;
                break;
            case 'must-revalidate':
                cacheControlOptions['must-revalidate'] = true;
                break;
            case 'private':
                cacheControlOptions['private'] = true;
                break;
        }
    }
    return cacheControlOptions;
}
const SECURE_LOCALHOST_DOMAINS = ['localhost', '127.0.0.1'];
function isSyntheticNetworkRequestLocalhost(event) {
    try {
        const hostname = new URL(event.args.data.url).hostname;
        return SECURE_LOCALHOST_DOMAINS.includes(hostname) || hostname.endsWith('.localhost');
    }
    catch {
        return false;
    }
}

var Network = /*#__PURE__*/Object.freeze({
	__proto__: null,
	CACHEABLE_STATUS_CODES: CACHEABLE_STATUS_CODES,
	NON_NETWORK_SCHEMES: NON_NETWORK_SCHEMES$1,
	STATIC_RESOURCE_TYPES: STATIC_RESOURCE_TYPES,
	isSyntheticNetworkRequestEventRenderBlocking: isSyntheticNetworkRequestEventRenderBlocking,
	isSyntheticNetworkRequestHighPriority: isSyntheticNetworkRequestHighPriority,
	isSyntheticNetworkRequestLocalhost: isSyntheticNetworkRequestLocalhost,
	parseCacheControl: parseCacheControl
});

// Copyright 2023 The Chromium Authors
var _a$3;
class SamplesIntegrator {
    #constructedProfileCalls = [];
    #currentJSStack = [];
    #processId;
    #threadId;
    #lockedJsStackDepth = [];
    #fakeJSInvocation = false;
    #profileModel;
    #nodeForGC = new Map();
    #engineConfig;
    #profileId;
    jsSampleEvents = [];
    constructor(profileModel, profileId, pid, tid, configuration) {
        this.#profileModel = profileModel;
        this.#threadId = tid;
        this.#processId = pid;
        this.#engineConfig = configuration || defaults();
        this.#profileId = profileId;
    }
    buildProfileCalls(traceEvents) {
        const mergedEvents = mergeEventsInOrder(traceEvents, this.callsFromProfileSamples());
        const stack = [];
        for (let i = 0; i < mergedEvents.length; i++) {
            const event = mergedEvents[i];
            if (event.ph === "I"  && !extractSampleTraceId(event)) {
                continue;
            }
            if (stack.length === 0) {
                if (isProfileCall(event)) {
                    this.#onProfileCall(event);
                    continue;
                }
                stack.push(event);
                this.#onTraceEventStart(event);
                continue;
            }
            const parentEvent = stack.at(-1);
            if (parentEvent === undefined) {
                continue;
            }
            const begin = event.ts;
            const parentBegin = parentEvent.ts;
            const parentDuration = parentEvent.dur || 0;
            const parentEnd = parentBegin + parentDuration;
            const startsAfterParent = begin >= parentEnd;
            if (startsAfterParent) {
                this.#onTraceEventEnd(parentEvent);
                stack.pop();
                i--;
                continue;
            }
            if (isProfileCall(event)) {
                this.#onProfileCall(event, parentEvent);
                continue;
            }
            this.#onTraceEventStart(event);
            stack.push(event);
        }
        while (stack.length) {
            const last = stack.pop();
            if (last) {
                this.#onTraceEventEnd(last);
            }
        }
        sortTraceEventsInPlace(this.jsSampleEvents);
        return this.#constructedProfileCalls;
    }
    #onTraceEventStart(event) {
        if (event.name === "RunMicrotasks"  || event.name === "RunTask" ) {
            this.#lockedJsStackDepth = [];
            this.#truncateJSStack(0, event.ts);
            this.#fakeJSInvocation = false;
        }
        if (this.#fakeJSInvocation) {
            this.#truncateJSStack(this.#lockedJsStackDepth.pop() || 0, event.ts);
            this.#fakeJSInvocation = false;
        }
        this.#extractStackTrace(event);
        this.#lockedJsStackDepth.push(this.#currentJSStack.length);
    }
    #onProfileCall(event, parent) {
        if ((parent && isJSInvocationEvent(parent)) || this.#fakeJSInvocation) {
            this.#extractStackTrace(event);
        }
        else if (isProfileCall(event) && this.#currentJSStack.length === 0) {
            this.#fakeJSInvocation = true;
            const stackDepthBefore = this.#currentJSStack.length;
            this.#extractStackTrace(event);
            this.#lockedJsStackDepth.push(stackDepthBefore);
        }
    }
    #onTraceEventEnd(event) {
        const endTime = Micro(event.ts + (event.dur ?? 0));
        this.#truncateJSStack(this.#lockedJsStackDepth.pop() || 0, endTime);
    }
    callsFromProfileSamples() {
        const samples = this.#profileModel.samples;
        const timestamps = this.#profileModel.timestamps;
        if (!samples) {
            return [];
        }
        const calls = [];
        let prevNode;
        for (let i = 0; i < samples.length; i++) {
            const node = this.#profileModel.nodeByIndex(i);
            const timestamp = milliToMicro(Milli(timestamps[i]));
            if (!node) {
                continue;
            }
            const call = makeProfileCall(node, this.#profileId, i, timestamp, this.#processId, this.#threadId);
            calls.push(call);
            if (this.#engineConfig.debugMode) {
                const traceId = this.#profileModel.traceIds?.[i];
                this.jsSampleEvents.push(this.#makeJSSampleEvent(call, timestamp, traceId));
            }
            if (node.id === this.#profileModel.gcNode?.id && prevNode) {
                this.#nodeForGC.set(call, prevNode);
                continue;
            }
            prevNode = node;
        }
        return calls;
    }
    #makeProfileCallsForStack(profileCall, overrideTimeStamp) {
        let node = this.#profileModel.nodeById(profileCall.nodeId);
        const isGarbageCollection = node?.id === this.#profileModel.gcNode?.id;
        if (isGarbageCollection) {
            node = this.#nodeForGC.get(profileCall) || null;
        }
        if (!node) {
            return [];
        }
        const callFrames = new Array(node.depth + 1 + Number(isGarbageCollection));
        let i = callFrames.length - 1;
        if (isGarbageCollection) {
            callFrames[i--] = profileCall;
        }
        while (node) {
            callFrames[i--] = makeProfileCall(node, profileCall.profileId, profileCall.sampleIndex, overrideTimeStamp ?? profileCall.ts, this.#processId, this.#threadId);
            node = node.parent;
        }
        return callFrames;
    }
    #getStackForSampleTraceId(traceId, timestamp) {
        const nodeId = this.#profileModel.traceIds?.[traceId];
        const node = nodeId && this.#profileModel.nodeById(nodeId);
        const maybeCallForTraceId = node && makeProfileCall(node, this.#profileId, -1, timestamp, this.#processId, this.#threadId);
        if (!maybeCallForTraceId) {
            return null;
        }
        if (this.#engineConfig.debugMode) {
            this.jsSampleEvents.push(this.#makeJSSampleEvent(maybeCallForTraceId, timestamp, traceId));
        }
        return this.#makeProfileCallsForStack(maybeCallForTraceId);
    }
    #extractStackTrace(event) {
        let stackTrace = this.#currentJSStack;
        if (isProfileCall(event)) {
            stackTrace = this.#makeProfileCallsForStack(event);
        }
        const traceId = extractSampleTraceId(event);
        const maybeCallForTraceId = traceId && this.#getStackForSampleTraceId(traceId, event.ts);
        if (maybeCallForTraceId) {
            stackTrace = maybeCallForTraceId;
        }
        _a$3.filterStackFrames(stackTrace, this.#engineConfig);
        const endTime = event.ts + (event.dur || 0);
        const minFrames = Math.min(stackTrace.length, this.#currentJSStack.length);
        let i;
        for (i = this.#lockedJsStackDepth.at(-1) || 0; i < minFrames; ++i) {
            const newFrame = stackTrace[i].callFrame;
            const oldFrame = this.#currentJSStack[i].callFrame;
            if (!_a$3.framesAreEqual(newFrame, oldFrame)) {
                break;
            }
            this.#currentJSStack[i].dur =
                Micro(Math.max(this.#currentJSStack[i].dur || 0, endTime - this.#currentJSStack[i].ts));
        }
        this.#truncateJSStack(i, event.ts);
        for (; i < stackTrace.length; ++i) {
            const call = stackTrace[i];
            if (call.nodeId === this.#profileModel.programNode?.id || call.nodeId === this.#profileModel.root?.id ||
                call.nodeId === this.#profileModel.idleNode?.id || call.nodeId === this.#profileModel.gcNode?.id) {
                continue;
            }
            this.#currentJSStack.push(call);
            this.#constructedProfileCalls.push(call);
        }
    }
    #truncateJSStack(depth, time) {
        if (this.#lockedJsStackDepth.length) {
            const lockedDepth = this.#lockedJsStackDepth.at(-1);
            if (lockedDepth && depth < lockedDepth) {
                console.error(`Child stack is shallower (${depth}) than the parent stack (${lockedDepth}) at ${time}`);
                depth = lockedDepth;
            }
        }
        if (this.#currentJSStack.length < depth) {
            console.error(`Trying to truncate higher than the current stack size at ${time}`);
            depth = this.#currentJSStack.length;
        }
        for (let k = 0; k < this.#currentJSStack.length; ++k) {
            this.#currentJSStack[k].dur = Micro(Math.max(time - this.#currentJSStack[k].ts, 0));
        }
        this.#currentJSStack.length = depth;
    }
    #makeJSSampleEvent(call, timestamp, traceId) {
        const JSSampleEvent = {
            name: "JSSample" ,
            cat: 'devtools.timeline',
            args: {
                data: { traceId, stackTrace: this.#makeProfileCallsForStack(call).map(e => e.callFrame) },
            },
            ph: "I" ,
            ts: timestamp,
            dur: Micro(0),
            pid: this.#processId,
            tid: this.#threadId,
        };
        return JSSampleEvent;
    }
    static framesAreEqual(frame1, frame2) {
        return frame1.scriptId === frame2.scriptId && frame1.functionName === frame2.functionName &&
            frame1.lineNumber === frame2.lineNumber;
    }
    static showNativeName(name, runtimeCallStatsEnabled) {
        return runtimeCallStatsEnabled && Boolean(_a$3.nativeGroup(name));
    }
    static nativeGroup(nativeName) {
        if (nativeName.startsWith('Parse')) {
            return "Parse" ;
        }
        if (nativeName.startsWith('Compile') || nativeName.startsWith('Recompile')) {
            return "Compile" ;
        }
        return null;
    }
    static isNativeRuntimeFrame(frame) {
        return frame.url === 'native V8Runtime';
    }
    static filterStackFrames(stack, engineConfig) {
        const showAllEvents = engineConfig.showAllEvents;
        if (showAllEvents) {
            return;
        }
        let previousNativeFrameName = null;
        let j = 0;
        for (let i = 0; i < stack.length; ++i) {
            const frame = stack[i].callFrame;
            const nativeRuntimeFrame = _a$3.isNativeRuntimeFrame(frame);
            if (nativeRuntimeFrame &&
                !_a$3.showNativeName(frame.functionName, engineConfig.includeRuntimeCallStats)) {
                continue;
            }
            const nativeFrameName = nativeRuntimeFrame ? _a$3.nativeGroup(frame.functionName) : null;
            if (previousNativeFrameName && previousNativeFrameName === nativeFrameName) {
                continue;
            }
            previousNativeFrameName = nativeFrameName;
            stack[j++] = stack[i];
        }
        stack.length = j;
    }
    static createFakeTraceFromCpuProfile(profile, tid) {
        if (!profile) {
            return { traceEvents: [], metadata: {} };
        }
        const cpuProfileEvent = {
            cat: 'disabled-by-default-devtools.timeline',
            name: "CpuProfile" ,
            ph: "X" ,
            pid: ProcessID(1),
            tid,
            ts: Micro(profile.startTime),
            dur: Micro(profile.endTime - profile.startTime),
            args: { data: { cpuProfile: profile } },
            id: '0x1',
        };
        return {
            traceEvents: [cpuProfileEvent],
            metadata: {
                dataOrigin: "CPUProfile" ,
            }
        };
    }
    static extractCpuProfileFromFakeTrace(traceEvents) {
        const profileEvent = traceEvents.find(e => isSyntheticCpuProfile(e));
        const profile = profileEvent?.args.data.cpuProfile;
        if (!profile) {
            throw new Error('Missing cpuProfile data');
        }
        return profile;
    }
}
_a$3 = SamplesIntegrator;

var SamplesIntegrator$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	SamplesIntegrator: SamplesIntegrator
});

// Copyright 2022 The Chromium Authors

var helpers = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Extensions: Extensions,
	Network: Network,
	SamplesIntegrator: SamplesIntegrator$1,
	SyntheticEvents: SyntheticEvents,
	Timing: Timing,
	Trace: Trace,
	TreeHelpers: TreeHelpers
});

// Copyright 2024 The Chromium Authors
function threadKey(data) {
    return `${data.pid}-${data.tid}`;
}
let animationFrameStarts = new Map();
let animationFrameEnds = new Map();
let animationFramePresentations = new Map();
let animationFrames = [];
let presentationForFrame = new Map();
function reset$t() {
    animationFrameStarts = new Map();
    animationFrameEnds = new Map();
    animationFrames = [];
    presentationForFrame = new Map();
    animationFramePresentations = new Map();
    isEnabled = false;
}
let isEnabled = false;
function handleUserConfig$2(config) {
    isEnabled = config.enableAnimationsFrameHandler;
}
function handleEvent$t(event) {
    if (!isEnabled) {
        return;
    }
    if (isAnimationFrameAsyncStart(event)) {
        const key = threadKey(event);
        const existing = animationFrameStarts.get(key) ?? [];
        existing.push(event);
        animationFrameStarts.set(key, existing);
    }
    else if (isAnimationFrameAsyncEnd(event)) {
        const key = threadKey(event);
        const existing = animationFrameEnds.get(key) ?? [];
        existing.push(event);
        animationFrameEnds.set(key, existing);
    }
    else if (isAnimationFramePresentation(event) && event.args?.id) {
        animationFramePresentations.set(event.args.id, event);
    }
}
async function finalize$L() {
    for (const [key, startEvents] of animationFrameStarts.entries()) {
        const endEvents = animationFrameEnds.get(key);
        if (!endEvents) {
            continue;
        }
        sortTraceEventsInPlace(startEvents);
        sortTraceEventsInPlace(endEvents);
        for (let i = 0; i < startEvents.length; i++) {
            const endEvent = endEvents.at(i);
            if (!endEvent) {
                break;
            }
            const startEvent = startEvents[i];
            const syntheticEvent = SyntheticEventsManager
                .registerSyntheticEvent({
                rawSourceEvent: startEvent,
                ...startEvent,
                dur: Micro(endEvent.ts - startEvent.ts),
                args: {
                    data: {
                        beginEvent: startEvent,
                        endEvent,
                    },
                },
            });
            animationFrames.push(syntheticEvent);
            const id = startEvent.args?.id;
            if (id) {
                const presentationEvent = animationFramePresentations.get(id);
                if (presentationEvent) {
                    presentationForFrame.set(syntheticEvent, presentationEvent);
                }
            }
        }
    }
}
function data$t() {
    return {
        animationFrames,
        presentationForFrame,
    };
}
function deps$f() {
    return ['Meta'];
}

var AnimationFramesHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$t,
	deps: deps$f,
	finalize: finalize$L,
	handleEvent: handleEvent$t,
	handleUserConfig: handleUserConfig$2,
	reset: reset$t
});

// Copyright 2022 The Chromium Authors
let animations = [];
let animationsSyntheticEvents = [];
function reset$s() {
    animations = [];
    animationsSyntheticEvents = [];
}
function handleEvent$s(event) {
    if (isAnimation(event)) {
        animations.push(event);
        return;
    }
}
async function finalize$K() {
    const syntheticEvents = createMatchedSortedSyntheticEvents(animations);
    animationsSyntheticEvents.push(...syntheticEvents);
}
function data$s() {
    return {
        animations: animationsSyntheticEvents,
    };
}

var AnimationHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$s,
	finalize: finalize$K,
	handleEvent: handleEvent$s,
	reset: reset$s
});

// Copyright 2024 The Chromium Authors
let flowDataByGroupToken = new Map();
let boundFlowData = new Map();
let flowsById = new Map();
let flowEvents = [];
let nonFlowEvents = [];
let flows = [];
const ID_COMPONENT_SEPARATOR = '-$-';
function reset$r() {
    flows = [];
    flowEvents = [];
    nonFlowEvents = [];
    flowDataByGroupToken = new Map();
    boundFlowData = new Map();
    flowsById = new Map();
}
function handleEvent$r(event) {
    if (isFlowPhaseEvent(event)) {
        flowEvents.push(event);
        return;
    }
    nonFlowEvents.push(event);
}
function processNonFlowEvent(event) {
    const flowDataForEvent = boundFlowData.get(event.ts)?.get(event.pid)?.get(event.tid)?.get(event.cat);
    if (!flowDataForEvent) {
        return;
    }
    const { flows, bindingParsed } = flowDataForEvent;
    if (bindingParsed) {
        return;
    }
    for (const flowId of flows) {
        const flow = getWithDefault(flowsById, flowId, () => new Map());
        flow.set(event.ts, event);
    }
    flowDataForEvent.bindingParsed = true;
}
function processFlowEvent(flowPhaseEvent) {
    const flowGroup = flowGroupTokenForFlowPhaseEvent(flowPhaseEvent);
    switch (flowPhaseEvent.ph) {
        case ("s" ): {
            const flowMetadata = { flowId: flowPhaseEvent.id, times: new Map([[flowPhaseEvent.ts, undefined]]) };
            flowDataByGroupToken.set(flowGroup, flowPhaseEvent.id);
            addFlowIdToEventBinding(flowPhaseEvent, flowMetadata.flowId);
            return;
        }
        case ("t" ): {
            const flowId = flowDataByGroupToken.get(flowGroup);
            if (flowId === undefined) {
                return;
            }
            addFlowIdToEventBinding(flowPhaseEvent, flowId);
            return;
        }
        case ("f" ): {
            const flowId = flowDataByGroupToken.get(flowGroup);
            if (flowId === undefined) {
                return;
            }
            addFlowIdToEventBinding(flowPhaseEvent, flowId);
            flowDataByGroupToken.delete(flowGroup);
        }
    }
}
function addFlowIdToEventBinding(event, flowId) {
    const flowsByPid = getWithDefault(boundFlowData, event.ts, () => new Map());
    const flowsByTid = getWithDefault(flowsByPid, event.pid, () => new Map());
    const flowsByCat = getWithDefault(flowsByTid, event.tid, () => new Map());
    const flowData = getWithDefault(flowsByCat, event.cat, () => ({ flows: new Set(), bindingParsed: false }));
    flowData.flows.add(flowId);
}
function flowGroupTokenForFlowPhaseEvent(event) {
    return `${event.cat}${ID_COMPONENT_SEPARATOR}${event.name}${ID_COMPONENT_SEPARATOR}${event.id}`;
}
async function finalize$J() {
    flowEvents.forEach(processFlowEvent);
    nonFlowEvents.forEach(processNonFlowEvent);
    flows = [...flowsById.values()]
        .map(flowMapping => [...flowMapping.values()])
        .map(flow => flow.filter(event => event !== undefined))
        .filter(flow => flow.length > 1);
}
function data$r() {
    return {
        flows,
    };
}

var FlowsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$r,
	finalize: finalize$J,
	handleEvent: handleEvent$r,
	reset: reset$r
});

// Copyright 2023 The Chromium Authors
let runningInProcessEvents = new Map();
let doneWithProcessEvents = new Map();
let createdSyntheticEvents = new Map();
let utilityThreads = new Map();
let v8HelperThreads = new Map();
function reset$q() {
    runningInProcessEvents = new Map();
    doneWithProcessEvents = new Map();
    createdSyntheticEvents = new Map();
    utilityThreads = new Map();
    v8HelperThreads = new Map();
}
function handleEvent$q(event) {
    if (isAuctionWorkletRunningInProcess(event)) {
        runningInProcessEvents.set(event.args.data.pid, event);
        return;
    }
    if (isAuctionWorkletDoneWithProcess(event)) {
        doneWithProcessEvents.set(event.args.data.pid, event);
        return;
    }
    if (isThreadName(event)) {
        if (event.args.name === 'auction_worklet.CrUtilityMain') {
            utilityThreads.set(event.pid, event);
            return;
        }
        if (event.args.name === 'AuctionV8HelperThread') {
            v8HelperThreads.set(event.pid, event);
        }
    }
}
function workletType(input) {
    switch (input) {
        case 'seller':
            return "seller" ;
        case 'bidder':
            return "bidder" ;
        default:
            return "unknown" ;
    }
}
function makeSyntheticEventBase(event) {
    return SyntheticEventsManager
        .registerSyntheticEvent({
        rawSourceEvent: event,
        name: 'SyntheticAuctionWorklet',
        s: "t" ,
        cat: event.cat,
        tid: event.tid,
        ts: event.ts,
        ph: "I" ,
        pid: event.args.data.pid,
        host: event.args.data.host,
        target: event.args.data.target,
        type: workletType(event.args.data.type),
    });
}
async function finalize$I() {
    for (const [pid, utilityThreadNameEvent] of utilityThreads) {
        const v8HelperEvent = v8HelperThreads.get(pid);
        if (!v8HelperEvent) {
            continue;
        }
        const runningEvent = runningInProcessEvents.get(pid);
        const doneWithEvent = doneWithProcessEvents.get(pid);
        let syntheticEvent = null;
        if (runningEvent) {
            syntheticEvent = {
                ...makeSyntheticEventBase(runningEvent),
                args: {
                    data: {
                        runningInProcessEvent: runningEvent,
                        utilityThread: utilityThreadNameEvent,
                        v8HelperThread: v8HelperEvent,
                    },
                },
            };
            if (doneWithEvent) {
                syntheticEvent.args.data.doneWithProcessEvent = doneWithEvent;
            }
        }
        else if (doneWithEvent) {
            syntheticEvent = {
                ...makeSyntheticEventBase(doneWithEvent),
                args: {
                    data: {
                        doneWithProcessEvent: doneWithEvent,
                        utilityThread: utilityThreadNameEvent,
                        v8HelperThread: v8HelperEvent,
                    },
                },
            };
            if (runningEvent) {
                syntheticEvent.args.data.runningInProcessEvent = runningEvent;
            }
        }
        if (syntheticEvent === null) {
            continue;
        }
        createdSyntheticEvents.set(pid, syntheticEvent);
    }
}
function data$q() {
    return {
        worklets: createdSyntheticEvents,
    };
}

var AuctionWorkletsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$q,
	finalize: finalize$I,
	handleEvent: handleEvent$q,
	reset: reset$q
});

// Copyright 2022 The Chromium Authors
let config$1;
let rendererProcessesByFrameId = new Map();
let mainFrameId = '';
let mainFrameURL = '';
let framesByProcessId = new Map();
let browserProcessId = ProcessID(-1);
let browserThreadId = ThreadID(-1);
let gpuProcessId = ProcessID(-1);
let gpuThreadId = ThreadID(-1);
let viewportRect = null;
let devicePixelRatio = null;
let processNames = new Map();
let topLevelRendererIds = new Set();
function makeNewTraceBounds() {
    return {
        min: Micro(Number.POSITIVE_INFINITY),
        max: Micro(Number.NEGATIVE_INFINITY),
        range: Micro(Number.POSITIVE_INFINITY),
    };
}
let traceBounds = makeNewTraceBounds();
let navigationsByFrameId = new Map();
let navigationsByNavigationId = new Map();
let softNavigationsById = new Map();
let finalDisplayUrlByNavigationId = new Map();
let mainFrameNavigations = [];
let threadsInProcess = new Map();
let traceStartedTimeFromTracingStartedEvent = Micro(-1);
const eventPhasesOfInterestForTraceBounds = new Set([
    "B" ,
    "E" ,
    "X" ,
    "I" ,
]);
let traceIsGeneric = true;
const CHROME_WEB_TRACE_EVENTS = new Set([
    "TracingStartedInPage" ,
    "TracingSessionIdForWorker" ,
    "TracingStartedInBrowser" ,
    "CpuProfile" ,
]);
function reset$p() {
    navigationsByFrameId = new Map();
    navigationsByNavigationId = new Map();
    softNavigationsById = new Map();
    finalDisplayUrlByNavigationId = new Map();
    processNames = new Map();
    mainFrameNavigations = [];
    browserProcessId = ProcessID(-1);
    browserThreadId = ThreadID(-1);
    gpuProcessId = ProcessID(-1);
    gpuThreadId = ThreadID(-1);
    viewportRect = null;
    topLevelRendererIds = new Set();
    threadsInProcess = new Map();
    rendererProcessesByFrameId = new Map();
    framesByProcessId = new Map();
    traceBounds = makeNewTraceBounds();
    traceStartedTimeFromTracingStartedEvent = Micro(-1);
    traceIsGeneric = true;
}
function updateRendererProcessByFrame(event, frame) {
    const framesInProcessById = getWithDefault(framesByProcessId, frame.processId, () => new Map());
    framesInProcessById.set(frame.frame, frame);
    const rendererProcessInFrame = getWithDefault(rendererProcessesByFrameId, frame.frame, () => new Map());
    const rendererProcessInfo = getWithDefault(rendererProcessInFrame, frame.processId, () => {
        return [];
    });
    const lastProcessData = rendererProcessInfo.at(-1);
    if (lastProcessData && lastProcessData.frame.url === frame.url) {
        return;
    }
    rendererProcessInfo.push({
        frame,
        window: {
            min: event.ts,
            max: Micro(0),
            range: Micro(0),
        },
    });
}
function handleEvent$p(event) {
    if (traceIsGeneric && CHROME_WEB_TRACE_EVENTS.has(event.name)) {
        traceIsGeneric = false;
    }
    if (isProcessName(event)) {
        processNames.set(event.pid, event);
    }
    if (event.ts !== 0 && !event.name.endsWith('::UMA') && eventPhasesOfInterestForTraceBounds.has(event.ph)) {
        traceBounds.min = Micro(Math.min(event.ts, traceBounds.min));
        const eventDuration = event.dur ?? Micro(0);
        traceBounds.max = Micro(Math.max(event.ts + eventDuration, traceBounds.max));
    }
    if (isProcessName(event) && (event.args.name === 'Browser' || event.args.name === 'HeadlessBrowser')) {
        browserProcessId = event.pid;
        return;
    }
    if (isProcessName(event) && (event.args.name === 'Gpu' || event.args.name === 'GPU Process')) {
        gpuProcessId = event.pid;
        return;
    }
    if (isThreadName(event) && event.args.name === 'CrGpuMain') {
        gpuThreadId = event.tid;
        return;
    }
    if (isThreadName(event) && event.args.name === 'CrBrowserMain') {
        browserThreadId = event.tid;
    }
    if (isMainFrameViewport(event) && viewportRect === null) {
        const rectAsArray = event.args.data.viewport_rect;
        const viewportX = rectAsArray[0];
        const viewportY = rectAsArray[1];
        const viewportWidth = rectAsArray[2];
        const viewportHeight = rectAsArray[5];
        viewportRect = { x: viewportX, y: viewportY, width: viewportWidth, height: viewportHeight };
        devicePixelRatio = event.args.data.dpr;
    }
    if (isTracingStartedInBrowser(event)) {
        traceStartedTimeFromTracingStartedEvent = event.ts;
        if (!event.args.data) {
            throw new Error('No frames found in trace data');
        }
        for (const frame of (event.args.data.frames ?? [])) {
            updateRendererProcessByFrame(event, frame);
            if (!frame.parent) {
                topLevelRendererIds.add(frame.processId);
            }
            const traceHasPrimaryMainFrameFlag = 'isInPrimaryMainFrame' in frame;
            const traceHasOutermostMainFrameFlag = 'isOutermostMainFrame' in frame;
            if (traceHasPrimaryMainFrameFlag && traceHasOutermostMainFrameFlag) {
                if (frame.isInPrimaryMainFrame && frame.isOutermostMainFrame) {
                    mainFrameId = frame.frame;
                    mainFrameURL = frame.url;
                }
            }
            else if (traceHasOutermostMainFrameFlag) {
                if (frame.isOutermostMainFrame) {
                    mainFrameId = frame.frame;
                    mainFrameURL = frame.url;
                }
            }
            else if (!frame.parent && frame.url) {
                mainFrameId = frame.frame;
                mainFrameURL = frame.url;
            }
        }
        return;
    }
    if (isFrameCommittedInBrowser(event)) {
        const frame = event.args.data;
        if (!frame) {
            return;
        }
        updateRendererProcessByFrame(event, frame);
        if (frame.parent) {
            return;
        }
        topLevelRendererIds.add(frame.processId);
        return;
    }
    if (isCommitLoad(event)) {
        const frameData = event.args.data;
        if (!frameData) {
            return;
        }
        const { frame, name, url } = frameData;
        updateRendererProcessByFrame(event, { processId: event.pid, frame, name, url });
        return;
    }
    if (isThreadName(event)) {
        const threads = getWithDefault(threadsInProcess, event.pid, () => new Map());
        threads.set(event.tid, event);
        return;
    }
    if (isNavigationStart(event) && event.args.data) {
        const navigationId = event.args.data.navigationId;
        if (navigationsByNavigationId.has(navigationId)) {
            return;
        }
        navigationsByNavigationId.set(navigationId, event);
        finalDisplayUrlByNavigationId.set(navigationId, event.args.data.documentLoaderURL);
        const frameId = event.args.frame;
        const existingFrameNavigations = navigationsByFrameId.get(frameId) || [];
        existingFrameNavigations.push(event);
        navigationsByFrameId.set(frameId, existingFrameNavigations);
        if (frameId === mainFrameId) {
            mainFrameNavigations.push(event);
        }
        return;
    }
    if (isSoftNavigationStart(event)) {
        softNavigationsById.set(event.args.context.performanceTimelineNavigationId, event);
    }
    if (isResourceSendRequest(event)) {
        if (event.args.data.resourceType !== 'Document') {
            return;
        }
        const maybeNavigationId = event.args.data.requestId;
        const navigation = navigationsByNavigationId.get(maybeNavigationId);
        if (!navigation) {
            return;
        }
        finalDisplayUrlByNavigationId.set(maybeNavigationId, event.args.data.url);
        return;
    }
    if (isDidCommitSameDocumentNavigation(event)) {
        if (event.args.render_frame_host.frame_type !== 'PRIMARY_MAIN_FRAME') {
            return;
        }
        const navigation = mainFrameNavigations.at(-1);
        const key = navigation?.args.data?.navigationId ?? '';
        finalDisplayUrlByNavigationId.set(key, event.args.url);
        return;
    }
}
async function finalize$H(options) {
    config$1 = { showAllEvents: Boolean(options?.showAllEvents) };
    if (traceStartedTimeFromTracingStartedEvent >= 0) {
        traceBounds.min = traceStartedTimeFromTracingStartedEvent;
    }
    traceBounds.range = Micro(traceBounds.max - traceBounds.min);
    for (const [, processWindows] of rendererProcessesByFrameId) {
        const processWindowValues = [...processWindows.values()].flat().sort((a, b) => {
            return a.window.min - b.window.min;
        });
        for (let i = 0; i < processWindowValues.length; i++) {
            const currentWindow = processWindowValues[i];
            const nextWindow = processWindowValues[i + 1];
            if (!nextWindow) {
                currentWindow.window.max = Micro(traceBounds.max);
                currentWindow.window.range = Micro(traceBounds.max - currentWindow.window.min);
            }
            else {
                currentWindow.window.max = Micro(nextWindow.window.min - 1);
                currentWindow.window.range = Micro(currentWindow.window.max - currentWindow.window.min);
            }
        }
    }
    for (const [frameId, navigations] of navigationsByFrameId) {
        if (rendererProcessesByFrameId.has(frameId)) {
            continue;
        }
        navigationsByFrameId.delete(frameId);
        for (const navigation of navigations) {
            if (!navigation.args.data) {
                continue;
            }
            navigationsByNavigationId.delete(navigation.args.data.navigationId);
        }
    }
    const firstMainFrameNav = mainFrameNavigations.at(0);
    const firstNavTimeThreshold = secondsToMicro(Seconds(0.5));
    if (firstMainFrameNav) {
        const navigationIsWithinThreshold = firstMainFrameNav.ts - traceBounds.min < firstNavTimeThreshold;
        if (firstMainFrameNav.args.data?.isOutermostMainFrame && firstMainFrameNav.args.data?.documentLoaderURL &&
            navigationIsWithinThreshold) {
            mainFrameURL = firstMainFrameNav.args.data.documentLoaderURL;
        }
    }
}
function data$p() {
    return {
        config: config$1,
        traceBounds,
        browserProcessId,
        browserThreadId,
        processNames,
        gpuProcessId,
        gpuThreadId: gpuThreadId === ThreadID(-1) ? undefined : gpuThreadId,
        viewportRect: viewportRect || undefined,
        devicePixelRatio: devicePixelRatio ?? undefined,
        mainFrameId,
        mainFrameURL,
        navigationsByFrameId,
        navigationsByNavigationId,
        softNavigationsById,
        finalDisplayUrlByNavigationId,
        threadsInProcess,
        rendererProcessesByFrame: rendererProcessesByFrameId,
        topLevelRendererIds,
        frameByProcessId: framesByProcessId,
        mainFrameNavigations,
        traceIsGeneric,
    };
}

var MetaHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$p,
	finalize: finalize$H,
	handleEvent: handleEvent$p,
	reset: reset$p
});

// Copyright 2022 The Chromium Authors
const MILLISECONDS_TO_MICROSECONDS = 1000;
const SECONDS_TO_MICROSECONDS = 1000000;
let webSocketData = new Map();
let linkPreconnectEvents = [];
let requestMap = new Map();
let requestsById = new Map();
let requestsByTime = [];
let requestIdsByURL = new Map();
let networkRequestEventByInitiatorUrl = new Map();
let eventToInitiatorMap$1 = new Map();
let entityMappings$1 = {
    eventsByEntity: new Map(),
    entityByEvent: new Map(),
    createdEntityCache: new Map(),
    entityByUrlCache: new Map(),
};
function storeTraceEventWithRequestId(requestId, key, value) {
    if (!requestMap.has(requestId)) {
        requestMap.set(requestId, {});
    }
    const traceEvents = requestMap.get(requestId);
    if (!traceEvents) {
        throw new Error(`Unable to locate trace events for request ID ${requestId}`);
    }
    if (Array.isArray(traceEvents[key])) {
        const target = traceEvents[key];
        const values = value;
        target.push(...values);
    }
    else {
        traceEvents[key] = value;
    }
}
function firstPositiveValueInList(entries) {
    for (const entry of entries) {
        if (entry && entry > 0) {
            return entry;
        }
    }
    return 0;
}
function reset$o() {
    requestsById = new Map();
    requestMap = new Map();
    requestsByTime = [];
    networkRequestEventByInitiatorUrl = new Map();
    eventToInitiatorMap$1 = new Map();
    webSocketData = new Map();
    requestIdsByURL = new Map();
    entityMappings$1 = {
        eventsByEntity: new Map(),
        entityByEvent: new Map(),
        createdEntityCache: new Map(),
        entityByUrlCache: new Map(),
    };
    linkPreconnectEvents = [];
}
function handleEvent$o(event) {
    if (isResourceChangePriority(event)) {
        storeTraceEventWithRequestId(event.args.data.requestId, 'changePriority', event);
        return;
    }
    if (isResourceWillSendRequest(event)) {
        storeTraceEventWithRequestId(event.args.data.requestId, 'willSendRequests', [event]);
        return;
    }
    if (isResourceSendRequest(event)) {
        storeTraceEventWithRequestId(event.args.data.requestId, 'sendRequests', [event]);
        return;
    }
    if (isResourceReceiveResponse(event)) {
        storeTraceEventWithRequestId(event.args.data.requestId, 'receiveResponse', event);
        return;
    }
    if (isResourceReceivedData(event)) {
        storeTraceEventWithRequestId(event.args.data.requestId, 'receivedData', [event]);
        return;
    }
    if (isResourceFinish(event)) {
        storeTraceEventWithRequestId(event.args.data.requestId, 'resourceFinish', event);
        return;
    }
    if (isResourceMarkAsCached(event)) {
        storeTraceEventWithRequestId(event.args.data.requestId, 'resourceMarkAsCached', event);
        return;
    }
    if (isPreloadRenderBlockingStatusChangeEvent(event)) {
        storeTraceEventWithRequestId(event.args.data.requestId, 'preloadRenderBlockingStatusChange', [event]);
    }
    if (isWebSocketCreate(event) || isWebSocketInfo(event) ||
        isWebSocketTransfer(event)) {
        const identifier = event.args.data.identifier;
        if (!webSocketData.has(identifier)) {
            if (event.args.data.frame) {
                webSocketData.set(identifier, {
                    frame: event.args.data.frame,
                    webSocketIdentifier: identifier,
                    events: [],
                    syntheticConnection: null,
                });
            }
            else if (event.args.data.workerId) {
                webSocketData.set(identifier, {
                    workerId: event.args.data.workerId,
                    webSocketIdentifier: identifier,
                    events: [],
                    syntheticConnection: null,
                });
            }
        }
        webSocketData.get(identifier)?.events.push(event);
    }
    if (isLinkPreconnect(event)) {
        linkPreconnectEvents.push(event);
        return;
    }
}
async function finalize$G() {
    const { rendererProcessesByFrame } = data$p();
    for (const [requestId, request] of requestMap.entries()) {
        if (!request.sendRequests) {
            continue;
        }
        const redirects = [];
        for (let i = 0; i < request.sendRequests.length - 1; i++) {
            const sendRequest = request.sendRequests[i];
            const nextSendRequest = request.sendRequests[i + 1];
            let ts = sendRequest.ts;
            let dur = Micro(nextSendRequest.ts - sendRequest.ts);
            if (request.willSendRequests?.[i] && request.willSendRequests[i + 1]) {
                const willSendRequest = request.willSendRequests[i];
                const nextWillSendRequest = request.willSendRequests[i + 1];
                ts = willSendRequest.ts;
                dur = Micro(nextWillSendRequest.ts - willSendRequest.ts);
            }
            redirects.push({
                url: sendRequest.args.data.url,
                priority: sendRequest.args.data.priority,
                requestMethod: sendRequest.args.data.requestMethod,
                ts,
                dur,
            });
        }
        const firstSendRequest = request.sendRequests[0];
        const finalSendRequest = request.sendRequests[request.sendRequests.length - 1];
        if (finalSendRequest.args.data.url.startsWith('data:')) {
            continue;
        }
        const isLightrider = globalThis.isLightrider;
        if (isLightrider && request.resourceFinish && request.receiveResponse?.args.data.headers) {
            const lrSizeHeader = request.receiveResponse.args.data.headers.find(h => h.name === 'X-TotalFetchedSize');
            if (lrSizeHeader) {
                const size = parseFloat(lrSizeHeader.value);
                if (!isNaN(size)) {
                    request.resourceFinish.args.data.encodedDataLength = size;
                }
            }
        }
        const isPushedResource = request.resourceFinish?.args.data.encodedDataLength !== 0;
        const isDiskCached = !!request.receiveResponse && request.receiveResponse.args.data.fromCache &&
            !request.receiveResponse.args.data.fromServiceWorker && !isPushedResource;
        const isMemoryCached = request.resourceMarkAsCached !== undefined;
        let timing = isMemoryCached ? undefined : request.receiveResponse?.args.data.timing;
        let lrServerResponseTime;
        if (isLightrider && request.receiveResponse?.args.data.headers) {
            timing = {
                requestTime: microToSeconds(request.sendRequests.at(0)?.ts ?? 0),
                connectEnd: 0,
                connectStart: 0,
                dnsEnd: 0,
                dnsStart: 0,
                proxyEnd: 0,
                proxyStart: 0,
                pushEnd: 0,
                pushStart: 0,
                receiveHeadersEnd: 0,
                receiveHeadersStart: 0,
                sendEnd: 0,
                sendStart: 0,
                sslEnd: 0,
                sslStart: 0,
                workerReady: 0,
                workerStart: 0,
                ...timing,
            };
            const TCPMsHeader = request.receiveResponse.args.data.headers.find(h => h.name === 'X-TCPMs');
            const TCPMs = TCPMsHeader ? Math.max(0, parseInt(TCPMsHeader.value, 10)) : 0;
            if (request.receiveResponse.args.data.protocol.startsWith('h3')) {
                timing.connectStart = 0;
                timing.connectEnd = TCPMs;
            }
            else {
                timing.connectStart = 0;
                timing.sslStart = TCPMs / 2;
                timing.connectEnd = TCPMs;
                timing.sslEnd = TCPMs;
            }
            const ResponseMsHeader = request.receiveResponse.args.data.headers.find(h => h.name === 'X-ResponseMs');
            if (ResponseMsHeader) {
                lrServerResponseTime = Math.max(0, parseInt(ResponseMsHeader.value, 10));
            }
        }
        const allowedProtocols = [
            'blob:',
            'file:',
            'filesystem:',
            'http:',
            'https:',
        ];
        if (!allowedProtocols.some(p => firstSendRequest.args.data.url.startsWith(p))) {
            continue;
        }
        const initialPriority = finalSendRequest.args.data.priority;
        let finalPriority = initialPriority;
        if (request.changePriority) {
            finalPriority = request.changePriority.args.data.priority;
        }
        const startTime = (request.willSendRequests?.length) ? Micro(request.willSendRequests[0].ts) :
            Micro(firstSendRequest.ts);
        const endRedirectTime = (request.willSendRequests?.length) ?
            Micro(request.willSendRequests[request.willSendRequests.length - 1].ts) :
            Micro(finalSendRequest.ts);
        const endTime = request.resourceFinish ? request.resourceFinish.ts : endRedirectTime;
        const finishTime = request.resourceFinish?.args.data.finishTime ?
            Micro(request.resourceFinish.args.data.finishTime * SECONDS_TO_MICROSECONDS) :
            Micro(endTime);
        const networkDuration = Micro(timing ? (finishTime || endRedirectTime) - endRedirectTime : 0);
        const processingDuration = Micro(endTime - (finishTime || endTime));
        const redirectionDuration = Micro(endRedirectTime - startTime);
        const queueingFromTraceData = timing ? timing.requestTime * SECONDS_TO_MICROSECONDS - endRedirectTime : 0;
        const queueing = Micro(clamp$1(queueingFromTraceData, 0, Number.MAX_VALUE));
        const stalled = timing ?
            Micro(firstPositiveValueInList([
                timing.dnsStart * MILLISECONDS_TO_MICROSECONDS,
                timing.connectStart * MILLISECONDS_TO_MICROSECONDS,
                timing.sendStart * MILLISECONDS_TO_MICROSECONDS,
                request.receiveResponse ? (request.receiveResponse.ts - endRedirectTime) : null,
            ])) :
            (request.receiveResponse ? Micro(request.receiveResponse.ts - startTime) : Micro(0));
        const sendStartTime = timing ?
            Micro(timing.requestTime * SECONDS_TO_MICROSECONDS + timing.sendStart * MILLISECONDS_TO_MICROSECONDS) :
            startTime;
        const waiting = timing ?
            Micro((timing.receiveHeadersEnd - timing.sendEnd) * MILLISECONDS_TO_MICROSECONDS) :
            Micro(0);
        const serverResponseTime = timing ?
            Micro(((timing.receiveHeadersStart ?? timing.receiveHeadersEnd) - timing.sendEnd) *
                MILLISECONDS_TO_MICROSECONDS) :
            Micro(0);
        const downloadStart = timing ?
            Micro(timing.requestTime * SECONDS_TO_MICROSECONDS + timing.receiveHeadersEnd * MILLISECONDS_TO_MICROSECONDS) :
            startTime;
        const download = timing ? Micro(((finishTime || downloadStart) - downloadStart)) :
            request.receiveResponse ? Micro(endTime - request.receiveResponse.ts) :
                Micro(0);
        const totalTime = Micro(networkDuration + processingDuration);
        const dnsLookup = timing ? Micro((timing.dnsEnd - timing.dnsStart) * MILLISECONDS_TO_MICROSECONDS) :
            Micro(0);
        const ssl = timing ? Micro((timing.sslEnd - timing.sslStart) * MILLISECONDS_TO_MICROSECONDS) :
            Micro(0);
        const proxyNegotiation = timing ?
            Micro((timing.proxyEnd - timing.proxyStart) * MILLISECONDS_TO_MICROSECONDS) :
            Micro(0);
        const requestSent = timing ?
            Micro((timing.sendEnd - timing.sendStart) * MILLISECONDS_TO_MICROSECONDS) :
            Micro(0);
        const initialConnection = timing ?
            Micro((timing.connectEnd - timing.connectStart) * MILLISECONDS_TO_MICROSECONDS) :
            Micro(0);
        const { frame, url, renderBlocking: sendRequestIsRenderBlocking } = finalSendRequest.args.data;
        const { encodedDataLength, decodedBodyLength } = request.resourceFinish ? request.resourceFinish.args.data : { encodedDataLength: 0, decodedBodyLength: 0 };
        const parsedUrl = new URL(url);
        const isHttps = parsedUrl.protocol === 'https:';
        const requestingFrameUrl = activeURLForFrameAtTime(frame, finalSendRequest.ts, rendererProcessesByFrame) || '';
        const preloadRenderBlockingStatusChange = request.preloadRenderBlockingStatusChange?.at(-1)?.args.data.renderBlocking;
        const isRenderBlocking = preloadRenderBlockingStatusChange ?? sendRequestIsRenderBlocking ?? 'non_blocking';
        const networkEvent = SyntheticEventsManager.registerSyntheticEvent({
            rawSourceEvent: finalSendRequest,
            args: {
                data: {
                    syntheticData: {
                        dnsLookup,
                        download,
                        downloadStart,
                        finishTime,
                        initialConnection,
                        isDiskCached,
                        isHttps,
                        isMemoryCached,
                        isPushedResource,
                        networkDuration,
                        processingDuration,
                        proxyNegotiation,
                        queueing,
                        redirectionDuration,
                        requestSent,
                        sendStartTime,
                        ssl,
                        stalled,
                        totalTime,
                        waiting,
                        serverResponseTime,
                    },
                    decodedBodyLength,
                    encodedDataLength,
                    frame,
                    fromServiceWorker: request.receiveResponse?.args.data.fromServiceWorker,
                    isLinkPreload: finalSendRequest.args.data.isLinkPreload || false,
                    mimeType: request.receiveResponse?.args.data.mimeType ?? '',
                    priority: finalPriority,
                    initialPriority,
                    protocol: request.receiveResponse?.args.data.protocol ?? 'unknown',
                    redirects,
                    renderBlocking: isRenderBlocking,
                    requestId,
                    requestingFrameUrl,
                    requestMethod: finalSendRequest.args.data.requestMethod,
                    resourceType: finalSendRequest.args.data.resourceType ?? "Other" ,
                    statusCode: request.receiveResponse?.args.data.statusCode ?? 0,
                    responseHeaders: request.receiveResponse?.args.data.headers ?? null,
                    fetchPriorityHint: finalSendRequest.args.data.fetchPriorityHint ?? 'auto',
                    initiator: finalSendRequest.args.data.initiator,
                    stackTrace: finalSendRequest.args.data.stackTrace,
                    timing,
                    lrServerResponseTime,
                    url,
                    failed: request.resourceFinish?.args.data.didFail ?? false,
                    finished: Boolean(request.resourceFinish),
                    hasResponse: Boolean(request.receiveResponse),
                    connectionId: request.receiveResponse?.args.data.connectionId,
                    connectionReused: request.receiveResponse?.args.data.connectionReused,
                },
            },
            cat: 'loading',
            name: "SyntheticNetworkRequest" ,
            ph: "X" ,
            dur: Micro(endTime - startTime),
            tdur: Micro(endTime - startTime),
            ts: Micro(startTime),
            tts: Micro(startTime),
            pid: finalSendRequest.pid,
            tid: finalSendRequest.tid,
        });
        requestsByTime.push(networkEvent);
        requestsById.set(networkEvent.args.data.requestId, networkEvent);
        const requestsForUrl = requestIdsByURL.get(networkEvent.args.data.url) ?? [];
        requestsForUrl.push(networkEvent.args.data.requestId);
        requestIdsByURL.set(networkEvent.args.data.url, requestsForUrl);
        addNetworkRequestToEntityMapping(networkEvent, entityMappings$1, request);
        const initiatorUrl = networkEvent.args.data.initiator?.url ||
            getStackTraceTopCallFrameInEventPayload(networkEvent)?.url;
        if (initiatorUrl) {
            const events = networkRequestEventByInitiatorUrl.get(initiatorUrl) ?? [];
            events.push(networkEvent);
            networkRequestEventByInitiatorUrl.set(initiatorUrl, events);
        }
    }
    for (const request of requestsByTime) {
        const initiatedEvents = networkRequestEventByInitiatorUrl.get(request.args.data.url);
        if (initiatedEvents) {
            for (const initiatedEvent of initiatedEvents) {
                eventToInitiatorMap$1.set(initiatedEvent, request);
            }
        }
    }
    finalizeWebSocketData();
}
function data$o() {
    return {
        byId: requestsById,
        byTime: requestsByTime,
        requestIdsByURL,
        incompleteInitiator: eventToInitiatorMap$1,
        webSocket: [...webSocketData.values()],
        entityMappings: {
            entityByEvent: entityMappings$1.entityByEvent,
            eventsByEntity: entityMappings$1.eventsByEntity,
            createdEntityCache: entityMappings$1.createdEntityCache,
            entityByUrlCache: entityMappings$1.entityByUrlCache,
        },
        linkPreconnectEvents,
    };
}
function deps$e() {
    return ['Meta'];
}
function finalizeWebSocketData() {
    webSocketData.forEach(data => {
        let startEvent = null;
        let endEvent = null;
        for (const event of data.events) {
            if (isWebSocketCreate(event)) {
                startEvent = event;
            }
            if (isWebSocketDestroy(event)) {
                endEvent = event;
            }
        }
        data.syntheticConnection = createSyntheticWebSocketConnection(startEvent, endEvent, data.events[0]);
    });
}
function createSyntheticWebSocketConnection(startEvent, endEvent, firstRecordedEvent) {
    const { traceBounds } = data$p();
    const startTs = startEvent ? startEvent.ts : traceBounds.min;
    const endTs = endEvent ? endEvent.ts : traceBounds.max;
    const duration = endTs - startTs;
    const mainEvent = startEvent || endEvent || firstRecordedEvent;
    return {
        name: 'SyntheticWebSocketConnection',
        cat: mainEvent.cat,
        ph: "X" ,
        ts: startTs,
        dur: duration,
        pid: mainEvent.pid,
        tid: mainEvent.tid,
        s: mainEvent.s,
        rawSourceEvent: mainEvent,
        _tag: 'SyntheticEntryTag',
        args: {
            data: {
                identifier: mainEvent.args.data.identifier,
                priority: "Low" ,
                url: mainEvent.args.data.url || '',
            },
        },
    };
}

var NetworkRequestsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$o,
	deps: deps$e,
	finalize: finalize$G,
	handleEvent: handleEvent$o,
	reset: reset$o
});

// Copyright 2016 The Chromium Authors
class ProfileNode {
    callFrame;
    callUID;
    self;
    total;
    id;
    parent;
    children;
    originalFunctionName = null;
    depth;
    deoptReason;
    constructor(callFrame) {
        this.callFrame = callFrame;
        this.callUID = `${callFrame.functionName}@${callFrame.scriptId}:${callFrame.lineNumber}:${callFrame.columnNumber}`;
        this.self = 0;
        this.total = 0;
        this.id = 0;
        this.parent = null;
        this.children = [];
    }
    get scriptId() {
        return String(this.callFrame.scriptId);
    }
    get url() {
        return this.callFrame.url;
    }
    get lineNumber() {
        return this.callFrame.lineNumber;
    }
    get columnNumber() {
        return this.callFrame.columnNumber;
    }
    get functionName() {
        return this.originalFunctionName ?? this.callFrame.functionName;
    }
    setOriginalFunctionName(name) {
        this.originalFunctionName = name;
    }
}
class ProfileTreeModel {
    root;
    total;
    maxDepth;
    initialize(root) {
        this.root = root;
        this.assignDepthsAndParents();
        this.total = this.calculateTotals(this.root);
    }
    assignDepthsAndParents() {
        const root = this.root;
        root.depth = -1;
        root.parent = null;
        this.maxDepth = 0;
        const nodesToTraverse = [root];
        while (nodesToTraverse.length) {
            const parent = nodesToTraverse.pop();
            const depth = parent.depth + 1;
            if (depth > this.maxDepth) {
                this.maxDepth = depth;
            }
            const children = parent.children;
            for (const child of children) {
                child.depth = depth;
                child.parent = parent;
                nodesToTraverse.push(child);
            }
        }
    }
    calculateTotals(root) {
        const nodesToTraverse = [root];
        const dfsList = [];
        while (nodesToTraverse.length) {
            const node = nodesToTraverse.pop();
            node.total = node.self;
            dfsList.push(node);
            nodesToTraverse.push(...node.children);
        }
        while (dfsList.length > 1) {
            const node = dfsList.pop();
            if (node.parent) {
                node.parent.total += node.total;
            }
        }
        return root.total;
    }
}

// Copyright 2014 The Chromium Authors
class CPUProfileNode extends ProfileNode {
    id;
    self;
    positionTicks;
    deoptReason;
    constructor(node, samplingInterval ) {
        const callFrame = node.callFrame || {
            functionName: node['functionName'],
            scriptId: node['scriptId'],
            url: node['url'],
            lineNumber: node['lineNumber'] - 1,
            columnNumber: node['columnNumber'] - 1,
        };
        super(callFrame);
        this.id = node.id;
        this.self = (node.hitCount || 0) * samplingInterval;
        this.positionTicks = node.positionTicks;
        this.deoptReason = node.deoptReason && node.deoptReason !== 'no reason' ? node.deoptReason : null;
    }
}
class CPUProfileDataModel extends ProfileTreeModel {
    profileStartTime;
    profileEndTime;
    timestamps;
    samples;
    traceIds;
    lines;
    columns;
    totalHitCount;
    profileHead;
    #idToParsedNode;
    gcNode;
    programNode;
    idleNode;
    #stackStartTimes;
    #stackChildrenDuration;
    constructor(profile) {
        super();
        const isLegacyFormat = Boolean(profile['head']);
        if (isLegacyFormat) {
            this.profileStartTime = profile.startTime * 1000;
            this.profileEndTime = profile.endTime * 1000;
            this.timestamps = profile.timestamps;
            this.compatibilityConversionHeadToNodes(profile);
        }
        else {
            this.profileStartTime = profile.startTime / 1000;
            this.profileEndTime = profile.endTime / 1000;
            this.timestamps = this.convertTimeDeltas(profile);
        }
        this.traceIds = profile.traceIds;
        this.samples = profile.samples;
        this.lines = profile.lines;
        this.columns = profile.columns;
        this.totalHitCount = 0;
        this.profileHead = this.translateProfileTree(profile.nodes);
        this.initialize(this.profileHead);
        this.extractMetaNodes();
        if (this.samples?.length) {
            this.sortSamples();
            this.normalizeTimestamps();
            this.fixMissingSamples();
        }
    }
    compatibilityConversionHeadToNodes(profile) {
        if (!profile.head || profile.nodes) {
            return;
        }
        const nodes = [];
        convertNodesTree(profile.head);
        profile.nodes = nodes;
        delete profile.head;
        function convertNodesTree(node) {
            nodes.push(node);
            node.children = node.children.map(convertNodesTree);
            return node.id;
        }
    }
    convertTimeDeltas(profile) {
        if (!profile.timeDeltas) {
            return [];
        }
        let lastTimeMicroSec = profile.startTime;
        const timestamps = new Array(profile.timeDeltas.length);
        for (let i = 0; i < profile.timeDeltas.length; ++i) {
            lastTimeMicroSec += profile.timeDeltas[i];
            timestamps[i] = lastTimeMicroSec;
        }
        return timestamps;
    }
    translateProfileTree(nodes) {
        function buildChildrenFromParents(nodes) {
            if (nodes[0].children) {
                return;
            }
            nodes[0].children = [];
            for (let i = 1; i < nodes.length; ++i) {
                const node = nodes[i];
                const parentNode = protocolNodeById.get(node.parent);
                if (!parentNode) {
                    continue;
                }
                if (parentNode.children) {
                    parentNode.children.push(node.id);
                }
                else {
                    parentNode.children = [node.id];
                }
            }
        }
        function buildHitCountFromSamples(nodes, samples) {
            if (typeof (nodes[0].hitCount) === 'number') {
                return;
            }
            if (!samples) {
                throw new Error('Error: Neither hitCount nor samples are present in profile.');
            }
            for (let i = 0; i < nodes.length; ++i) {
                nodes[i].hitCount = 0;
            }
            for (let i = 0; i < samples.length; ++i) {
                const node = protocolNodeById.get(samples[i]);
                if (node?.hitCount === undefined) {
                    continue;
                }
                node.hitCount++;
            }
        }
        const protocolNodeById = new Map();
        for (let i = 0; i < nodes.length; ++i) {
            const node = nodes[i];
            protocolNodeById.set(node.id, node);
        }
        buildHitCountFromSamples(nodes, this.samples);
        buildChildrenFromParents(nodes);
        this.totalHitCount = nodes.reduce((acc, node) => acc + (node.hitCount || 0), 0);
        const sampleTime = (this.profileEndTime - this.profileStartTime) / this.totalHitCount;
        const root = nodes[0];
        const idToUseForRemovedNode = new Map([[root.id, root.id]]);
        this.#idToParsedNode = new Map();
        const resultRoot = new CPUProfileNode(root, sampleTime);
        this.#idToParsedNode.set(root.id, resultRoot);
        if (!root.children) {
            throw new Error('Missing children for root');
        }
        const parentNodeStack = root.children.map(() => resultRoot);
        const sourceNodeStack = root.children.map(id => protocolNodeById.get(id));
        while (sourceNodeStack.length) {
            let parentNode = parentNodeStack.pop();
            const sourceNode = sourceNodeStack.pop();
            if (!sourceNode || !parentNode) {
                continue;
            }
            if (!sourceNode.children) {
                sourceNode.children = [];
            }
            const targetNode = new CPUProfileNode(sourceNode, sampleTime);
            parentNode.children.push(targetNode);
            parentNode = targetNode;
            idToUseForRemovedNode.set(sourceNode.id, parentNode.id);
            parentNodeStack.push.apply(parentNodeStack, sourceNode.children.map(() => parentNode));
            sourceNodeStack.push.apply(sourceNodeStack, sourceNode.children.map(id => protocolNodeById.get(id)));
            this.#idToParsedNode.set(sourceNode.id, targetNode);
        }
        if (this.samples) {
            this.samples = this.samples.map(id => idToUseForRemovedNode.get(id));
        }
        return resultRoot;
    }
    sortSamples() {
        if (!this.timestamps || !this.samples) {
            return;
        }
        const timestamps = this.timestamps;
        const samples = this.samples;
        const orderedIndices = timestamps.map((_x, index) => index);
        orderedIndices.sort((a, b) => timestamps[a] - timestamps[b]);
        this.timestamps = [];
        this.samples = [];
        for (let i = 0; i < orderedIndices.length; i++) {
            const orderedIndex = orderedIndices[i];
            this.timestamps.push(timestamps[orderedIndex]);
            this.samples.push(samples[orderedIndex]);
        }
    }
    normalizeTimestamps() {
        if (!this.samples) {
            return;
        }
        let timestamps = this.timestamps;
        if (!timestamps) {
            const profileStartTime = this.profileStartTime;
            const interval = (this.profileEndTime - profileStartTime) / this.samples.length;
            timestamps = new Array(this.samples.length + 1);
            for (let i = 0; i < timestamps.length; ++i) {
                timestamps[i] = profileStartTime + i * interval;
            }
            this.timestamps = timestamps;
            return;
        }
        for (let i = 0; i < timestamps.length; ++i) {
            timestamps[i] /= 1000;
        }
        if (this.samples.length === timestamps.length) {
            const lastTimestamp = timestamps.at(-1) || 0;
            const averageIntervalTime = (lastTimestamp - timestamps[0]) / (timestamps.length - 1);
            this.timestamps.push(lastTimestamp + averageIntervalTime);
        }
        this.profileStartTime = timestamps.at(0) || this.profileStartTime;
        this.profileEndTime = timestamps.at(-1) || this.profileEndTime;
    }
    extractMetaNodes() {
        const topLevelNodes = this.profileHead.children;
        for (let i = 0; i < topLevelNodes.length && !(this.gcNode && this.programNode && this.idleNode); i++) {
            const node = topLevelNodes[i];
            if (node.functionName === '(garbage collector)') {
                this.gcNode = node;
            }
            else if (node.functionName === '(program)') {
                this.programNode = node;
            }
            else if (node.functionName === '(idle)') {
                this.idleNode = node;
            }
        }
    }
    fixMissingSamples() {
        const samples = this.samples;
        if (!samples) {
            return;
        }
        const samplesCount = samples.length;
        if (!this.programNode || samplesCount < 3) {
            return;
        }
        const idToNode = this.#idToParsedNode;
        const programNodeId = this.programNode.id;
        const gcNodeId = this.gcNode ? this.gcNode.id : -1;
        const idleNodeId = this.idleNode ? this.idleNode.id : -1;
        let prevNodeId = samples[0];
        let nodeId = samples[1];
        for (let sampleIndex = 1; sampleIndex < samplesCount - 1; sampleIndex++) {
            const nextNodeId = samples[sampleIndex + 1];
            const prevNode = idToNode.get(prevNodeId);
            const nextNode = idToNode.get(nextNodeId);
            if (prevNodeId === undefined || nextNodeId === undefined || !prevNode || !nextNode) {
                console.error(`Unexpectedly found undefined nodes: ${prevNodeId} ${nextNodeId}`);
                continue;
            }
            if (nodeId === programNodeId && !isSystemNode(prevNodeId) && !isSystemNode(nextNodeId) &&
                bottomNode(prevNode) === bottomNode(nextNode)) {
                samples[sampleIndex] = prevNodeId;
            }
            prevNodeId = nodeId;
            nodeId = nextNodeId;
        }
        function bottomNode(node) {
            while (node.parent?.parent) {
                node = node.parent;
            }
            return node;
        }
        function isSystemNode(nodeId) {
            return nodeId === programNodeId || nodeId === gcNodeId || nodeId === idleNodeId;
        }
    }
    forEachFrame(openFrameCallback, closeFrameCallback, startTime, stopTime) {
        if (!this.profileHead || !this.samples) {
            return;
        }
        startTime = startTime || 0;
        stopTime = stopTime || Infinity;
        const samples = this.samples;
        const timestamps = this.timestamps;
        const idToNode = this.#idToParsedNode;
        const gcNode = this.gcNode;
        const samplesCount = samples.length;
        const startIndex = lowerBound(timestamps, startTime, DEFAULT_COMPARATOR);
        let stackTop = 0;
        const stackNodes = [];
        let prevId = this.profileHead.id;
        let sampleTime;
        let gcParentNode = null;
        const stackDepth = this.maxDepth + 3;
        if (!this.#stackStartTimes) {
            this.#stackStartTimes = new Array(stackDepth);
        }
        const stackStartTimes = this.#stackStartTimes;
        if (!this.#stackChildrenDuration) {
            this.#stackChildrenDuration = new Array(stackDepth);
        }
        const stackChildrenDuration = this.#stackChildrenDuration;
        let node;
        let sampleIndex;
        for (sampleIndex = startIndex; sampleIndex < samplesCount; sampleIndex++) {
            sampleTime = timestamps[sampleIndex];
            if (sampleTime >= stopTime) {
                break;
            }
            const id = samples[sampleIndex];
            if (id === prevId) {
                continue;
            }
            node = idToNode.get(id);
            let prevNode = idToNode.get(prevId) || null;
            if (!prevNode) {
                continue;
            }
            if (gcNode && node === gcNode) {
                gcParentNode = prevNode;
                openFrameCallback(gcParentNode.depth + 1, gcNode, sampleIndex, sampleTime);
                stackStartTimes[++stackTop] = sampleTime;
                stackChildrenDuration[stackTop] = 0;
                prevId = id;
                continue;
            }
            if (gcNode && prevNode === gcNode && gcParentNode) {
                const start = stackStartTimes[stackTop];
                const duration = sampleTime - start;
                stackChildrenDuration[stackTop - 1] += duration;
                closeFrameCallback(gcParentNode.depth + 1, gcNode, sampleIndex, start, duration, duration - stackChildrenDuration[stackTop]);
                --stackTop;
                prevNode = gcParentNode;
                prevId = prevNode.id;
                gcParentNode = null;
            }
            while (node && node.depth > prevNode.depth) {
                stackNodes.push(node);
                node = node.parent;
            }
            while (prevNode && prevNode !== node) {
                const start = stackStartTimes[stackTop];
                const duration = sampleTime - start;
                stackChildrenDuration[stackTop - 1] += duration;
                closeFrameCallback(prevNode.depth, prevNode, sampleIndex, start, duration, duration - stackChildrenDuration[stackTop]);
                --stackTop;
                if (node && node.depth === prevNode.depth) {
                    stackNodes.push(node);
                    node = node.parent;
                }
                prevNode = prevNode.parent;
            }
            while (stackNodes.length) {
                const currentNode = stackNodes.pop();
                if (!currentNode) {
                    break;
                }
                node = currentNode;
                openFrameCallback(currentNode.depth, currentNode, sampleIndex, sampleTime);
                stackStartTimes[++stackTop] = sampleTime;
                stackChildrenDuration[stackTop] = 0;
            }
            prevId = id;
        }
        sampleTime = timestamps[sampleIndex] || this.profileEndTime;
        if (node && gcParentNode && idToNode.get(prevId) === gcNode) {
            const start = stackStartTimes[stackTop];
            const duration = sampleTime - start;
            stackChildrenDuration[stackTop - 1] += duration;
            closeFrameCallback(gcParentNode.depth + 1, node, sampleIndex, start, duration, duration - stackChildrenDuration[stackTop]);
            --stackTop;
            prevId = gcParentNode.id;
        }
        for (let node = idToNode.get(prevId); node?.parent; node = node.parent) {
            const start = stackStartTimes[stackTop];
            const duration = sampleTime - start;
            stackChildrenDuration[stackTop - 1] += duration;
            closeFrameCallback(node.depth, node, sampleIndex, start, duration, duration - stackChildrenDuration[stackTop]);
            --stackTop;
        }
    }
    nodeByIndex(index) {
        return this.samples && this.#idToParsedNode.get(this.samples[index]) || null;
    }
    nodeById(nodeId) {
        return this.#idToParsedNode.get(nodeId) || null;
    }
    nodes() {
        if (!this.#idToParsedNode) {
            return null;
        }
        return [...this.#idToParsedNode.values()];
    }
}

// Copyright 2022 The Chromium Authors
let profilesInProcess = new Map();
let entryToNode$2 = new Map();
let preprocessedData = new Map();
const PROFILE_SOURCES_BY_PRIORITY = {
    cpuProfile: ['Inspector'],
    performanceTrace: ['Internal', 'Inspector'],
};
function parseCPUProfileData(parseOptions) {
    const priorityList = parseOptions.isCPUProfile ? PROFILE_SOURCES_BY_PRIORITY.cpuProfile : PROFILE_SOURCES_BY_PRIORITY.performanceTrace;
    for (const [processId, profiles] of preprocessedData) {
        const profilesByThread = new Map();
        for (const [profileId, preProcessedData] of profiles) {
            const threadId = preProcessedData.threadId;
            if (threadId === undefined) {
                continue;
            }
            const listForThread = getWithDefault(profilesByThread, threadId, () => []);
            listForThread.push({ id: profileId, data: preProcessedData });
        }
        for (const [threadId, candidates] of profilesByThread) {
            if (!candidates.length) {
                continue;
            }
            let chosen = candidates[0];
            for (const source of priorityList) {
                const match = candidates.find(p => p.data.source === source);
                if (match) {
                    chosen = match;
                    break;
                }
            }
            const chosenData = chosen.data;
            if (!chosenData.rawProfile.nodes.length) {
                continue;
            }
            const indexStack = [];
            const profileModel = new CPUProfileDataModel(chosenData.rawProfile);
            const profileTree = makeEmptyTraceEntryTree();
            profileTree.maxDepth = profileModel.maxDepth;
            const selectedProfileId = chosen.id;
            const finalizedData = {
                rawProfile: chosenData.rawProfile,
                parsedProfile: profileModel,
                profileCalls: [],
                profileTree,
                profileId: selectedProfileId,
            };
            const dataByThread = getWithDefault(profilesInProcess, processId, () => new Map());
            dataByThread.set(threadId, finalizedData);
            if (parseOptions.isCPUProfile) {
                buildProfileCallsForCPUProfile();
            }
            function buildProfileCallsForCPUProfile() {
                profileModel.forEachFrame(openFrameCallback, closeFrameCallback);
                function openFrameCallback(depth, node, sampleIndex, timeStampMilliseconds) {
                    if (threadId === undefined) {
                        return;
                    }
                    const ts = milliToMicro(Milli(timeStampMilliseconds));
                    const nodeId = node.id;
                    const profileCall = makeProfileCall(node, selectedProfileId, sampleIndex, ts, processId, threadId);
                    finalizedData.profileCalls.push(profileCall);
                    indexStack.push(finalizedData.profileCalls.length - 1);
                    const traceEntryNode = makeEmptyTraceEntryNode(profileCall, nodeId);
                    entryToNode$2.set(profileCall, traceEntryNode);
                    traceEntryNode.depth = depth;
                    if (indexStack.length === 1) {
                        finalizedData.profileTree?.roots.add(traceEntryNode);
                    }
                }
                function closeFrameCallback(_depth, _node, _sampleIndex, _timeStampMillis, durMs, selfTimeMs) {
                    const profileCallIndex = indexStack.pop();
                    const profileCall = profileCallIndex !== undefined && finalizedData.profileCalls[profileCallIndex];
                    if (!profileCall) {
                        return;
                    }
                    const { callFrame, ts, pid, tid } = profileCall;
                    const traceEntryNode = entryToNode$2.get(profileCall);
                    if (callFrame === undefined || ts === undefined || pid === undefined || selectedProfileId === undefined ||
                        tid === undefined || traceEntryNode === undefined) {
                        return;
                    }
                    const dur = milliToMicro(Milli(durMs));
                    const selfTime = milliToMicro(Milli(selfTimeMs));
                    profileCall.dur = dur;
                    traceEntryNode.selfTime = selfTime;
                    const parentIndex = indexStack.at(-1);
                    const parent = parentIndex !== undefined && finalizedData.profileCalls.at(parentIndex);
                    const parentNode = parent && entryToNode$2.get(parent);
                    if (!parentNode) {
                        return;
                    }
                    traceEntryNode.parent = parentNode;
                    parentNode.children.push(traceEntryNode);
                }
            }
        }
    }
}
function reset$n() {
    preprocessedData = new Map();
    profilesInProcess = new Map();
    entryToNode$2 = new Map();
}
function handleEvent$n(event) {
    if (isSyntheticCpuProfile(event)) {
        const profileData = getOrCreatePreProcessedData(event.pid, event.id);
        profileData.rawProfile = event.args.data.cpuProfile;
        profileData.threadId = event.tid;
        return;
    }
    if (isProfile(event)) {
        const profileData = getOrCreatePreProcessedData(event.pid, event.id);
        profileData.rawProfile.startTime = event.ts;
        profileData.threadId = event.tid;
        assignProfileSourceIfKnown(profileData, event.args?.data?.source);
        return;
    }
    if (isProfileChunk(event)) {
        const profileData = getOrCreatePreProcessedData(event.pid, event.id);
        const cdpProfile = profileData.rawProfile;
        const nodesAndSamples = event.args?.data?.cpuProfile || { samples: [] };
        const samples = nodesAndSamples?.samples || [];
        const traceIds = event.args?.data?.cpuProfile?.trace_ids;
        for (const n of nodesAndSamples?.nodes || []) {
            const lineNumber = typeof n.callFrame.lineNumber === 'undefined' ? -1 : n.callFrame.lineNumber;
            const columnNumber = typeof n.callFrame.columnNumber === 'undefined' ? -1 : n.callFrame.columnNumber;
            const scriptId = String(n.callFrame.scriptId);
            const url = n.callFrame.url || '';
            const node = {
                ...n,
                callFrame: {
                    ...n.callFrame,
                    url,
                    lineNumber,
                    columnNumber,
                    scriptId,
                },
            };
            cdpProfile.nodes.push(node);
        }
        const timeDeltas = event.args.data?.timeDeltas || [];
        const lines = event.args.data?.lines || Array(samples.length).fill(0);
        const columns = event.args.data?.columns || Array(samples.length).fill(0);
        cdpProfile.samples?.push(...samples);
        cdpProfile.timeDeltas?.push(...timeDeltas);
        cdpProfile.lines?.push(...lines);
        cdpProfile.columns?.push(...columns);
        if (traceIds) {
            cdpProfile.traceIds ??= {};
            for (const key in traceIds) {
                cdpProfile.traceIds[key] = traceIds[key];
            }
        }
        if (cdpProfile.samples && cdpProfile.timeDeltas && cdpProfile.samples.length !== cdpProfile.timeDeltas.length) {
            console.error('Failed to parse CPU profile.');
            return;
        }
        if (!cdpProfile.endTime && cdpProfile.timeDeltas) {
            const timeDeltas = cdpProfile.timeDeltas;
            cdpProfile.endTime = timeDeltas.reduce((x, y) => x + y, cdpProfile.startTime);
        }
        assignProfileSourceIfKnown(profileData, event.args?.data?.source);
        return;
    }
}
async function finalize$F(parseOptions = {}) {
    parseCPUProfileData(parseOptions);
}
function assignProfileSourceIfKnown(profileData, source) {
    if (VALID_PROFILE_SOURCES.includes(source)) {
        profileData.source = source;
    }
}
function data$n() {
    return {
        profilesInProcess,
        entryToNode: entryToNode$2,
    };
}
function getOrCreatePreProcessedData(processId, profileId) {
    const profileById = getWithDefault(preprocessedData, processId, () => new Map());
    return getWithDefault(profileById, profileId, () => ({
        rawProfile: {
            startTime: 0,
            endTime: 0,
            nodes: [],
            samples: [],
            timeDeltas: [],
            lines: [],
            columns: [],
        },
        profileId,
    }));
}
function getProfileCallFunctionName(data, entry) {
    const profile = data.profilesInProcess.get(entry.pid)?.get(entry.tid);
    const node = profile?.parsedProfile.nodeById(entry.nodeId);
    if (node?.functionName) {
        return node.functionName;
    }
    return entry.callFrame.functionName;
}

var SamplesHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$n,
	finalize: finalize$F,
	getProfileCallFunctionName: getProfileCallFunctionName,
	handleEvent: handleEvent$n,
	reset: reset$n
});

// Copyright 2022 The Chromium Authors
let processes = new Map();
let entityMappings = {
    eventsByEntity: new Map(),
    entityByEvent: new Map(),
    createdEntityCache: new Map(),
    entityByUrlCache: new Map(),
};
let compositorTileWorkers = Array();
let entryToNode$1 = new Map();
let completeEventStack = [];
let config = defaults();
const makeRendererProcess = () => ({
    url: null,
    isOnMainFrame: false,
    threads: new Map(),
});
const makeRendererThread = () => ({
    name: null,
    entries: [],
    profileCalls: [],
    layoutEvents: [],
    recalcStyleEvents: [],
});
const getOrCreateRendererProcess = (processes, pid) => {
    return getWithDefault(processes, pid, makeRendererProcess);
};
const getOrCreateRendererThread = (process, tid) => {
    return getWithDefault(process.threads, tid, makeRendererThread);
};
function handleUserConfig$1(userConfig) {
    config = userConfig;
}
function reset$m() {
    processes = new Map();
    entryToNode$1 = new Map();
    entityMappings = {
        eventsByEntity: new Map(),
        entityByEvent: new Map(),
        createdEntityCache: new Map(),
        entityByUrlCache: new Map(),
    };
    completeEventStack = [];
    compositorTileWorkers = [];
}
function handleEvent$m(event) {
    if (isThreadName(event) && event.args.name?.startsWith('CompositorTileWorker')) {
        compositorTileWorkers.push({
            pid: event.pid,
            tid: event.tid,
        });
    }
    if (isBegin(event) || isEnd(event)) {
        const process = getOrCreateRendererProcess(processes, event.pid);
        const thread = getOrCreateRendererThread(process, event.tid);
        const completeEvent = makeCompleteEvent(event);
        if (!completeEvent) {
            return;
        }
        thread.entries.push(completeEvent);
        return;
    }
    if (isInstant(event) || isComplete(event)) {
        const process = getOrCreateRendererProcess(processes, event.pid);
        const thread = getOrCreateRendererThread(process, event.tid);
        thread.entries.push(event);
    }
    if (isLayout(event)) {
        const process = getOrCreateRendererProcess(processes, event.pid);
        const thread = getOrCreateRendererThread(process, event.tid);
        thread.layoutEvents.push(event);
    }
    if (isRecalcStyle(event)) {
        const process = getOrCreateRendererProcess(processes, event.pid);
        const thread = getOrCreateRendererThread(process, event.tid);
        thread.recalcStyleEvents.push(event);
    }
}
async function finalize$E() {
    const { mainFrameId, rendererProcessesByFrame, threadsInProcess } = data$p();
    entityMappings = data$o().entityMappings;
    assignMeta(processes, mainFrameId, rendererProcessesByFrame, threadsInProcess);
    sanitizeProcesses(processes);
    buildHierarchy(processes);
    sanitizeThreads(processes);
}
function data$m() {
    return {
        processes,
        compositorTileWorkers: gatherCompositorThreads(),
        entryToNode: entryToNode$1,
        entityMappings: {
            entityByEvent: entityMappings.entityByEvent,
            eventsByEntity: entityMappings.eventsByEntity,
            createdEntityCache: entityMappings.createdEntityCache,
            entityByUrlCache: entityMappings.entityByUrlCache,
        },
    };
}
function gatherCompositorThreads() {
    const threadsByProcess = new Map();
    for (const worker of compositorTileWorkers) {
        const byProcess = threadsByProcess.get(worker.pid) || [];
        byProcess.push(worker.tid);
        threadsByProcess.set(worker.pid, byProcess);
    }
    return threadsByProcess;
}
function assignMeta(processes, mainFrameId, rendererProcessesByFrame, threadsInProcess) {
    assignOrigin(processes, rendererProcessesByFrame);
    assignIsMainFrame(processes, mainFrameId, rendererProcessesByFrame);
    assignThreadName(processes, threadsInProcess);
}
function assignOrigin(processes, rendererProcessesByFrame) {
    for (const renderProcessesByPid of rendererProcessesByFrame.values()) {
        for (const [pid, processWindows] of renderProcessesByPid) {
            for (const processInfo of processWindows.flat()) {
                const process = getOrCreateRendererProcess(processes, pid);
                if (process.url === null || process.url === 'about:blank') {
                    try {
                        new URL(processInfo.frame.url);
                        process.url = processInfo.frame.url;
                    }
                    catch {
                        process.url = null;
                    }
                }
            }
        }
    }
}
function assignIsMainFrame(processes, mainFrameId, rendererProcessesByFrame) {
    for (const [frameId, renderProcessesByPid] of rendererProcessesByFrame) {
        for (const [pid] of renderProcessesByPid) {
            const process = getOrCreateRendererProcess(processes, pid);
            if (frameId === mainFrameId) {
                process.isOnMainFrame = true;
            }
        }
    }
}
function assignThreadName(processes, threadsInProcess) {
    for (const [pid, process] of processes) {
        for (const [tid, threadInfo] of threadsInProcess.get(pid) ?? []) {
            const thread = getOrCreateRendererThread(process, tid);
            thread.name = threadInfo?.args.name ?? `${tid}`;
        }
    }
}
function sanitizeProcesses(processes) {
    const auctionWorklets = data$q().worklets;
    const metaData = data$p();
    if (metaData.traceIsGeneric) {
        return;
    }
    for (const [pid, process] of processes) {
        if (process.url === null) {
            const maybeWorklet = auctionWorklets.get(pid);
            if (maybeWorklet) {
                process.url = maybeWorklet.host;
            }
            else {
                processes.delete(pid);
            }
            continue;
        }
    }
}
function sanitizeThreads(processes) {
    for (const [, process] of processes) {
        for (const [tid, thread] of process.threads) {
            if (!thread.tree?.roots.size) {
                process.threads.delete(tid);
            }
        }
    }
}
function buildHierarchy(processes, options) {
    const samplesData = data$n();
    for (const [pid, process] of processes) {
        for (const [tid, thread] of process.threads) {
            if (!thread.entries.length) {
                thread.tree = makeEmptyTraceEntryTree();
                continue;
            }
            sortTraceEventsInPlace(thread.entries);
            const samplesDataForThread = samplesData.profilesInProcess.get(pid)?.get(tid);
            if (samplesDataForThread) {
                const cpuProfile = samplesDataForThread.parsedProfile;
                const samplesIntegrator = cpuProfile &&
                    new SamplesIntegrator(cpuProfile, samplesDataForThread.profileId, pid, tid, config);
                const profileCalls = samplesIntegrator?.buildProfileCalls(thread.entries);
                if (samplesIntegrator && profileCalls) {
                    thread.entries = mergeEventsInOrder(thread.entries, profileCalls);
                    thread.profileCalls = profileCalls;
                    const jsSamples = samplesIntegrator.jsSampleEvents;
                    if (jsSamples.length) {
                        thread.entries = mergeEventsInOrder(thread.entries, jsSamples);
                    }
                }
            }
            const treeData = treify(thread.entries, options);
            thread.tree = treeData.tree;
            for (const [entry, node] of treeData.entryToNode) {
                entryToNode$1.set(entry, node);
                addEventToEntityMapping(entry, entityMappings);
            }
        }
    }
}
function makeCompleteEvent(event) {
    if (isEnd(event)) {
        const beginEvent = completeEventStack.pop();
        if (!beginEvent) {
            return null;
        }
        if (beginEvent.name !== event.name || beginEvent.cat !== event.cat) {
            console.error('Begin/End events mismatch at ' + beginEvent.ts + ' (' + beginEvent.name + ') vs. ' + event.ts + ' (' +
                event.name + ')');
            return null;
        }
        beginEvent.dur = Micro(event.ts - beginEvent.ts);
        return null;
    }
    const syntheticComplete = {
        ...event,
        ph: "X" ,
        dur: Micro(0),
    };
    completeEventStack.push(syntheticComplete);
    return syntheticComplete;
}
function deps$d() {
    return ['Meta', 'Samples', 'AuctionWorklets', 'NetworkRequests'];
}

var RendererHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	assignIsMainFrame: assignIsMainFrame,
	assignMeta: assignMeta,
	assignOrigin: assignOrigin,
	assignThreadName: assignThreadName,
	buildHierarchy: buildHierarchy,
	data: data$m,
	deps: deps$d,
	finalize: finalize$E,
	handleEvent: handleEvent$m,
	handleUserConfig: handleUserConfig$1,
	makeCompleteEvent: makeCompleteEvent,
	reset: reset$m,
	sanitizeProcesses: sanitizeProcesses,
	sanitizeThreads: sanitizeThreads
});

// Copyright 2024 The Chromium Authors
let schedulerToRunEntryPoints = new Map();
let taskScheduleForTaskRunEvent = new Map();
let asyncCallToScheduler = new Map();
let runEntryPointToScheduler = new Map();
function reset$l() {
    schedulerToRunEntryPoints = new Map();
    asyncCallToScheduler = new Map();
    taskScheduleForTaskRunEvent = new Map();
    runEntryPointToScheduler = new Map();
}
function handleEvent$l(_) {
}
async function finalize$D() {
    const { flows } = data$r();
    const { entryToNode } = data$m();
    for (const flow of flows) {
        let maybeAsyncTaskScheduled = flow.at(0);
        if (!maybeAsyncTaskScheduled) {
            continue;
        }
        if (isDebuggerAsyncTaskRun(maybeAsyncTaskScheduled)) {
            maybeAsyncTaskScheduled = taskScheduleForTaskRunEvent.get(maybeAsyncTaskScheduled);
        }
        if (!maybeAsyncTaskScheduled || !isDebuggerAsyncTaskScheduled(maybeAsyncTaskScheduled)) {
            continue;
        }
        const taskName = maybeAsyncTaskScheduled.args.taskName;
        const asyncTaskRun = flow.at(1);
        if (!asyncTaskRun || !isDebuggerAsyncTaskRun(asyncTaskRun)) {
            continue;
        }
        taskScheduleForTaskRunEvent.set(asyncTaskRun, maybeAsyncTaskScheduled);
        const asyncCaller = findNearestJSAncestor(maybeAsyncTaskScheduled, entryToNode);
        const asyncEntryPoint = findFirstJsInvocationForAsyncTaskRun(asyncTaskRun, entryToNode);
        runEntryPointToScheduler.set(asyncEntryPoint || asyncTaskRun, { taskName, scheduler: asyncCaller || maybeAsyncTaskScheduled });
        if (!asyncCaller || !asyncEntryPoint) {
            continue;
        }
        const entryPoints = getWithDefault(schedulerToRunEntryPoints, asyncCaller, () => []);
        entryPoints.push(asyncEntryPoint);
        const scheduledProfileCalls = findFirstJSCallsForAsyncTaskRun(asyncTaskRun, entryToNode);
        for (const call of scheduledProfileCalls) {
            asyncCallToScheduler.set(call, { taskName, scheduler: asyncCaller });
        }
    }
}
function findNearestJSAncestor(asyncTaskScheduled, entryToNode) {
    let node = entryToNode.get(asyncTaskScheduled)?.parent;
    while (node) {
        if (isProfileCall(node.entry) || acceptJSInvocationsPredicate(node.entry)) {
            return node.entry;
        }
        node = node.parent;
    }
    return null;
}
function acceptJSInvocationsPredicate(event) {
    const eventIsConsoleRunTask = isConsoleRunTask(event);
    const eventIsV8EntryPoint = event.name.startsWith('v8') || event.name.startsWith('V8');
    return isJSInvocationEvent(event) && (eventIsConsoleRunTask || !eventIsV8EntryPoint);
}
function findFirstJsInvocationForAsyncTaskRun(asyncTaskRun, entryToNode) {
    return findFirstDescendantsOfType(asyncTaskRun, entryToNode, acceptJSInvocationsPredicate, isDebuggerAsyncTaskRun)
        .at(0);
}
function findFirstJSCallsForAsyncTaskRun(asyncTaskRun, entryToNode) {
    return findFirstDescendantsOfType(asyncTaskRun, entryToNode, isProfileCall, isDebuggerAsyncTaskRun);
}
function findFirstDescendantsOfType(root, entryToNode, predicateAccept, predicateIgnore) {
    const node = entryToNode.get(root);
    if (!node) {
        return [];
    }
    const childrenGroups = [[...node.children]];
    const firstDescendants = [];
    for (let i = 0; i < childrenGroups.length; i++) {
        const siblings = childrenGroups[i];
        for (let j = 0; j < siblings.length; j++) {
            const node = siblings[j];
            if (predicateAccept(node.entry)) {
                firstDescendants.push(node.entry);
            }
            else if (!predicateIgnore(node.entry)) {
                childrenGroups.push([...node.children]);
            }
        }
    }
    return firstDescendants;
}
function data$l() {
    return {
        schedulerToRunEntryPoints,
        asyncCallToScheduler,
        runEntryPointToScheduler,
    };
}
function deps$c() {
    return ['Renderer', 'Flows'];
}

var AsyncJSCallsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$l,
	deps: deps$c,
	finalize: finalize$D,
	handleEvent: handleEvent$l,
	reset: reset$l
});

// Copyright 2025 The Chromium Authors
let domStatsByFrameId = new Map();
function reset$k() {
    domStatsByFrameId = new Map();
}
function handleEvent$k(event) {
    if (!isDOMStats(event)) {
        return;
    }
    const domStatEvents = getWithDefault(domStatsByFrameId, event.args.data.frame, () => []);
    domStatEvents.push(event);
}
async function finalize$C() {
}
function data$k() {
    return { domStatsByFrameId };
}

var DOMStatsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$k,
	finalize: finalize$C,
	handleEvent: handleEvent$k,
	reset: reset$k
});

// Copyright 2022 The Chromium Authors
let syntheticEvents = [];
let measureTraceByTraceId = new Map();
let performanceMeasureEvents = [];
let performanceMarkEvents = [];
let consoleTimings = [];
let timestampEvents = [];
function reset$j() {
    syntheticEvents = [];
    performanceMeasureEvents = [];
    performanceMarkEvents = [];
    consoleTimings = [];
    timestampEvents = [];
    measureTraceByTraceId = new Map();
}
const resourceTimingNames = [
    'workerStart',
    'redirectStart',
    'redirectEnd',
    'fetchStart',
    'domainLookupStart',
    'domainLookupEnd',
    'connectStart',
    'connectEnd',
    'secureConnectionStart',
    'requestStart',
    'responseStart',
    'responseEnd',
];
const navTimingNames = [
    'navigationStart',
    'unloadEventStart',
    'unloadEventEnd',
    'redirectStart',
    'redirectEnd',
    'fetchStart',
    'commitNavigationEnd',
    'domainLookupStart',
    'domainLookupEnd',
    'connectStart',
    'connectEnd',
    'secureConnectionStart',
    'requestStart',
    'responseStart',
    'responseEnd',
    'domLoading',
    'domInteractive',
    'domContentLoadedEventStart',
    'domContentLoadedEventEnd',
    'domComplete',
    'loadEventStart',
    'loadEventEnd',
];
const ignoredNames = [...resourceTimingNames, ...navTimingNames];
function getEventTimings(event) {
    if ('dur' in event) {
        return { start: event.ts, end: Micro(event.ts + (event.dur ?? 0)) };
    }
    if (isConsoleTimeStamp(event)) {
        const { start, end } = event.args.data || {};
        if (typeof start === 'number' && typeof end === 'number') {
            return { start: Micro(start), end: Micro(end) };
        }
    }
    return { start: event.ts, end: event.ts };
}
function getEventTrack(event) {
    if (event.cat === 'blink.user_timing') {
        const detailString = event.args.data.beginEvent.args?.detail;
        if (detailString) {
            const details = parseDevtoolsDetails(detailString, 'devtools');
            if (details && 'track' in details) {
                return details.track;
            }
        }
    }
    else if (isConsoleTimeStamp(event)) {
        const track = event.args.data?.track;
        return typeof track === 'string' ? track : undefined;
    }
    return undefined;
}
function userTimingComparator(a, b, originalArray) {
    const { start: aStart, end: aEnd } = getEventTimings(a);
    const { start: bStart, end: bEnd } = getEventTimings(b);
    const timeDifference = compareBeginAndEnd(aStart, bStart, aEnd, bEnd);
    if (timeDifference) {
        return timeDifference;
    }
    const aTrack = getEventTrack(a);
    const bTrack = getEventTrack(b);
    if (aTrack !== bTrack) {
        return 0;
    }
    const aIndex = originalArray.indexOf(a);
    const bIndex = originalArray.indexOf(b);
    return bIndex - aIndex;
}
function handleEvent$j(event) {
    if (ignoredNames.includes(event.name)) {
        return;
    }
    if (isUserTimingMeasure(event)) {
        measureTraceByTraceId.set(event.args.traceId, event);
    }
    if (isPerformanceMeasure(event)) {
        performanceMeasureEvents.push(event);
        return;
    }
    if (isPerformanceMark(event)) {
        performanceMarkEvents.push(event);
    }
    if (isConsoleTime(event)) {
        consoleTimings.push(event);
    }
    if (isConsoleTimeStamp(event)) {
        timestampEvents.push(event);
    }
}
async function finalize$B() {
    const asyncEvents = [...performanceMeasureEvents, ...consoleTimings];
    syntheticEvents = createMatchedSortedSyntheticEvents(asyncEvents);
    syntheticEvents = syntheticEvents.sort((a, b) => userTimingComparator(a, b, [...syntheticEvents]));
    timestampEvents = timestampEvents.sort((a, b) => userTimingComparator(a, b, [...timestampEvents]));
}
function data$j() {
    return {
        consoleTimings: syntheticEvents.filter(e => e.cat === 'blink.console'),
        performanceMeasures: syntheticEvents.filter(e => e.cat === 'blink.user_timing'),
        performanceMarks: performanceMarkEvents,
        timestampEvents,
        measureTraceByTraceId,
    };
}

var UserTimingsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$j,
	finalize: finalize$B,
	handleEvent: handleEvent$j,
	reset: reset$j,
	userTimingComparator: userTimingComparator
});

// Copyright 2024 The Chromium Authors
let extensionTrackEntries = [];
let extensionTrackData = [];
let extensionMarkers = [];
let entryToNode = new Map();
let timeStampByName = new Map();
let syntheticConsoleEntriesForTimingsTrack = [];
function handleEvent$i(_event) {
}
function reset$i() {
    extensionTrackEntries = [];
    syntheticConsoleEntriesForTimingsTrack = [];
    extensionTrackData = [];
    extensionMarkers = [];
    entryToNode = new Map();
    timeStampByName = new Map();
}
async function finalize$A() {
    createExtensionFlameChartEntries();
}
function createExtensionFlameChartEntries() {
    const pairedMeasures = data$j().performanceMeasures;
    const marks = data$j().performanceMarks;
    const mergedRawExtensionEvents = mergeEventsInOrder(pairedMeasures, marks);
    extractPerformanceAPIExtensionEntries(mergedRawExtensionEvents);
    extractConsoleAPIExtensionEntries();
    sortTraceEventsInPlace(extensionTrackEntries);
    buildTrackDataFromExtensionEntries(extensionTrackEntries, extensionTrackData, entryToNode);
}
function extractConsoleAPIExtensionEntries() {
    const consoleTimeStamps = data$j().timestampEvents;
    for (const currentTimeStamp of consoleTimeStamps) {
        if (!currentTimeStamp.args.data) {
            continue;
        }
        const timeStampName = String(currentTimeStamp.args.data.name ?? currentTimeStamp.args.data.message);
        timeStampByName.set(timeStampName, currentTimeStamp);
        const { devtoolsObj: extensionData, userDetail } = extensionDataInConsoleTimeStamp(currentTimeStamp);
        const start = currentTimeStamp.args.data.start;
        const end = currentTimeStamp.args.data.end;
        if (!extensionData && !start && !end) {
            continue;
        }
        const startTimeStamp = typeof start === 'number' ? Micro(start) : timeStampByName.get(String(start))?.ts;
        const endTimeStamp = typeof end === 'number' ? Micro(end) : timeStampByName.get(String(end))?.ts;
        if (endTimeStamp !== undefined && startTimeStamp === undefined) {
            continue;
        }
        const entryStartTime = startTimeStamp ?? currentTimeStamp.ts;
        const entryEndTime = endTimeStamp ?? currentTimeStamp.ts;
        if (extensionData) {
            const unregisteredExtensionEntry = {
                ...currentTimeStamp,
                name: timeStampName,
                cat: 'devtools.extension',
                devtoolsObj: extensionData,
                userDetail,
                rawSourceEvent: currentTimeStamp,
                dur: Micro(entryEndTime - entryStartTime),
                ts: entryStartTime,
                ph: "X" ,
            };
            const extensionEntry = SyntheticEventsManager
                .registerSyntheticEvent(unregisteredExtensionEntry);
            extensionTrackEntries.push(extensionEntry);
            continue;
        }
        const unregisteredSyntheticTimeStamp = {
            ...currentTimeStamp,
            name: timeStampName,
            cat: 'disabled-by-default-v8.inspector',
            ph: "X" ,
            ts: entryStartTime,
            dur: Micro(entryEndTime - entryStartTime),
            rawSourceEvent: currentTimeStamp
        };
        const syntheticTimeStamp = SyntheticEventsManager.registerSyntheticEvent(unregisteredSyntheticTimeStamp);
        syntheticConsoleEntriesForTimingsTrack.push(syntheticTimeStamp);
    }
}
function extractPerformanceAPIExtensionEntries(timings) {
    for (const timing of timings) {
        const { devtoolsObj, userDetail } = extensionDataInPerformanceTiming(timing);
        if (!devtoolsObj) {
            continue;
        }
        const extensionSyntheticEntry = {
            name: timing.name,
            ph: isExtensionPayloadMarker(devtoolsObj) ? "I"  :
                "X" ,
            pid: timing.pid,
            tid: timing.tid,
            ts: timing.ts,
            dur: timing.dur,
            cat: 'devtools.extension',
            devtoolsObj,
            userDetail,
            rawSourceEvent: isSyntheticUserTiming(timing) ? timing.rawSourceEvent : timing,
        };
        if (isExtensionPayloadMarker(devtoolsObj)) {
            const extensionMarker = SyntheticEventsManager
                .registerSyntheticEvent(extensionSyntheticEntry);
            extensionMarkers.push(extensionMarker);
            continue;
        }
        if (isExtensionEntryObj(extensionSyntheticEntry.devtoolsObj)) {
            const extensionTrackEntry = SyntheticEventsManager
                .registerSyntheticEvent(extensionSyntheticEntry);
            extensionTrackEntries.push(extensionTrackEntry);
            continue;
        }
    }
}
function extensionDataInPerformanceTiming(timing) {
    const timingDetail = isPerformanceMark(timing) ? timing.args.data?.detail : timing.args.data.beginEvent.args.detail;
    if (!timingDetail) {
        return { devtoolsObj: null, userDetail: null };
    }
    const devtoolsObj = parseDevtoolsDetails(timingDetail, 'devtools');
    let userDetail = null;
    try {
        userDetail = JSON.parse(timingDetail);
        delete userDetail.devtools;
    }
    catch {
    }
    return { devtoolsObj, userDetail };
}
function extensionDataInConsoleTimeStamp(timeStamp) {
    if (!timeStamp.args.data || !timeStamp.args.data.track) {
        return { devtoolsObj: null, userDetail: null };
    }
    let userDetail = null;
    try {
        userDetail = JSON.parse(timeStamp.args.data?.devtools || '""');
    }
    catch {
    }
    const devtoolsObj = {
        color: String(timeStamp.args.data.color),
        track: String(timeStamp.args.data.track),
        dataType: 'track-entry',
        trackGroup: timeStamp.args.data.trackGroup !== undefined ? String(timeStamp.args.data.trackGroup) : undefined,
    };
    return { devtoolsObj, userDetail };
}
function data$i() {
    return {
        entryToNode,
        extensionTrackData,
        extensionMarkers,
        syntheticConsoleEntriesForTimingsTrack,
    };
}
function deps$b() {
    return ['UserTimings'];
}

var ExtensionTraceDataHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$i,
	deps: deps$b,
	extensionDataInConsoleTimeStamp: extensionDataInConsoleTimeStamp,
	extensionDataInPerformanceTiming: extensionDataInPerformanceTiming,
	extractConsoleAPIExtensionEntries: extractConsoleAPIExtensionEntries,
	extractPerformanceAPIExtensionEntries: extractPerformanceAPIExtensionEntries,
	finalize: finalize$A,
	handleEvent: handleEvent$i,
	reset: reset$i
});

// Copyright 2023 The Chromium Authors
let paintEvents = [];
let snapshotEvents = [];
let paintToSnapshotMap = new Map();
let lastPaintForLayerId = {};
let currentMainFrameLayerTreeId = null;
let updateLayerEvents = [];
let relevantEvents = [];
function reset$h() {
    paintEvents = [];
    snapshotEvents = [];
    paintToSnapshotMap = new Map();
    lastPaintForLayerId = {};
    currentMainFrameLayerTreeId = null;
    updateLayerEvents = [];
    relevantEvents = [];
}
function handleEvent$h(event) {
    if (isPaint(event) || isDisplayListItemListSnapshot(event) ||
        isUpdateLayer(event) || isSetLayerId(event)) {
        relevantEvents.push(event);
    }
}
async function finalize$z() {
    const metaData = data$p();
    sortTraceEventsInPlace(relevantEvents);
    for (const event of relevantEvents) {
        if (isSetLayerId(event)) {
            if (metaData.mainFrameId !== event.args.data.frame) {
                continue;
            }
            currentMainFrameLayerTreeId = event.args.data.layerTreeId;
        }
        else if (isUpdateLayer(event)) {
            updateLayerEvents.push(event);
        }
        else if (isPaint(event)) {
            if (!event.args.data.layerId) {
                continue;
            }
            paintEvents.push(event);
            lastPaintForLayerId[event.args.data.layerId] = event;
            continue;
        }
        else if (isDisplayListItemListSnapshot(event)) {
            let lastUpdateLayerEventForThread = null;
            for (let i = updateLayerEvents.length - 1; i > -1; i--) {
                const updateEvent = updateLayerEvents[i];
                if (updateEvent.pid === event.pid && updateEvent.tid === event.tid) {
                    lastUpdateLayerEventForThread = updateEvent;
                    break;
                }
            }
            if (!lastUpdateLayerEventForThread) {
                continue;
            }
            if (lastUpdateLayerEventForThread.args.layerTreeId !== currentMainFrameLayerTreeId) {
                continue;
            }
            const paintEvent = lastPaintForLayerId[lastUpdateLayerEventForThread.args.layerId];
            if (!paintEvent) {
                continue;
            }
            snapshotEvents.push(event);
            paintToSnapshotMap.set(paintEvent, event);
        }
    }
}
function data$h() {
    return {
        paints: paintEvents,
        snapshots: snapshotEvents,
        paintsToSnapshots: paintToSnapshotMap,
    };
}
function deps$a() {
    return ['Meta'];
}

var LayerTreeHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$h,
	deps: deps$a,
	finalize: finalize$z,
	handleEvent: handleEvent$h,
	reset: reset$h
});

function getThreadTypeForRendererThread(pid, thread, auctionWorkletsData) {
    let threadType = "OTHER" ;
    if (thread.name === 'CrRendererMain') {
        threadType = "MAIN_THREAD" ;
    }
    else if (thread.name === 'DedicatedWorker thread') {
        threadType = "WORKER" ;
    }
    else if (thread.name?.startsWith('CompositorTileWorker')) {
        threadType = "RASTERIZER" ;
    }
    else if (auctionWorkletsData.worklets.has(pid)) {
        threadType = "AUCTION_WORKLET" ;
    }
    else if (thread.name?.startsWith('ThreadPool')) {
        threadType = "THREAD_POOL" ;
    }
    return threadType;
}
function threadsInRenderer(rendererData, auctionWorkletsData) {
    const foundThreads = [];
    if (rendererData.processes.size) {
        for (const [pid, process] of rendererData.processes) {
            for (const [tid, thread] of process.threads) {
                if (!thread.tree) {
                    continue;
                }
                const threadType = getThreadTypeForRendererThread(pid, thread, auctionWorkletsData);
                foundThreads.push({
                    name: thread.name,
                    pid,
                    tid,
                    processIsOnMainFrame: process.isOnMainFrame,
                    entries: thread.entries,
                    tree: thread.tree,
                    type: threadType,
                    entryToNode: rendererData.entryToNode,
                });
            }
        }
    }
    return foundThreads;
}
const threadsInHandlerDataCache = new WeakMap();
function threadsInTrace(handlerData) {
    const cached = threadsInHandlerDataCache.get(handlerData);
    if (cached) {
        return cached;
    }
    const threadsFromRenderer = threadsInRenderer(handlerData.Renderer, handlerData.AuctionWorklets);
    if (threadsFromRenderer.length) {
        threadsInHandlerDataCache.set(handlerData, threadsFromRenderer);
        return threadsFromRenderer;
    }
    const foundThreads = [];
    if (handlerData.Samples.profilesInProcess.size) {
        for (const [pid, process] of handlerData.Samples.profilesInProcess) {
            for (const [tid, thread] of process) {
                if (!thread.profileTree) {
                    continue;
                }
                foundThreads.push({
                    pid,
                    tid,
                    name: null,
                    entries: thread.profileCalls,
                    processIsOnMainFrame: false,
                    tree: thread.profileTree,
                    type: "CPU_PROFILE" ,
                    entryToNode: handlerData.Samples.entryToNode,
                });
            }
        }
    }
    threadsInHandlerDataCache.set(handlerData, foundThreads);
    return foundThreads;
}

var Threads = /*#__PURE__*/Object.freeze({
	__proto__: null,
	threadsInRenderer: threadsInRenderer,
	threadsInTrace: threadsInTrace
});

// Copyright 2023 The Chromium Authors
let model = null;
let relevantFrameEvents = [];
function isFrameEvent(event) {
    return (isSetLayerId(event) || isBeginFrame(event) || isDroppedFrame(event) ||
        isRequestMainThreadFrame(event) || isBeginMainThreadFrame(event) ||
        isNeedsBeginFrameChanged(event) ||
        isCommit(event) || isCompositeLayers(event) ||
        isActivateLayerTree(event) || isDrawFrame(event));
}
function entryIsTopLevel(entry) {
    const devtoolsTimelineCategory = 'disabled-by-default-devtools.timeline';
    return entry.name === "RunTask"  && entry.cat.includes(devtoolsTimelineCategory);
}
const MAIN_FRAME_MARKERS = new Set([
    "ScheduleStyleRecalculation" ,
    "InvalidateLayout" ,
    "BeginMainThreadFrame" ,
    "ScrollLayer" ,
]);
function reset$g() {
    model = null;
    relevantFrameEvents = [];
}
function handleEvent$g(event) {
    if (isFrameEvent(event) || isLayerTreeHostImplSnapshot(event) || entryIsTopLevel(event) ||
        MAIN_FRAME_MARKERS.has(event.name) || isPaint(event)) {
        relevantFrameEvents.push(event);
    }
}
async function finalize$y() {
    sortTraceEventsInPlace(relevantFrameEvents);
    const modelForTrace = new TimelineFrameModel(relevantFrameEvents, data$m(), data$q(), data$p(), data$h());
    model = modelForTrace;
}
function data$g() {
    return {
        frames: model?.frames() ?? [],
        framesById: model?.framesById() ?? {},
    };
}
function deps$9() {
    return ['Meta', 'Renderer', 'AuctionWorklets', 'LayerTree'];
}
class TimelineFrameModel {
    #frames = [];
    #frameById = {};
    #beginFrameQueue = new TimelineFrameBeginFrameQueue();
    #lastFrame = null;
    #mainFrameCommitted = false;
    #mainFrameRequested = false;
    #lastLayerTree = null;
    #framePendingActivation = null;
    #framePendingCommit = null;
    #lastBeginFrame = null;
    #lastNeedsBeginFrame = null;
    #lastTaskBeginTime = null;
    #layerTreeId = null;
    #activeProcessId = null;
    #activeThreadId = null;
    #layerTreeData;
    constructor(allEvents, rendererData, auctionWorkletsData, metaData, layerTreeData) {
        const mainThreads = threadsInRenderer(rendererData, auctionWorkletsData).filter(thread => {
            return thread.type === "MAIN_THREAD"  && thread.processIsOnMainFrame;
        });
        const threadData = mainThreads.map(thread => {
            return {
                tid: thread.tid,
                pid: thread.pid,
                startTime: thread.entries[0].ts,
            };
        });
        this.#layerTreeData = layerTreeData;
        this.#addTraceEvents(allEvents, threadData, metaData.mainFrameId);
    }
    framesById() {
        return this.#frameById;
    }
    frames() {
        return this.#frames;
    }
    #handleBeginFrame(startTime, seqId) {
        if (!this.#lastFrame) {
            this.#startFrame(startTime, seqId);
        }
        this.#lastBeginFrame = startTime;
        this.#beginFrameQueue.addFrameIfNotExists(seqId, startTime, false, false);
    }
    #handleDroppedFrame(startTime, seqId, isPartial) {
        if (!this.#lastFrame) {
            this.#startFrame(startTime, seqId);
        }
        this.#beginFrameQueue.addFrameIfNotExists(seqId, startTime, true, isPartial);
        this.#beginFrameQueue.setDropped(seqId, true);
        this.#beginFrameQueue.setPartial(seqId, isPartial);
    }
    #handleDrawFrame(startTime, seqId) {
        if (!this.#lastFrame) {
            this.#startFrame(startTime, seqId);
            return;
        }
        if (this.#mainFrameCommitted || !this.#mainFrameRequested) {
            if (this.#lastNeedsBeginFrame) {
                const idleTimeEnd = this.#framePendingActivation ? this.#framePendingActivation.triggerTime :
                    (this.#lastBeginFrame || this.#lastNeedsBeginFrame);
                if (idleTimeEnd > this.#lastFrame.startTime) {
                    this.#lastFrame.idle = true;
                    this.#lastBeginFrame = null;
                }
                this.#lastNeedsBeginFrame = null;
            }
            const framesToVisualize = this.#beginFrameQueue.processPendingBeginFramesOnDrawFrame(seqId);
            for (const frame of framesToVisualize) {
                const isLastFrameIdle = this.#lastFrame.idle;
                this.#startFrame(frame.startTime, seqId);
                if (isLastFrameIdle && this.#framePendingActivation) {
                    this.#commitPendingFrame();
                }
                if (frame.isDropped) {
                    this.#lastFrame.dropped = true;
                }
                if (frame.isPartial) {
                    this.#lastFrame.isPartial = true;
                }
            }
        }
        this.#mainFrameCommitted = false;
    }
    #handleActivateLayerTree() {
        if (!this.#lastFrame) {
            return;
        }
        if (this.#framePendingActivation && !this.#lastNeedsBeginFrame) {
            this.#commitPendingFrame();
        }
    }
    #handleRequestMainThreadFrame() {
        if (!this.#lastFrame) {
            return;
        }
        this.#mainFrameRequested = true;
    }
    #handleCommit() {
        if (!this.#framePendingCommit) {
            return;
        }
        this.#framePendingActivation = this.#framePendingCommit;
        this.#framePendingCommit = null;
        this.#mainFrameRequested = false;
        this.#mainFrameCommitted = true;
    }
    #handleLayerTreeSnapshot(layerTree) {
        this.#lastLayerTree = layerTree;
    }
    #handleNeedFrameChanged(startTime, needsBeginFrame) {
        if (needsBeginFrame) {
            this.#lastNeedsBeginFrame = startTime;
        }
    }
    #startFrame(startTime, seqId) {
        if (this.#lastFrame) {
            this.#flushFrame(this.#lastFrame, startTime);
        }
        this.#lastFrame =
            new TimelineFrame(seqId, startTime, Micro(startTime - data$p().traceBounds.min));
    }
    #flushFrame(frame, endTime) {
        frame.setLayerTree(this.#lastLayerTree);
        frame.setEndTime(endTime);
        if (this.#lastLayerTree) {
            this.#lastLayerTree.paints = frame.paints;
        }
        const lastFrame = this.#frames[this.#frames.length - 1];
        if (this.#frames.length && lastFrame &&
            (frame.startTime !== lastFrame.endTime || frame.startTime > frame.endTime)) {
            console.assert(false, `Inconsistent frame time for frame ${this.#frames.length} (${frame.startTime} - ${frame.endTime})`);
        }
        const newFramesLength = this.#frames.push(frame);
        frame.setIndex(newFramesLength - 1);
        if (typeof frame.mainFrameId === 'number') {
            this.#frameById[frame.mainFrameId] = frame;
        }
    }
    #commitPendingFrame() {
        if (!this.#framePendingActivation || !this.#lastFrame) {
            return;
        }
        this.#lastFrame.paints = this.#framePendingActivation.paints;
        this.#lastFrame.mainFrameId = this.#framePendingActivation.mainFrameId;
        this.#framePendingActivation = null;
    }
    #addTraceEvents(events, threadData, mainFrameId) {
        let j = 0;
        this.#activeThreadId = threadData.length && threadData[0].tid || null;
        this.#activeProcessId = threadData.length && threadData[0].pid || null;
        for (let i = 0; i < events.length; ++i) {
            while (j + 1 < threadData.length && threadData[j + 1].startTime <= events[i].ts) {
                this.#activeThreadId = threadData[++j].tid;
                this.#activeProcessId = threadData[j].pid;
            }
            this.#addTraceEvent(events[i], mainFrameId);
        }
        this.#activeThreadId = null;
        this.#activeProcessId = null;
    }
    #addTraceEvent(event, mainFrameId) {
        if (isSetLayerId(event) && event.args.data.frame === mainFrameId) {
            this.#layerTreeId = event.args.data.layerTreeId;
        }
        else if (isLayerTreeHostImplSnapshot(event) && Number(event.id) === this.#layerTreeId) {
            this.#handleLayerTreeSnapshot({
                entry: event,
                paints: [],
            });
        }
        else {
            if (isFrameEvent(event)) {
                this.#processCompositorEvents(event);
            }
            if (event.tid === this.#activeThreadId && event.pid === this.#activeProcessId) {
                this.#addMainThreadTraceEvent(event);
            }
        }
    }
    #processCompositorEvents(entry) {
        if (entry.args['layerTreeId'] !== this.#layerTreeId) {
            return;
        }
        if (isBeginFrame(entry)) {
            this.#handleBeginFrame(entry.ts, entry.args['frameSeqId']);
        }
        else if (isDrawFrame(entry)) {
            this.#handleDrawFrame(entry.ts, entry.args['frameSeqId']);
        }
        else if (isActivateLayerTree(entry)) {
            this.#handleActivateLayerTree();
        }
        else if (isRequestMainThreadFrame(entry)) {
            this.#handleRequestMainThreadFrame();
        }
        else if (isNeedsBeginFrameChanged(entry)) {
            this.#handleNeedFrameChanged(entry.ts, entry.args['data'] && Boolean(entry.args['data']['needsBeginFrame']));
        }
        else if (isDroppedFrame(entry)) {
            this.#handleDroppedFrame(entry.ts, entry.args['frameSeqId'], Boolean(entry.args['hasPartialUpdate']));
        }
    }
    #addMainThreadTraceEvent(entry) {
        if (entryIsTopLevel(entry)) {
            this.#lastTaskBeginTime = entry.ts;
        }
        if (!this.#framePendingCommit && MAIN_FRAME_MARKERS.has(entry.name)) {
            this.#framePendingCommit = new PendingFrame(this.#lastTaskBeginTime || entry.ts);
        }
        if (!this.#framePendingCommit) {
            return;
        }
        if (isBeginMainThreadFrame(entry) && entry.args.data.frameId) {
            this.#framePendingCommit.mainFrameId = entry.args.data.frameId;
        }
        if (isPaint(entry)) {
            const snapshot = this.#layerTreeData.paintsToSnapshots.get(entry);
            if (snapshot) {
                this.#framePendingCommit.paints.push(new LayerPaintEvent(entry, snapshot));
            }
        }
        if ((isCompositeLayers(entry) || isCommit(entry)) &&
            entry.args['layerTreeId'] === this.#layerTreeId) {
            this.#handleCommit();
        }
    }
}
class TimelineFrame {
    cat = 'devtools.legacy_frame';
    name = 'frame';
    ph = "X" ;
    ts;
    pid = ProcessID(-1);
    tid = ThreadID(-1);
    index = -1;
    startTime;
    startTimeOffset;
    endTime;
    duration;
    idle;
    dropped;
    isPartial;
    layerTree;
    paints;
    mainFrameId;
    seqId;
    constructor(seqId, startTime, startTimeOffset) {
        this.seqId = seqId;
        this.startTime = startTime;
        this.ts = startTime;
        this.startTimeOffset = startTimeOffset;
        this.endTime = this.startTime;
        this.duration = Micro(0);
        this.idle = false;
        this.dropped = false;
        this.isPartial = false;
        this.layerTree = null;
        this.paints = [];
        this.mainFrameId = undefined;
    }
    setIndex(i) {
        this.index = i;
    }
    setEndTime(endTime) {
        this.endTime = endTime;
        this.duration = Micro(this.endTime - this.startTime);
    }
    setLayerTree(layerTree) {
        this.layerTree = layerTree;
    }
    get dur() {
        return this.duration;
    }
}
class LayerPaintEvent {
    #event;
    #snapshot;
    constructor(event, snapshot) {
        this.#event = event;
        this.#snapshot = snapshot;
    }
    layerId() {
        return this.#event.args.data.layerId;
    }
    event() {
        return this.#event;
    }
    picture() {
        const rect = this.#snapshot.args.snapshot.params?.layer_rect;
        const pictureData = this.#snapshot.args.snapshot.skp64;
        return rect && pictureData ? { rect, serializedPicture: pictureData } : null;
    }
}
class PendingFrame {
    paints;
    mainFrameId;
    triggerTime;
    constructor(triggerTime) {
        this.paints = [];
        this.mainFrameId = undefined;
        this.triggerTime = triggerTime;
    }
}
class BeginFrameInfo {
    seqId;
    startTime;
    isDropped;
    isPartial;
    constructor(seqId, startTime, isDropped, isPartial) {
        this.seqId = seqId;
        this.startTime = startTime;
        this.isDropped = isDropped;
        this.isPartial = isPartial;
    }
}
class TimelineFrameBeginFrameQueue {
    queueFrames = [];
    mapFrames = {};
    addFrameIfNotExists(seqId, startTime, isDropped, isPartial) {
        if (!(seqId in this.mapFrames)) {
            this.mapFrames[seqId] = new BeginFrameInfo(seqId, startTime, isDropped, isPartial);
            this.queueFrames.push(seqId);
        }
    }
    setDropped(seqId, isDropped) {
        if (seqId in this.mapFrames) {
            this.mapFrames[seqId].isDropped = isDropped;
        }
    }
    setPartial(seqId, isPartial) {
        if (seqId in this.mapFrames) {
            this.mapFrames[seqId].isPartial = isPartial;
        }
    }
    processPendingBeginFramesOnDrawFrame(seqId) {
        const framesToVisualize = [];
        if (seqId in this.mapFrames) {
            while (this.queueFrames[0] !== seqId) {
                const currentSeqId = this.queueFrames[0];
                if (this.mapFrames[currentSeqId].isDropped) {
                    framesToVisualize.push(this.mapFrames[currentSeqId]);
                }
                delete this.mapFrames[currentSeqId];
                this.queueFrames.shift();
            }
            framesToVisualize.push(this.mapFrames[seqId]);
            delete this.mapFrames[seqId];
            this.queueFrames.shift();
        }
        return framesToVisualize;
    }
}
function framesWithinWindow(frames, startTime, endTime) {
    const firstFrame = lowerBound(frames, startTime || 0, (time, frame) => time - frame.endTime);
    const lastFrame = lowerBound(frames, endTime || Infinity, (time, frame) => time - frame.startTime);
    return frames.slice(firstFrame, lastFrame);
}

var FramesHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	LayerPaintEvent: LayerPaintEvent,
	PendingFrame: PendingFrame,
	TimelineFrameBeginFrameQueue: TimelineFrameBeginFrameQueue,
	TimelineFrameModel: TimelineFrameModel,
	data: data$g,
	deps: deps$9,
	finalize: finalize$y,
	framesWithinWindow: framesWithinWindow,
	handleEvent: handleEvent$g,
	reset: reset$g
});

// Copyright 2022 The Chromium Authors
let eventsInProcessThread = new Map();
let mainGPUThreadTasks = [];
function reset$f() {
    eventsInProcessThread = new Map();
    mainGPUThreadTasks = [];
}
function handleEvent$f(event) {
    if (!isGPUTask(event)) {
        return;
    }
    addEventToProcessThread(event, eventsInProcessThread);
}
async function finalize$x() {
    const { gpuProcessId, gpuThreadId } = data$p();
    const gpuThreadsForProcess = eventsInProcessThread.get(gpuProcessId);
    if (gpuThreadsForProcess && gpuThreadId) {
        mainGPUThreadTasks = gpuThreadsForProcess.get(gpuThreadId) || [];
    }
}
function data$f() {
    return {
        mainGPUThreadTasks,
    };
}
function deps$8() {
    return ['Meta'];
}

var GPUHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$f,
	deps: deps$8,
	finalize: finalize$x,
	handleEvent: handleEvent$f,
	reset: reset$f
});

// Copyright 2024 The Chromium Authors
let paintImageEvents$1 = new Map();
let decodeLazyPixelRefEvents = new Map();
let paintImageByLazyPixelRef = new Map();
let eventToPaintImage = new Map();
let urlToPaintImage = new Map();
let paintEventToCorrectedDisplaySize = new Map();
let didCorrectForHostDpr = false;
function reset$e() {
    paintImageEvents$1 = new Map();
    decodeLazyPixelRefEvents = new Map();
    paintImageByLazyPixelRef = new Map();
    eventToPaintImage = new Map();
    urlToPaintImage = new Map();
    paintEventToCorrectedDisplaySize = new Map();
    didCorrectForHostDpr = false;
}
function handleEvent$e(event) {
    if (isPaintImage(event)) {
        const forProcess = paintImageEvents$1.get(event.pid) || new Map();
        const forThread = forProcess.get(event.tid) || [];
        forThread.push(event);
        forProcess.set(event.tid, forThread);
        paintImageEvents$1.set(event.pid, forProcess);
        if (event.args.data.url) {
            const paintsForUrl = getWithDefault(urlToPaintImage, event.args.data.url, () => []);
            paintsForUrl.push(event);
        }
        return;
    }
    if (isDecodeLazyPixelRef(event) && typeof event.args?.LazyPixelRef !== 'undefined') {
        const forProcess = decodeLazyPixelRefEvents.get(event.pid) || new Map();
        const forThread = forProcess.get(event.tid) || [];
        forThread.push(event);
        forProcess.set(event.tid, forThread);
        decodeLazyPixelRefEvents.set(event.pid, forProcess);
    }
    if (isDrawLazyPixelRef(event) && typeof event.args?.LazyPixelRef !== 'undefined') {
        const lastPaintEvent = paintImageEvents$1.get(event.pid)?.get(event.tid)?.at(-1);
        if (!lastPaintEvent) {
            return;
        }
        paintImageByLazyPixelRef.set(event.args.LazyPixelRef, lastPaintEvent);
        return;
    }
    if (isDecodeImage(event)) {
        const lastPaintImageEventOnThread = paintImageEvents$1.get(event.pid)?.get(event.tid)?.at(-1);
        if (lastPaintImageEventOnThread) {
            eventToPaintImage.set(event, lastPaintImageEventOnThread);
            return;
        }
        const lastDecodeLazyPixelRef = decodeLazyPixelRefEvents.get(event.pid)?.get(event.tid)?.at(-1);
        if (typeof lastDecodeLazyPixelRef?.args?.LazyPixelRef === 'undefined') {
            return;
        }
        const paintEvent = paintImageByLazyPixelRef.get(lastDecodeLazyPixelRef.args.LazyPixelRef);
        if (!paintEvent) {
            return;
        }
        eventToPaintImage.set(event, paintEvent);
    }
}
async function finalize$w(options) {
    if (!options.metadata?.hostDPR) {
        return;
    }
    const { devicePixelRatio: emulatedDpr } = data$p();
    if (!emulatedDpr) {
        return;
    }
    for (const byThread of paintImageEvents$1.values()) {
        for (const paintEvents of byThread.values()) {
            for (const paintEvent of paintEvents) {
                const cssPixelsWidth = paintEvent.args.data.width / options.metadata.hostDPR;
                const cssPixelsHeight = paintEvent.args.data.height / options.metadata.hostDPR;
                const width = cssPixelsWidth * emulatedDpr;
                const height = cssPixelsHeight * emulatedDpr;
                paintEventToCorrectedDisplaySize.set(paintEvent, { width, height });
            }
        }
    }
    didCorrectForHostDpr = true;
}
function data$e() {
    return {
        paintImageByDrawLazyPixelRef: paintImageByLazyPixelRef,
        paintImageForEvent: eventToPaintImage,
        paintImageEventForUrl: urlToPaintImage,
        paintEventToCorrectedDisplaySize,
        didCorrectForHostDpr,
    };
}

var ImagePaintingHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$e,
	finalize: finalize$w,
	handleEvent: handleEvent$e,
	reset: reset$e
});

// Copyright 2023 The Chromium Authors
let lastScheduleStyleRecalcByFrame = new Map();
let lastInvalidationEventForFrame = new Map();
let lastRecalcByFrame = new Map();
let eventToInitiatorMap = new Map();
let initiatorToEventsMap = new Map();
let timerInstallEventsById = new Map();
let requestIdleCallbackEventsById = new Map();
let webSocketCreateEventsById = new Map();
let schedulePostTaskCallbackEventsById = new Map();
function reset$d() {
    lastScheduleStyleRecalcByFrame = new Map();
    lastInvalidationEventForFrame = new Map();
    lastRecalcByFrame = new Map();
    timerInstallEventsById = new Map();
    eventToInitiatorMap = new Map();
    initiatorToEventsMap = new Map();
    requestIdleCallbackEventsById = new Map();
    webSocketCreateEventsById = new Map();
    schedulePostTaskCallbackEventsById = new Map();
}
function storeInitiator(data) {
    eventToInitiatorMap.set(data.event, data.initiator);
    const eventsForInitiator = initiatorToEventsMap.get(data.initiator) || [];
    eventsForInitiator.push(data.event);
    initiatorToEventsMap.set(data.initiator, eventsForInitiator);
}
function handleEvent$d(event) {
    if (isScheduleStyleRecalculation(event)) {
        lastScheduleStyleRecalcByFrame.set(event.args.data.frame, event);
    }
    else if (isRecalcStyle(event)) {
        if (event.args.beginData) {
            lastRecalcByFrame.set(event.args.beginData.frame, event);
            const scheduledStyleForFrame = lastScheduleStyleRecalcByFrame.get(event.args.beginData.frame);
            if (scheduledStyleForFrame) {
                storeInitiator({
                    event,
                    initiator: scheduledStyleForFrame,
                });
            }
        }
    }
    else if (isInvalidateLayout(event)) {
        let invalidationInitiator = event;
        if (!lastInvalidationEventForFrame.has(event.args.data.frame)) {
            const lastRecalcStyleForFrame = lastRecalcByFrame.get(event.args.data.frame);
            if (lastRecalcStyleForFrame) {
                const { endTime } = eventTimingsMicroSeconds(lastRecalcStyleForFrame);
                const initiatorOfRecalcStyle = eventToInitiatorMap.get(lastRecalcStyleForFrame);
                if (initiatorOfRecalcStyle && endTime && endTime > event.ts) {
                    invalidationInitiator = initiatorOfRecalcStyle;
                }
            }
        }
        lastInvalidationEventForFrame.set(event.args.data.frame, invalidationInitiator);
    }
    else if (isLayout(event)) {
        const lastInvalidation = lastInvalidationEventForFrame.get(event.args.beginData.frame);
        if (lastInvalidation) {
            storeInitiator({
                event,
                initiator: lastInvalidation,
            });
        }
        lastInvalidationEventForFrame.delete(event.args.beginData.frame);
    }
    else if (isTimerInstall(event)) {
        timerInstallEventsById.set(event.args.data.timerId, event);
    }
    else if (isTimerFire(event)) {
        const matchingInstall = timerInstallEventsById.get(event.args.data.timerId);
        if (matchingInstall) {
            storeInitiator({ event, initiator: matchingInstall });
        }
    }
    else if (isRequestIdleCallback(event)) {
        requestIdleCallbackEventsById.set(event.args.data.id, event);
    }
    else if (isFireIdleCallback(event)) {
        const matchingRequestEvent = requestIdleCallbackEventsById.get(event.args.data.id);
        if (matchingRequestEvent) {
            storeInitiator({
                event,
                initiator: matchingRequestEvent,
            });
        }
    }
    else if (isWebSocketCreate(event)) {
        webSocketCreateEventsById.set(event.args.data.identifier, event);
    }
    else if (isWebSocketInfo(event) || isWebSocketTransfer(event)) {
        const matchingCreateEvent = webSocketCreateEventsById.get(event.args.data.identifier);
        if (matchingCreateEvent) {
            storeInitiator({
                event,
                initiator: matchingCreateEvent,
            });
        }
    }
    else if (isSchedulePostTaskCallback(event)) {
        schedulePostTaskCallbackEventsById.set(event.args.data.taskId, event);
    }
    else if (isRunPostTaskCallback(event) || isAbortPostTaskCallback(event)) {
        const matchingSchedule = schedulePostTaskCallbackEventsById.get(event.args.data.taskId);
        if (matchingSchedule) {
            storeInitiator({ event, initiator: matchingSchedule });
        }
    }
}
function createRelationshipsFromFlows() {
    const flows = data$r().flows;
    for (let i = 0; i < flows.length; i++) {
        const flow = flows[i];
        for (let j = 0; j < flow.length - 1; j++) {
            storeInitiator({ event: flow[j + 1], initiator: flow[j] });
        }
    }
}
function createRelationshipsFromAsyncJSCalls() {
    const asyncCallEntries = data$l().schedulerToRunEntryPoints.entries();
    for (const [asyncCaller, asyncCallees] of asyncCallEntries) {
        for (const asyncCallee of asyncCallees) {
            storeInitiator({ event: asyncCallee, initiator: asyncCaller });
        }
    }
}
async function finalize$v() {
    createRelationshipsFromFlows();
    createRelationshipsFromAsyncJSCalls();
}
function data$d() {
    return {
        eventToInitiator: eventToInitiatorMap,
        initiatorToEvents: initiatorToEventsMap,
    };
}
function deps$7() {
    return ['Flows', 'AsyncJSCalls'];
}

var InitiatorsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$d,
	deps: deps$7,
	finalize: finalize$v,
	handleEvent: handleEvent$d,
	reset: reset$d
});

// Copyright 2023 The Chromium Authors
const frameStateByFrame = new Map();
let maxInvalidationsPerEvent = null;
function reset$c() {
    frameStateByFrame.clear();
    maxInvalidationsPerEvent = null;
}
function handleUserConfig(userConfig) {
    maxInvalidationsPerEvent = userConfig.maxInvalidationEventsPerEvent;
}
function getState(frameId) {
    let frameState = frameStateByFrame.get(frameId);
    if (!frameState) {
        frameState = {
            invalidationsForEvent: new Map(),
            invalidationCountForEvent: new Map(),
            lastRecalcStyleEvent: null,
            pendingInvalidations: [],
            hasPainted: false,
        };
        frameStateByFrame.set(frameId, frameState);
    }
    return frameState;
}
function getFrameId(event) {
    if (isRecalcStyle(event) || isLayout(event)) {
        return event.args.beginData?.frame ?? null;
    }
    return event.args?.data?.frame ?? null;
}
function addInvalidationToEvent(frameState, event, invalidation) {
    const existingInvalidations = frameState.invalidationsForEvent.get(event) || [];
    existingInvalidations.push(invalidation);
    if (maxInvalidationsPerEvent !== null && existingInvalidations.length > maxInvalidationsPerEvent) {
        existingInvalidations.shift();
    }
    frameState.invalidationsForEvent.set(event, existingInvalidations);
    const count = frameState.invalidationCountForEvent.get(event) ?? 0;
    frameState.invalidationCountForEvent.set(event, count + 1);
}
function handleEvent$c(event) {
    if (maxInvalidationsPerEvent === 0) {
        return;
    }
    const frameId = getFrameId(event);
    if (!frameId) {
        return;
    }
    const thisFrame = getState(frameId);
    if (isRecalcStyle(event)) {
        thisFrame.lastRecalcStyleEvent = event;
        for (const invalidation of thisFrame.pendingInvalidations) {
            if (isLayoutInvalidationTracking(invalidation)) {
                continue;
            }
            addInvalidationToEvent(thisFrame, event, invalidation);
        }
        return;
    }
    if (isInvalidationTracking(event)) {
        if (thisFrame.hasPainted) {
            thisFrame.pendingInvalidations.length = 0;
            thisFrame.lastRecalcStyleEvent = null;
            thisFrame.hasPainted = false;
        }
        if (thisFrame.lastRecalcStyleEvent &&
            (isScheduleStyleInvalidationTracking(event) ||
                isStyleRecalcInvalidationTracking(event) ||
                isStyleInvalidatorInvalidationTracking(event))) {
            const recalcLastRecalc = thisFrame.lastRecalcStyleEvent;
            const recalcEndTime = recalcLastRecalc.ts + (recalcLastRecalc.dur || 0);
            if (event.ts >= recalcLastRecalc.ts && event.ts <= recalcEndTime) {
                addInvalidationToEvent(thisFrame, recalcLastRecalc, event);
            }
        }
        thisFrame.pendingInvalidations.push(event);
        return;
    }
    if (isPaint(event)) {
        thisFrame.hasPainted = true;
        return;
    }
    if (isLayout(event)) {
        for (const invalidation of thisFrame.pendingInvalidations) {
            if (!isLayoutInvalidationTracking(invalidation)) {
                continue;
            }
            addInvalidationToEvent(thisFrame, event, invalidation);
        }
    }
}
async function finalize$u() {
}
function data$c() {
    const invalidationsForEvent = new Map();
    const invalidationCountForEvent = new Map();
    for (const frame of frameStateByFrame.values()) {
        for (const [event, invalidations] of frame.invalidationsForEvent.entries()) {
            invalidationsForEvent.set(event, invalidations);
        }
        for (const [event, count] of frame.invalidationCountForEvent.entries()) {
            invalidationCountForEvent.set(event, count);
        }
    }
    return {
        invalidationsForEvent,
        invalidationCountForEvent,
    };
}

var InvalidationsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$c,
	finalize: finalize$u,
	handleEvent: handleEvent$c,
	handleUserConfig: handleUserConfig,
	reset: reset$c
});

// Copyright 2022 The Chromium Authors
let metricScoresByFrameId = new Map();
let allMarkerEvents = [];
function reset$b() {
    metricScoresByFrameId = new Map();
    pageLoadEventsArray = [];
    allMarkerEvents = [];
    selectedLCPCandidateEvents = new Set();
}
let pageLoadEventsArray = [];
let selectedLCPCandidateEvents = new Set();
function handleEvent$b(event) {
    if (!eventIsPageLoadEvent(event)) {
        return;
    }
    pageLoadEventsArray.push(event);
}
function storePageLoadMetricAgainstNavigationId(navigation, event) {
    const frameId = getFrameIdForPageLoadEvent(event);
    const { rendererProcessesByFrame } = data$p();
    const rendererProcessesInFrame = rendererProcessesByFrame.get(frameId);
    if (!rendererProcessesInFrame) {
        return;
    }
    const processData = rendererProcessesInFrame.get(event.pid);
    if (!processData) {
        return;
    }
    if (isNavigationStart(event)) {
        return;
    }
    if (isFirstContentfulPaint(event)) {
        const fcpTime = Micro(event.ts - navigation.ts);
        const classification = scoreClassificationForFirstContentfulPaint(fcpTime);
        const metricScore = { event, metricName: "FCP" , classification, navigation, timing: fcpTime };
        storeMetricScore(frameId, navigation, metricScore);
        return;
    }
    if (isFirstPaint(event)) {
        const paintTime = Micro(event.ts - navigation.ts);
        const classification = "unclassified" ;
        const metricScore = { event, metricName: "FP" , classification, navigation, timing: paintTime };
        storeMetricScore(frameId, navigation, metricScore);
        return;
    }
    if (isMarkDOMContent(event)) {
        const dclTime = Micro(event.ts - navigation.ts);
        const metricScore = {
            event,
            metricName: "DCL" ,
            classification: scoreClassificationForDOMContentLoaded(),
            navigation,
            timing: dclTime,
        };
        storeMetricScore(frameId, navigation, metricScore);
        return;
    }
    if (isInteractiveTime(event)) {
        const ttiValue = Micro(event.ts - navigation.ts);
        const tti = {
            event,
            metricName: "TTI" ,
            classification: scoreClassificationForTimeToInteractive(ttiValue),
            navigation,
            timing: ttiValue,
        };
        storeMetricScore(frameId, navigation, tti);
        const tbtValue = milliToMicro(Milli(event.args.args.total_blocking_time_ms));
        const tbt = {
            event,
            metricName: "TBT" ,
            classification: scoreClassificationForTotalBlockingTime(tbtValue),
            navigation,
            timing: tbtValue,
        };
        storeMetricScore(frameId, navigation, tbt);
        return;
    }
    if (isMarkLoad(event)) {
        const loadTime = Micro(event.ts - navigation.ts);
        const metricScore = {
            event,
            metricName: "L" ,
            classification: "unclassified" ,
            navigation,
            timing: loadTime,
        };
        storeMetricScore(frameId, navigation, metricScore);
        return;
    }
    if (isAnyLargestContentfulPaintCandidate(event)) {
        const candidateIndex = event.args.data?.candidateIndex;
        if (!candidateIndex) {
            throw new Error('Largest Contentful Paint unexpectedly had no candidateIndex.');
        }
        const lcpTime = Micro(event.ts - navigation.ts);
        const lcp = {
            event,
            metricName: "LCP" ,
            classification: scoreClassificationForLargestContentfulPaint(lcpTime),
            navigation,
            timing: lcpTime,
        };
        const metricsByNavigation = getWithDefault(metricScoresByFrameId, frameId, () => new Map());
        const metrics = getWithDefault(metricsByNavigation, navigation, () => new Map());
        const lastLCPCandidate = metrics.get("LCP" );
        if (lastLCPCandidate === undefined) {
            selectedLCPCandidateEvents.add(lcp.event);
            storeMetricScore(frameId, navigation, lcp);
            return;
        }
        const lastLCPCandidateEvent = lastLCPCandidate.event;
        if (!isAnyLargestContentfulPaintCandidate(lastLCPCandidateEvent)) {
            return;
        }
        const lastCandidateIndex = lastLCPCandidateEvent.args.data?.candidateIndex;
        if (!lastCandidateIndex) {
            return;
        }
        if (lastCandidateIndex < candidateIndex) {
            selectedLCPCandidateEvents.delete(lastLCPCandidateEvent);
            selectedLCPCandidateEvents.add(lcp.event);
            storeMetricScore(frameId, navigation, lcp);
        }
        return;
    }
    if (isLayoutShift(event)) {
        return;
    }
    if (isSoftNavigationStart(event)) {
        return;
    }
    return assertNever(event, `Unexpected event type: ${event}`);
}
function storeMetricScore(frameId, navigation, metricScore) {
    const metricsByNavigation = getWithDefault(metricScoresByFrameId, frameId, () => new Map());
    const metrics = getWithDefault(metricsByNavigation, navigation, () => new Map());
    metrics.delete(metricScore.metricName);
    metrics.set(metricScore.metricName, metricScore);
}
function getFrameIdForPageLoadEvent(event) {
    if (isFirstContentfulPaint(event) || isInteractiveTime(event) ||
        isAnyLargestContentfulPaintCandidate(event) || isNavigationStart(event) ||
        isSoftNavigationStart(event) || isLayoutShift(event) ||
        isFirstPaint(event)) {
        return event.args.frame;
    }
    if (isMarkDOMContent(event) || isMarkLoad(event)) {
        const frameId = event.args.data?.frame;
        if (!frameId) {
            throw new Error('MarkDOMContent unexpectedly had no frame ID.');
        }
        return frameId;
    }
    assertNever(event, `Unexpected event type: ${event}`);
}
function getNavigationForPageLoadEvent(event) {
    if (isFirstContentfulPaint(event) || isAnyLargestContentfulPaintCandidate(event) ||
        isFirstPaint(event)) {
        const { navigationsByNavigationId, softNavigationsById } = data$p();
        let navigation;
        if (event.name === "largestContentfulPaint::CandidateForSoftNavigation"  &&
            event.args.data?.performanceTimelineNavigationId) {
            navigation = softNavigationsById.get(event.args.data.performanceTimelineNavigationId);
            if (!navigation) {
                return null;
            }
        }
        else {
            const navigationId = event.args.data?.navigationId;
            if (!navigationId) {
                throw new Error(`Trace event unexpectedly had no navigation ID: ${JSON.stringify(event, null, 2)}`);
            }
            navigation = navigationsByNavigationId.get(navigationId);
        }
        if (!navigation) {
            return null;
        }
        return navigation;
    }
    if (isSoftNavigationStart(event)) {
        const { softNavigationsById } = data$p();
        return softNavigationsById.get(event.args.context.performanceTimelineNavigationId) ?? null;
    }
    if (isMarkDOMContent(event) || isInteractiveTime(event) ||
        isLayoutShift(event) || isMarkLoad(event)) {
        const frameId = getFrameIdForPageLoadEvent(event);
        const { navigationsByFrameId } = data$p();
        return getNavigationForTraceEvent(event, frameId, navigationsByFrameId);
    }
    if (isNavigationStart(event)) {
        return null;
    }
    return assertNever(event, `Unexpected event type: ${event}`);
}
function scoreClassificationForFirstContentfulPaint(fcpScoreInMicroseconds) {
    const FCP_GOOD_TIMING = secondsToMicro(Seconds(1.8));
    const FCP_MEDIUM_TIMING = secondsToMicro(Seconds(3.0));
    let scoreClassification = "bad" ;
    if (fcpScoreInMicroseconds <= FCP_MEDIUM_TIMING) {
        scoreClassification = "ok" ;
    }
    if (fcpScoreInMicroseconds <= FCP_GOOD_TIMING) {
        scoreClassification = "good" ;
    }
    return scoreClassification;
}
function scoreClassificationForTimeToInteractive(ttiTimeInMicroseconds) {
    const TTI_GOOD_TIMING = secondsToMicro(Seconds(3.8));
    const TTI_MEDIUM_TIMING = secondsToMicro(Seconds(7.3));
    let scoreClassification = "bad" ;
    if (ttiTimeInMicroseconds <= TTI_MEDIUM_TIMING) {
        scoreClassification = "ok" ;
    }
    if (ttiTimeInMicroseconds <= TTI_GOOD_TIMING) {
        scoreClassification = "good" ;
    }
    return scoreClassification;
}
function scoreClassificationForLargestContentfulPaint(lcpTimeInMicroseconds) {
    const LCP_GOOD_TIMING = secondsToMicro(Seconds(2.5));
    const LCP_MEDIUM_TIMING = secondsToMicro(Seconds(4));
    let scoreClassification = "bad" ;
    if (lcpTimeInMicroseconds <= LCP_MEDIUM_TIMING) {
        scoreClassification = "ok" ;
    }
    if (lcpTimeInMicroseconds <= LCP_GOOD_TIMING) {
        scoreClassification = "good" ;
    }
    return scoreClassification;
}
function scoreClassificationForDOMContentLoaded(_dclTimeInMicroseconds) {
    return "unclassified" ;
}
function scoreClassificationForTotalBlockingTime(tbtTimeInMicroseconds) {
    const TBT_GOOD_TIMING = milliToMicro(Milli(200));
    const TBT_MEDIUM_TIMING = milliToMicro(Milli(600));
    let scoreClassification = "bad" ;
    if (tbtTimeInMicroseconds <= TBT_MEDIUM_TIMING) {
        scoreClassification = "ok" ;
    }
    if (tbtTimeInMicroseconds <= TBT_GOOD_TIMING) {
        scoreClassification = "good" ;
    }
    return scoreClassification;
}
function gatherFinalLCPEvents() {
    const allFinalLCPEvents = [];
    const dataForAllFrames = [...metricScoresByFrameId.values()];
    const dataForAllNavigations = dataForAllFrames.flatMap(frameData => [...frameData.values()]);
    for (let i = 0; i < dataForAllNavigations.length; i++) {
        const navigationData = dataForAllNavigations[i];
        const lcpInNavigation = navigationData.get("LCP" );
        if (!lcpInNavigation?.event) {
            continue;
        }
        allFinalLCPEvents.push(lcpInNavigation.event);
    }
    return allFinalLCPEvents;
}
async function finalize$t() {
    pageLoadEventsArray.sort((a, b) => a.ts - b.ts);
    for (const pageLoadEvent of pageLoadEventsArray) {
        const navigation = getNavigationForPageLoadEvent(pageLoadEvent);
        if (navigation) {
            storePageLoadMetricAgainstNavigationId(navigation, pageLoadEvent);
        }
    }
    const allFinalLCPEvents = gatherFinalLCPEvents();
    const mainFrame = data$p().mainFrameId;
    const allEventsButLCP = pageLoadEventsArray.filter(event => !isAnyLargestContentfulPaintCandidate(event));
    const markerEvents = [...allFinalLCPEvents, ...allEventsButLCP].filter(isMarkerEvent);
    allMarkerEvents =
        markerEvents.filter(event => getFrameIdForPageLoadEvent(event) === mainFrame).sort((a, b) => a.ts - b.ts);
}
function data$b() {
    return {
        metricScoresByFrameId,
        allMarkerEvents,
    };
}
function deps$6() {
    return ['Meta'];
}
function metricIsLCP(metric) {
    return metric.metricName === "LCP" ;
}

var PageLoadMetricsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$b,
	deps: deps$6,
	finalize: finalize$t,
	getFrameIdForPageLoadEvent: getFrameIdForPageLoadEvent,
	handleEvent: handleEvent$b,
	metricIsLCP: metricIsLCP,
	reset: reset$b,
	scoreClassificationForDOMContentLoaded: scoreClassificationForDOMContentLoaded,
	scoreClassificationForFirstContentfulPaint: scoreClassificationForFirstContentfulPaint,
	scoreClassificationForLargestContentfulPaint: scoreClassificationForLargestContentfulPaint,
	scoreClassificationForTimeToInteractive: scoreClassificationForTimeToInteractive,
	scoreClassificationForTotalBlockingTime: scoreClassificationForTotalBlockingTime
});

// Copyright 2022 The Chromium Authors
let imagePaintsByNodeIdAndProcess = new Map();
let lcpRequestByNavigationId = new Map();
function reset$a() {
    imagePaintsByNodeIdAndProcess = new Map();
    lcpRequestByNavigationId = new Map();
}
function handleEvent$a(event) {
    if (!isLargestImagePaintCandidate(event) || !event.args.data) {
        return;
    }
    const imagePaintsByNodeId = getWithDefault(imagePaintsByNodeIdAndProcess, event.pid, () => new Map());
    imagePaintsByNodeId.set(event.args.data.DOMNodeId, event);
}
async function finalize$s() {
    const requests = data$o().byTime;
    const { traceBounds, navigationsByNavigationId } = data$p();
    const metricScoresByFrameId = data$b().metricScoresByFrameId;
    for (const [navigationId, navigation] of navigationsByNavigationId) {
        const lcpMetric = metricScoresByFrameId.get(navigation.args.frame)?.get(navigation)?.get("LCP" );
        const lcpEvent = lcpMetric?.event;
        if (!lcpEvent || !isAnyLargestContentfulPaintCandidate(lcpEvent)) {
            continue;
        }
        const nodeId = lcpEvent.args.data?.nodeId;
        if (!nodeId) {
            continue;
        }
        const lcpImagePaintEvent = imagePaintsByNodeIdAndProcess.get(lcpEvent.pid)?.get(nodeId);
        const lcpUrl = lcpImagePaintEvent?.args.data?.imageUrl;
        if (!lcpUrl) {
            continue;
        }
        const startTime = navigation?.ts ?? traceBounds.min;
        const endTime = lcpImagePaintEvent.ts;
        let lcpRequest;
        for (const request of requests) {
            if (request.ts < startTime) {
                continue;
            }
            if (request.ts >= endTime) {
                break;
            }
            if (request.args.data.url === lcpUrl || request.args.data.redirects.some(r => r.url === lcpUrl)) {
                lcpRequest = request;
                break;
            }
        }
        if (lcpRequest) {
            lcpRequestByNavigationId.set(navigationId, lcpRequest);
        }
    }
}
function data$a() {
    return { lcpRequestByNavigationId };
}
function deps$5() {
    return ['Meta', 'NetworkRequests', 'PageLoadMetrics'];
}

var LargestImagePaintHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$a,
	deps: deps$5,
	finalize: finalize$s,
	handleEvent: handleEvent$a,
	reset: reset$a
});

// Copyright 2022 The Chromium Authors
let textPaintByDOMNodeId = new Map();
function reset$9() {
    textPaintByDOMNodeId = new Map();
}
function handleEvent$9(event) {
    if (!isLargestTextPaintCandidate(event)) {
        return;
    }
    if (!event.args.data) {
        return;
    }
    textPaintByDOMNodeId.set(event.args.data.DOMNodeId, event);
}
async function finalize$r() {
}
function data$9() {
    return textPaintByDOMNodeId;
}

var LargestTextPaintHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$9,
	finalize: finalize$r,
	handleEvent: handleEvent$9,
	reset: reset$9
});

// Copyright 2022 The Chromium Authors
let unpairedAsyncEvents = [];
let legacyScreenshotEvents = [];
let modernScreenshotEvents = [];
let syntheticScreenshots = [];
function reset$8() {
    unpairedAsyncEvents = [];
    legacyScreenshotEvents = [];
    syntheticScreenshots = [];
    modernScreenshotEvents = [];
}
function handleEvent$8(event) {
    if (isLegacyScreenshot(event)) {
        legacyScreenshotEvents.push(event);
    }
    else if (isScreenshot(event)) {
        modernScreenshotEvents.push(event);
    }
    else if (isPipelineReporter(event)) {
        unpairedAsyncEvents.push(event);
    }
}
async function finalize$q() {
    const pipelineReporterEvents = createMatchedSortedSyntheticEvents(unpairedAsyncEvents);
    Object.fromEntries(pipelineReporterEvents.map(evt => {
        const args = evt.args.data.beginEvent.args;
        const frameReporter = 'frame_reporter' in args ? args.frame_reporter : args.chrome_frame_reporter;
        const frameSequenceId = frameReporter.frame_sequence;
        const presentationTs = Micro(evt.ts + evt.dur);
        return [frameSequenceId, presentationTs];
    }));
    for (const snapshotEvent of legacyScreenshotEvents) {
        const { cat, name, ph, pid, tid } = snapshotEvent;
        const syntheticEvent = SyntheticEventsManager.registerSyntheticEvent({
            rawSourceEvent: snapshotEvent,
            cat,
            name,
            ph,
            pid,
            tid,
            ts: snapshotEvent.ts,
            args: {
                dataUri: `data:image/jpg;base64,${snapshotEvent.args.snapshot}`,
            },
        });
        syntheticScreenshots.push(syntheticEvent);
    }
}
function screenshotImageDataUri(event) {
    if (isLegacySyntheticScreenshot(event)) {
        return event.args.dataUri;
    }
    return `data:image/jpg;base64,${event.args.snapshot}`;
}
function data$8() {
    return {
        legacySyntheticScreenshots: syntheticScreenshots.length ? syntheticScreenshots : null,
        screenshots: modernScreenshotEvents.length ? modernScreenshotEvents : null,
    };
}
function deps$4() {
    return ['Meta'];
}

var ScreenshotsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$8,
	deps: deps$4,
	finalize: finalize$q,
	handleEvent: handleEvent$8,
	reset: reset$8,
	screenshotImageDataUri: screenshotImageDataUri
});

// Copyright 2022 The Chromium Authors
const MAX_CLUSTER_DURATION = milliToMicro(Milli(5000));
const MAX_SHIFT_TIME_DELTA = milliToMicro(Milli(1000));
let layoutShiftEvents = [];
let layoutInvalidationEvents = [];
let scheduleStyleInvalidationEvents = [];
let styleRecalcInvalidationEvents = [];
let renderFrameImplCreateChildFrameEvents = [];
let domLoadingEvents = [];
let layoutImageUnsizedEvents = [];
let remoteFonts = [];
let backendNodeIds = new Set();
let prePaintEvents = [];
let paintImageEvents = [];
let sessionMaxScore = 0;
let clsWindowID = -1;
let clusters = [];
let clustersByNavigationId = new Map();
let scoreRecords = [];
function reset$7() {
    layoutShiftEvents = [];
    layoutInvalidationEvents = [];
    scheduleStyleInvalidationEvents = [];
    styleRecalcInvalidationEvents = [];
    prePaintEvents = [];
    paintImageEvents = [];
    renderFrameImplCreateChildFrameEvents = [];
    layoutImageUnsizedEvents = [];
    domLoadingEvents = [];
    remoteFonts = [];
    backendNodeIds = new Set();
    clusters = [];
    sessionMaxScore = 0;
    scoreRecords = [];
    clsWindowID = -1;
    clustersByNavigationId = new Map();
}
function handleEvent$7(event) {
    if (isLayoutShift(event) && !event.args.data?.had_recent_input) {
        layoutShiftEvents.push(event);
        return;
    }
    if (isLayoutInvalidationTracking(event)) {
        layoutInvalidationEvents.push(event);
        return;
    }
    if (isScheduleStyleInvalidationTracking(event)) {
        scheduleStyleInvalidationEvents.push(event);
    }
    if (isStyleRecalcInvalidationTracking(event)) {
        styleRecalcInvalidationEvents.push(event);
    }
    if (isPrePaint(event)) {
        prePaintEvents.push(event);
        return;
    }
    if (isRenderFrameImplCreateChildFrame(event)) {
        renderFrameImplCreateChildFrameEvents.push(event);
    }
    if (isDomLoading(event)) {
        domLoadingEvents.push(event);
    }
    if (isLayoutImageUnsized(event)) {
        layoutImageUnsizedEvents.push(event);
    }
    if (isBeginRemoteFontLoad(event)) {
        remoteFonts.push({
            display: event.args.display,
            url: event.args.url,
            beginRemoteFontLoadEvent: event,
        });
    }
    if (isRemoteFontLoaded(event)) {
        for (const remoteFont of remoteFonts) {
            if (remoteFont.url === event.args.url) {
                remoteFont.name = event.args.name;
            }
        }
    }
    if (isPaintImage(event)) {
        paintImageEvents.push(event);
    }
}
function traceWindowFromTime(time) {
    return {
        min: time,
        max: time,
        range: Micro(0),
    };
}
function updateTraceWindowMax(traceWindow, newMax) {
    traceWindow.max = newMax;
    traceWindow.range = Micro(traceWindow.max - traceWindow.min);
}
function findScreenshots(timestamp) {
    const data = data$8();
    if (data.screenshots) {
        const before = findPreviousEventBeforeTimestamp(data.screenshots, timestamp);
        const after = before ? data.screenshots[data.screenshots.indexOf(before) + 1] : null;
        return { before, after };
    }
    if (data.legacySyntheticScreenshots) {
        const before = findPreviousEventBeforeTimestamp(data.legacySyntheticScreenshots, timestamp);
        const after = before ? data.legacySyntheticScreenshots[data.legacySyntheticScreenshots.indexOf(before) + 1] : null;
        return { before, after };
    }
    return { before: null, after: null };
}
function buildScoreRecords() {
    const { traceBounds } = data$p();
    scoreRecords.push({ ts: traceBounds.min, score: 0 });
    for (const cluster of clusters) {
        let clusterScore = 0;
        if (cluster.events[0].args.data) {
            scoreRecords.push({ ts: cluster.clusterWindow.min, score: cluster.events[0].args.data.weighted_score_delta });
        }
        for (let i = 0; i < cluster.events.length; i++) {
            const event = cluster.events[i];
            if (!event.args.data) {
                continue;
            }
            clusterScore += event.args.data.weighted_score_delta;
            scoreRecords.push({ ts: event.ts, score: clusterScore });
        }
        scoreRecords.push({ ts: cluster.clusterWindow.max, score: 0 });
    }
}
function collectNodes() {
    backendNodeIds.clear();
    for (const layoutShift of layoutShiftEvents) {
        if (!layoutShift.args.data?.impacted_nodes) {
            continue;
        }
        for (const node of layoutShift.args.data.impacted_nodes) {
            backendNodeIds.add(node.node_id);
        }
    }
    for (const layoutInvalidation of layoutInvalidationEvents) {
        if (!layoutInvalidation.args.data?.nodeId) {
            continue;
        }
        backendNodeIds.add(layoutInvalidation.args.data.nodeId);
    }
    for (const scheduleStyleInvalidation of scheduleStyleInvalidationEvents) {
        if (!scheduleStyleInvalidation.args.data?.nodeId) {
            continue;
        }
        backendNodeIds.add(scheduleStyleInvalidation.args.data.nodeId);
    }
}
async function finalize$p() {
    layoutShiftEvents.sort((a, b) => a.ts - b.ts);
    prePaintEvents.sort((a, b) => a.ts - b.ts);
    layoutInvalidationEvents.sort((a, b) => a.ts - b.ts);
    renderFrameImplCreateChildFrameEvents.sort((a, b) => a.ts - b.ts);
    domLoadingEvents.sort((a, b) => a.ts - b.ts);
    layoutImageUnsizedEvents.sort((a, b) => a.ts - b.ts);
    remoteFonts.sort((a, b) => a.beginRemoteFontLoadEvent.ts - b.beginRemoteFontLoadEvent.ts);
    paintImageEvents.sort((a, b) => a.ts - b.ts);
    await buildLayoutShiftsClusters();
    buildScoreRecords();
    collectNodes();
}
async function buildLayoutShiftsClusters() {
    const { navigationsByFrameId, mainFrameId, traceBounds } = data$p();
    const navigations = navigationsByFrameId.get(mainFrameId) || [];
    if (layoutShiftEvents.length === 0) {
        return;
    }
    let firstShiftTime = layoutShiftEvents[0].ts;
    let lastShiftTime = layoutShiftEvents[0].ts;
    let lastShiftNavigation = null;
    for (const event of layoutShiftEvents) {
        const clusterDurationExceeded = event.ts - firstShiftTime > MAX_CLUSTER_DURATION;
        const maxTimeDeltaSinceLastShiftExceeded = event.ts - lastShiftTime > MAX_SHIFT_TIME_DELTA;
        const currentShiftNavigation = nearestIndexFromEnd(navigations, nav => nav.ts < event.ts);
        const hasNavigated = lastShiftNavigation !== currentShiftNavigation && currentShiftNavigation !== null;
        if (clusterDurationExceeded || maxTimeDeltaSinceLastShiftExceeded || hasNavigated || !clusters.length) {
            const clusterStartTime = event.ts;
            const endTimeByMaxSessionDuration = clusterDurationExceeded ? firstShiftTime + MAX_CLUSTER_DURATION : Infinity;
            const endTimeByMaxShiftGap = maxTimeDeltaSinceLastShiftExceeded ? lastShiftTime + MAX_SHIFT_TIME_DELTA : Infinity;
            const endTimeByNavigation = hasNavigated ? navigations[currentShiftNavigation].ts : Infinity;
            const previousClusterEndTime = Math.min(endTimeByMaxSessionDuration, endTimeByMaxShiftGap, endTimeByNavigation);
            if (clusters.length > 0) {
                const currentCluster = clusters[clusters.length - 1];
                updateTraceWindowMax(currentCluster.clusterWindow, Micro(previousClusterEndTime));
            }
            const navigationId = currentShiftNavigation === null ?
                NO_NAVIGATION :
                navigations[currentShiftNavigation].args.data?.navigationId;
            clusters.push(SyntheticEventsManager
                .registerSyntheticEvent({
                name: 'SyntheticLayoutShiftCluster',
                rawSourceEvent: event,
                events: [],
                clusterWindow: traceWindowFromTime(clusterStartTime),
                clusterCumulativeScore: 0,
                scoreWindows: {
                    good: traceWindowFromTime(clusterStartTime),
                },
                navigationId,
                ts: event.ts,
                pid: event.pid,
                tid: event.tid,
                ph: "X" ,
                cat: '',
                dur: Micro(-1),
            }));
            firstShiftTime = clusterStartTime;
        }
        const currentCluster = clusters[clusters.length - 1];
        const timeFromNavigation = currentShiftNavigation !== null ?
            Micro(event.ts - navigations[currentShiftNavigation].ts) :
            undefined;
        currentCluster.clusterCumulativeScore += event.args.data ? event.args.data.weighted_score_delta : 0;
        if (!event.args.data) {
            continue;
        }
        const shift = SyntheticEventsManager.registerSyntheticEvent({
            rawSourceEvent: event,
            ...event,
            name: "SyntheticLayoutShift" ,
            args: {
                frame: event.args.frame,
                data: {
                    ...event.args.data,
                    rawEvent: event,
                    navigationId: currentCluster.navigationId ?? undefined,
                },
            },
            parsedData: {
                timeFromNavigation,
                screenshots: findScreenshots(event.ts),
                cumulativeWeightedScoreInWindow: currentCluster.clusterCumulativeScore,
                sessionWindowData: { cumulativeWindowScore: 0, id: clusters.length },
            },
        });
        currentCluster.events.push(shift);
        updateTraceWindowMax(currentCluster.clusterWindow, event.ts);
        lastShiftTime = event.ts;
        lastShiftNavigation = currentShiftNavigation;
    }
    for (const cluster of clusters) {
        let weightedScore = 0;
        let windowID = -1;
        if (cluster === clusters[clusters.length - 1]) {
            const clusterEndByMaxDuration = MAX_CLUSTER_DURATION + cluster.clusterWindow.min;
            const clusterEndByMaxGap = cluster.clusterWindow.max + MAX_SHIFT_TIME_DELTA;
            const nextNavigationIndex = nearestIndexFromBeginning(navigations, nav => nav.ts > cluster.clusterWindow.max);
            const nextNavigationTime = nextNavigationIndex ? navigations[nextNavigationIndex].ts : Infinity;
            const clusterEnd = Math.min(clusterEndByMaxDuration, clusterEndByMaxGap, traceBounds.max, nextNavigationTime);
            updateTraceWindowMax(cluster.clusterWindow, Micro(clusterEnd));
        }
        let largestScore = 0;
        let worstShiftEvent = null;
        for (const shift of cluster.events) {
            weightedScore += shift.args.data ? shift.args.data.weighted_score_delta : 0;
            windowID = shift.parsedData.sessionWindowData.id;
            const ts = shift.ts;
            shift.parsedData.sessionWindowData.cumulativeWindowScore = cluster.clusterCumulativeScore;
            if (weightedScore < 0.1 ) {
                updateTraceWindowMax(cluster.scoreWindows.good, ts);
            }
            else if (weightedScore >= 0.1  && weightedScore < 0.25 ) {
                if (!cluster.scoreWindows.needsImprovement) {
                    updateTraceWindowMax(cluster.scoreWindows.good, Micro(ts - 1));
                    cluster.scoreWindows.needsImprovement = traceWindowFromTime(ts);
                }
                updateTraceWindowMax(cluster.scoreWindows.needsImprovement, ts);
            }
            else if (weightedScore >= 0.25 ) {
                if (!cluster.scoreWindows.bad) {
                    if (cluster.scoreWindows.needsImprovement) {
                        updateTraceWindowMax(cluster.scoreWindows.needsImprovement, Micro(ts - 1));
                    }
                    else {
                        updateTraceWindowMax(cluster.scoreWindows.good, Micro(ts - 1));
                    }
                    cluster.scoreWindows.bad = traceWindowFromTime(shift.ts);
                }
                updateTraceWindowMax(cluster.scoreWindows.bad, ts);
            }
            if (cluster.scoreWindows.bad) {
                updateTraceWindowMax(cluster.scoreWindows.bad, cluster.clusterWindow.max);
            }
            else if (cluster.scoreWindows.needsImprovement) {
                updateTraceWindowMax(cluster.scoreWindows.needsImprovement, cluster.clusterWindow.max);
            }
            else {
                updateTraceWindowMax(cluster.scoreWindows.good, cluster.clusterWindow.max);
            }
            const score = shift.args.data?.weighted_score_delta;
            if (score !== undefined && score > largestScore) {
                largestScore = score;
                worstShiftEvent = shift;
            }
        }
        if (worstShiftEvent) {
            cluster.worstShiftEvent = worstShiftEvent;
            cluster.rawSourceEvent = worstShiftEvent.rawSourceEvent;
        }
        cluster.ts = cluster.events[0].ts;
        const lastShiftTimings = eventTimingsMicroSeconds(cluster.events[cluster.events.length - 1]);
        cluster.dur = Micro((lastShiftTimings.endTime - cluster.events[0].ts) + MAX_SHIFT_TIME_DELTA);
        if (weightedScore > sessionMaxScore) {
            clsWindowID = windowID;
            sessionMaxScore = weightedScore;
        }
        if (cluster.navigationId) {
            const clustersForId = getWithDefault(clustersByNavigationId, cluster.navigationId, () => {
                return [];
            });
            clustersForId.push(cluster);
        }
    }
}
function data$7() {
    return {
        clusters,
        sessionMaxScore,
        clsWindowID,
        prePaintEvents,
        layoutInvalidationEvents,
        scheduleStyleInvalidationEvents,
        styleRecalcInvalidationEvents,
        renderFrameImplCreateChildFrameEvents,
        domLoadingEvents,
        layoutImageUnsizedEvents,
        remoteFonts,
        scoreRecords,
        backendNodeIds,
        clustersByNavigationId,
        paintImageEvents,
    };
}
function deps$3() {
    return ['Screenshots', 'Meta'];
}
function scoreClassificationForLayoutShift(score) {
    let state = "good" ;
    if (score >= 0.1 ) {
        state = "ok" ;
    }
    if (score >= 0.25 ) {
        state = "bad" ;
    }
    return state;
}

var LayoutShiftsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	MAX_CLUSTER_DURATION: MAX_CLUSTER_DURATION,
	MAX_SHIFT_TIME_DELTA: MAX_SHIFT_TIME_DELTA,
	data: data$7,
	deps: deps$3,
	finalize: finalize$p,
	handleEvent: handleEvent$7,
	reset: reset$7,
	scoreClassificationForLayoutShift: scoreClassificationForLayoutShift
});

// Copyright 2023 The Chromium Authors
let updateCountersByProcess = new Map();
function reset$6() {
    updateCountersByProcess = new Map();
}
function handleEvent$6(event) {
    if (isUpdateCounters(event)) {
        const countersForProcess = getWithDefault(updateCountersByProcess, event.pid, () => []);
        countersForProcess.push(event);
        updateCountersByProcess.set(event.pid, countersForProcess);
    }
}
async function finalize$o() {
}
function data$6() {
    return { updateCountersByProcess };
}

var MemoryHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$6,
	finalize: finalize$o,
	handleEvent: handleEvent$6,
	reset: reset$6
});

// Copyright 2024 The Chromium Authors
let frames = new Map();
function reset$5() {
    frames = new Map();
}
function handleEvent$5(event) {
    if (isTracingStartedInBrowser(event)) {
        for (const frame of event.args.data?.frames ?? []) {
            frames.set(frame.frame, frame);
        }
        return;
    }
    if (isCommitLoad(event)) {
        const frameData = event.args.data;
        if (!frameData) {
            return;
        }
        const frame = frames.get(frameData.frame);
        if (!frame) {
            return;
        }
        frames.set(frameData.frame, {
            ...frame,
            url: frameData.url || frame.url,
            name: frameData.name || frameData.name,
        });
    }
}
async function finalize$n() {
}
function data$5() {
    return {
        frames,
    };
}

var PageFramesHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$5,
	finalize: finalize$n,
	handleEvent: handleEvent$5,
	reset: reset$5
});

// Copyright 2025 The Chromium Authors
let scriptById = new Map();
let frameIdByIsolate = new Map();
function deps$2() {
    return ['Meta', 'NetworkRequests'];
}
function reset$4() {
    scriptById = new Map();
    frameIdByIsolate = new Map();
}
function handleEvent$4(event) {
    const getOrMakeScript = (isolate, scriptIdAsNumber) => {
        const scriptId = String(scriptIdAsNumber);
        const key = `${isolate}.${scriptId}`;
        return getWithDefault(scriptById, key, () => ({ isolate, scriptId, frame: '', ts: event.ts }));
    };
    if (isRundownScriptCompiled(event) && event.args.data) {
        const { isolate, scriptId, frame } = event.args.data;
        const script = getOrMakeScript(isolate, scriptId);
        script.frame = frame;
        script.ts = event.ts;
        return;
    }
    if (isRundownScript(event)) {
        const { isolate, scriptId, url, sourceUrl, sourceMapUrl, sourceMapUrlElided } = event.args.data;
        const script = getOrMakeScript(isolate, scriptId);
        if (!script.frame) {
            script.frame = frameIdByIsolate.get(String(isolate)) ?? '';
        }
        script.url = url;
        script.ts = event.ts;
        if (sourceUrl) {
            script.sourceUrl = sourceUrl;
        }
        if (sourceMapUrlElided) {
            script.sourceMapUrlElided = true;
        }
        else if (sourceMapUrl) {
            script.sourceMapUrl = sourceMapUrl;
        }
        return;
    }
    if (isRundownScriptSource(event)) {
        const { isolate, scriptId, sourceText } = event.args.data;
        const script = getOrMakeScript(isolate, scriptId);
        script.content = sourceText;
        return;
    }
    if (isRundownScriptSourceLarge(event)) {
        const { isolate, scriptId, sourceText } = event.args.data;
        const script = getOrMakeScript(isolate, scriptId);
        script.content = (script.content ?? '') + sourceText;
        return;
    }
    if (isFunctionCall(event) && event.args.data?.isolate && event.args.data.frame) {
        const { isolate, frame } = event.args.data;
        const existingValue = frameIdByIsolate.get(isolate);
        if (existingValue !== frame) {
            frameIdByIsolate.set(isolate, frame);
            for (const script of scriptById.values()) {
                if (!script.frame && script.isolate === isolate) {
                    script.frame = frame;
                }
            }
        }
    }
}
function findFrame(meta, frameId) {
    for (const frames of meta.frameByProcessId?.values()) {
        const frame = frames.get(frameId);
        if (frame) {
            return frame;
        }
    }
    return null;
}
function findNetworkRequest(networkRequests, script) {
    if (!script.url) {
        return null;
    }
    return networkRequests.find(request => request.args.data.url === script.url) ?? null;
}
function computeMappingEndColumns(map) {
    const result = new Map();
    const mappings = map.mappings();
    for (let i = 0; i < mappings.length - 1; i++) {
        const mapping = mappings[i];
        const nextMapping = mappings[i + 1];
        if (mapping.lineNumber === nextMapping.lineNumber) {
            result.set(mapping, nextMapping.columnNumber);
        }
    }
    return result;
}
function computeGeneratedFileSizes(script) {
    if (!script.sourceMap) {
        throw new Error('expected source map');
    }
    const map = script.sourceMap;
    const content = script.content ?? '';
    const contentLength = content.length;
    const lines = content.split('\n');
    const files = {};
    const totalBytes = contentLength;
    let unmappedBytes = totalBytes;
    const mappingEndCols = computeMappingEndColumns(script.sourceMap);
    for (const mapping of map.mappings()) {
        const source = mapping.sourceURL;
        const lineNum = mapping.lineNumber;
        const colNum = mapping.columnNumber;
        const lastColNum = mappingEndCols.get(mapping);
        if (!source) {
            continue;
        }
        const line = lines[lineNum];
        if (line === null || line === undefined) {
            const errorMessage = `${map.url()} mapping for line out of bounds: ${lineNum + 1}`;
            return { errorMessage };
        }
        if (colNum > line.length) {
            const errorMessage = `${map.url()} mapping for column out of bounds: ${lineNum + 1}:${colNum}`;
            return { errorMessage };
        }
        let mappingLength = 0;
        if (lastColNum !== undefined) {
            if (lastColNum > line.length) {
                const errorMessage = `${map.url()} mapping for last column out of bounds: ${lineNum + 1}:${lastColNum}`;
                return { errorMessage };
            }
            mappingLength = lastColNum - colNum;
        }
        else {
            mappingLength = line.length - colNum + 1;
        }
        files[source] = (files[source] || 0) + mappingLength;
        unmappedBytes -= mappingLength;
    }
    return {
        files,
        unmappedBytes,
        totalBytes,
    };
}
function getScriptGeneratedSizes(script) {
    if (script.sourceMap && !script.sizes) {
        script.sizes = computeGeneratedFileSizes(script);
    }
    return script.sizes ?? null;
}
function findCachedRawSourceMap(script, options) {
    if (options.isFreshRecording || !options.metadata?.sourceMaps) {
        return;
    }
    if (script.sourceMapUrlElided) {
        if (!script.url) {
            return;
        }
        const cachedSourceMap = options.metadata.sourceMaps.find(m => m.url === script.url);
        if (cachedSourceMap) {
            return cachedSourceMap.sourceMap;
        }
        return;
    }
    if (!script.sourceMapUrl) {
        return;
    }
    const isDataUrl = script.sourceMapUrl.startsWith('data:');
    if (!isDataUrl) {
        const cachedSourceMap = options.metadata.sourceMaps.find(m => m.sourceMapUrl === script.sourceMapUrl);
        if (cachedSourceMap) {
            return cachedSourceMap.sourceMap;
        }
    }
    return;
}
async function finalize$m(options) {
    const meta = data$p();
    const networkRequests = [...data$o().byId.values()];
    const documentUrls = new Set();
    for (const frames of meta.frameByProcessId.values()) {
        for (const frame of frames.values()) {
            documentUrls.add(frame.url);
        }
    }
    for (const script of scriptById.values()) {
        script.request = findNetworkRequest(networkRequests, script) ?? undefined;
        script.inline = !!script.url && documentUrls.has(script.url);
    }
    if (!options.resolveSourceMap) {
        return;
    }
    const promises = [];
    for (const script of scriptById.values()) {
        if (!script.frame || !script.url || (!script.sourceMapUrl && !script.sourceMapUrlElided)) {
            continue;
        }
        const frameUrl = findFrame(meta, script.frame)?.url;
        if (!frameUrl) {
            continue;
        }
        let sourceUrl = script.url;
        if (script.sourceUrl) {
            sourceUrl = ParsedURL.completeURL(frameUrl, script.sourceUrl) ?? script.sourceUrl;
        }
        let sourceMapUrl;
        if (script.sourceMapUrl) {
            sourceMapUrl =
                ParsedURL.completeURL(sourceUrl, script.sourceMapUrl);
            if (!sourceMapUrl) {
                continue;
            }
            script.sourceMapUrl = sourceMapUrl;
        }
        const params = {
            scriptId: script.scriptId,
            scriptUrl: script.url,
            sourceUrl: sourceUrl,
            sourceMapUrl: sourceMapUrl ?? '',
            frame: script.frame,
            cachedRawSourceMap: findCachedRawSourceMap(script, options),
        };
        const promise = options.resolveSourceMap(params).then(sourceMap => {
            if (sourceMap) {
                script.sourceMap = sourceMap;
            }
        });
        promises.push(promise.catch(e => {
            console.error('Uncaught error when resolving source map', params, e);
        }));
    }
    await Promise.all(promises);
}
function data$4() {
    return {
        scripts: [...scriptById.values()],
    };
}

var ScriptsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$4,
	deps: deps$2,
	finalize: finalize$m,
	getScriptGeneratedSizes: getScriptGeneratedSizes,
	handleEvent: handleEvent$4,
	reset: reset$4
});

// Copyright 2024 The Chromium Authors
let lastRecalcStyleEvent = null;
let lastInvalidatedNode = null;
let selectorDataForRecalcStyle = new Map();
let invalidatedNodeList = new Array();
function reset$3() {
    lastRecalcStyleEvent = null;
    lastInvalidatedNode = null;
    selectorDataForRecalcStyle = new Map();
    invalidatedNodeList = [];
}
function handleEvent$3(event) {
    if (isStyleRecalcInvalidationTracking(event)) {
        if (event.args.data.subtree &&
            event.args.data.reason === "Related style rule"  &&
            lastInvalidatedNode && event.args.data.nodeId === lastInvalidatedNode.backendNodeId) {
            lastInvalidatedNode.subtree = true;
            return;
        }
    }
    if (isSelectorStats(event) && lastRecalcStyleEvent && event.args.selector_stats) {
        selectorDataForRecalcStyle.set(lastRecalcStyleEvent, {
            timings: event.args.selector_stats.selector_timings,
        });
        return;
    }
    if (isStyleInvalidatorInvalidationTracking(event)) {
        const selectorList = new Array();
        event.args.data.selectors?.forEach(selector => {
            selectorList.push({
                selector: selector.selector,
                styleSheetId: selector.style_sheet_id,
            });
        });
        if (selectorList.length > 0) {
            lastInvalidatedNode = {
                frame: event.args.data.frame,
                backendNodeId: event.args.data.nodeId,
                type: "StyleInvalidatorInvalidationTracking" ,
                selectorList,
                ts: event.ts,
                tts: event.tts,
                subtree: false,
                lastRecalcStyleEventTs: lastRecalcStyleEvent ? lastRecalcStyleEvent.ts : Micro(0),
            };
            invalidatedNodeList.push(lastInvalidatedNode);
        }
    }
    if (isRecalcStyle(event)) {
        lastRecalcStyleEvent = event;
        return;
    }
}
async function finalize$l() {
}
function data$3() {
    return {
        dataForRecalcStyleEvent: selectorDataForRecalcStyle,
        invalidatedNodeList,
    };
}

var SelectorStatsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$3,
	finalize: finalize$l,
	handleEvent: handleEvent$3,
	reset: reset$3
});

// Copyright 2022 The Chromium Authors
let beginCommitCompositorFrameEvents = [];
let parseMetaViewportEvents = [];
const LONG_INTERACTION_THRESHOLD = milliToMicro(Milli(200));
const INP_GOOD_TIMING = LONG_INTERACTION_THRESHOLD;
const INP_MEDIUM_TIMING = milliToMicro(Milli(500));
let longestInteractionEvent = null;
let interactionEvents = [];
let interactionEventsWithNoNesting = [];
let eventTimingStartEventsForInteractions = [];
let eventTimingEndEventsForInteractions = [];
function reset$2() {
    beginCommitCompositorFrameEvents = [];
    parseMetaViewportEvents = [];
    interactionEvents = [];
    eventTimingStartEventsForInteractions = [];
    eventTimingEndEventsForInteractions = [];
    interactionEventsWithNoNesting = [];
    longestInteractionEvent = null;
}
function handleEvent$2(event) {
    if (isBeginCommitCompositorFrame(event)) {
        beginCommitCompositorFrameEvents.push(event);
        return;
    }
    if (isParseMetaViewport(event)) {
        parseMetaViewportEvents.push(event);
        return;
    }
    if (!isEventTiming(event)) {
        return;
    }
    if (isEventTimingEnd(event)) {
        eventTimingEndEventsForInteractions.push(event);
    }
    if (!event.args.data || !isEventTimingStart(event)) {
        return;
    }
    const { duration, interactionId } = event.args.data;
    if (duration < 1 || interactionId === undefined || interactionId === 0) {
        return;
    }
    eventTimingStartEventsForInteractions.push(event);
}
const pointerEventTypes = new Set([
    'pointerdown',
    'touchstart',
    'pointerup',
    'touchend',
    'mousedown',
    'mouseup',
    'click',
]);
const keyboardEventTypes = new Set([
    'keydown',
    'keypress',
    'keyup',
]);
function categoryOfInteraction(interaction) {
    if (pointerEventTypes.has(interaction.type)) {
        return 'POINTER';
    }
    if (keyboardEventTypes.has(interaction.type)) {
        return 'KEYBOARD';
    }
    return 'OTHER';
}
function removeNestedInteractionsAndSetProcessingTime(interactions) {
    const earliestEventForEndTimePerCategory = {
        POINTER: new Map(),
        KEYBOARD: new Map(),
        OTHER: new Map(),
    };
    function storeEventIfEarliestForCategoryAndEndTime(interaction) {
        const category = categoryOfInteraction(interaction);
        const earliestEventForEndTime = earliestEventForEndTimePerCategory[category];
        const endTime = Micro(interaction.ts + interaction.dur);
        const earliestCurrentEvent = earliestEventForEndTime.get(endTime);
        if (!earliestCurrentEvent) {
            earliestEventForEndTime.set(endTime, interaction);
            return;
        }
        if (interaction.ts < earliestCurrentEvent.ts) {
            earliestEventForEndTime.set(endTime, interaction);
        }
        else if (interaction.ts === earliestCurrentEvent.ts &&
            interaction.interactionId === earliestCurrentEvent.interactionId) {
            const currentProcessingDuration = earliestCurrentEvent.processingEnd - earliestCurrentEvent.processingStart;
            const newProcessingDuration = interaction.processingEnd - interaction.processingStart;
            if (newProcessingDuration > currentProcessingDuration) {
                earliestEventForEndTime.set(endTime, interaction);
            }
        }
        if (interaction.processingStart < earliestCurrentEvent.processingStart) {
            earliestCurrentEvent.processingStart = interaction.processingStart;
            writeSyntheticTimespans(earliestCurrentEvent);
        }
        if (interaction.processingEnd > earliestCurrentEvent.processingEnd) {
            earliestCurrentEvent.processingEnd = interaction.processingEnd;
            writeSyntheticTimespans(earliestCurrentEvent);
        }
    }
    for (const interaction of interactions) {
        storeEventIfEarliestForCategoryAndEndTime(interaction);
    }
    const keptEvents = Object.values(earliestEventForEndTimePerCategory)
        .flatMap(eventsByEndTime => Array.from(eventsByEndTime.values()));
    keptEvents.sort((eventA, eventB) => {
        return eventA.ts - eventB.ts;
    });
    return keptEvents;
}
function writeSyntheticTimespans(event) {
    const startEvent = event.args.data.beginEvent;
    const endEvent = event.args.data.endEvent;
    event.inputDelay = Micro(event.processingStart - startEvent.ts);
    event.mainThreadHandling = Micro(event.processingEnd - event.processingStart);
    event.presentationDelay = Micro(endEvent.ts - event.processingEnd);
}
async function finalize$k() {
    const { navigationsByFrameId } = data$p();
    const beginAndEndEvents = mergeOrdered(eventTimingStartEventsForInteractions, eventTimingEndEventsForInteractions, eventTimeComparator);
    const beginEventById = new Map();
    for (const event of beginAndEndEvents) {
        if (isEventTimingStart(event)) {
            const forId = beginEventById.get(event.id) ?? [];
            forId.push(event);
            beginEventById.set(event.id, forId);
        }
        else if (isEventTimingEnd(event)) {
            const beginEvents = beginEventById.get(event.id) ?? [];
            const beginEvent = beginEvents.pop();
            if (!beginEvent) {
                continue;
            }
            const { type, interactionId, timeStamp, processingStart, processingEnd } = beginEvent.args.data;
            if (!type || !interactionId || !timeStamp || !processingStart || !processingEnd) {
                continue;
            }
            const processingStartRelativeToTraceTime = Micro(milliToMicro(processingStart) - milliToMicro(timeStamp) + beginEvent.ts);
            const processingEndRelativeToTraceTime = Micro((milliToMicro(processingEnd) - milliToMicro(timeStamp)) + beginEvent.ts);
            const frameId = beginEvent.args.frame ?? beginEvent.args.data.frame ?? '';
            const navigation = getNavigationForTraceEvent(beginEvent, frameId, navigationsByFrameId);
            const navigationId = navigation?.args.data?.navigationId;
            const interactionEvent = SyntheticEventsManager.registerSyntheticEvent({
                rawSourceEvent: beginEvent,
                cat: beginEvent.cat,
                name: beginEvent.name,
                pid: beginEvent.pid,
                tid: beginEvent.tid,
                ph: beginEvent.ph,
                processingStart: processingStartRelativeToTraceTime,
                processingEnd: processingEndRelativeToTraceTime,
                inputDelay: Micro(-1),
                mainThreadHandling: Micro(-1),
                presentationDelay: Micro(-1),
                args: {
                    data: {
                        beginEvent,
                        endEvent: event,
                        frame: frameId,
                        navigationId,
                    },
                },
                ts: beginEvent.ts,
                dur: Micro(event.ts - beginEvent.ts),
                type: beginEvent.args.data.type,
                interactionId: beginEvent.args.data.interactionId,
            });
            writeSyntheticTimespans(interactionEvent);
            interactionEvents.push(interactionEvent);
        }
    }
    sortTraceEventsInPlace(interactionEvents);
    interactionEventsWithNoNesting.push(...removeNestedInteractionsAndSetProcessingTime(interactionEvents));
    for (const interactionEvent of interactionEventsWithNoNesting) {
        if (!longestInteractionEvent || longestInteractionEvent.dur < interactionEvent.dur) {
            longestInteractionEvent = interactionEvent;
        }
    }
}
function data$2() {
    return {
        beginCommitCompositorFrameEvents,
        parseMetaViewportEvents,
        interactionEvents,
        interactionEventsWithNoNesting,
        longestInteractionEvent,
        interactionsOverThreshold: new Set(interactionEvents.filter(event => {
            return event.dur > LONG_INTERACTION_THRESHOLD;
        })),
    };
}
function deps$1() {
    return ['Meta'];
}
function scoreClassificationForInteractionToNextPaint(timing) {
    if (timing <= INP_GOOD_TIMING) {
        return "good" ;
    }
    if (timing <= INP_MEDIUM_TIMING) {
        return "ok" ;
    }
    return "bad" ;
}

var UserInteractionsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	LONG_INTERACTION_THRESHOLD: LONG_INTERACTION_THRESHOLD,
	categoryOfInteraction: categoryOfInteraction,
	data: data$2,
	deps: deps$1,
	finalize: finalize$k,
	handleEvent: handleEvent$2,
	removeNestedInteractionsAndSetProcessingTime: removeNestedInteractionsAndSetProcessingTime,
	reset: reset$2,
	scoreClassificationForInteractionToNextPaint: scoreClassificationForInteractionToNextPaint
});

// Copyright 2023 The Chromium Authors
let sessionIdEvents = [];
let workerIdByThread = new Map();
let workerURLById = new Map();
function reset$1() {
    sessionIdEvents = [];
    workerIdByThread = new Map();
    workerURLById = new Map();
}
function handleEvent$1(event) {
    if (isTracingSessionIdForWorker(event)) {
        sessionIdEvents.push(event);
    }
}
async function finalize$j() {
    for (const sessionIdEvent of sessionIdEvents) {
        if (!sessionIdEvent.args.data) {
            continue;
        }
        workerIdByThread.set(sessionIdEvent.args.data.workerThreadId, sessionIdEvent.args.data.workerId);
        workerURLById.set(sessionIdEvent.args.data.workerId, sessionIdEvent.args.data.url);
    }
}
function data$1() {
    return {
        workerSessionIdEvents: sessionIdEvents,
        workerIdByThread,
        workerURLById,
    };
}

var WorkersHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	data: data$1,
	finalize: finalize$j,
	handleEvent: handleEvent$1,
	reset: reset$1
});

// Copyright 2023 The Chromium Authors
let warningsPerEvent = new Map();
let eventsPerWarning = new Map();
let allEventsStack = [];
let jsInvokeStack = [];
let taskReflowEvents = [];
let longTaskEvents = [];
const FORCED_REFLOW_THRESHOLD = milliToMicro(Milli(30));
const LONG_MAIN_THREAD_TASK_THRESHOLD = milliToMicro(Milli(50));
function reset() {
    warningsPerEvent = new Map();
    eventsPerWarning = new Map();
    allEventsStack = [];
    jsInvokeStack = [];
    taskReflowEvents = [];
    longTaskEvents = [];
}
function storeWarning(event, warning) {
    const existingWarnings = getWithDefault(warningsPerEvent, event, () => []);
    existingWarnings.push(warning);
    warningsPerEvent.set(event, existingWarnings);
    const existingEvents = getWithDefault(eventsPerWarning, warning, () => []);
    existingEvents.push(event);
    eventsPerWarning.set(warning, existingEvents);
}
function handleEvent(event) {
    processForcedReflowWarning(event);
    if (event.name === "RunTask" ) {
        const { duration } = eventTimingsMicroSeconds(event);
        if (duration > LONG_MAIN_THREAD_TASK_THRESHOLD) {
            longTaskEvents.push(event);
        }
        return;
    }
    if (isFireIdleCallback(event)) {
        const { duration } = eventTimingsMilliSeconds(event);
        if (duration > event.args.data.allottedMilliseconds) {
            storeWarning(event, 'IDLE_CALLBACK_OVER_TIME');
        }
        return;
    }
}
function processForcedReflowWarning(event) {
    accomodateEventInStack(event, allEventsStack);
    accomodateEventInStack(event, jsInvokeStack,  isJSInvocationEvent(event));
    if (jsInvokeStack.length) {
        if (event.name === "Layout"  || event.name === "UpdateLayoutTree" ) {
            taskReflowEvents.push(event);
            return;
        }
    }
    if (allEventsStack.length === 1) {
        const totalTime = taskReflowEvents.reduce((time, event) => time + (event.dur || 0), 0);
        if (totalTime >= FORCED_REFLOW_THRESHOLD) {
            taskReflowEvents.forEach(reflowEvent => storeWarning(reflowEvent, 'FORCED_REFLOW'));
        }
        taskReflowEvents.length = 0;
    }
}
function accomodateEventInStack(event, stack, pushEventToStack = true) {
    let nextItem = stack.at(-1);
    while (nextItem && event.ts > nextItem.ts + (nextItem.dur || 0)) {
        stack.pop();
        nextItem = stack.at(-1);
    }
    if (!pushEventToStack) {
        return;
    }
    stack.push(event);
}
function deps() {
    return ['UserInteractions', 'Workers'];
}
async function finalize$i() {
    const longInteractions = data$2().interactionsOverThreshold;
    for (const interaction of longInteractions) {
        storeWarning(interaction, 'LONG_INTERACTION');
    }
    for (const event of longTaskEvents) {
        if (!(event.tid, data$1().workerIdByThread.has(event.tid))) {
            storeWarning(event, 'LONG_TASK');
        }
    }
    longTaskEvents.length = 0;
}
function data() {
    return {
        perEvent: warningsPerEvent,
        perWarning: eventsPerWarning,
    };
}

var WarningsHandler = /*#__PURE__*/Object.freeze({
	__proto__: null,
	FORCED_REFLOW_THRESHOLD: FORCED_REFLOW_THRESHOLD,
	LONG_MAIN_THREAD_TASK_THRESHOLD: LONG_MAIN_THREAD_TASK_THRESHOLD,
	data: data,
	deps: deps,
	finalize: finalize$i,
	handleEvent: handleEvent,
	reset: reset
});

// Copyright 2022 The Chromium Authors

var ModelHandlers = /*#__PURE__*/Object.freeze({
	__proto__: null,
	AnimationFrames: AnimationFramesHandler,
	Animations: AnimationHandler,
	AsyncJSCalls: AsyncJSCallsHandler,
	AuctionWorklets: AuctionWorkletsHandler,
	DOMStats: DOMStatsHandler,
	ExtensionTraceData: ExtensionTraceDataHandler,
	Flows: FlowsHandler,
	Frames: FramesHandler,
	GPU: GPUHandler,
	ImagePainting: ImagePaintingHandler,
	Initiators: InitiatorsHandler,
	Invalidations: InvalidationsHandler,
	LargestImagePaint: LargestImagePaintHandler,
	LargestTextPaint: LargestTextPaintHandler,
	LayerTree: LayerTreeHandler,
	LayoutShifts: LayoutShiftsHandler,
	Memory: MemoryHandler,
	Meta: MetaHandler,
	NetworkRequests: NetworkRequestsHandler,
	PageFrames: PageFramesHandler,
	PageLoadMetrics: PageLoadMetricsHandler,
	Renderer: RendererHandler,
	Samples: SamplesHandler,
	Screenshots: ScreenshotsHandler,
	Scripts: ScriptsHandler,
	SelectorStats: SelectorStatsHandler,
	UserInteractions: UserInteractionsHandler,
	UserTimings: UserTimingsHandler,
	Warnings: WarningsHandler,
	Workers: WorkersHandler
});

var types$2 = /*#__PURE__*/Object.freeze({
	__proto__: null
});

// Copyright 2022 The Chromium Authors

var handlers = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Helpers: helpers$1,
	ModelHandlers: ModelHandlers,
	Threads: Threads,
	Types: types$2
});

// Copyright 2024 The Chromium Authors
class EntityMapper {
    #parsedTrace;
    #entityMappings;
    #firstPartyEntity;
    #thirdPartyEvents = [];
    #resolvedCallFrames = new Set();
    constructor(parsedTrace) {
        this.#parsedTrace = parsedTrace;
        this.#entityMappings = this.#parsedTrace.data.Renderer.entityMappings;
        this.#firstPartyEntity = this.#findFirstPartyEntity();
        this.#thirdPartyEvents = this.#getThirdPartyEvents();
    }
    #findFirstPartyEntity() {
        const nav = Array.from(this.#parsedTrace.data.Meta.navigationsByNavigationId.values()).sort((a, b) => a.ts - b.ts)[0];
        const firstPartyUrl = nav?.args.data?.documentLoaderURL ?? this.#parsedTrace.data.Meta.mainFrameURL;
        if (!firstPartyUrl) {
            return null;
        }
        return getEntityForUrl(firstPartyUrl, this.#entityMappings) ?? null;
    }
    #getThirdPartyEvents() {
        const entries = Array.from(this.#entityMappings.eventsByEntity.entries());
        const thirdPartyEvents = entries.flatMap(([entity, events]) => {
            return entity !== this.#firstPartyEntity ? events : [];
        });
        return thirdPartyEvents;
    }
    entityForEvent(event) {
        return this.#entityMappings.entityByEvent.get(event) ?? null;
    }
    eventsForEntity(entity) {
        return this.#entityMappings.eventsByEntity.get(entity) ?? [];
    }
    firstPartyEntity() {
        return this.#firstPartyEntity;
    }
    thirdPartyEvents() {
        return this.#thirdPartyEvents;
    }
    mappings() {
        return this.#entityMappings;
    }
    updateSourceMapEntities(callFrame, sourceURL) {
        if (this.#resolvedCallFrames.has(callFrame)) {
            return;
        }
        const compiledURL = callFrame.url;
        const currentEntity = getEntityForUrl(compiledURL, this.#entityMappings);
        const resolvedEntity = getEntityForUrl(sourceURL, this.#entityMappings);
        if ((resolvedEntity === currentEntity) || (!currentEntity || !resolvedEntity)) {
            return;
        }
        const currentEntityEvents = (currentEntity && this.#entityMappings.eventsByEntity.get(currentEntity)) ?? [];
        const sourceLocationEvents = [];
        const unrelatedEvents = [];
        currentEntityEvents?.forEach(e => {
            const cf = getStackTraceTopCallFrameInEventPayload(e);
            const matchesCallFrame = cf && isMatchingCallFrame(cf, callFrame);
            if (matchesCallFrame) {
                sourceLocationEvents.push(e);
            }
            else {
                unrelatedEvents.push(e);
            }
        });
        this.#entityMappings.eventsByEntity.set(currentEntity, unrelatedEvents);
        this.#entityMappings.eventsByEntity.set(resolvedEntity, sourceLocationEvents);
        sourceLocationEvents.forEach(e => {
            this.#entityMappings.entityByEvent.set(e, resolvedEntity);
        });
        this.#resolvedCallFrames.add(callFrame);
    }
    updateExtensionEntitiesWithName(executionContextNamesByOrigin) {
        const entities = Array.from(this.#entityMappings.eventsByEntity.keys());
        for (const [origin, name] of executionContextNamesByOrigin) {
            const entity = entities.find(e => e.domains[0] === origin);
            if (entity) {
                entity.name = entity.company = name;
            }
        }
    }
}

var EntityMapper$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	EntityMapper: EntityMapper
});

// Copyright 2024 The Chromium Authors
class EventsSerializer {
    #modifiedProfileCallByKey = new Map();
    keyForEvent(event) {
        if (isProfileCall(event)) {
            return `${"p" }-${event.pid}-${event.tid}-${SampleIndex(event.sampleIndex)}-${event.nodeId}`;
        }
        if (isLegacyTimelineFrame(event)) {
            return `${"l" }-${event.index}`;
        }
        if (isJSSample(event)) {
            return null;
        }
        const rawEvents = SyntheticEventsManager.getActiveManager().getRawTraceEvents();
        const isSynthetic = isSyntheticBased(event);
        const index = rawEvents.indexOf(isSynthetic ? event.rawSourceEvent : event);
        if (index === -1) {
            return null;
        }
        const key = isSyntheticBased(event) ?
            `${"s" }-${index}` :
            `${"r" }-${index}`;
        if (key.length < 3) {
            return null;
        }
        return key;
    }
    eventForKey(key, parsedTrace) {
        const eventValues = traceEventKeyToValues(key);
        if (EventsSerializer.isProfileCallKey(eventValues)) {
            return this.#getModifiedProfileCallByKeyValues(eventValues, parsedTrace);
        }
        if (EventsSerializer.isLegacyTimelineFrameKey(eventValues)) {
            const event = parsedTrace.data.Frames.frames.at(eventValues.rawIndex);
            if (!event) {
                throw new Error(`Unknown trace event. Could not find frame with index ${eventValues.rawIndex}`);
            }
            return event;
        }
        if (EventsSerializer.isSyntheticEventKey(eventValues)) {
            const syntheticEvents = SyntheticEventsManager.getActiveManager().getSyntheticTraces();
            const syntheticEvent = syntheticEvents.at(eventValues.rawIndex);
            if (!syntheticEvent) {
                throw new Error(`Unknown trace event. Attempted to get a synthetic event from an unknown raw event index: ${eventValues.rawIndex}`);
            }
            return syntheticEvent;
        }
        if (EventsSerializer.isRawEventKey(eventValues)) {
            const rawEvents = SyntheticEventsManager.getActiveManager().getRawTraceEvents();
            return rawEvents[eventValues.rawIndex];
        }
        throw new Error(`Unknown trace event. Serializable key values: ${eventValues.join('-')}`);
    }
    static isProfileCallKey(key) {
        return key.type === "p" ;
    }
    static isLegacyTimelineFrameKey(key) {
        return key.type === "l" ;
    }
    static isRawEventKey(key) {
        return key.type === "r" ;
    }
    static isSyntheticEventKey(key) {
        return key.type === "s" ;
    }
    #getModifiedProfileCallByKeyValues(key, parsedTrace) {
        const cacheResult = this.#modifiedProfileCallByKey.get(key);
        if (cacheResult) {
            return cacheResult;
        }
        const profileCallsInThread = parsedTrace.data.Renderer.processes.get(key.processID)?.threads.get(key.threadID)?.profileCalls;
        if (!profileCallsInThread) {
            throw new Error(`Unknown profile call serializable key: ${(key)}`);
        }
        const match = profileCallsInThread?.find((e) => {
            return e.sampleIndex === key.sampleIndex && e.nodeId === key.protocol;
        });
        if (!match) {
            throw new Error(`Unknown profile call serializable key: ${(JSON.stringify(key))}`);
        }
        this.#modifiedProfileCallByKey.set(key, match);
        return match;
    }
}

var EventsSerializer$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	EventsSerializer: EventsSerializer
});

// Copyright 2023 The Chromium Authors
const filmStripCache = new WeakMap();
function fromHandlerData(data, customZeroTime) {
    const frames = [];
    const zeroTime = typeof customZeroTime !== 'undefined' ? customZeroTime : data.Meta.traceBounds.min;
    const spanTime = data.Meta.traceBounds.range;
    const fromCache = filmStripCache.get(data)?.get(zeroTime);
    if (fromCache) {
        return fromCache;
    }
    const screenshots = data.Screenshots.screenshots ?? data.Screenshots.legacySyntheticScreenshots ?? [];
    for (const screenshotEvent of screenshots) {
        if (screenshotEvent.ts < zeroTime) {
            continue;
        }
        const frame = {
            index: frames.length,
            screenshotEvent,
        };
        frames.push(frame);
    }
    const result = {
        zeroTime,
        spanTime,
        frames: Array.from(frames),
    };
    const cachedForData = getWithDefault(filmStripCache, data, () => new Map());
    cachedForData.set(zeroTime, result);
    return result;
}
function frameClosestToTimestamp(filmStrip, searchTimestamp) {
    const closestFrameIndexBeforeTimestamp = nearestIndexFromEnd(filmStrip.frames, frame => frame.screenshotEvent.ts < searchTimestamp);
    if (closestFrameIndexBeforeTimestamp === null) {
        return null;
    }
    return filmStrip.frames[closestFrameIndexBeforeTimestamp];
}

var FilmStrip = /*#__PURE__*/Object.freeze({
	__proto__: null,
	frameClosestToTimestamp: frameClosestToTimestamp,
	fromHandlerData: fromHandlerData
});

// Copyright 2024 The Chromium Authors
const stackTraceForEventInTrace = new Map();
function clearCacheForTrace(data) {
    stackTraceForEventInTrace.delete(data);
}
function get(event, data) {
    let cacheForTrace = stackTraceForEventInTrace.get(data);
    if (!cacheForTrace) {
        cacheForTrace = new Map();
        stackTraceForEventInTrace.set(data, cacheForTrace);
    }
    const resultFromCache = cacheForTrace.get(event);
    if (resultFromCache) {
        return resultFromCache;
    }
    let result = null;
    if (isSyntheticExtensionEntry(event)) {
        result = getForExtensionEntry(event, data);
    }
    else if (isPerformanceMeasureBegin(event)) {
        result = getForPerformanceMeasure(event, data);
    }
    else {
        result = getForEvent(event, data);
        const payloadCallFrames = getTraceEventPayloadStackAsProtocolCallFrame(event).filter(callFrame => !isNativeJSFunction(callFrame));
        if (!result.callFrames.length) {
            result.callFrames = payloadCallFrames;
        }
        else {
            for (let i = 0; i < payloadCallFrames.length && i < result.callFrames.length; i++) {
                result.callFrames[i] = payloadCallFrames[i];
            }
        }
    }
    if (result) {
        cacheForTrace.set(event, result);
    }
    return result;
}
function getForEvent(event, data) {
    const entryToNode = data.Renderer.entryToNode.size > 0 ? data.Renderer.entryToNode : data.Samples.entryToNode;
    const topStackTrace = { callFrames: [] };
    let stackTrace = topStackTrace;
    let currentEntry;
    let node = entryToNode.get(event);
    const traceCache = stackTraceForEventInTrace.get(data) || new Map();
    stackTraceForEventInTrace.set(data, traceCache);
    while (node) {
        if (!isProfileCall(node.entry)) {
            const maybeAsyncParent = data.AsyncJSCalls.runEntryPointToScheduler.get(node.entry);
            if (!maybeAsyncParent) {
                node = node.parent;
                continue;
            }
            const maybeAsyncParentNode = maybeAsyncParent && entryToNode.get(maybeAsyncParent.scheduler);
            if (maybeAsyncParentNode) {
                stackTrace = addAsyncParentToStack(stackTrace, maybeAsyncParent.taskName);
                node = maybeAsyncParentNode;
            }
            continue;
        }
        currentEntry = node.entry;
        const stackTraceFromCache = traceCache.get(node.entry);
        if (stackTraceFromCache) {
            stackTrace.callFrames.push(...stackTraceFromCache.callFrames.filter(callFrame => !isNativeJSFunction(callFrame)));
            stackTrace.parent = stackTraceFromCache.parent;
            stackTrace.description = stackTrace.description || stackTraceFromCache.description;
            break;
        }
        if (!isNativeJSFunction(currentEntry.callFrame)) {
            stackTrace.callFrames.push(currentEntry.callFrame);
        }
        const maybeAsyncParentEvent = data.AsyncJSCalls.asyncCallToScheduler.get(currentEntry);
        const maybeAsyncParentNode = maybeAsyncParentEvent && entryToNode.get(maybeAsyncParentEvent.scheduler);
        if (maybeAsyncParentNode) {
            stackTrace = addAsyncParentToStack(stackTrace, maybeAsyncParentEvent.taskName);
            node = maybeAsyncParentNode;
            continue;
        }
        node = node.parent;
    }
    return topStackTrace;
}
function addAsyncParentToStack(stackTrace, taskName) {
    const parent = { callFrames: [] };
    stackTrace.parent = parent;
    parent.description = taskName;
    return parent;
}
function getForExtensionEntry(event, data) {
    const rawEvent = event.rawSourceEvent;
    if (isPerformanceMeasureBegin(rawEvent)) {
        return getForPerformanceMeasure(rawEvent, data);
    }
    if (!rawEvent) {
        return null;
    }
    return get(rawEvent, data);
}
function getForPerformanceMeasure(event, data) {
    let rawEvent = event;
    if (event.args.traceId === undefined) {
        return null;
    }
    rawEvent = data.UserTimings.measureTraceByTraceId.get(event.args.traceId);
    if (!rawEvent) {
        return null;
    }
    return get(rawEvent, data);
}
function isNativeJSFunction({ columnNumber, lineNumber, url, scriptId }) {
    return lineNumber === -1 && columnNumber === -1 && url === '' && scriptId === '0';
}
function getTraceEventPayloadStackAsProtocolCallFrame(event) {
    const payloadCallStack = getZeroIndexedStackTraceInEventPayload(event) || [];
    const callFrames = [];
    for (const frame of payloadCallStack) {
        callFrames.push({ ...frame, scriptId: String(frame.scriptId) });
    }
    return callFrames;
}

var StackTraceForEvent = /*#__PURE__*/Object.freeze({
	__proto__: null,
	clearCacheForTrace: clearCacheForTrace,
	get: get,
	stackTraceForEventInTrace: stackTraceForEventInTrace
});

function getNetworkInitiator(data, event) {
    const networkHandlerInitiator = data.NetworkRequests.incompleteInitiator.get(event);
    if (networkHandlerInitiator?.args.data.mimeType === 'text/css') {
        return networkHandlerInitiator;
    }
    const stack = get(event.rawSourceEvent, data);
    const initiatorCallFrame = stack?.parent?.callFrames.at(0);
    if (!initiatorCallFrame) {
        return networkHandlerInitiator;
    }
    const matchingRequestIds = data.NetworkRequests.requestIdsByURL.get(initiatorCallFrame.url) ?? [];
    const matchingRequests = matchingRequestIds.map(id => data.NetworkRequests.byId.get(id))
        .filter(req => req !== undefined)
        .filter(req => req.ts < event.ts);
    return matchingRequests.at(-1);
}

var Initiators = /*#__PURE__*/Object.freeze({
	__proto__: null,
	getNetworkInitiator: getNetworkInitiator
});

// Copyright 2023 The Chromium Authors
const IDLE_FUNCTION_CALL_NAMES = new Set([
    '(program)',
    '(idle)',
    '(root)',
]);
function calculateWindow(traceBounds, mainThreadEntries) {
    if (!mainThreadEntries.length) {
        return traceBounds;
    }
    const entriesWithIdleRemoved = mainThreadEntries.filter(entry => {
        if (isProfileCall(entry) &&
            (IDLE_FUNCTION_CALL_NAMES.has(entry.callFrame.functionName) || !entry.callFrame.functionName)) {
            return false;
        }
        return true;
    });
    if (entriesWithIdleRemoved.length === 0) {
        return traceBounds;
    }
    function findLowUtilizationRegion(startIndex, stopIndex) {
        const threshold = 0.1;
        let cutIndex = startIndex;
        const entryAtCut = entriesWithIdleRemoved[cutIndex];
        const timings = eventTimingsMicroSeconds(entryAtCut);
        let cutTime = (timings.startTime + timings.endTime) / 2;
        let usedTime = 0;
        const step = Math.sign(stopIndex - startIndex);
        for (let i = startIndex; i !== stopIndex; i += step) {
            const task = entriesWithIdleRemoved[i];
            const taskTimings = eventTimingsMicroSeconds(task);
            const taskTime = (taskTimings.startTime + taskTimings.endTime) / 2;
            const interval = Math.abs(cutTime - taskTime);
            if (usedTime < threshold * interval) {
                cutIndex = i;
                cutTime = taskTime;
                usedTime = 0;
            }
            usedTime += taskTimings.duration;
        }
        return cutIndex;
    }
    const rightIndex = findLowUtilizationRegion(entriesWithIdleRemoved.length - 1, 0);
    const leftIndex = findLowUtilizationRegion(0, rightIndex);
    const leftTimings = eventTimingsMicroSeconds(entriesWithIdleRemoved[leftIndex]);
    const rightTimings = eventTimingsMicroSeconds(entriesWithIdleRemoved[rightIndex]);
    let leftTime = leftTimings.startTime;
    let rightTime = rightTimings.endTime;
    const zoomedInSpan = rightTime - leftTime;
    if (zoomedInSpan < traceBounds.range * 0.1) {
        return traceBounds;
    }
    leftTime = Micro(Math.max(leftTime - 0.05 * zoomedInSpan, traceBounds.min));
    rightTime = Micro(Math.min(rightTime + 0.05 * zoomedInSpan, traceBounds.max));
    return {
        min: leftTime,
        max: rightTime,
        range: Micro(rightTime - leftTime),
    };
}

var MainThreadActivity = /*#__PURE__*/Object.freeze({
	__proto__: null,
	calculateWindow: calculateWindow
});

// Copyright 2025 The Chromium Authors
const ABSOLUTE_SIZE_THRESHOLD_BYTES = 1024 * 0.5;
const RELATIVE_SIZE_THRESHOLD = 0.1;
function normalizeSource(source) {
    source = source.replace(/\?$/, '');
    const lastNodeModulesIndex = source.lastIndexOf('node_modules');
    if (lastNodeModulesIndex !== -1) {
        source = source.substring(lastNodeModulesIndex);
    }
    return source;
}
function shouldIgnoreSource(source) {
    if (source.includes('webpack/bootstrap')) {
        return true;
    }
    if (source.includes('(webpack)/buildin')) {
        return true;
    }
    if (source.includes('external ')) {
        return true;
    }
    return false;
}
function normalizeDuplication(duplication) {
    for (const [key, data] of duplication) {
        data.duplicates.sort((a, b) => b.attributedSize - a.attributedSize);
        if (data.duplicates.length > 1) {
            const largestResourceSize = data.duplicates[0].attributedSize;
            data.duplicates = data.duplicates.filter(duplicate => {
                const percentSize = duplicate.attributedSize / largestResourceSize;
                return percentSize >= RELATIVE_SIZE_THRESHOLD;
            });
        }
        data.duplicates = data.duplicates.filter(duplicate => duplicate.attributedSize >= ABSOLUTE_SIZE_THRESHOLD_BYTES);
        if (data.duplicates.length <= 1) {
            duplication.delete(key);
            continue;
        }
        data.estimatedDuplicateBytes = data.duplicates.slice(1).reduce((acc, cur) => acc + cur.attributedSize, 0);
    }
}
function indexOfOrLength(haystack, needle, startPosition = 0) {
    const index = haystack.indexOf(needle, startPosition);
    return index === -1 ? haystack.length : index;
}
function getNodeModuleName(source) {
    const sourceSplit = source.split('node_modules/');
    source = sourceSplit[sourceSplit.length - 1];
    const indexFirstSlash = indexOfOrLength(source, '/');
    if (source[0] === '@') {
        return source.slice(0, indexOfOrLength(source, '/', indexFirstSlash + 1));
    }
    return source.slice(0, indexFirstSlash);
}
function groupByNodeModules(duplication) {
    const groupedDuplication = new Map();
    for (const [source, data] of duplication) {
        if (!source.includes('node_modules')) {
            groupedDuplication.set(source, data);
            continue;
        }
        const nodeModuleKey = 'node_modules/' + getNodeModuleName(source);
        const aggregatedData = groupedDuplication.get(nodeModuleKey) ?? {
            duplicates: [],
            estimatedDuplicateBytes: 0,
        };
        groupedDuplication.set(nodeModuleKey, aggregatedData);
        for (const { script, attributedSize } of data.duplicates) {
            let duplicate = aggregatedData.duplicates.find(d => d.script === script);
            if (!duplicate) {
                duplicate = { script, attributedSize: 0 };
                aggregatedData.duplicates.push(duplicate);
            }
            duplicate.attributedSize += attributedSize;
        }
    }
    return groupedDuplication;
}
function sorted(duplication) {
    return new Map([...duplication].sort((a, b) => b[1].estimatedDuplicateBytes - a[1].estimatedDuplicateBytes));
}
function computeScriptDuplication(scriptsData, compressionRatios) {
    const sourceDatasMap = new Map();
    for (const script of scriptsData.scripts) {
        if (!script.content || !script.sourceMap) {
            continue;
        }
        const sizes = getScriptGeneratedSizes(script);
        if (!sizes) {
            continue;
        }
        if ('errorMessage' in sizes) {
            console.error(sizes.errorMessage);
            continue;
        }
        const sourceDataArray = [];
        sourceDatasMap.set(script, sourceDataArray);
        const sources = script.sourceMap.sourceURLs();
        for (let i = 0; i < sources.length; i++) {
            if (shouldIgnoreSource(sources[i])) {
                continue;
            }
            const sourceSize = sizes.files[sources[i]];
            sourceDataArray.push({
                source: normalizeSource(sources[i]),
                resourceSize: sourceSize,
            });
        }
    }
    const duplication = new Map();
    for (const [script, sourceDataArray] of sourceDatasMap) {
        for (const sourceData of sourceDataArray) {
            let data = duplication.get(sourceData.source);
            if (!data) {
                data = { estimatedDuplicateBytes: 0, duplicates: [] };
                duplication.set(sourceData.source, data);
            }
            const compressionRatio = script.request ? compressionRatios.get(script.request?.args.data.requestId) ?? 1 : 1;
            const transferSize = Math.round(sourceData.resourceSize * compressionRatio);
            data.duplicates.push({
                script,
                attributedSize: transferSize,
            });
        }
    }
    const duplicationGroupedByNodeModules = groupByNodeModules(duplication);
    normalizeDuplication(duplication);
    normalizeDuplication(duplicationGroupedByNodeModules);
    return {
        duplication: sorted(duplication),
        duplicationGroupedByNodeModules: sorted(duplicationGroupedByNodeModules),
    };
}

var ScriptDuplication = /*#__PURE__*/Object.freeze({
	__proto__: null,
	computeScriptDuplication: computeScriptDuplication,
	getNodeModuleName: getNodeModuleName,
	normalizeDuplication: normalizeDuplication,
	normalizeSource: normalizeSource
});

// Copyright 2017 The Chromium Authors
class TraceFilter {
}
class VisibleEventsFilter extends TraceFilter {
    visibleTypes;
    constructor(visibleTypes) {
        super();
        this.visibleTypes = new Set(visibleTypes);
    }
    accept(event) {
        if (isSyntheticExtensionEntry(event)) {
            return true;
        }
        return this.visibleTypes.has(VisibleEventsFilter.eventType(event));
    }
    static eventType(event) {
        if (event.cat.includes('blink.console')) {
            return "ConsoleTime" ;
        }
        if (event.cat.includes('blink.user_timing')) {
            return "UserTiming" ;
        }
        return event.name;
    }
}
class InvisibleEventsFilter extends TraceFilter {
    #invisibleTypes;
    constructor(invisibleTypes) {
        super();
        this.#invisibleTypes = new Set(invisibleTypes);
    }
    accept(event) {
        return !this.#invisibleTypes.has(VisibleEventsFilter.eventType(event));
    }
}
class ExclusiveNameFilter extends TraceFilter {
    #excludeNames;
    constructor(excludeNames) {
        super();
        this.#excludeNames = new Set(excludeNames);
    }
    accept(event) {
        return !this.#excludeNames.has(event.name);
    }
}

var TraceFilter$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ExclusiveNameFilter: ExclusiveNameFilter,
	InvisibleEventsFilter: InvisibleEventsFilter,
	TraceFilter: TraceFilter,
	VisibleEventsFilter: VisibleEventsFilter
});

// Copyright 2016 The Chromium Authors
let Node$1 = class Node {
    totalTime;
    selfTime;
    transferSize;
    id;
    event;
    events;
    parent;
    groupId;
    isGroupNodeInternal;
    depth;
    constructor(id, event) {
        this.totalTime = 0;
        this.selfTime = 0;
        this.transferSize = 0;
        this.id = id;
        this.event = event;
        this.events = [event];
        this.groupId = '';
        this.isGroupNodeInternal = false;
        this.depth = 0;
    }
    isGroupNode() {
        return this.isGroupNodeInternal;
    }
    hasChildren() {
        throw new Error('Not implemented');
    }
    setHasChildren(_value) {
        throw new Error('Not implemented');
    }
    children() {
        throw new Error('Not implemented');
    }
    searchTree(matchFunction, results) {
        results = results || [];
        if (this.event && matchFunction(this.event)) {
            results.push(this);
        }
        for (const child of this.children().values()) {
            child.searchTree(matchFunction, results);
        }
        return results;
    }
};
class TopDownNode extends Node$1 {
    root;
    hasChildrenInternal;
    childrenInternal;
    parent;
    constructor(id, event, parent) {
        super(id, event);
        this.root = parent?.root ?? null;
        this.hasChildrenInternal = false;
        this.childrenInternal = null;
        this.parent = parent;
    }
    hasChildren() {
        return this.hasChildrenInternal;
    }
    setHasChildren(value) {
        this.hasChildrenInternal = value;
    }
    children() {
        return this.childrenInternal || this.buildChildren();
    }
    buildChildren() {
        const path = [];
        for (let node = this; node.parent && !node.isGroupNode(); node = node.parent) {
            path.push((node));
        }
        path.reverse();
        const children = new Map();
        const self = this;
        const root = this.root;
        if (!root) {
            this.childrenInternal = children;
            return this.childrenInternal;
        }
        const startTime = root.startTime;
        const endTime = root.endTime;
        const instantEventCallback = (root.doNotAggregate || root.includeInstantEvents) ? onInstantEvent : undefined;
        const eventIdCallback = root.doNotAggregate ? undefined : generateEventID;
        const eventGroupIdCallback = root.getEventGroupIdCallback();
        let depth = 0;
        let matchedDepth = 0;
        let currentDirectChild = null;
        forEachEvent(root.events, {
            onStartEvent,
            onEndEvent,
            onInstantEvent: instantEventCallback,
            startTime: milliToMicro(startTime),
            endTime: milliToMicro(endTime),
            eventFilter: root.filter,
            ignoreAsyncEvents: false,
        });
        function onStartEvent(e) {
            const { startTime: currentStartTime, endTime: currentEndTime } = eventTimingsMilliSeconds(e);
            ++depth;
            if (depth > path.length + 2) {
                return;
            }
            if (!matchPath(e)) {
                return;
            }
            const actualEndTime = currentEndTime !== undefined ? Math.min(currentEndTime, endTime) : endTime;
            const duration = actualEndTime - Math.max(startTime, currentStartTime);
            if (duration < 0) {
                console.error('Negative event duration');
            }
            processEvent(e, duration);
        }
        function onInstantEvent(e) {
            ++depth;
            if (matchedDepth === path.length && depth <= path.length + 2) {
                processEvent(e, 0);
            }
            --depth;
        }
        function processEvent(e, duration) {
            if (depth === path.length + 2) {
                if (!currentDirectChild) {
                    return;
                }
                currentDirectChild.setHasChildren(true);
                currentDirectChild.selfTime -= duration;
                return;
            }
            let id;
            let groupId = '';
            if (!eventIdCallback) {
                id = Symbol('uniqueId');
            }
            else {
                id = eventIdCallback(e);
                groupId = eventGroupIdCallback ? eventGroupIdCallback(e) : '';
                if (groupId) {
                    id += '/' + groupId;
                }
            }
            let node = children.get(id);
            if (!node) {
                node = new TopDownNode(id, e, self);
                node.groupId = groupId;
                children.set(id, node);
            }
            else {
                node.events.push(e);
            }
            node.selfTime += duration;
            node.totalTime += duration;
            if (isReceivedDataEvent(e)) {
                node.transferSize += e.args.data.encodedDataLength;
            }
            currentDirectChild = node;
        }
        function matchPath(e) {
            const { endTime } = eventTimingsMilliSeconds(e);
            if (matchedDepth === path.length) {
                return true;
            }
            if (matchedDepth !== depth - 1) {
                return false;
            }
            if (!endTime) {
                return false;
            }
            if (!eventIdCallback) {
                if (e === path[matchedDepth].event) {
                    ++matchedDepth;
                }
                return false;
            }
            let id = eventIdCallback(e);
            const groupId = eventGroupIdCallback ? eventGroupIdCallback(e) : '';
            if (groupId) {
                id += '/' + groupId;
            }
            if (id === path[matchedDepth].id) {
                ++matchedDepth;
            }
            return false;
        }
        function onEndEvent() {
            --depth;
            if (matchedDepth > depth) {
                matchedDepth = depth;
            }
        }
        this.childrenInternal = children;
        return children;
    }
}
class TopDownRootNode extends TopDownNode {
    filter;
    startTime;
    endTime;
    eventGroupIdCallback;
    doNotAggregate;
    includeInstantEvents;
    totalTime;
    selfTime;
    constructor(events, { filters, startTime, endTime, doNotAggregate, eventGroupIdCallback, includeInstantEvents }) {
        super('', events[0], null);
        this.event = events[0];
        this.root = this;
        this.events = events;
        this.filter = (e) => filters.every(f => f.accept(e));
        this.startTime = startTime;
        this.endTime = endTime;
        this.eventGroupIdCallback = eventGroupIdCallback;
        this.doNotAggregate = doNotAggregate;
        this.includeInstantEvents = includeInstantEvents;
        this.totalTime = endTime - startTime;
        this.selfTime = this.totalTime;
    }
    children() {
        return this.childrenInternal || this.grouppedTopNodes();
    }
    grouppedTopNodes() {
        const flatNodes = super.children();
        for (const node of flatNodes.values()) {
            this.selfTime -= node.totalTime;
        }
        if (!this.eventGroupIdCallback) {
            return flatNodes;
        }
        const groupNodes = new Map();
        for (const node of flatNodes.values()) {
            const groupId = this.eventGroupIdCallback(node.event);
            let groupNode = groupNodes.get(groupId);
            if (!groupNode) {
                groupNode = new GroupNode(groupId, this, node.events);
                groupNodes.set(groupId, groupNode);
            }
            else {
                groupNode.events.push(...node.events);
            }
            groupNode.addChild(node, node.selfTime, node.totalTime, node.transferSize);
        }
        this.childrenInternal = groupNodes;
        return groupNodes;
    }
    getEventGroupIdCallback() {
        return this.eventGroupIdCallback;
    }
}
class BottomUpRootNode extends Node$1 {
    childrenInternal;
    textFilter;
    filter;
    startTime;
    endTime;
    totalTime;
    eventGroupIdCallback;
    calculateTransferSize;
    forceGroupIdCallback;
    constructor(events, { textFilter, filters, startTime, endTime, eventGroupIdCallback, calculateTransferSize, forceGroupIdCallback, }) {
        super('', events[0]);
        this.childrenInternal = null;
        this.events = events;
        this.textFilter = textFilter;
        this.filter = (e) => filters.every(f => f.accept(e));
        this.startTime = startTime;
        this.endTime = endTime;
        this.eventGroupIdCallback = eventGroupIdCallback;
        this.totalTime = endTime - startTime;
        this.calculateTransferSize = calculateTransferSize;
        this.forceGroupIdCallback = forceGroupIdCallback;
    }
    hasChildren() {
        return true;
    }
    filterChildren(children) {
        for (const [id, child] of children) {
            if (child.event && child.depth <= 1 && !this.textFilter.accept(child.event)) {
                children.delete((id));
            }
        }
        return children;
    }
    children() {
        if (!this.childrenInternal) {
            this.childrenInternal = this.filterChildren(this.grouppedTopNodes());
        }
        return this.childrenInternal;
    }
    ungroupedTopNodes() {
        const root = this;
        const startTime = this.startTime;
        const endTime = this.endTime;
        const idStack = [];
        const nodeById = new Map();
        const selfTimeStack = [endTime - startTime];
        const firstNodeStack = [];
        const totalTimeById = new Map();
        const eventGroupIdCallback = this.eventGroupIdCallback;
        const forceGroupIdCallback = this.forceGroupIdCallback;
        const sumTransferSizeOfInstantEvent = (e) => {
            if (isReceivedDataEvent(e)) {
                let id = generateEventID(e);
                if (this.forceGroupIdCallback && this.eventGroupIdCallback) {
                    id = `${id}-${this.eventGroupIdCallback(e)}`;
                }
                let node = nodeById.get(id);
                if (!node) {
                    node = new BottomUpNode(root, id, e, false, root);
                    nodeById.set(id, node);
                }
                else {
                    node.events.push(e);
                }
                if (e.name === 'ResourceReceivedData') {
                    node.transferSize += e.args.data.encodedDataLength;
                }
                else if (e.args.data.encodedDataLength > 0) {
                    node.transferSize = e.args.data.encodedDataLength;
                }
            }
        };
        forEachEvent(this.events, {
            onStartEvent,
            onEndEvent,
            onInstantEvent: this.calculateTransferSize ? sumTransferSizeOfInstantEvent : undefined,
            startTime: milliToMicro(this.startTime),
            endTime: milliToMicro(this.endTime),
            eventFilter: this.filter,
            ignoreAsyncEvents: false,
        });
        function onStartEvent(e) {
            const { startTime: currentStartTime, endTime: currentEndTime } = eventTimingsMilliSeconds(e);
            const actualEndTime = currentEndTime !== undefined ? Math.min(currentEndTime, endTime) : endTime;
            const duration = actualEndTime - Math.max(currentStartTime, startTime);
            selfTimeStack[selfTimeStack.length - 1] -= duration;
            selfTimeStack.push(duration);
            let id = generateEventID(e);
            if (forceGroupIdCallback && eventGroupIdCallback) {
                id = `${id}-${eventGroupIdCallback(e)}`;
            }
            idStack.push(id);
            const noNodeOnStack = !totalTimeById.has(id);
            if (noNodeOnStack) {
                totalTimeById.set(id, duration);
            }
            firstNodeStack.push(noNodeOnStack);
        }
        function onEndEvent(event) {
            const id = idStack.pop();
            if (!id) {
                return;
            }
            let node = nodeById.get(id);
            if (!node) {
                node = new BottomUpNode(root, id, event, false, root);
                nodeById.set(id, node);
            }
            else {
                node.events.push(event);
            }
            node.selfTime += selfTimeStack.pop() || 0;
            if (firstNodeStack.pop()) {
                node.totalTime += totalTimeById.get(id) || 0;
                totalTimeById.delete(id);
            }
            if (idStack.length > 0) {
                node.setHasChildren(true);
            }
        }
        this.selfTime = selfTimeStack.pop() || 0;
        for (const pair of nodeById) {
            if (pair[1].selfTime <= 0 && (!this.calculateTransferSize || pair[1].transferSize <= 0)) {
                nodeById.delete((pair[0]));
            }
        }
        return nodeById;
    }
    grouppedTopNodes() {
        const flatNodes = this.ungroupedTopNodes();
        if (!this.eventGroupIdCallback) {
            return flatNodes;
        }
        const groupNodes = new Map();
        for (const node of flatNodes.values()) {
            const groupId = this.eventGroupIdCallback(node.event);
            let groupNode = groupNodes.get(groupId);
            if (!groupNode) {
                groupNode = new GroupNode(groupId, this, node.events);
                groupNodes.set(groupId, groupNode);
            }
            else {
                for (const e of node.events) {
                    groupNode.events.push(e);
                }
            }
            groupNode.addChild(node, node.selfTime, node.selfTime, node.transferSize);
        }
        return groupNodes;
    }
}
class GroupNode extends Node$1 {
    childrenInternal;
    isGroupNodeInternal;
    events;
    constructor(id, parent, events) {
        super(id, events[0]);
        this.events = events;
        this.childrenInternal = new Map();
        this.parent = parent;
        this.isGroupNodeInternal = true;
    }
    addChild(child, selfTime, totalTime, transferSize) {
        this.childrenInternal.set(child.id, child);
        this.selfTime += selfTime;
        this.totalTime += totalTime;
        this.transferSize += transferSize;
        child.parent = this;
    }
    hasChildren() {
        return true;
    }
    children() {
        return this.childrenInternal;
    }
}
class BottomUpNode extends Node$1 {
    parent;
    root;
    depth;
    cachedChildren;
    hasChildrenInternal;
    constructor(root, id, event, hasChildren, parent) {
        super(id, event);
        this.parent = parent;
        this.root = root;
        this.depth = (parent.depth || 0) + 1;
        this.cachedChildren = null;
        this.hasChildrenInternal = hasChildren;
    }
    hasChildren() {
        return this.hasChildrenInternal;
    }
    setHasChildren(value) {
        this.hasChildrenInternal = value;
    }
    children() {
        if (this.cachedChildren) {
            return this.cachedChildren;
        }
        const selfTimeStack = [0];
        const eventIdStack = [];
        const eventStack = [];
        const nodeById = new Map();
        const startTime = this.root.startTime;
        const endTime = this.root.endTime;
        let lastTimeMarker = startTime;
        const self = this;
        forEachEvent(this.root.events, {
            onStartEvent,
            onEndEvent,
            startTime: milliToMicro(startTime),
            endTime: milliToMicro(endTime),
            eventFilter: this.root.filter,
            ignoreAsyncEvents: false,
        });
        function onStartEvent(e) {
            const { startTime: currentStartTime, endTime: currentEndTime } = eventTimingsMilliSeconds(e);
            const actualEndTime = currentEndTime !== undefined ? Math.min(currentEndTime, endTime) : endTime;
            const duration = actualEndTime - Math.max(currentStartTime, startTime);
            if (duration < 0) {
                console.assert(false, 'Negative duration of an event');
            }
            selfTimeStack[selfTimeStack.length - 1] -= duration;
            selfTimeStack.push(duration);
            const id = generateEventID(e);
            eventIdStack.push(id);
            eventStack.push(e);
        }
        function onEndEvent(e) {
            const { startTime: currentStartTime, endTime: currentEndTime } = eventTimingsMilliSeconds(e);
            const selfTime = selfTimeStack.pop();
            const id = eventIdStack.pop();
            eventStack.pop();
            let node;
            for (node = self; node.depth > 1; node = node.parent) {
                if (node.id !== eventIdStack[eventIdStack.length + 1 - node.depth]) {
                    return;
                }
            }
            if (node.id !== id || eventIdStack.length < self.depth) {
                return;
            }
            const childId = eventIdStack[eventIdStack.length - self.depth];
            node = nodeById.get(childId);
            if (!node) {
                const event = eventStack[eventStack.length - self.depth];
                const hasChildren = eventStack.length > self.depth;
                node = new BottomUpNode(self.root, childId, event, hasChildren, self);
                nodeById.set(childId, node);
            }
            else {
                node.events.push(e);
            }
            const actualEndTime = currentEndTime !== undefined ? Math.min(currentEndTime, endTime) : endTime;
            const totalTime = actualEndTime - Math.max(currentStartTime, lastTimeMarker);
            node.selfTime += selfTime || 0;
            node.totalTime += totalTime;
            lastTimeMarker = actualEndTime;
        }
        this.cachedChildren = this.root.filterChildren(nodeById);
        return this.cachedChildren;
    }
    searchTree(matchFunction, results) {
        results = results || [];
        if (this.event && matchFunction(this.event)) {
            results.push(this);
        }
        return results;
    }
}
function eventStackFrame(event) {
    if (isProfileCall(event)) {
        return event.callFrame;
    }
    const topFrame = event.args?.data?.stackTrace?.[0];
    if (!topFrame) {
        return null;
    }
    return { ...topFrame, scriptId: String(topFrame.scriptId) };
}
function generateEventID(event) {
    if (isProfileCall(event)) {
        const name = SamplesIntegrator.isNativeRuntimeFrame(event.callFrame) ?
            SamplesIntegrator.nativeGroup(event.callFrame.functionName) :
            event.callFrame.functionName;
        const location = event.callFrame.scriptId || event.callFrame.url || '';
        return `f:${name}@${location}:${event.callFrame.lineNumber}:${event.callFrame.columnNumber}`;
    }
    if (isConsoleTimeStamp(event) && event.args.data) {
        return `${event.name}:${event.args.data.name}`;
    }
    if (isSyntheticNetworkRequest(event) || isReceivedDataEvent(event)) {
        return `req:${event.args.data.requestId}`;
    }
    return event.name;
}

var TraceTree = /*#__PURE__*/Object.freeze({
	__proto__: null,
	BottomUpNode: BottomUpNode,
	BottomUpRootNode: BottomUpRootNode,
	GroupNode: GroupNode,
	Node: Node$1,
	TopDownNode: TopDownNode,
	TopDownRootNode: TopDownRootNode,
	eventStackFrame: eventStackFrame,
	generateEventID: generateEventID
});

// Copyright 2024 The Chromium Authors
function collectMainThreadActivity(data) {
    const mainFrameMainThread = data.Renderer.processes.values()
        .find(p => {
        const url = p.url ?? '';
        return p.isOnMainFrame && !url.startsWith('about:') && !url.startsWith('chrome:');
    })
        ?.threads.values()
        .find(t => t.name === 'CrRendererMain');
    if (!mainFrameMainThread) {
        return [];
    }
    return mainFrameMainThread.entries;
}
function summarizeByThirdParty(data, traceBounds) {
    const mainThreadEvents = collectMainThreadActivity(data).sort(eventTimeComparator);
    const groupingFunction = (event) => {
        const entity = data.Renderer.entityMappings.entityByEvent.get(event);
        return entity?.name ?? '';
    };
    const node = getBottomUpTree(mainThreadEvents, traceBounds, groupingFunction);
    const summaries = summarizeBottomUpByEntity(node, data);
    return summaries;
}
function summarizeByURL(data, traceBounds) {
    const mainThreadEvents = collectMainThreadActivity(data).sort(eventTimeComparator);
    const groupingFunction = (event) => {
        return getNonResolvedURL(event, data) ?? '';
    };
    const node = getBottomUpTree(mainThreadEvents, traceBounds, groupingFunction);
    const summaries = summarizeBottomUpByURL(node, data);
    return summaries;
}
function summarizeBottomUpByEntity(root, data) {
    const summaries = [];
    const topNodes = [...root.children().values()].flat();
    for (const node of topNodes) {
        if (node.id === '') {
            continue;
        }
        const entity = data.Renderer.entityMappings.entityByEvent.get(node.event);
        if (!entity) {
            continue;
        }
        const summary = {
            transferSize: node.transferSize,
            mainThreadTime: Milli(node.selfTime),
            entity,
            relatedEvents: data.Renderer.entityMappings.eventsByEntity.get(entity) ?? [],
        };
        summaries.push(summary);
    }
    return summaries;
}
function summarizeBottomUpByURL(root, data) {
    const summaries = [];
    const allRequests = data.NetworkRequests.byTime;
    const topNodes = [...root.children().values()].flat();
    for (const node of topNodes) {
        if (node.id === '' || typeof node.id !== 'string') {
            continue;
        }
        const entity = data.Renderer.entityMappings.entityByEvent.get(node.event);
        if (!entity) {
            continue;
        }
        const url = node.id;
        const request = allRequests.find(r => r.args.data.url === url);
        const summary = {
            request,
            url,
            entity,
            transferSize: node.transferSize,
            mainThreadTime: Milli(node.selfTime),
        };
        summaries.push(summary);
    }
    return summaries;
}
function getBottomUpTree(mainThreadEvents, tracebounds, groupingFunction) {
    const visibleEvents = VISIBLE_TRACE_EVENT_TYPES.values().toArray();
    const filter = new VisibleEventsFilter(visibleEvents.concat(["SyntheticNetworkRequest" ]));
    const startTime = microToMilli(tracebounds.min);
    const endTime = microToMilli(tracebounds.max);
    return new BottomUpRootNode(mainThreadEvents, {
        textFilter: new ExclusiveNameFilter([]),
        filters: [filter],
        startTime,
        endTime,
        eventGroupIdCallback: groupingFunction,
        calculateTransferSize: true,
        forceGroupIdCallback: true,
    });
}

var ThirdParties$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	summarizeByThirdParty: summarizeByThirdParty,
	summarizeByURL: summarizeByURL
});

// Copyright 2023 The Chromium Authors

var extras = /*#__PURE__*/Object.freeze({
	__proto__: null,
	FilmStrip: FilmStrip,
	Initiators: Initiators,
	MainThreadActivity: MainThreadActivity,
	ScriptDuplication: ScriptDuplication,
	StackTraceForEvent: StackTraceForEvent,
	ThirdParties: ThirdParties$1,
	TraceFilter: TraceFilter$1,
	TraceTree: TraceTree
});

// Copyright 2024 The Chromium Authors
/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
const MIN_PASSING_SCORE = 0.90000000000000002220446049250313080847263336181640625;
const MAX_AVERAGE_SCORE = 0.899999999999999911182158029987476766109466552734375;
const MIN_AVERAGE_SCORE = 0.5;
const MAX_FAILING_SCORE = 0.499999999999999944488848768742172978818416595458984375;
function erf(x) {
    const sign = Math.sign(x);
    x = Math.abs(x);
    const a1 = 0.254829592;
    const a2 = -0.284496736;
    const a3 = 1.421413741;
    const a4 = -1.453152027;
    const a5 = 1.061405429;
    const p = 0.3275911;
    const t = 1 / (1 + p * x);
    const y = t * (a1 + t * (a2 + t * (a3 + t * (a4 + t * a5))));
    return sign * (1 - y * Math.exp(-x * x));
}
function getLogNormalScore({ median, p10 }, value) {
    if (median <= 0) {
        throw new Error('median must be greater than zero');
    }
    if (p10 <= 0) {
        throw new Error('p10 must be greater than zero');
    }
    if (p10 >= median) {
        throw new Error('p10 must be less than the median');
    }
    if (value <= 0) {
        return 1;
    }
    const INVERSE_ERFC_ONE_FIFTH = 0.9061938024368232;
    const xRatio = Math.max(Number.MIN_VALUE, value / median);
    const xLogRatio = Math.log(xRatio);
    const p10Ratio = Math.max(Number.MIN_VALUE, p10 / median);
    const p10LogRatio = -Math.log(p10Ratio);
    const standardizedX = xLogRatio * INVERSE_ERFC_ONE_FIFTH / p10LogRatio;
    const complementaryPercentile = (1 - erf(standardizedX)) / 2;
    let score;
    if (value <= p10) {
        score = Math.max(MIN_PASSING_SCORE, Math.min(1, complementaryPercentile));
    }
    else if (value <= median) {
        score = Math.max(MIN_AVERAGE_SCORE, Math.min(MAX_AVERAGE_SCORE, complementaryPercentile));
    }
    else {
        score = Math.max(0, Math.min(MAX_FAILING_SCORE, complementaryPercentile));
    }
    return score;
}
function linearInterpolation(x0, y0, x1, y1, x) {
    const slope = (y1 - y0) / (x1 - x0);
    return y0 + (x - x0) * slope;
}

var Statistics = /*#__PURE__*/Object.freeze({
	__proto__: null,
	getLogNormalScore: getLogNormalScore,
	linearInterpolation: linearInterpolation
});

// Copyright 2024 The Chromium Authors
const GRAPH_SAVINGS_PRECISION = 50;
function getInsight(insightName, insightSet) {
    return insightSet.model[insightName];
}
function getLCP(insightSet) {
    const insight = getInsight("LCPBreakdown" , insightSet);
    if (!insight || !insight.lcpMs || !insight.lcpEvent) {
        return null;
    }
    const value = milliToMicro(insight.lcpMs);
    return { value, event: insight.lcpEvent };
}
function getINP(insightSet) {
    const insight = getInsight("INPBreakdown" , insightSet);
    if (!insight?.longestInteractionEvent?.dur) {
        return null;
    }
    const value = insight.longestInteractionEvent.dur;
    return { value, event: insight.longestInteractionEvent };
}
function getCLS(insightSet) {
    const insight = getInsight("CLSCulprits" , insightSet);
    if (!insight) {
        return { value: 0, worstClusterEvent: null };
    }
    let maxScore = 0;
    let worstCluster;
    for (const cluster of insight.clusters) {
        if (cluster.clusterCumulativeScore > maxScore) {
            maxScore = cluster.clusterCumulativeScore;
            worstCluster = cluster;
        }
    }
    return { value: maxScore, worstClusterEvent: worstCluster ?? null };
}
function evaluateLCPMetricScore(value) {
    return getLogNormalScore({ p10: 2500, median: 4000 }, value);
}
function evaluateINPMetricScore(value) {
    return getLogNormalScore({ p10: 200, median: 500 }, value);
}
function evaluateCLSMetricScore(value) {
    return getLogNormalScore({ p10: 0.1, median: 0.25 }, value);
}
function getPageResult(cruxFieldData, url, origin, scope = null) {
    return cruxFieldData.find(result => {
        const key = scope ? result[`${scope.pageScope}-${scope.deviceScope}`]?.record.key :
            (result['url-ALL'] || result['origin-ALL'])?.record.key;
        return (key?.url && key.url === url) || (key?.origin && key.origin === origin);
    });
}
function getMetricResult(pageResult, name, scope = null) {
    const scopes = [];
    if (scope) {
        scopes.push(scope);
    }
    else {
        scopes.push({ pageScope: 'url', deviceScope: 'ALL' });
        scopes.push({ pageScope: 'origin', deviceScope: 'ALL' });
    }
    for (const scope of scopes) {
        const key = `${scope.pageScope}-${scope.deviceScope}`;
        let value = pageResult[key]?.record.metrics[name]?.percentiles?.p75;
        if (typeof value === 'string') {
            value = Number(value);
        }
        if (typeof value === 'number' && Number.isFinite(value)) {
            return { value, pageScope: scope.pageScope };
        }
    }
    return null;
}
function getMetricTimingResult(pageResult, name, scope = null) {
    const result = getMetricResult(pageResult, name, scope);
    if (result) {
        const valueMs = result.value;
        return { value: milliToMicro(valueMs), pageScope: result.pageScope };
    }
    return null;
}
function getFieldMetricsForInsightSet(insightSet, metadata, scope = null) {
    const cruxFieldData = metadata?.cruxFieldData;
    if (!cruxFieldData) {
        return null;
    }
    const pageResult = getPageResult(cruxFieldData, insightSet.url.href, insightSet.url.origin, scope);
    if (!pageResult) {
        return null;
    }
    return {
        fcp: getMetricTimingResult(pageResult, 'first_contentful_paint', scope),
        lcp: getMetricTimingResult(pageResult, 'largest_contentful_paint', scope),
        inp: getMetricTimingResult(pageResult, 'interaction_to_next_paint', scope),
        cls: getMetricResult(pageResult, 'cumulative_layout_shift', scope),
        lcpBreakdown: {
            ttfb: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_time_to_first_byte', scope),
            loadDelay: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_resource_load_delay', scope),
            loadDuration: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_resource_load_duration', scope),
            renderDelay: getMetricTimingResult(pageResult, 'largest_contentful_paint_image_element_render_delay', scope),
        }
    };
}
function calculateMetricWeightsForSorting(insightSet, metadata) {
    const weights = {
        lcp: 1 / 3,
        inp: 1 / 3,
        cls: 1 / 3,
    };
    const cruxFieldData = metadata?.cruxFieldData;
    if (!cruxFieldData) {
        return weights;
    }
    const fieldMetrics = getFieldMetricsForInsightSet(insightSet, metadata);
    if (!fieldMetrics) {
        return weights;
    }
    const fieldLcp = fieldMetrics.lcp?.value ?? null;
    const fieldInp = fieldMetrics.inp?.value ?? null;
    const fieldCls = fieldMetrics.cls?.value ?? null;
    const fieldLcpScore = fieldLcp !== null ? evaluateLCPMetricScore(microToMilli(fieldLcp)) : 0;
    const fieldInpScore = fieldInp !== null ? evaluateINPMetricScore(microToMilli(fieldInp)) : 0;
    const fieldClsScore = fieldCls !== null ? evaluateCLSMetricScore(fieldCls) : 0;
    const fieldLcpScoreInverted = 1 - fieldLcpScore;
    const fieldInpScoreInverted = 1 - fieldInpScore;
    const fieldClsScoreInverted = 1 - fieldClsScore;
    const invertedSum = fieldLcpScoreInverted + fieldInpScoreInverted + fieldClsScoreInverted;
    if (!invertedSum) {
        return weights;
    }
    weights.lcp = fieldLcpScoreInverted / invertedSum;
    weights.inp = fieldInpScoreInverted / invertedSum;
    weights.cls = fieldClsScoreInverted / invertedSum;
    return weights;
}
function estimateSavingsWithGraphs$1(wastedBytesByRequestId, simulator, graph) {
    const simulationBeforeChanges = simulator.simulate(graph);
    const originalTransferSizes = new Map();
    graph.traverse(node => {
        if (node.type !== 'network') {
            return;
        }
        const wastedBytes = wastedBytesByRequestId.get(node.request.requestId);
        if (!wastedBytes) {
            return;
        }
        const original = node.request.transferSize;
        originalTransferSizes.set(node.request.requestId, original);
        node.request.transferSize = Math.max(original - wastedBytes, 0);
    });
    const simulationAfterChanges = simulator.simulate(graph);
    graph.traverse(node => {
        if (node.type !== 'network') {
            return;
        }
        const originalTransferSize = originalTransferSizes.get(node.request.requestId);
        if (originalTransferSize === undefined) {
            return;
        }
        node.request.transferSize = originalTransferSize;
    });
    let savings = simulationBeforeChanges.timeInMs - simulationAfterChanges.timeInMs;
    savings = Math.round(savings / GRAPH_SAVINGS_PRECISION) * GRAPH_SAVINGS_PRECISION;
    return Milli(savings);
}
function metricSavingsForWastedBytes(wastedBytesByRequestId, context) {
    if (!context.navigation || !context.lantern) {
        return;
    }
    if (!wastedBytesByRequestId.size) {
        return { FCP: Milli(0), LCP: Milli(0) };
    }
    const simulator = context.lantern.simulator;
    const fcpGraph = context.lantern.metrics.firstContentfulPaint.optimisticGraph;
    const lcpGraph = context.lantern.metrics.largestContentfulPaint.optimisticGraph;
    return {
        FCP: estimateSavingsWithGraphs$1(wastedBytesByRequestId, simulator, fcpGraph),
        LCP: estimateSavingsWithGraphs$1(wastedBytesByRequestId, simulator, lcpGraph),
    };
}
function isRequestCompressed(request) {
    if (!request.args.data.responseHeaders) {
        return false;
    }
    const patterns = [
        /^content-encoding$/i, /^x-content-encoding-over-network$/i,
        /^x-original-content-encoding$/i,
    ];
    const compressionTypes = ['gzip', 'br', 'deflate', 'zstd'];
    return request.args.data.responseHeaders.some(header => patterns.some(p => header.name.match(p)) && compressionTypes.includes(header.value));
}
function isRequestServedFromBrowserCache(request) {
    if (!request.args.data.responseHeaders || request.args.data.failed) {
        return false;
    }
    if (request.args.data.statusCode === 304) {
        return true;
    }
    const { transferSize, resourceSize } = getRequestSizes(request);
    const ratio = resourceSize ? transferSize / resourceSize : 0;
    if (ratio < 0.01) {
        return true;
    }
    return false;
}
function getRequestSizes(request) {
    const resourceSize = request.args.data.decodedBodyLength;
    const transferSize = request.args.data.encodedDataLength;
    return { resourceSize, transferSize };
}
function estimateCompressedContentSize(request, totalBytes, resourceType) {
    if (!request || isRequestServedFromBrowserCache(request)) {
        switch (resourceType) {
            case 'Stylesheet':
                return Math.round(totalBytes * 0.2);
            case 'Script':
            case 'Document':
                return Math.round(totalBytes * 0.33);
            default:
                return Math.round(totalBytes * 0.5);
        }
    }
    const { transferSize, resourceSize } = getRequestSizes(request);
    let contentTransferSize = transferSize;
    if (!isRequestCompressed(request)) {
        contentTransferSize = resourceSize;
    }
    if (request.args.data.resourceType === resourceType) {
        return contentTransferSize;
    }
    const compressionRatio = Number.isFinite(resourceSize) && resourceSize > 0 ? (contentTransferSize / resourceSize) : 1;
    return Math.round(totalBytes * compressionRatio);
}
function estimateCompressionRatioForScript(script) {
    if (!script.request) {
        return 1;
    }
    const request = script.request;
    const contentLength = request.args.data.decodedBodyLength ?? script.content?.length ?? 0;
    const compressedSize = estimateCompressedContentSize(request, contentLength, "Script" );
    if (contentLength === 0 || compressedSize === 0) {
        return 1;
    }
    const compressionRatio = compressedSize / contentLength;
    return compressionRatio;
}
function calculateDocFirstByteTs(docRequest) {
    if (docRequest.args.data.protocol === 'file') {
        return docRequest.ts;
    }
    const timing = docRequest.args.data.timing;
    if (!timing) {
        return null;
    }
    return Micro(secondsToMicro(timing.requestTime) +
        milliToMicro(timing.receiveHeadersStart ?? timing.receiveHeadersEnd));
}
function insightBounds(insight, insightSetBounds) {
    const overlays = insight.createOverlays?.() ?? [];
    const windows = overlays.map(traceWindowFromOverlay).filter(bounds => !!bounds);
    const overlaysBounds = combineTraceWindowsMicro(windows);
    if (overlaysBounds) {
        return overlaysBounds;
    }
    return insightSetBounds;
}

var Common = /*#__PURE__*/Object.freeze({
	__proto__: null,
	calculateDocFirstByteTs: calculateDocFirstByteTs,
	calculateMetricWeightsForSorting: calculateMetricWeightsForSorting,
	estimateCompressedContentSize: estimateCompressedContentSize,
	estimateCompressionRatioForScript: estimateCompressionRatioForScript,
	evaluateCLSMetricScore: evaluateCLSMetricScore,
	evaluateINPMetricScore: evaluateINPMetricScore,
	evaluateLCPMetricScore: evaluateLCPMetricScore,
	getCLS: getCLS,
	getFieldMetricsForInsightSet: getFieldMetricsForInsightSet,
	getINP: getINP,
	getInsight: getInsight,
	getLCP: getLCP,
	insightBounds: insightBounds,
	isRequestCompressed: isRequestCompressed,
	isRequestServedFromBrowserCache: isRequestServedFromBrowserCache,
	metricSavingsForWastedBytes: metricSavingsForWastedBytes
});

// Copyright 2024 The Chromium Authors
var InsightWarning;
(function (InsightWarning) {
    InsightWarning["NO_FP"] = "NO_FP";
    InsightWarning["NO_LCP"] = "NO_LCP";
    InsightWarning["NO_DOCUMENT_REQUEST"] = "NO_DOCUMENT_REQUEST";
    InsightWarning["NO_LAYOUT"] = "NO_LAYOUT";
})(InsightWarning || (InsightWarning = {}));
var InsightCategory;
(function (InsightCategory) {
    InsightCategory["ALL"] = "All";
    InsightCategory["INP"] = "INP";
    InsightCategory["LCP"] = "LCP";
    InsightCategory["CLS"] = "CLS";
})(InsightCategory || (InsightCategory = {}));

var types$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	get InsightCategory () { return InsightCategory; },
	get InsightWarning () { return InsightWarning; }
});

// Copyright 2025 The Chromium Authors
const UIStrings$K = {
    title: 'Use efficient cache lifetimes',
    description: 'A long cache lifetime can speed up repeat visits to your page. [Learn more about caching](https://developer.chrome.com/docs/performance/insights/cache).',
    requestColumn: 'Request',
    cacheTTL: 'Cache TTL',
    noRequestsToCache: 'No requests with inefficient cache policies',
    others: '{PH1} others',
};
const str_$J = registerUIStrings('models/trace/insights/Cache.ts', UIStrings$K);
const i18nString$v = getLocalizedString.bind(undefined, str_$J);
const IGNORE_THRESHOLD_IN_PERCENT = 0.925;
function finalize$h(partialModel) {
    return {
        insightKey: "Cache" ,
        strings: UIStrings$K,
        title: i18nString$v(UIStrings$K.title),
        description: i18nString$v(UIStrings$K.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/cache',
        category: InsightCategory.ALL,
        state: partialModel.requests.length > 0 ? 'fail' : 'pass',
        ...partialModel,
    };
}
function isCacheable(request) {
    if (NON_NETWORK_SCHEMES$1.includes(request.args.data.protocol)) {
        return false;
    }
    return Boolean(CACHEABLE_STATUS_CODES.has(request.args.data.statusCode) &&
        STATIC_RESOURCE_TYPES.has(request.args.data.resourceType || "Other" ));
}
function computeCacheLifetimeInSeconds(headers, cacheControl) {
    if (cacheControl?.['max-age'] !== undefined) {
        return cacheControl['max-age'];
    }
    const expiresHeaders = headers.find(h => h.name === 'expires')?.value ?? null;
    if (expiresHeaders) {
        const expires = new Date(expiresHeaders).getTime();
        if (!expires) {
            return 0;
        }
        return Math.ceil((expires - Date.now()) / 1000);
    }
    return null;
}
function getCacheHitProbability(maxAgeInSeconds) {
    const RESOURCE_AGE_IN_HOURS_DECILES = [0, 0.2, 1, 3, 8, 12, 24, 48, 72, 168, 8760, Infinity];
    const maxAgeInHours = maxAgeInSeconds / 3600;
    const upperDecileIndex = RESOURCE_AGE_IN_HOURS_DECILES.findIndex(decile => decile >= maxAgeInHours);
    if (upperDecileIndex === RESOURCE_AGE_IN_HOURS_DECILES.length - 1) {
        return 1;
    }
    if (upperDecileIndex === 0) {
        return 0;
    }
    const upperDecileValue = RESOURCE_AGE_IN_HOURS_DECILES[upperDecileIndex];
    const lowerDecileValue = RESOURCE_AGE_IN_HOURS_DECILES[upperDecileIndex - 1];
    const upperDecile = upperDecileIndex / 10;
    const lowerDecile = (upperDecileIndex - 1) / 10;
    return linearInterpolation(lowerDecileValue, lowerDecile, upperDecileValue, upperDecile, maxAgeInHours);
}
function getCombinedHeaders(responseHeaders) {
    const headers = new Map();
    for (const header of responseHeaders) {
        const name = header.name.toLowerCase();
        if (headers.get(name)) {
            headers.set(name, `${headers.get(name)}, ${header.value}`);
        }
        else {
            headers.set(name, header.value);
        }
    }
    return headers;
}
function cachingDisabled(headers, parsedCacheControl) {
    const cacheControl = headers?.get('cache-control') ?? null;
    const pragma = headers?.get('pragma') ?? null;
    if (!cacheControl && pragma?.includes('no-cache')) {
        return true;
    }
    if (parsedCacheControl &&
        (parsedCacheControl['must-revalidate'] || parsedCacheControl['no-cache'] || parsedCacheControl['no-store'] ||
            parsedCacheControl['private'])) {
        return true;
    }
    return false;
}
function isCacheInsight(model) {
    return model.insightKey === "Cache" ;
}
function generateInsight$h(data, context) {
    const isWithinContext = (event) => eventIsInBounds(event, context.bounds);
    const contextRequests = data.NetworkRequests.byTime.filter(isWithinContext);
    const results = [];
    let totalWastedBytes = 0;
    const wastedBytesByRequestId = new Map();
    for (const req of contextRequests) {
        if (!req.args.data.responseHeaders || !isCacheable(req)) {
            continue;
        }
        const headers = getCombinedHeaders(req.args.data.responseHeaders);
        const cacheControl = headers.get('cache-control') ?? null;
        const parsedDirectives = parseCacheControl(cacheControl);
        if (cachingDisabled(headers, parsedDirectives)) {
            continue;
        }
        let ttl = computeCacheLifetimeInSeconds(req.args.data.responseHeaders, parsedDirectives);
        if (ttl !== null && (!Number.isFinite(ttl) || ttl <= 0)) {
            continue;
        }
        ttl = ttl || 0;
        const ttlDays = ttl / 86400;
        if (ttlDays >= 30) {
            continue;
        }
        const cacheHitProbability = getCacheHitProbability(ttl);
        if (cacheHitProbability > IGNORE_THRESHOLD_IN_PERCENT) {
            continue;
        }
        const transferSize = req.args.data.encodedDataLength || 0;
        const wastedBytes = (1 - cacheHitProbability) * transferSize;
        wastedBytesByRequestId.set(req.args.data.requestId, wastedBytes);
        totalWastedBytes += wastedBytes;
        results.push({ request: req, ttl, wastedBytes });
    }
    results.sort((a, b) => {
        return b.request.args.data.decodedBodyLength - a.request.args.data.decodedBodyLength || a.ttl - b.ttl;
    });
    return finalize$h({
        relatedEvents: results.map(r => r.request),
        requests: results,
        metricSavings: metricSavingsForWastedBytes(wastedBytesByRequestId, context),
        wastedBytes: totalWastedBytes,
    });
}
function createOverlayForRequest$3(request) {
    return {
        type: 'ENTRY_OUTLINE',
        entry: request,
        outlineReason: 'ERROR',
    };
}
function createOverlays$h(model) {
    return model.requests.map(req => createOverlayForRequest$3(req.request));
}

var Cache = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$K,
	cachingDisabled: cachingDisabled,
	computeCacheLifetimeInSeconds: computeCacheLifetimeInSeconds,
	createOverlayForRequest: createOverlayForRequest$3,
	createOverlays: createOverlays$h,
	generateInsight: generateInsight$h,
	getCombinedHeaders: getCombinedHeaders,
	i18nString: i18nString$v,
	isCacheInsight: isCacheInsight,
	isCacheable: isCacheable
});

// Copyright 2024 The Chromium Authors
const UIStrings$J = {
    title: 'Layout shift culprits',
    description: 'Layout shifts occur when elements move absent any user interaction. [Investigate the causes of layout shifts](https://developer.chrome.com/docs/performance/insights/cls-culprit), such as elements being added, removed, or their fonts changing as the page loads.',
    worstLayoutShiftCluster: 'Worst layout shift cluster',
    worstCluster: 'Worst cluster',
    layoutShiftCluster: 'Layout shift cluster @ {PH1}',
    topCulprits: 'Top layout shift culprits',
    injectedIframe: 'Injected iframe',
    webFont: 'Web font',
    animation: 'Animation',
    unsizedImage: 'Unsized image element',
    noLayoutShifts: 'No layout shifts',
    noCulprits: 'Could not detect any layout shift culprits',
};
const str_$I = registerUIStrings('models/trace/insights/CLSCulprits.ts', UIStrings$J);
const i18nString$u = getLocalizedString.bind(undefined, str_$I);
const ACTIONABLE_FAILURE_REASONS = [
    {
        flag: 1 << 0,
        failure: "ACCELERATED_ANIMATIONS_DISABLED" ,
    },
    {
        flag: 1 << 1,
        failure: "EFFECT_SUPPRESSED_BY_DEVTOOLS" ,
    },
    {
        flag: 1 << 2,
        failure: "INVALID_ANIMATION_OR_EFFECT" ,
    },
    {
        flag: 1 << 3,
        failure: "EFFECT_HAS_UNSUPPORTED_TIMING_PARAMS" ,
    },
    {
        flag: 1 << 4,
        failure: "EFFECT_HAS_NON_REPLACE_COMPOSITE_MODE" ,
    },
    {
        flag: 1 << 5,
        failure: "TARGET_HAS_INVALID_COMPOSITING_STATE" ,
    },
    {
        flag: 1 << 6,
        failure: "TARGET_HAS_INCOMPATIBLE_ANIMATIONS" ,
    },
    {
        flag: 1 << 7,
        failure: "TARGET_HAS_CSS_OFFSET" ,
    },
    {
        flag: 1 << 9,
        failure: "ANIMATION_AFFECTS_NON_CSS_PROPERTIES" ,
    },
    {
        flag: 1 << 10,
        failure: "TRANSFORM_RELATED_PROPERTY_CANNOT_BE_ACCELERATED_ON_TARGET" ,
    },
    {
        flag: 1 << 11,
        failure: "TRANSFROM_BOX_SIZE_DEPENDENT" ,
    },
    {
        flag: 1 << 12,
        failure: "FILTER_RELATED_PROPERTY_MAY_MOVE_PIXELS" ,
    },
    {
        flag: 1 << 13,
        failure: "UNSUPPORTED_CSS_PROPERTY" ,
    },
    {
        flag: 1 << 15,
        failure: "MIXED_KEYFRAME_VALUE_TYPES" ,
    },
    {
        flag: 1 << 16,
        failure: "TIMELINE_SOURCE_HAS_INVALID_COMPOSITING_STATE" ,
    },
    {
        flag: 1 << 17,
        failure: "ANIMATION_HAS_NO_VISIBLE_CHANGE" ,
    },
    {
        flag: 1 << 18,
        failure: "AFFECTS_IMPORTANT_PROPERTY" ,
    },
    {
        flag: 1 << 19,
        failure: "SVG_TARGET_HAS_INDEPENDENT_TRANSFORM_PROPERTY" ,
    },
];
const ROOT_CAUSE_WINDOW = secondsToMicro(Seconds(0.5));
function isInRootCauseWindow(event, targetEvent) {
    const eventEnd = event.dur ? event.ts + event.dur : event.ts;
    return eventEnd < targetEvent.ts && eventEnd >= targetEvent.ts - ROOT_CAUSE_WINDOW;
}
function getNonCompositedFailure(animationEvent) {
    const failures = [];
    const beginEvent = animationEvent.args.data.beginEvent;
    const instantEvents = animationEvent.args.data.instantEvents || [];
    for (const event of instantEvents) {
        const failureMask = event.args.data.compositeFailed;
        const unsupportedProperties = event.args.data.unsupportedProperties;
        if (!failureMask) {
            continue;
        }
        const failureReasons = ACTIONABLE_FAILURE_REASONS.filter(reason => failureMask & reason.flag).map(reason => reason.failure);
        const failure = {
            name: beginEvent.args.data.displayName,
            failureReasons,
            unsupportedProperties,
            animation: animationEvent,
        };
        failures.push(failure);
    }
    return failures;
}
function getNonCompositedFailureRootCauses(animationEvents, prePaintEvents, shiftsByPrePaint, rootCausesByShift) {
    const allAnimationFailures = [];
    for (const animation of animationEvents) {
        const failures = getNonCompositedFailure(animation);
        if (!failures) {
            continue;
        }
        allAnimationFailures.push(...failures);
        const nextPrePaint = getNextEvent(prePaintEvents, animation);
        if (!nextPrePaint) {
            continue;
        }
        if (!isInRootCauseWindow(animation, nextPrePaint)) {
            continue;
        }
        const shifts = shiftsByPrePaint.get(nextPrePaint);
        if (!shifts) {
            continue;
        }
        for (const shift of shifts) {
            const rootCausesForShift = rootCausesByShift.get(shift);
            if (!rootCausesForShift) {
                throw new Error('Unaccounted shift');
            }
            rootCausesForShift.nonCompositedAnimations.push(...failures);
        }
    }
    return allAnimationFailures;
}
function getShiftsByPrePaintEvents(layoutShifts, prePaintEvents) {
    const shiftsByPrePaint = new Map();
    for (const prePaintEvent of prePaintEvents) {
        const firstShiftIndex = nearestIndexFromBeginning(layoutShifts, shift => shift.ts >= prePaintEvent.ts);
        if (firstShiftIndex === null) {
            continue;
        }
        for (let i = firstShiftIndex; i < layoutShifts.length; i++) {
            const shift = layoutShifts[i];
            if (shift.ts >= prePaintEvent.ts && shift.ts <= prePaintEvent.ts + prePaintEvent.dur) {
                const shiftsInPrePaint = getWithDefault(shiftsByPrePaint, prePaintEvent, () => []);
                shiftsInPrePaint.push(shift);
            }
            if (shift.ts > prePaintEvent.ts + prePaintEvent.dur) {
                break;
            }
        }
    }
    return shiftsByPrePaint;
}
function getNextEvent(sourceEvents, targetEvent) {
    const index = nearestIndexFromBeginning(sourceEvents, source => source.ts > targetEvent.ts + (targetEvent.dur || 0));
    if (index === null) {
        return undefined;
    }
    return sourceEvents[index];
}
function getIframeRootCauses(data, iframeCreatedEvents, prePaintEvents, shiftsByPrePaint, rootCausesByShift, domLoadingEvents) {
    for (const iframeEvent of iframeCreatedEvents) {
        const nextPrePaint = getNextEvent(prePaintEvents, iframeEvent);
        if (!nextPrePaint) {
            continue;
        }
        const shifts = shiftsByPrePaint.get(nextPrePaint);
        if (!shifts) {
            continue;
        }
        for (const shift of shifts) {
            const rootCausesForShift = rootCausesByShift.get(shift);
            if (!rootCausesForShift) {
                throw new Error('Unaccounted shift');
            }
            const domEvent = domLoadingEvents.find(e => {
                const maxIframe = Micro(iframeEvent.ts + (iframeEvent.dur ?? 0));
                return e.ts >= iframeEvent.ts && e.ts <= maxIframe;
            });
            if (domEvent?.args.frame) {
                const frame = domEvent.args.frame;
                let url;
                const processes = data.Meta.rendererProcessesByFrame.get(frame);
                if (processes && processes.size > 0) {
                    url = [...processes.values()][0]?.[0].frame.url;
                }
                rootCausesForShift.iframes.push({ frame, url });
            }
        }
    }
    return rootCausesByShift;
}
function getUnsizedImageRootCauses(unsizedImageEvents, paintImageEvents, shiftsByPrePaint, rootCausesByShift) {
    shiftsByPrePaint.forEach((shifts, prePaint) => {
        const paintImage = getNextEvent(paintImageEvents, prePaint);
        if (!paintImage) {
            return;
        }
        const matchingNode = unsizedImageEvents.find(unsizedImage => unsizedImage.args.data.nodeId === paintImage.args.data.nodeId);
        if (!matchingNode) {
            return;
        }
        for (const shift of shifts) {
            const rootCausesForShift = rootCausesByShift.get(shift);
            if (!rootCausesForShift) {
                throw new Error('Unaccounted shift');
            }
            rootCausesForShift.unsizedImages.push({
                backendNodeId: matchingNode.args.data.nodeId,
                paintImageEvent: paintImage,
            });
        }
    });
    return rootCausesByShift;
}
function isCLSCulpritsInsight(insight) {
    return insight.insightKey === "CLSCulprits" ;
}
function getFontRootCauses(networkRequests, prePaintEvents, shiftsByPrePaint, rootCausesByShift) {
    const fontRequests = networkRequests.filter(req => req.args.data.resourceType === 'Font' && req.args.data.mimeType.startsWith('font'));
    for (const req of fontRequests) {
        const nextPrePaint = getNextEvent(prePaintEvents, req);
        if (!nextPrePaint) {
            continue;
        }
        if (!isInRootCauseWindow(req, nextPrePaint)) {
            continue;
        }
        const shifts = shiftsByPrePaint.get(nextPrePaint);
        if (!shifts) {
            continue;
        }
        for (const shift of shifts) {
            const rootCausesForShift = rootCausesByShift.get(shift);
            if (!rootCausesForShift) {
                throw new Error('Unaccounted shift');
            }
            rootCausesForShift.webFonts.push(req);
        }
    }
    return rootCausesByShift;
}
function getTopCulprits(cluster, culpritsByShift) {
    const MAX_TOP_CULPRITS = 3;
    const causes = [];
    const shifts = cluster.events;
    for (const shift of shifts) {
        const culprits = culpritsByShift.get(shift);
        if (!culprits) {
            continue;
        }
        const fontReq = culprits.webFonts;
        const iframes = culprits.iframes;
        const animations = culprits.nonCompositedAnimations;
        const unsizedImages = culprits.unsizedImages;
        for (let i = 0; i < fontReq.length && causes.length < MAX_TOP_CULPRITS; i++) {
            causes.push({ type: 0 , description: i18nString$u(UIStrings$J.webFont) });
        }
        for (let i = 0; i < iframes.length && causes.length < MAX_TOP_CULPRITS; i++) {
            causes.push({ type: 1 , description: i18nString$u(UIStrings$J.injectedIframe) });
        }
        for (let i = 0; i < animations.length && causes.length < MAX_TOP_CULPRITS; i++) {
            causes.push({ type: 2 , description: i18nString$u(UIStrings$J.animation) });
        }
        for (let i = 0; i < unsizedImages.length && causes.length < MAX_TOP_CULPRITS; i++) {
            causes.push({
                type: 3 ,
                description: i18nString$u(UIStrings$J.unsizedImage),
                url: unsizedImages[i].paintImageEvent.args.data.url || '',
                backendNodeId: unsizedImages[i].backendNodeId,
                frame: unsizedImages[i].paintImageEvent.args.data.frame || '',
            });
        }
        if (causes.length >= MAX_TOP_CULPRITS) {
            break;
        }
    }
    return causes.slice(0, MAX_TOP_CULPRITS);
}
function finalize$g(partialModel) {
    let state = 'pass';
    if (partialModel.worstCluster) {
        const classification = scoreClassificationForLayoutShift(partialModel.worstCluster.clusterCumulativeScore);
        if (classification === "good" ) {
            state = 'informative';
        }
        else {
            state = 'fail';
        }
    }
    return {
        insightKey: "CLSCulprits" ,
        strings: UIStrings$J,
        title: i18nString$u(UIStrings$J.title),
        description: i18nString$u(UIStrings$J.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/cls-culprit',
        category: InsightCategory.CLS,
        state,
        ...partialModel,
    };
}
function generateInsight$g(data, context) {
    const isWithinContext = (event) => eventIsInBounds(event, context.bounds);
    const compositeAnimationEvents = data.Animations.animations.filter(isWithinContext);
    const iframeEvents = data.LayoutShifts.renderFrameImplCreateChildFrameEvents.filter(isWithinContext);
    const networkRequests = data.NetworkRequests.byTime.filter(isWithinContext);
    const domLoadingEvents = data.LayoutShifts.domLoadingEvents.filter(isWithinContext);
    const unsizedImageEvents = data.LayoutShifts.layoutImageUnsizedEvents.filter(isWithinContext);
    const clusterKey = context.navigation ? context.navigationId : NO_NAVIGATION;
    const clusters = data.LayoutShifts.clustersByNavigationId.get(clusterKey) ?? [];
    const clustersByScore = clusters.toSorted((a, b) => b.clusterCumulativeScore - a.clusterCumulativeScore);
    const worstCluster = clustersByScore.at(0);
    const layoutShifts = clusters.flatMap(cluster => cluster.events);
    const prePaintEvents = data.LayoutShifts.prePaintEvents.filter(isWithinContext);
    const paintImageEvents = data.LayoutShifts.paintImageEvents.filter(isWithinContext);
    const rootCausesByShift = new Map();
    const shiftsByPrePaint = getShiftsByPrePaintEvents(layoutShifts, prePaintEvents);
    for (const shift of layoutShifts) {
        rootCausesByShift.set(shift, { iframes: [], webFonts: [], nonCompositedAnimations: [], unsizedImages: [] });
    }
    getIframeRootCauses(data, iframeEvents, prePaintEvents, shiftsByPrePaint, rootCausesByShift, domLoadingEvents);
    getFontRootCauses(networkRequests, prePaintEvents, shiftsByPrePaint, rootCausesByShift);
    getUnsizedImageRootCauses(unsizedImageEvents, paintImageEvents, shiftsByPrePaint, rootCausesByShift);
    const animationFailures = getNonCompositedFailureRootCauses(compositeAnimationEvents, prePaintEvents, shiftsByPrePaint, rootCausesByShift);
    const relatedEvents = [...layoutShifts];
    if (worstCluster) {
        relatedEvents.push(worstCluster);
    }
    const topCulpritsByCluster = new Map();
    for (const cluster of clusters) {
        topCulpritsByCluster.set(cluster, getTopCulprits(cluster, rootCausesByShift));
    }
    return finalize$g({
        relatedEvents,
        animationFailures,
        shifts: rootCausesByShift,
        clusters,
        worstCluster,
        topCulpritsByCluster,
    });
}
function createOverlays$g(model) {
    const clustersByScore = model.clusters.toSorted((a, b) => b.clusterCumulativeScore - a.clusterCumulativeScore) ?? [];
    const worstCluster = clustersByScore[0];
    if (!worstCluster) {
        return [];
    }
    const range = Micro(worstCluster.dur ?? 0);
    const max = Micro(worstCluster.ts + range);
    return [{
            type: 'TIMESPAN_BREAKDOWN',
            sections: [
                {
                    bounds: { min: worstCluster.ts, range, max },
                    label: i18nString$u(UIStrings$J.worstLayoutShiftCluster),
                    showDuration: false,
                },
            ],
            entry: worstCluster.events[0],
            renderLocation: 'ABOVE_EVENT',
        }];
}

var CLSCulprits = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$J,
	createOverlays: createOverlays$g,
	generateInsight: generateInsight$g,
	getNonCompositedFailure: getNonCompositedFailure,
	i18nString: i18nString$u,
	isCLSCulpritsInsight: isCLSCulpritsInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$I = {
    title: 'Document request latency',
    description: 'Your first network request is the most important. [Reduce its latency](https://developer.chrome.com/docs/performance/insights/document-latency) by avoiding redirects, ensuring a fast server response, and enabling text compression.',
    passingRedirects: 'Avoids redirects',
    failedRedirects: 'Had redirects ({PH1} redirects, +{PH2})',
    passingServerResponseTime: 'Server responds quickly (observed {PH1})',
    failedServerResponseTime: 'Server responded slowly (observed {PH1})',
    passingTextCompression: 'Applies text compression',
    failedTextCompression: 'No compression applied',
    redirectsLabel: 'Redirects',
    serverResponseTimeLabel: 'Server response time',
    uncompressedDownload: 'Uncompressed download',
};
const str_$H = registerUIStrings('models/trace/insights/DocumentLatency.ts', UIStrings$I);
const i18nString$t = getLocalizedString.bind(undefined, str_$H);
const TOO_SLOW_THRESHOLD_MS = 600;
const TARGET_MS = 100;
const IGNORE_THRESHOLD_IN_BYTES = 1400;
function isDocumentLatencyInsight(x) {
    return x.insightKey === 'DocumentLatency';
}
function getServerResponseTime(request) {
    const isLightrider = globalThis.isLightrider;
    if (isLightrider) {
        return request.args.data.lrServerResponseTime ?? null;
    }
    const timing = request.args.data.timing;
    if (!timing) {
        return null;
    }
    const ms = microToMilli(request.args.data.syntheticData.serverResponseTime);
    return Math.round(ms);
}
function getCompressionSavings(request) {
    const isCompressed = isRequestCompressed(request);
    if (isCompressed) {
        return 0;
    }
    const originalSize = request.args.data.decodedBodyLength;
    let estimatedSavings = 0;
    switch (request.args.data.mimeType) {
        case 'text/css':
            estimatedSavings = Math.round(originalSize * 0.8);
            break;
        case 'text/html':
        case 'text/javascript':
            estimatedSavings = Math.round(originalSize * 0.67);
            break;
        case 'text/plain':
        case 'text/xml':
        case 'text/x-component':
        case 'application/javascript':
        case 'application/json':
        case 'application/manifest+json':
        case 'application/vnd.api+json':
        case 'application/xml':
        case 'application/xhtml+xml':
        case 'application/rss+xml':
        case 'application/atom+xml':
        case 'application/vnd.ms-fontobject':
        case 'application/x-font-ttf':
        case 'application/x-font-opentype':
        case 'application/x-font-truetype':
        case 'image/svg+xml':
        case 'image/x-icon':
        case 'image/vnd.microsoft.icon':
        case 'font/ttf':
        case 'font/eot':
        case 'font/otf':
        case 'font/opentype':
            estimatedSavings = Math.round(originalSize * 0.5);
            break;
    }
    return estimatedSavings < IGNORE_THRESHOLD_IN_BYTES ? 0 : estimatedSavings;
}
function finalize$f(partialModel) {
    let hasFailure = false;
    if (partialModel.data) {
        hasFailure = !partialModel.data.checklist.usesCompression.value ||
            !partialModel.data.checklist.serverResponseIsFast.value || !partialModel.data.checklist.noRedirects.value;
    }
    return {
        insightKey: "DocumentLatency" ,
        strings: UIStrings$I,
        title: i18nString$t(UIStrings$I.title),
        description: i18nString$t(UIStrings$I.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/document-latency',
        category: InsightCategory.ALL,
        state: hasFailure ? 'fail' : 'pass',
        ...partialModel,
    };
}
function generateInsight$f(data, context) {
    if (!context.navigation) {
        return finalize$f({});
    }
    const millisToString$1 = context.options.insightTimeFormatters?.milli ?? millisToString;
    const documentRequest = data.NetworkRequests.byId.get(context.navigationId);
    if (!documentRequest) {
        return finalize$f({ warnings: [InsightWarning.NO_DOCUMENT_REQUEST] });
    }
    const serverResponseTime = getServerResponseTime(documentRequest);
    if (serverResponseTime === null) {
        throw new Error('missing document request timing');
    }
    const serverResponseTooSlow = serverResponseTime > TOO_SLOW_THRESHOLD_MS;
    let overallSavingsMs = 0;
    if (serverResponseTime > TOO_SLOW_THRESHOLD_MS) {
        overallSavingsMs = Math.max(serverResponseTime - TARGET_MS, 0);
    }
    const redirectDuration = Math.round(documentRequest.args.data.syntheticData.redirectionDuration / 1000);
    overallSavingsMs += redirectDuration;
    const metricSavings = {
        FCP: overallSavingsMs,
        LCP: overallSavingsMs,
    };
    const uncompressedResponseBytes = getCompressionSavings(documentRequest);
    const noRedirects = redirectDuration === 0;
    const serverResponseIsFast = !serverResponseTooSlow;
    const usesCompression = uncompressedResponseBytes === 0;
    return finalize$f({
        relatedEvents: [documentRequest],
        data: {
            serverResponseTime,
            redirectDuration: Milli(redirectDuration),
            uncompressedResponseBytes,
            documentRequest,
            checklist: {
                noRedirects: {
                    label: noRedirects ? i18nString$t(UIStrings$I.passingRedirects) : i18nString$t(UIStrings$I.failedRedirects, {
                        PH1: documentRequest.args.data.redirects.length,
                        PH2: millisToString$1(redirectDuration),
                    }),
                    value: noRedirects
                },
                serverResponseIsFast: {
                    label: serverResponseIsFast ?
                        i18nString$t(UIStrings$I.passingServerResponseTime, { PH1: millisToString$1(serverResponseTime) }) :
                        i18nString$t(UIStrings$I.failedServerResponseTime, { PH1: millisToString$1(serverResponseTime) }),
                    value: serverResponseIsFast
                },
                usesCompression: {
                    label: usesCompression ? i18nString$t(UIStrings$I.passingTextCompression) :
                        i18nString$t(UIStrings$I.failedTextCompression),
                    value: usesCompression
                },
            },
        },
        metricSavings,
        wastedBytes: uncompressedResponseBytes,
    });
}
function createOverlays$f(model) {
    if (!model.data?.documentRequest) {
        return [];
    }
    const overlays = [];
    const event = model.data.documentRequest;
    const redirectDurationMicro = milliToMicro(model.data.redirectDuration);
    const sections = [];
    if (model.data.redirectDuration) {
        const bounds = traceWindowFromMicroSeconds(event.ts, (event.ts + redirectDurationMicro));
        sections.push({ bounds, label: i18nString$t(UIStrings$I.redirectsLabel), showDuration: true });
        overlays.push({ type: 'CANDY_STRIPED_TIME_RANGE', bounds, entry: event });
    }
    if (!model.data.checklist.serverResponseIsFast.value) {
        const serverResponseTimeMicro = milliToMicro(model.data.serverResponseTime);
        const sendEnd = event.args.data.timing?.sendEnd ?? Milli(0);
        const sendEndMicro = milliToMicro(sendEnd);
        const bounds = traceWindowFromMicroSeconds(sendEndMicro, (sendEndMicro + serverResponseTimeMicro));
        sections.push({ bounds, label: i18nString$t(UIStrings$I.serverResponseTimeLabel), showDuration: true });
    }
    if (model.data.uncompressedResponseBytes) {
        const bounds = traceWindowFromMicroSeconds(event.args.data.syntheticData.downloadStart, (event.args.data.syntheticData.downloadStart + event.args.data.syntheticData.download));
        sections.push({ bounds, label: i18nString$t(UIStrings$I.uncompressedDownload), showDuration: true });
        overlays.push({ type: 'CANDY_STRIPED_TIME_RANGE', bounds, entry: event });
    }
    if (sections.length) {
        overlays.push({
            type: 'TIMESPAN_BREAKDOWN',
            sections,
            entry: model.data.documentRequest,
            renderLocation: 'BELOW_EVENT',
        });
    }
    overlays.push({
        type: 'ENTRY_SELECTED',
        entry: model.data.documentRequest,
    });
    return overlays;
}

var DocumentLatency = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$I,
	createOverlays: createOverlays$f,
	generateInsight: generateInsight$f,
	i18nString: i18nString$t,
	isDocumentLatencyInsight: isDocumentLatencyInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$H = {
    title: 'Optimize DOM size',
    description: 'A large DOM can increase the duration of style calculations and layout reflows, impacting page responsiveness. A large DOM will also increase memory usage. [Learn how to avoid an excessive DOM size](https://developer.chrome.com/docs/performance/insights/dom-size).',
    statistic: 'Statistic',
    value: 'Value',
    element: 'Element',
    totalElements: 'Total elements',
    maxDOMDepth: 'DOM depth',
    maxChildren: 'Most children',
    topUpdatesDescription: 'These are the largest layout and style recalculation events. Their performance impact may be reduced by making the DOM simpler.',
    duration: 'Duration',
    largeLayout: 'Layout ({PH1} objects)',
    largeStyleRecalc: 'Style recalculation ({PH1} elements)',
};
const str_$G = registerUIStrings('models/trace/insights/DOMSize.ts', UIStrings$H);
const i18nString$s = getLocalizedString.bind(undefined, str_$G);
const DOM_SIZE_DURATION_THRESHOLD = milliToMicro(Milli(40));
const LAYOUT_OBJECTS_THRESHOLD = 100;
const STYLE_RECALC_ELEMENTS_THRESHOLD = 300;
function finalize$e(partialModel) {
    const relatedEvents = [...partialModel.largeLayoutUpdates, ...partialModel.largeStyleRecalcs];
    return {
        insightKey: "DOMSize" ,
        strings: UIStrings$H,
        title: i18nString$s(UIStrings$H.title),
        description: i18nString$s(UIStrings$H.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/dom-size',
        category: InsightCategory.INP,
        state: relatedEvents.length > 0 ? 'informative' : 'pass',
        ...partialModel,
        relatedEvents,
    };
}
function isDomSizeInsight(model) {
    return model.insightKey === "DOMSize" ;
}
function generateInsight$e(data, context) {
    const isWithinContext = (event) => eventIsInBounds(event, context.bounds);
    const mainTid = context.navigation?.tid;
    const largeLayoutUpdates = [];
    const largeStyleRecalcs = [];
    const threads = threadsInRenderer(data.Renderer, data.AuctionWorklets);
    for (const thread of threads) {
        if (thread.type !== "MAIN_THREAD" ) {
            continue;
        }
        if (mainTid === undefined) {
            if (!thread.processIsOnMainFrame) {
                continue;
            }
        }
        else if (thread.tid !== mainTid) {
            continue;
        }
        const rendererThread = data.Renderer.processes.get(thread.pid)?.threads.get(thread.tid);
        if (!rendererThread) {
            continue;
        }
        const { entries, layoutEvents, recalcStyleEvents } = rendererThread;
        if (!entries.length) {
            continue;
        }
        const first = entries[0];
        const last = entries[entries.length - 1];
        const timeRange = traceWindowFromMicroSeconds(first.ts, Micro(last.ts + (last.dur ?? 0)));
        if (!boundsIncludeTimeRange({ timeRange, bounds: context.bounds })) {
            continue;
        }
        for (const event of layoutEvents) {
            if (event.dur < DOM_SIZE_DURATION_THRESHOLD || !isWithinContext(event)) {
                continue;
            }
            const { dirtyObjects } = event.args.beginData;
            if (dirtyObjects > LAYOUT_OBJECTS_THRESHOLD) {
                largeLayoutUpdates.push(event);
            }
        }
        for (const event of recalcStyleEvents) {
            if (event.dur < DOM_SIZE_DURATION_THRESHOLD || !isWithinContext(event)) {
                continue;
            }
            const { elementCount } = event.args;
            if (elementCount > STYLE_RECALC_ELEMENTS_THRESHOLD) {
                largeStyleRecalcs.push(event);
            }
        }
    }
    const largeUpdates = [
        ...largeLayoutUpdates.map(event => {
            const duration = (event.dur / 1000);
            const size = event.args.beginData.dirtyObjects;
            const label = i18nString$s(UIStrings$H.largeLayout, { PH1: size });
            return { label, duration, size, event };
        }),
        ...largeStyleRecalcs.map(event => {
            const duration = (event.dur / 1000);
            const size = event.args.elementCount;
            const label = i18nString$s(UIStrings$H.largeStyleRecalc, { PH1: size });
            return { label, duration, size, event };
        }),
    ].sort((a, b) => b.duration - a.duration).slice(0, 5);
    const domStatsEvents = data.DOMStats.domStatsByFrameId.get(context.frameId)?.filter(isWithinContext) ?? [];
    let maxDOMStats;
    for (const domStats of domStatsEvents) {
        const navigationPid = context.navigation?.pid;
        if (navigationPid && domStats.pid !== navigationPid) {
            continue;
        }
        if (!maxDOMStats || domStats.args.data.totalElements > maxDOMStats.args.data.totalElements) {
            maxDOMStats = domStats;
        }
    }
    return finalize$e({
        largeLayoutUpdates,
        largeStyleRecalcs,
        largeUpdates,
        maxDOMStats,
    });
}
function createOverlays$e(model) {
    const entries = [...model.largeStyleRecalcs, ...model.largeLayoutUpdates];
    return entries.map(entry => ({
        type: 'ENTRY_OUTLINE',
        entry,
        outlineReason: 'ERROR',
    }));
}

var DOMSize = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$H,
	createOverlays: createOverlays$e,
	generateInsight: generateInsight$e,
	i18nString: i18nString$s,
	isDomSizeInsight: isDomSizeInsight
});

// Copyright 2025 The Chromium Authors
const UIStrings$G = {
    title: 'Duplicated JavaScript',
    description: 'Remove large, [duplicate JavaScript modules](https://developer.chrome.com/docs/performance/insights/duplicated-javascript) from bundles to reduce unnecessary bytes consumed by network activity.',
    columnSource: 'Source',
    columnDuplicatedBytes: 'Duplicated bytes',
};
const str_$F = registerUIStrings('models/trace/insights/DuplicatedJavaScript.ts', UIStrings$G);
const i18nString$r = getLocalizedString.bind(undefined, str_$F);
function finalize$d(partialModel) {
    const requests = partialModel.scriptsWithDuplication.map(script => script.request).filter(e => !!e);
    return {
        insightKey: "DuplicatedJavaScript" ,
        strings: UIStrings$G,
        title: i18nString$r(UIStrings$G.title),
        description: i18nString$r(UIStrings$G.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/duplicated-javascript',
        category: InsightCategory.LCP,
        state: Boolean(partialModel.duplication.values().next().value) ? 'fail' : 'pass',
        relatedEvents: [...new Set(requests)],
        ...partialModel,
    };
}
function isDuplicatedJavaScriptInsight(model) {
    return model.insightKey === "DuplicatedJavaScript" ;
}
function generateInsight$d(data, context) {
    const scripts = data.Scripts.scripts.filter(script => {
        if (script.frame !== context.frameId) {
            return false;
        }
        if (script.url?.startsWith('chrome-extension://')) {
            return false;
        }
        return timestampIsInBounds(context.bounds, script.ts);
    });
    const compressionRatios = new Map();
    for (const script of scripts) {
        if (script.request) {
            compressionRatios.set(script.request.args.data.requestId, estimateCompressionRatioForScript(script));
        }
    }
    const { duplication, duplicationGroupedByNodeModules } = computeScriptDuplication({ scripts }, compressionRatios);
    const scriptsWithDuplication = [...duplication.values().flatMap(data => data.duplicates.map(d => d.script))];
    const wastedBytesByRequestId = new Map();
    for (const { duplicates } of duplication.values()) {
        for (let i = 1; i < duplicates.length; i++) {
            const sourceData = duplicates[i];
            if (!sourceData.script.request) {
                continue;
            }
            const transferSize = sourceData.attributedSize;
            const requestId = sourceData.script.request.args.data.requestId;
            wastedBytesByRequestId.set(requestId, (wastedBytesByRequestId.get(requestId) || 0) + transferSize);
        }
    }
    return finalize$d({
        duplication,
        duplicationGroupedByNodeModules,
        scriptsWithDuplication: [...new Set(scriptsWithDuplication)],
        scripts,
        mainDocumentUrl: context.navigation?.args.data?.url ?? data.Meta.mainFrameURL,
        metricSavings: metricSavingsForWastedBytes(wastedBytesByRequestId, context),
        wastedBytes: wastedBytesByRequestId.values().reduce((acc, cur) => acc + cur, 0),
    });
}
function createOverlays$d(model) {
    return model.scriptsWithDuplication.map(script => script.request).filter(e => !!e).map(request => {
        return {
            type: 'ENTRY_OUTLINE',
            entry: request,
            outlineReason: 'ERROR',
        };
    });
}

var DuplicatedJavaScript = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$G,
	createOverlays: createOverlays$d,
	generateInsight: generateInsight$d,
	i18nString: i18nString$r,
	isDuplicatedJavaScriptInsight: isDuplicatedJavaScriptInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$F = {
    title: 'Font display',
    description: 'Consider setting [`font-display`](https://developer.chrome.com/docs/performance/insights/font-display) to `swap` or `optional` to ensure text is consistently visible. `swap` can be further optimized to mitigate layout shifts with [font metric overrides](https://developer.chrome.com/blog/font-fallbacks).',
    fontColumn: 'Font',
    wastedTimeColumn: 'Wasted time',
};
const str_$E = registerUIStrings('models/trace/insights/FontDisplay.ts', UIStrings$F);
const i18nString$q = getLocalizedString.bind(undefined, str_$E);
function finalize$c(partialModel) {
    return {
        insightKey: "FontDisplay" ,
        strings: UIStrings$F,
        title: i18nString$q(UIStrings$F.title),
        description: i18nString$q(UIStrings$F.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/font-display',
        category: InsightCategory.INP,
        state: partialModel.fonts.find(font => font.wastedTime > 0) ? 'fail' : 'pass',
        ...partialModel,
    };
}
function isFontDisplayInsight(model) {
    return model.insightKey === "FontDisplay" ;
}
function generateInsight$c(data, context) {
    const fonts = [];
    for (const remoteFont of data.LayoutShifts.remoteFonts) {
        const event = remoteFont.beginRemoteFontLoadEvent;
        if (!eventIsInBounds(event, context.bounds)) {
            continue;
        }
        const requestId = `${event.pid}.${event.args.id}`;
        const request = data.NetworkRequests.byId.get(requestId);
        if (!request) {
            continue;
        }
        if (!/^(block|fallback|auto)$/.test(remoteFont.display)) {
            continue;
        }
        const wastedTimeMicro = Micro(request.args.data.syntheticData.finishTime - request.args.data.syntheticData.sendStartTime);
        let wastedTime = floor(microToMilli(wastedTimeMicro), 1 / 5);
        if (wastedTime === 0) {
            continue;
        }
        wastedTime = Math.min(wastedTime, 3000);
        fonts.push({
            name: remoteFont.name,
            request,
            display: remoteFont.display,
            wastedTime,
        });
    }
    fonts.sort((a, b) => b.wastedTime - a.wastedTime);
    const savings = Math.max(...fonts.map(f => f.wastedTime));
    return finalize$c({
        relatedEvents: fonts.map(f => f.request),
        fonts,
        metricSavings: { FCP: savings },
    });
}
function createOverlays$c(model) {
    return model.fonts.map(font => ({
        type: 'ENTRY_OUTLINE',
        entry: font.request,
        outlineReason: font.wastedTime ? 'ERROR' : 'INFO',
    }));
}

var FontDisplay = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$F,
	createOverlays: createOverlays$c,
	generateInsight: generateInsight$c,
	i18nString: i18nString$q,
	isFontDisplayInsight: isFontDisplayInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$E = {
    title: 'Forced reflow',
    description: 'A forced reflow occurs when JavaScript queries geometric properties (such as `offsetWidth`) after styles have been invalidated by a change to the DOM state. This can result in poor performance. Learn more about [forced reflows](https://developer.chrome.com/docs/performance/insights/forced-reflow) and possible mitigations.',
    reflowCallFrames: 'Call frames that trigger reflow',
    topTimeConsumingFunctionCall: 'Top function call',
    totalReflowTime: 'Total reflow time',
    unattributed: '[unattributed]',
    anonymous: '(anonymous)',
};
const str_$D = registerUIStrings('models/trace/insights/ForcedReflow.ts', UIStrings$E);
const i18nString$p = getLocalizedString.bind(undefined, str_$D);
function getCallFrameId(callFrame) {
    return callFrame.scriptId + ':' + callFrame.lineNumber + ':' + callFrame.columnNumber;
}
function getLargestTopLevelFunctionData(forcedReflowEvents, traceParsedData) {
    const entryToNodeMap = traceParsedData.Renderer.entryToNode;
    const dataByTopLevelFunction = new Map();
    if (forcedReflowEvents.length === 0) {
        return;
    }
    for (const event of forcedReflowEvents) {
        const traceNode = entryToNodeMap.get(event);
        if (!traceNode) {
            continue;
        }
        let node = traceNode.parent;
        let topLevelFunctionCall;
        let topLevelFunctionCallEvent;
        while (node) {
            const eventData = node.entry;
            if (isProfileCall(eventData)) {
                topLevelFunctionCall = eventData.callFrame;
                topLevelFunctionCallEvent = eventData;
            }
            else {
                if (isFunctionCall(eventData) && eventData.args.data &&
                    objectIsCallFrame(eventData.args.data)) {
                    topLevelFunctionCall = eventData.args.data;
                    topLevelFunctionCallEvent = eventData;
                }
                break;
            }
            node = node.parent;
        }
        if (!topLevelFunctionCall || !topLevelFunctionCallEvent) {
            continue;
        }
        const aggregatedDataId = getCallFrameId(topLevelFunctionCall);
        const aggregatedData = getWithDefault(dataByTopLevelFunction, aggregatedDataId, () => ({
            topLevelFunctionCall,
            totalReflowTime: 0,
            topLevelFunctionCallEvents: [],
        }));
        aggregatedData.totalReflowTime += (event.dur ?? 0);
        aggregatedData.topLevelFunctionCallEvents.push(topLevelFunctionCallEvent);
    }
    let topTimeConsumingData = undefined;
    dataByTopLevelFunction.forEach(data => {
        if (!topTimeConsumingData || data.totalReflowTime > topTimeConsumingData.totalReflowTime) {
            topTimeConsumingData = data;
        }
    });
    return topTimeConsumingData;
}
function finalize$b(partialModel) {
    return {
        insightKey: "ForcedReflow" ,
        strings: UIStrings$E,
        title: i18nString$p(UIStrings$E.title),
        description: i18nString$p(UIStrings$E.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/forced-reflow',
        category: InsightCategory.ALL,
        state: partialModel.aggregatedBottomUpData.length !== 0 ? 'fail' : 'pass',
        ...partialModel,
    };
}
function getBottomCallFrameForEvent(event, traceParsedData) {
    const profileStackTrace = get(event, traceParsedData);
    const eventTopCallFrame = getStackTraceTopCallFrameInEventPayload(event);
    return profileStackTrace?.callFrames[0] ?? eventTopCallFrame ?? null;
}
function isForcedReflowInsight(model) {
    return model.insightKey === "ForcedReflow" ;
}
function generateInsight$b(traceParsedData, context) {
    const isWithinContext = (event) => {
        const frameId = frameIDForEvent(event);
        if (frameId !== context.frameId) {
            return false;
        }
        return eventIsInBounds(event, context.bounds);
    };
    const bottomUpDataMap = new Map();
    const events = traceParsedData.Warnings.perWarning.get('FORCED_REFLOW')?.filter(isWithinContext) ?? [];
    for (const event of events) {
        const bottomCallFrame = getBottomCallFrameForEvent(event, traceParsedData);
        const bottomCallId = bottomCallFrame ? getCallFrameId(bottomCallFrame) : 'UNATTRIBUTED';
        const bottomUpData = getWithDefault(bottomUpDataMap, bottomCallId, () => ({
            bottomUpData: bottomCallFrame,
            totalTime: 0,
            relatedEvents: [],
        }));
        bottomUpData.totalTime += event.dur ?? 0;
        bottomUpData.relatedEvents.push(event);
    }
    const topLevelFunctionCallData = getLargestTopLevelFunctionData(events, traceParsedData);
    return finalize$b({
        relatedEvents: events,
        topLevelFunctionCallData,
        aggregatedBottomUpData: [...bottomUpDataMap.values()],
    });
}
function createOverlays$b(model) {
    if (!model.topLevelFunctionCallData) {
        return [];
    }
    const allBottomUpEvents = [...model.aggregatedBottomUpData.values().flatMap(data => data.relatedEvents)];
    return [
        ...createOverlayForEvents(model.topLevelFunctionCallData.topLevelFunctionCallEvents, 'INFO'),
        ...createOverlayForEvents(allBottomUpEvents),
    ];
}
function createOverlayForEvents(events, outlineReason = 'ERROR') {
    return events.map(e => ({
        type: 'ENTRY_OUTLINE',
        entry: e,
        outlineReason,
    }));
}

var ForcedReflow = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$E,
	createOverlayForEvents: createOverlayForEvents,
	createOverlays: createOverlays$b,
	generateInsight: generateInsight$b,
	i18nString: i18nString$p,
	isForcedReflowInsight: isForcedReflowInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$D = {
    title: 'Improve image delivery',
    description: 'Reducing the download time of images can improve the perceived load time of the page and LCP. [Learn more about optimizing image size](https://developer.chrome.com/docs/performance/insights/image-delivery)',
    useCompression: 'Increasing the image compression factor could improve this image\'s download size.',
    useModernFormat: 'Using a modern image format (WebP, AVIF) or increasing the image compression could improve this image\'s download size.',
    useVideoFormat: 'Using video formats instead of GIFs can improve the download size of animated content.',
    useResponsiveSize: 'This image file is larger than it needs to be ({PH1}) for its displayed dimensions ({PH2}). Use responsive images to reduce the image download size.',
    optimizeFile: 'Optimize file size',
    others: '{PH1} others',
    noOptimizableImages: 'No optimizable images',
    estimatedSavings: '{PH1} (Est {PH2})',
};
const str_$C = registerUIStrings('models/trace/insights/ImageDelivery.ts', UIStrings$D);
const i18nString$o = getLocalizedString.bind(undefined, str_$C);
const TARGET_BYTES_PER_PIXEL_AVIF = 2 * 1 / 12;
const GIF_SIZE_THRESHOLD = 100 * 1024;
const BYTE_SAVINGS_THRESHOLD = 4096;
const BYTE_SAVINGS_THRESHOLD_RESPONSIVE_BREAKPOINTS = 12288;
var ImageOptimizationType;
(function (ImageOptimizationType) {
    ImageOptimizationType["ADJUST_COMPRESSION"] = "ADJUST_COMPRESSION";
    ImageOptimizationType["MODERN_FORMAT_OR_COMPRESSION"] = "MODERN_FORMAT_OR_COMPRESSION";
    ImageOptimizationType["VIDEO_FORMAT"] = "VIDEO_FORMAT";
    ImageOptimizationType["RESPONSIVE_SIZE"] = "RESPONSIVE_SIZE";
})(ImageOptimizationType || (ImageOptimizationType = {}));
function isImageDeliveryInsight(model) {
    return model.insightKey === 'ImageDelivery';
}
function getOptimizationMessage(optimization) {
    switch (optimization.type) {
        case ImageOptimizationType.ADJUST_COMPRESSION:
            return i18nString$o(UIStrings$D.useCompression);
        case ImageOptimizationType.MODERN_FORMAT_OR_COMPRESSION:
            return i18nString$o(UIStrings$D.useModernFormat);
        case ImageOptimizationType.VIDEO_FORMAT:
            return i18nString$o(UIStrings$D.useVideoFormat);
        case ImageOptimizationType.RESPONSIVE_SIZE:
            return i18nString$o(UIStrings$D.useResponsiveSize, {
                PH1: `${optimization.fileDimensions.width}x${optimization.fileDimensions.height}`,
                PH2: `${optimization.displayDimensions.width}x${optimization.displayDimensions.height}`,
            });
    }
}
function getOptimizationMessageWithBytes(optimization) {
    const byteSavingsText = bytesToString(optimization.byteSavings);
    const optimizationMessage = getOptimizationMessage(optimization);
    return i18nString$o(UIStrings$D.estimatedSavings, { PH1: optimizationMessage, PH2: byteSavingsText });
}
function finalize$a(partialModel) {
    return {
        insightKey: "ImageDelivery" ,
        strings: UIStrings$D,
        title: i18nString$o(UIStrings$D.title),
        description: i18nString$o(UIStrings$D.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/image-delivery',
        category: InsightCategory.LCP,
        state: partialModel.optimizableImages.length > 0 ? 'fail' : 'pass',
        ...partialModel,
        relatedEvents: new Map(partialModel.optimizableImages.map(image => [image.request, image.optimizations.map(getOptimizationMessageWithBytes)])),
    };
}
function estimateGIFPercentSavings(request) {
    return Math.round((29.1 * Math.log10(request.args.data.decodedBodyLength) - 100.7)) / 100;
}
function getDisplayedSize(data, paintImage) {
    return data.ImagePainting.paintEventToCorrectedDisplaySize.get(paintImage) ?? {
        width: paintImage.args.data.width,
        height: paintImage.args.data.height,
    };
}
function getPixelCounts(data, paintImage) {
    const { width, height } = getDisplayedSize(data, paintImage);
    return {
        filePixels: paintImage.args.data.srcWidth * paintImage.args.data.srcHeight,
        displayedPixels: width * height,
    };
}
function generateInsight$a(data, context) {
    const isWithinContext = (event) => eventIsInBounds(event, context.bounds);
    const contextRequests = data.NetworkRequests.byTime.filter(isWithinContext);
    const optimizableImages = [];
    for (const request of contextRequests) {
        if (request.args.data.resourceType !== 'Image') {
            continue;
        }
        if (request.args.data.mimeType === 'image/svg+xml') {
            continue;
        }
        const url = request.args.data.redirects[0]?.url ?? request.args.data.url;
        const imagePaints = data.ImagePainting.paintImageEventForUrl.get(url)?.filter(isWithinContext);
        if (!imagePaints?.length) {
            continue;
        }
        const largestImagePaint = imagePaints.reduce((prev, curr) => {
            const prevPixels = getPixelCounts(data, prev).displayedPixels;
            const currPixels = getPixelCounts(data, curr).displayedPixels;
            return prevPixels > currPixels ? prev : curr;
        });
        const { filePixels: imageFilePixels, displayedPixels: largestImageDisplayPixels, } = getPixelCounts(data, largestImagePaint);
        const imageBytes = Math.min(request.args.data.decodedBodyLength, request.args.data.encodedDataLength);
        const bytesPerPixel = imageBytes / imageFilePixels;
        let optimizations = [];
        if (request.args.data.mimeType === 'image/gif') {
            if (imageBytes > GIF_SIZE_THRESHOLD) {
                const percentSavings = estimateGIFPercentSavings(request);
                const byteSavings = Math.round(imageBytes * percentSavings);
                optimizations.push({ type: ImageOptimizationType.VIDEO_FORMAT, byteSavings });
            }
        }
        else if (bytesPerPixel > TARGET_BYTES_PER_PIXEL_AVIF) {
            const idealAvifImageSize = Math.round(TARGET_BYTES_PER_PIXEL_AVIF * imageFilePixels);
            const byteSavings = imageBytes - idealAvifImageSize;
            if (request.args.data.mimeType !== 'image/webp' && request.args.data.mimeType !== 'image/avif') {
                optimizations.push({ type: ImageOptimizationType.MODERN_FORMAT_OR_COMPRESSION, byteSavings });
            }
            else {
                optimizations.push({ type: ImageOptimizationType.ADJUST_COMPRESSION, byteSavings });
            }
        }
        const imageByteSavingsFromFormat = Math.max(0, ...optimizations.map(o => o.byteSavings));
        let imageByteSavings = imageByteSavingsFromFormat;
        const wastedPixelRatio = 1 - (largestImageDisplayPixels / imageFilePixels);
        if (wastedPixelRatio > 0 && !largestImagePaint.args.data.isCSS) {
            const byteSavings = Math.round(wastedPixelRatio * imageBytes);
            const hadBreakpoints = largestImagePaint.args.data.isPicture || largestImagePaint.args.data.srcsetAttribute;
            if (!hadBreakpoints || byteSavings > BYTE_SAVINGS_THRESHOLD_RESPONSIVE_BREAKPOINTS) {
                imageByteSavings += Math.round(wastedPixelRatio * (imageBytes - imageByteSavingsFromFormat));
                const { width, height } = getDisplayedSize(data, largestImagePaint);
                optimizations.push({
                    type: ImageOptimizationType.RESPONSIVE_SIZE,
                    byteSavings,
                    fileDimensions: {
                        width: Math.round(largestImagePaint.args.data.srcWidth),
                        height: Math.round(largestImagePaint.args.data.srcHeight),
                    },
                    displayDimensions: {
                        width: Math.round(width),
                        height: Math.round(height),
                    },
                });
            }
        }
        optimizations = optimizations.filter(optimization => optimization.byteSavings > BYTE_SAVINGS_THRESHOLD);
        if (optimizations.length > 0) {
            optimizableImages.push({
                request,
                largestImagePaint,
                optimizations,
                byteSavings: imageByteSavings,
            });
        }
    }
    const wastedBytesByRequestId = new Map();
    for (const image of optimizableImages) {
        wastedBytesByRequestId.set(image.request.args.data.requestId, image.byteSavings);
    }
    optimizableImages.sort((a, b) => {
        if (b.byteSavings !== a.byteSavings) {
            return b.byteSavings - a.byteSavings;
        }
        return b.request.args.data.decodedBodyLength - a.request.args.data.decodedBodyLength;
    });
    return finalize$a({
        optimizableImages,
        metricSavings: metricSavingsForWastedBytes(wastedBytesByRequestId, context),
        wastedBytes: optimizableImages.reduce((total, img) => total + img.byteSavings, 0),
    });
}
function createOverlayForRequest$2(request) {
    return {
        type: 'ENTRY_OUTLINE',
        entry: request,
        outlineReason: 'ERROR',
    };
}
function createOverlays$a(model) {
    return model.optimizableImages.map(image => createOverlayForRequest$2(image.request));
}

var ImageDelivery = /*#__PURE__*/Object.freeze({
	__proto__: null,
	get ImageOptimizationType () { return ImageOptimizationType; },
	UIStrings: UIStrings$D,
	createOverlayForRequest: createOverlayForRequest$2,
	createOverlays: createOverlays$a,
	generateInsight: generateInsight$a,
	getOptimizationMessage: getOptimizationMessage,
	getOptimizationMessageWithBytes: getOptimizationMessageWithBytes,
	i18nString: i18nString$o,
	isImageDeliveryInsight: isImageDeliveryInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$C = {
    description: 'Start investigating [how to improve INP](https://developer.chrome.com/docs/performance/insights/inp-breakdown) by looking at the longest subpart.',
    title: 'INP breakdown',
    subpart: 'Subpart',
    duration: 'Duration',
    inputDelay: 'Input delay',
    processingDuration: 'Processing duration',
    presentationDelay: 'Presentation delay',
    noInteractions: 'No interactions detected',
};
const str_$B = registerUIStrings('models/trace/insights/INPBreakdown.ts', UIStrings$C);
const i18nString$n = getLocalizedString.bind(undefined, str_$B);
function isINPBreakdownInsight(insight) {
    return insight.insightKey === "INPBreakdown" ;
}
function finalize$9(partialModel) {
    let state = 'pass';
    if (partialModel.longestInteractionEvent) {
        const classification = scoreClassificationForInteractionToNextPaint(partialModel.longestInteractionEvent.dur);
        if (classification === "good" ) {
            state = 'informative';
        }
        else {
            state = 'fail';
        }
    }
    return {
        insightKey: "INPBreakdown" ,
        strings: UIStrings$C,
        title: i18nString$n(UIStrings$C.title),
        description: i18nString$n(UIStrings$C.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/inp-breakdown',
        category: InsightCategory.INP,
        state,
        ...partialModel,
    };
}
function generateInsight$9(data, context) {
    const interactionEvents = data.UserInteractions.interactionEventsWithNoNesting.filter(event => {
        return eventIsInBounds(event, context.bounds);
    });
    if (!interactionEvents.length) {
        return finalize$9({});
    }
    const longestByInteractionId = new Map();
    for (const event of interactionEvents) {
        const key = event.interactionId;
        const longest = longestByInteractionId.get(key);
        if (!longest || event.dur > longest.dur) {
            longestByInteractionId.set(key, event);
        }
    }
    const normalizedInteractionEvents = [...longestByInteractionId.values()];
    normalizedInteractionEvents.sort((a, b) => b.dur - a.dur);
    const highPercentileIndex = Math.min(9, Math.floor(normalizedInteractionEvents.length / 50));
    return finalize$9({
        relatedEvents: [normalizedInteractionEvents[0]],
        longestInteractionEvent: normalizedInteractionEvents[0],
        highPercentileInteractionEvent: normalizedInteractionEvents[highPercentileIndex],
    });
}
function createOverlaysForSubpart(event, subpartIndex = -1) {
    const p1 = traceWindowFromMicroSeconds(event.ts, (event.ts + event.inputDelay));
    const p2 = traceWindowFromMicroSeconds(p1.max, (p1.max + event.mainThreadHandling));
    const p3 = traceWindowFromMicroSeconds(p2.max, (p2.max + event.presentationDelay));
    let sections = [
        { bounds: p1, label: i18nString$n(UIStrings$C.inputDelay), showDuration: true },
        { bounds: p2, label: i18nString$n(UIStrings$C.processingDuration), showDuration: true },
        { bounds: p3, label: i18nString$n(UIStrings$C.presentationDelay), showDuration: true },
    ];
    if (subpartIndex !== -1) {
        sections = [sections[subpartIndex]];
    }
    return [
        {
            type: 'TIMESPAN_BREAKDOWN',
            sections,
            renderLocation: 'BELOW_EVENT',
            entry: event,
        },
    ];
}
function createOverlays$9(model) {
    const event = model.longestInteractionEvent;
    if (!event) {
        return [];
    }
    return createOverlaysForSubpart(event);
}

var INPBreakdown = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$C,
	createOverlays: createOverlays$9,
	createOverlaysForSubpart: createOverlaysForSubpart,
	generateInsight: generateInsight$9,
	i18nString: i18nString$n,
	isINPBreakdownInsight: isINPBreakdownInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$B = {
    title: 'LCP breakdown',
    description: 'Each [subpart has specific improvement strategies](https://developer.chrome.com/docs/performance/insights/lcp-breakdown). Ideally, most of the LCP time should be spent on loading the resources, not within delays.',
    timeToFirstByte: 'Time to first byte',
    resourceLoadDelay: 'Resource load delay',
    resourceLoadDuration: 'Resource load duration',
    elementRenderDelay: 'Element render delay',
    subpart: 'Subpart',
    duration: 'Duration',
    fieldDuration: 'Field p75',
    noLcp: 'No LCP detected',
};
const str_$A = registerUIStrings('models/trace/insights/LCPBreakdown.ts', UIStrings$B);
const i18nString$m = getLocalizedString.bind(undefined, str_$A);
function isLCPBreakdownInsight(model) {
    return model.insightKey === 'LCPBreakdown';
}
function anyValuesNaN(...values) {
    return values.some(v => Number.isNaN(v));
}
function determineSubparts(nav, docRequest, lcpEvent, lcpRequest) {
    const firstDocByteTs = calculateDocFirstByteTs(docRequest);
    if (firstDocByteTs === null) {
        return null;
    }
    const ttfb = traceWindowFromMicroSeconds(nav.ts, firstDocByteTs);
    ttfb.label = i18nString$m(UIStrings$B.timeToFirstByte);
    let renderDelay = traceWindowFromMicroSeconds(ttfb.max, lcpEvent.ts);
    renderDelay.label = i18nString$m(UIStrings$B.elementRenderDelay);
    if (!lcpRequest) {
        if (anyValuesNaN(ttfb.range, renderDelay.range)) {
            return null;
        }
        return { ttfb, renderDelay };
    }
    const lcpStartTs = lcpRequest.ts;
    const lcpReqEndTs = lcpRequest.args.data.syntheticData.finishTime;
    const loadDelay = traceWindowFromMicroSeconds(ttfb.max, lcpStartTs);
    const loadDuration = traceWindowFromMicroSeconds(lcpStartTs, lcpReqEndTs);
    renderDelay = traceWindowFromMicroSeconds(lcpReqEndTs, lcpEvent.ts);
    loadDelay.label = i18nString$m(UIStrings$B.resourceLoadDelay);
    loadDuration.label = i18nString$m(UIStrings$B.resourceLoadDuration);
    renderDelay.label = i18nString$m(UIStrings$B.elementRenderDelay);
    if (anyValuesNaN(ttfb.range, loadDelay.range, loadDuration.range, renderDelay.range)) {
        return null;
    }
    return {
        ttfb,
        loadDelay,
        loadDuration,
        renderDelay,
    };
}
function finalize$8(partialModel) {
    const relatedEvents = [];
    if (partialModel.lcpEvent) {
        relatedEvents.push(partialModel.lcpEvent);
    }
    if (partialModel.lcpRequest) {
        relatedEvents.push(partialModel.lcpRequest);
    }
    let state = 'pass';
    if (partialModel.lcpMs !== undefined) {
        const classification = scoreClassificationForLargestContentfulPaint(milliToMicro(partialModel.lcpMs));
        if (classification === "good" ) {
            state = 'informative';
        }
        else {
            state = 'fail';
        }
    }
    return {
        insightKey: "LCPBreakdown" ,
        strings: UIStrings$B,
        title: i18nString$m(UIStrings$B.title),
        description: i18nString$m(UIStrings$B.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/lcp-breakdown',
        category: InsightCategory.LCP,
        state,
        ...partialModel,
        relatedEvents,
    };
}
function generateInsight$8(data, context) {
    if (!context.navigation) {
        return finalize$8({});
    }
    const networkRequests = data.NetworkRequests;
    const frameMetrics = data.PageLoadMetrics.metricScoresByFrameId.get(context.frameId);
    if (!frameMetrics) {
        throw new Error('no frame metrics');
    }
    const navMetrics = frameMetrics.get(context.navigation);
    if (!navMetrics) {
        throw new Error('no navigation metrics');
    }
    const metricScore = navMetrics.get("LCP" );
    const lcpEvent = metricScore?.event;
    if (!lcpEvent || !isAnyLargestContentfulPaintCandidate(lcpEvent)) {
        return finalize$8({ warnings: [InsightWarning.NO_LCP] });
    }
    const lcpMs = microToMilli(metricScore.timing);
    const lcpTs = metricScore.event?.ts ? microToMilli(metricScore.event?.ts) : undefined;
    const lcpRequest = data.LargestImagePaint.lcpRequestByNavigationId.get(context.navigationId);
    const docRequest = networkRequests.byId.get(context.navigationId);
    if (!docRequest) {
        return finalize$8({ lcpMs, lcpTs, lcpEvent, lcpRequest, warnings: [InsightWarning.NO_DOCUMENT_REQUEST] });
    }
    return finalize$8({
        lcpMs,
        lcpTs,
        lcpEvent,
        lcpRequest,
        subparts: determineSubparts(context.navigation, docRequest, lcpEvent, lcpRequest) ?? undefined,
    });
}
function createOverlays$8(model) {
    if (!model.subparts || !model.lcpTs) {
        return [];
    }
    const overlays = [
        {
            type: 'TIMESPAN_BREAKDOWN',
            sections: Object.values(model.subparts)
                .map((subpart) => ({ bounds: subpart, label: subpart.label, showDuration: true })),
        },
    ];
    if (model.lcpRequest) {
        overlays.push({ type: 'ENTRY_OUTLINE', entry: model.lcpRequest, outlineReason: 'INFO' });
    }
    return overlays;
}

var LCPBreakdown = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$B,
	createOverlays: createOverlays$8,
	generateInsight: generateInsight$8,
	i18nString: i18nString$m,
	isLCPBreakdownInsight: isLCPBreakdownInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$A = {
    title: 'LCP request discovery',
    description: '[Optimize LCP](https://developer.chrome.com/docs/performance/insights/lcp-discovery) by making the LCP image discoverable from the HTML immediately, and avoiding lazy-loading',
    lcpLoadDelay: 'LCP image loaded {PH1} after earliest start point.',
    fetchPriorityApplied: 'fetchpriority=high applied',
    fetchPriorityShouldBeApplied: 'fetchpriority=high should be applied',
    requestDiscoverable: 'Request is discoverable in initial document',
    lazyLoadNotApplied: 'lazy load not applied',
    noLcp: 'No LCP detected',
    noLcpResource: 'No LCP resource detected because the LCP is not an image',
};
const str_$z = registerUIStrings('models/trace/insights/LCPDiscovery.ts', UIStrings$A);
const i18nString$l = getLocalizedString.bind(undefined, str_$z);
function isLCPDiscoveryInsight(model) {
    return model.insightKey === 'LCPDiscovery';
}
function finalize$7(partialModel) {
    const relatedEvents = partialModel.lcpEvent && partialModel.lcpRequest ?
        [partialModel.lcpEvent, partialModel.lcpRequest] :
        [];
    return {
        insightKey: "LCPDiscovery" ,
        strings: UIStrings$A,
        title: i18nString$l(UIStrings$A.title),
        description: i18nString$l(UIStrings$A.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/lcp-discovery',
        category: InsightCategory.LCP,
        state: partialModel.lcpRequest && partialModel.checklist &&
            (!partialModel.checklist.eagerlyLoaded.value || !partialModel.checklist.requestDiscoverable.value ||
                !partialModel.checklist.priorityHinted.value) ?
            'fail' :
            'pass',
        ...partialModel,
        relatedEvents,
    };
}
function generateInsight$7(data, context) {
    if (!context.navigation) {
        return finalize$7({});
    }
    const networkRequests = data.NetworkRequests;
    const frameMetrics = data.PageLoadMetrics.metricScoresByFrameId.get(context.frameId);
    if (!frameMetrics) {
        throw new Error('no frame metrics');
    }
    const navMetrics = frameMetrics.get(context.navigation);
    if (!navMetrics) {
        throw new Error('no navigation metrics');
    }
    const metricScore = navMetrics.get("LCP" );
    const lcpEvent = metricScore?.event;
    if (!lcpEvent || !isAnyLargestContentfulPaintCandidate(lcpEvent)) {
        return finalize$7({ warnings: [InsightWarning.NO_LCP] });
    }
    const docRequest = networkRequests.byId.get(context.navigationId);
    if (!docRequest) {
        return finalize$7({ warnings: [InsightWarning.NO_DOCUMENT_REQUEST] });
    }
    const lcpRequest = data.LargestImagePaint.lcpRequestByNavigationId.get(context.navigationId);
    if (!lcpRequest) {
        return finalize$7({ lcpEvent });
    }
    const initiatorUrl = lcpRequest.args.data.initiator?.url;
    const initiatedByMainDoc = lcpRequest?.args.data.initiator?.type === 'parser' && docRequest.args.data.url === initiatorUrl;
    const imgPreloadedOrFoundInHTML = lcpRequest?.args.data.isLinkPreload || initiatedByMainDoc;
    const imageLoadingAttr = lcpEvent.args.data?.loadingAttr;
    const imageFetchPriorityHint = lcpRequest?.args.data.fetchPriorityHint;
    const earliestDiscoveryTime = calculateDocFirstByteTs(docRequest);
    const priorityHintFound = imageFetchPriorityHint === 'high';
    return finalize$7({
        lcpEvent,
        lcpRequest,
        earliestDiscoveryTimeTs: earliestDiscoveryTime ? Micro(earliestDiscoveryTime) : undefined,
        checklist: {
            priorityHinted: {
                label: priorityHintFound ? i18nString$l(UIStrings$A.fetchPriorityApplied) :
                    i18nString$l(UIStrings$A.fetchPriorityShouldBeApplied),
                value: priorityHintFound
            },
            requestDiscoverable: { label: i18nString$l(UIStrings$A.requestDiscoverable), value: imgPreloadedOrFoundInHTML },
            eagerlyLoaded: { label: i18nString$l(UIStrings$A.lazyLoadNotApplied), value: imageLoadingAttr !== 'lazy' },
        },
    });
}
function getImageData(model) {
    if (!model.lcpRequest || !model.checklist) {
        return null;
    }
    const shouldIncreasePriorityHint = !model.checklist.priorityHinted.value;
    const shouldPreloadImage = !model.checklist.requestDiscoverable.value;
    const shouldRemoveLazyLoading = !model.checklist.eagerlyLoaded.value;
    const imageLCP = shouldIncreasePriorityHint !== undefined && shouldPreloadImage !== undefined &&
        shouldRemoveLazyLoading !== undefined;
    if (!imageLCP) {
        return null;
    }
    const data = {
        checklist: model.checklist,
        request: model.lcpRequest,
        discoveryDelay: null,
        estimatedSavings: model.metricSavings?.LCP ?? null,
    };
    if (model.earliestDiscoveryTimeTs && model.lcpRequest) {
        const discoveryDelay = model.lcpRequest.ts - model.earliestDiscoveryTimeTs;
        data.discoveryDelay = Micro(discoveryDelay);
    }
    return data;
}
function createOverlays$7(model) {
    const imageResults = getImageData(model);
    if (!imageResults?.discoveryDelay) {
        return [];
    }
    const delay = traceWindowFromMicroSeconds(Micro(imageResults.request.ts - imageResults.discoveryDelay), imageResults.request.ts);
    return [
        {
            type: 'ENTRY_OUTLINE',
            entry: imageResults.request,
            outlineReason: 'ERROR',
        },
        {
            type: 'CANDY_STRIPED_TIME_RANGE',
            bounds: delay,
            entry: imageResults.request,
        },
        {
            type: 'TIMESPAN_BREAKDOWN',
            sections: [{
                    bounds: delay,
                    label: `${imageResults.discoveryDelay} microseconds`,
                    showDuration: false,
                }],
            entry: imageResults.request,
            renderLocation: 'ABOVE_EVENT',
        },
    ];
}

var LCPDiscovery = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$A,
	createOverlays: createOverlays$7,
	generateInsight: generateInsight$7,
	getImageData: getImageData,
	i18nString: i18nString$l,
	isLCPDiscoveryInsight: isLCPDiscoveryInsight
});

var polyfill_module_data_default = [
    {
        name: "focus-visible",
        modules: [
            "focus-visible"
        ]
    },
    {
        name: "Error.prototype.cause",
        modules: [
            "es.error.cause"
        ]
    },
    {
        name: "Array.prototype.at",
        modules: [
            "es.array.at",
            "esnext.array.at"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.concat",
        modules: [
            "es.array.concat"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.copyWithin",
        modules: [
            "es.array.copy-within"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.every",
        modules: [
            "es.array.every"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.fill",
        modules: [
            "es.array.fill"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.filter",
        modules: [
            "es.array.filter"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.find",
        modules: [
            "es.array.find"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.findIndex",
        modules: [
            "es.array.find-index"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.findLast",
        modules: [
            "es.array.find-last",
            "esnext.array.find-last"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.findLastIndex",
        modules: [
            "es.array.find-last-index",
            "esnext.array.find-last-index"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.flat",
        modules: [
            "es.array.flat"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.flatMap",
        modules: [
            "es.array.flat-map"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.forEach",
        modules: [
            "es.array.for-each"
        ],
        corejs: true
    },
    {
        name: "Array.from",
        modules: [
            "es.array.from"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.includes",
        modules: [
            "es.array.includes"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.indexOf",
        modules: [
            "es.array.index-of"
        ],
        corejs: true
    },
    {
        name: "Array.isArray",
        modules: [
            "es.array.is-array"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.join",
        modules: [
            "es.array.join"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.map",
        modules: [
            "es.array.map"
        ],
        corejs: true
    },
    {
        name: "Array.of",
        modules: [
            "es.array.of"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.slice",
        modules: [
            "es.array.slice"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.some",
        modules: [
            "es.array.some"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.sort",
        modules: [
            "es.array.sort"
        ],
        corejs: true
    },
    {
        name: "Array.prototype.unshift",
        modules: [
            "es.array.unshift"
        ],
        corejs: true
    },
    {
        name: "Math.acosh",
        modules: [
            "es.math.acosh"
        ],
        corejs: true
    },
    {
        name: "Math.asinh",
        modules: [
            "es.math.asinh"
        ],
        corejs: true
    },
    {
        name: "Math.atanh",
        modules: [
            "es.math.atanh"
        ],
        corejs: true
    },
    {
        name: "Math.cbrt",
        modules: [
            "es.math.cbrt"
        ],
        corejs: true
    },
    {
        name: "Math.clz32",
        modules: [
            "es.math.clz32"
        ],
        corejs: true
    },
    {
        name: "Math.cosh",
        modules: [
            "es.math.cosh"
        ],
        corejs: true
    },
    {
        name: "Math.expm1",
        modules: [
            "es.math.expm1"
        ],
        corejs: true
    },
    {
        name: "Math.fround",
        modules: [
            "es.math.fround"
        ],
        corejs: true
    },
    {
        name: "Math.hypot",
        modules: [
            "es.math.hypot"
        ],
        corejs: true
    },
    {
        name: "Math.imul",
        modules: [
            "es.math.imul"
        ],
        corejs: true
    },
    {
        name: "Math.log10",
        modules: [
            "es.math.log10"
        ],
        corejs: true
    },
    {
        name: "Math.log1p",
        modules: [
            "es.math.log1p"
        ],
        corejs: true
    },
    {
        name: "Math.log2",
        modules: [
            "es.math.log2"
        ],
        corejs: true
    },
    {
        name: "Math.sign",
        modules: [
            "es.math.sign"
        ],
        corejs: true
    },
    {
        name: "Math.sinh",
        modules: [
            "es.math.sinh"
        ],
        corejs: true
    },
    {
        name: "Math.tanh",
        modules: [
            "es.math.tanh"
        ],
        corejs: true
    },
    {
        name: "Math.trunc",
        modules: [
            "es.math.trunc"
        ],
        corejs: true
    },
    {
        name: "Object.assign",
        modules: [
            "es.object.assign"
        ],
        corejs: true
    },
    {
        name: "Object.create",
        modules: [
            "es.object.create"
        ],
        corejs: true
    },
    {
        name: "Object.entries",
        modules: [
            "es.object.entries"
        ],
        corejs: true
    },
    {
        name: "Object.freeze",
        modules: [
            "es.object.freeze"
        ],
        corejs: true
    },
    {
        name: "Object.fromEntries",
        modules: [
            "es.object.from-entries"
        ],
        corejs: true
    },
    {
        name: "Object.getOwnPropertyDescriptor",
        modules: [
            "es.object.get-own-property-descriptor"
        ],
        corejs: true
    },
    {
        name: "Object.getOwnPropertyDescriptors",
        modules: [
            "es.object.get-own-property-descriptors"
        ],
        corejs: true
    },
    {
        name: "Object.getPrototypeOf",
        modules: [
            "es.object.get-prototype-of"
        ],
        corejs: true
    },
    {
        name: "Object.hasOwn",
        modules: [
            "es.object.has-own",
            "esnext.object.has-own"
        ],
        corejs: true
    },
    {
        name: "Object.is",
        modules: [
            "es.object.is"
        ],
        corejs: true
    },
    {
        name: "Object.isExtensible",
        modules: [
            "es.object.is-extensible"
        ],
        corejs: true
    },
    {
        name: "Object.isFrozen",
        modules: [
            "es.object.is-frozen"
        ],
        corejs: true
    },
    {
        name: "Object.isSealed",
        modules: [
            "es.object.is-sealed"
        ],
        corejs: true
    },
    {
        name: "Object.keys",
        modules: [
            "es.object.keys"
        ],
        corejs: true
    },
    {
        name: "Object.preventExtensions",
        modules: [
            "es.object.prevent-extensions"
        ],
        corejs: true
    },
    {
        name: "Object.seal",
        modules: [
            "es.object.seal"
        ],
        corejs: true
    },
    {
        name: "Object.setPrototypeOf",
        modules: [
            "es.object.set-prototype-of"
        ],
        corejs: true
    },
    {
        name: "Object.values",
        modules: [
            "es.object.values"
        ],
        corejs: true
    },
    {
        name: "Promise.any",
        modules: [
            "es.promise.any",
            "esnext.promise.any"
        ],
        corejs: true
    },
    {
        name: "Reflect.apply",
        modules: [
            "es.reflect.apply"
        ],
        corejs: true
    },
    {
        name: "Reflect.construct",
        modules: [
            "es.reflect.construct"
        ],
        corejs: true
    },
    {
        name: "Reflect.deleteProperty",
        modules: [
            "es.reflect.delete-property"
        ],
        corejs: true
    },
    {
        name: "Reflect.get",
        modules: [
            "es.reflect.get"
        ],
        corejs: true
    },
    {
        name: "Reflect.getOwnPropertyDescriptor",
        modules: [
            "es.reflect.get-own-property-descriptor"
        ],
        corejs: true
    },
    {
        name: "Reflect.getPrototypeOf",
        modules: [
            "es.reflect.get-prototype-of"
        ],
        corejs: true
    },
    {
        name: "Reflect.has",
        modules: [
            "es.reflect.has"
        ],
        corejs: true
    },
    {
        name: "Reflect.isExtensible",
        modules: [
            "es.reflect.is-extensible"
        ],
        corejs: true
    },
    {
        name: "Reflect.ownKeys",
        modules: [
            "es.reflect.own-keys"
        ],
        corejs: true
    },
    {
        name: "Reflect.preventExtensions",
        modules: [
            "es.reflect.prevent-extensions"
        ],
        corejs: true
    },
    {
        name: "Reflect.setPrototypeOf",
        modules: [
            "es.reflect.set-prototype-of"
        ],
        corejs: true
    },
    {
        name: "String.prototype.codePointAt",
        modules: [
            "es.string.code-point-at"
        ],
        corejs: true
    },
    {
        name: "String.prototype.endsWith",
        modules: [
            "es.string.ends-with"
        ],
        corejs: true
    },
    {
        name: "String.fromCodePoint",
        modules: [
            "es.string.from-code-point"
        ],
        corejs: true
    },
    {
        name: "String.prototype.includes",
        modules: [
            "es.string.includes"
        ],
        corejs: true
    },
    {
        name: "String.prototype.matchAll",
        modules: [
            "es.string.match-all",
            "esnext.string.match-all"
        ],
        corejs: true
    },
    {
        name: "String.raw",
        modules: [
            "es.string.raw"
        ],
        corejs: true
    },
    {
        name: "String.prototype.repeat",
        modules: [
            "es.string.repeat"
        ],
        corejs: true
    },
    {
        name: "String.prototype.replaceAll",
        modules: [
            "es.string.replace-all",
            "esnext.string.replace-all"
        ],
        corejs: true
    },
    {
        name: "String.prototype.startsWith",
        modules: [
            "es.string.starts-with"
        ],
        corejs: true
    },
    {
        name: "String.prototype.substr",
        modules: [
            "es.string.substr"
        ],
        corejs: true
    },
    {
        name: "String.prototype.trim",
        modules: [
            "es.string.trim"
        ],
        corejs: true
    },
    {
        name: "String.prototype.trimEnd",
        modules: [
            "es.string.trim-end"
        ],
        corejs: true
    },
    {
        name: "String.prototype.trimStart",
        modules: [
            "es.string.trim-start"
        ],
        corejs: true
    },
    {
        name: "String.prototype.link",
        modules: [
            "es.string.link"
        ],
        corejs: true
    },
    {
        name: "Promise.allSettled",
        modules: [
            "esnext.promise.all-settled"
        ],
        corejs: true
    }
];
var polyfill_graph_data_default = {
    moduleSizes: [26070, 498, 282, 294, 281, 467, 161, 236, 229, 765, 546, 339, 1608, 723, 729, 1545, 438, 214, 657, 111, 759, 537, 209, 281, 685, 217, 757, 631, 293, 182, 475, 79, 407, 140, 366, 792, 269, 222, 158, 280, 188, 137, 158, 105, 189, 543, 160, 742, 1436, 88, 904, 146, 314, 375, 183, 1083, 195, 503, 269, 208, 334, 350, 460, 568, 229, 1155, 334, 266, 30, 120, 309, 370, 358, 1952, 1638, 304, 153, 274, 1288, 192, 543, 74, 144, 137, 33, 336, 457, 2122, 535, 711, 1323, 117, 1961, 244, 557, 318, 119, 124, 108, 144, 96, 133, 441, 210, 1627, 1956, 693, 1426, 863, 637, 301, 51, 708, 583, 119, 600, 221, 370, 728, 1085, 552, 629, 125, 1746, 97, 441, 543, 2756, 371, 447, 548, 243, 266, 217, 99, 440, 183, 546, 137, 464, 207, 983, 503, 237, 382, 249, 675, 402, 254, 223, 164, 214, 191, 831, 218, 202, 232, 124, 249, 160, 251, 217, 717, 78, 561, 1627, 256, 386, 225, 432, 499, 394, 364, 445, 634, 667, 177, 346, 470, 663, 142, 588, 414, 617, 1559, 380, 2520, 1040, 417, 289, 238, 220, 214, 303, 163, 141, 510, 397, 137, 137, 133, 133, 390, 266, 137, 183, 215, 191, 485, 328, 575, 799, 533, 148, 215, 589, 589, 130, 362, 562, 471, 179, 186, 1266, 1456, 521, 1536, 427, 444, 406, 912, 150, 283, 144, 485, 470, 205, 1268, 796, 658, 306, 3751, 814, 146, 2328, 1226, 922, 237, 206, 198, 250, 283, 60, 3e3],
    dependencies: {
        "Array.prototype.at": [0, 5, 69, 105, 106, 116, 164],
        "Array.prototype.concat": [0, 16, 21, 22, 26, 34, 40, 76, 78, 155, 165],
        "Array.prototype.copyWithin": [0, 5, 9, 37, 69, 105, 106, 116, 166],
        "Array.prototype.every": [0, 15, 17, 21, 22, 26, 53, 59, 76, 78, 155, 167],
        "Array.prototype.fill": [0, 5, 10, 69, 105, 106, 116, 168],
        "Array.prototype.filter": [0, 15, 16, 21, 22, 26, 53, 59, 76, 78, 155, 169],
        "Array.prototype.find": [0, 5, 15, 21, 22, 26, 53, 59, 69, 76, 78, 105, 106, 116, 155, 173],
        "Array.prototype.findIndex": [0, 5, 15, 21, 22, 26, 53, 59, 69, 76, 78, 105, 106, 116, 155, 170],
        "Array.prototype.findLast": [0, 5, 14, 53, 59, 69, 105, 106, 116, 172],
        "Array.prototype.findLastIndex": [0, 5, 14, 53, 59, 69, 105, 106, 116, 171],
        "Array.prototype.flat": [0, 21, 22, 26, 40, 50, 53, 59, 76, 78, 155, 175],
        "Array.prototype.flatMap": [0, 21, 22, 26, 40, 50, 53, 59, 76, 78, 155, 174],
        "Array.prototype.forEach": [0, 11, 15, 17, 21, 22, 26, 53, 59, 76, 78, 155, 176],
        "Array.from": [0, 12, 23, 24, 26, 34, 53, 59, 62, 63, 75, 78, 88, 155, 177],
        "Array.prototype.includes": [0, 5, 69, 105, 106, 116, 178],
        "Array.prototype.indexOf": [0, 17, 59, 179],
        "Array.isArray": [0, 76, 180],
        "Array.prototype.join": [0, 17, 181],
        "Array.prototype.map": [0, 15, 16, 21, 22, 26, 53, 59, 76, 78, 155, 182],
        "Array.of": [0, 26, 34, 78, 155, 183],
        "Array.prototype.slice": [0, 16, 19, 26, 34, 76, 78, 155, 184],
        "Array.prototype.some": [0, 15, 17, 21, 22, 26, 53, 59, 76, 78, 155, 185],
        "Array.prototype.sort": [0, 17, 19, 20, 26, 37, 42, 43, 46, 155, 156, 186],
        "Array.prototype.unshift": [0, 18, 37, 40, 76, 187],
        "Math.acosh": [0, 97, 188],
        "Math.asinh": [0, 189],
        "Math.atanh": [0, 190],
        "Math.cbrt": [0, 100, 191],
        "Math.clz32": [0, 192],
        "Math.cosh": [0, 93, 193],
        "Math.expm1": [0, 93, 194],
        "Math.fround": [0, 94, 95, 99, 100, 195],
        "Math.hypot": [0, 196],
        "Math.imul": [0, 197],
        "Math.log10": [0, 96, 198],
        "Math.log1p": [0, 97, 199],
        "Math.log2": [0, 98, 200],
        "Math.sign": [0, 100, 201],
        "Math.sinh": [0, 93, 202],
        "Math.tanh": [0, 93, 203],
        "Math.trunc": [0, 204],
        "Object.assign": [0, 104, 116, 205],
        "Object.create": [0, 69, 105, 106, 116, 206],
        "Object.entries": [0, 29, 112, 116, 119, 207],
        "Object.freeze": [0, 8, 19, 51, 73, 109, 113, 208],
        "Object.fromEntries": [0, 26, 34, 53, 59, 62, 63, 75, 87, 88, 155, 209],
        "Object.getOwnPropertyDescriptor": [0, 210],
        "Object.getOwnPropertyDescriptors": [0, 34, 211],
        "Object.getPrototypeOf": [0, 29, 112, 212],
        "Object.hasOwn": [0, 213],
        "Object.is": [0, 134, 217],
        "Object.isExtensible": [0, 8, 113, 214],
        "Object.isFrozen": [0, 8, 215],
        "Object.isSealed": [0, 8, 216],
        "Object.keys": [0, 116, 218],
        "Object.preventExtensions": [0, 8, 19, 51, 73, 109, 113, 219],
        "Object.seal": [0, 8, 19, 51, 73, 109, 113, 220],
        "Object.setPrototypeOf": [0, 4, 58, 83, 118, 221],
        "Object.values": [0, 29, 112, 116, 119, 222],
        "Promise.any": [0, 24, 26, 47, 53, 59, 62, 63, 75, 87, 88, 102, 122, 123, 124, 125, 155, 224],
        "Reflect.apply": [0, 52, 225],
        "Reflect.construct": [0, 3, 19, 26, 52, 55, 69, 78, 105, 106, 116, 155, 226],
        "Reflect.deleteProperty": [0, 227],
        "Reflect.get": [0, 29, 79, 112, 230],
        "Reflect.getOwnPropertyDescriptor": [0, 228],
        "Reflect.getPrototypeOf": [0, 29, 112, 229],
        "Reflect.has": [0, 231],
        "Reflect.isExtensible": [0, 8, 113, 232],
        "Reflect.ownKeys": [0, 233],
        "Reflect.preventExtensions": [0, 51, 234],
        "Reflect.setPrototypeOf": [0, 4, 58, 83, 118, 235],
        "String.prototype.codePointAt": [0, 26, 141, 155, 156, 236],
        "String.prototype.endsWith": [0, 26, 28, 59, 85, 103, 155, 156, 237],
        "String.fromCodePoint": [0, 238],
        "String.prototype.includes": [0, 26, 28, 85, 103, 155, 156, 239],
        "String.prototype.matchAll": [0, 3, 6, 26, 29, 31, 59, 69, 78, 85, 89, 90, 105, 106, 112, 116, 126, 127, 128, 129, 130, 131, 132, 135, 139, 141, 155, 156, 241],
        "String.raw": [0, 26, 155, 156, 242],
        "String.prototype.repeat": [0, 26, 142, 155, 156, 243],
        "String.prototype.replaceAll": [0, 26, 65, 85, 128, 129, 155, 156, 244],
        "String.prototype.startsWith": [0, 26, 28, 59, 85, 103, 155, 156, 245],
        "String.prototype.substr": [0, 26, 155, 156, 246],
        "String.prototype.trim": [0, 26, 144, 146, 155, 156, 163, 251],
        "String.prototype.trimEnd": [0, 26, 143, 144, 146, 155, 156, 163, 247, 249],
        "String.prototype.trimStart": [0, 26, 144, 145, 146, 155, 156, 163, 248, 250],
        "String.prototype.link": [0, 26, 30, 140, 155, 156, 240],
        "Promise.allSettled": [0, 24, 26, 47, 53, 59, 62, 63, 75, 87, 88, 102, 122, 123, 124, 125, 155, 223, 252],
        "focus-visible": [253]
    },
    maxSize: 155835
};
var polyfillModuleData = polyfill_module_data_default;
var graph$1 = polyfill_graph_data_default;
var CodePatternMatcher = class {
    constructor(patterns) {
        this.patterns = patterns;
    }
    match(code) {
        if (!this.re) {
            const patternsExpression = this.patterns.map((pattern) => `(${pattern.expression})`).join("|");
            this.re = new RegExp(`(^\r
|\r|
)|${patternsExpression}`, "g");
        }
        this.re.lastIndex = 0;
        const seen =  new Set();
        const matches = [];
        let result;
        let line = 0;
        let lineBeginsAtIndex = 0;
        while ((result = this.re.exec(code)) !== null) {
            const captureGroups = result.slice(1);
            const [isNewline, ...patternExpressionMatches] = captureGroups;
            if (isNewline) {
                line++;
                lineBeginsAtIndex = result.index + 1;
                continue;
            }
            const pattern = this.patterns[patternExpressionMatches.findIndex(Boolean)];
            if (seen.has(pattern)) {
                continue;
            }
            seen.add(pattern);
            matches.push({
                name: pattern.name,
                line,
                column: result.index - lineBeginsAtIndex
            });
        }
        return matches;
    }
};
function buildPolyfillExpression(object, property, coreJs3Module) {
    const qt = (token) => `['"]${token}['"]`;
    let expression = "";
    if (object) {
        expression += `${object}\\.${property}\\s?=[^=]`;
    }
    else {
        expression += `(?:window\\.|[\\s;]+)${property}\\s?=[^=]`;
    }
    if (object) {
        expression += `|${object}\\[${qt(property)}\\]\\s?=[^=]`;
    }
    expression += `|defineProperty\\(${object || "window"},\\s?${qt(property)}`;
    if (object) {
        expression += `|\\(${object},\\s*{${property}:.*},\\s*{${property}`;
    }
    if (object) {
        const objectWithoutPrototype = object.replace(".prototype", "");
        expression += `|{target:${qt(objectWithoutPrototype)}[^;]*},{${property}:`;
    }
    expression += `|${coreJs3Module.replaceAll(".", "\\.")}(?:\\.js)?"`;
    return expression;
}
function getCoreJsPolyfillData() {
    return polyfillModuleData.filter((d) => d.corejs).map((d) => {
        return {
            name: d.name,
            coreJs3Module: d.modules[0]
        };
    });
}
function getPolyfillPatterns() {
    const patterns = [];
    for (const { name, coreJs3Module } of getCoreJsPolyfillData()) {
        const parts = name.split(".");
        const object = parts.length > 1 ? parts.slice(0, parts.length - 1).join(".") : null;
        const property = parts[parts.length - 1];
        patterns.push({
            name,
            expression: buildPolyfillExpression(object, property, coreJs3Module)
        });
    }
    return patterns;
}
function getTransformPatterns() {
    const count = (content, pattern) => {
        if (typeof pattern === "string") {
            return content.split(pattern).length - 1;
        }
        return (content.match(pattern) ?? []).length;
    };
    return [
        {
            name: "@babel/plugin-transform-classes",
            expression: "Cannot call a class as a function",
            estimateBytes: (content) => {
                return 1e3 + (count(content, "_classCallCheck") - 1) * "_classCallCheck()".length;
            }
        },
        {
            name: "@babel/plugin-transform-regenerator",
            expression: "Generator is already running|regeneratorRuntime",
            estimateBytes: (content) => {
                return count(content, /regeneratorRuntime\(?\)?\.a?wrap/g) * 80;
            }
        },
        {
            name: "@babel/plugin-transform-spread",
            expression: "Invalid attempt to spread non-iterable instance",
            estimateBytes: (content) => {
                const per = "_toConsumableArray()".length;
                return 1169 + count(content, /\.apply\(void 0,\s?_toConsumableArray/g) * per;
            }
        }
    ];
}
function estimateWastedBytes(content, matches) {
    const polyfillResults = matches.filter((m) => !m.name.startsWith("@"));
    const transformResults = matches.filter((m) => m.name.startsWith("@"));
    let estimatedWastedBytesFromPolyfills = 0;
    const modulesSeen =  new Set();
    for (const result of polyfillResults) {
        const modules = graph$1.dependencies[result.name];
        if (!modules)
            continue;
        for (const module of modules) {
            modulesSeen.add(module);
        }
    }
    estimatedWastedBytesFromPolyfills += [...modulesSeen].reduce((acc, moduleIndex) => {
        return acc + graph$1.moduleSizes[moduleIndex];
    }, 0);
    estimatedWastedBytesFromPolyfills = Math.min(estimatedWastedBytesFromPolyfills, graph$1.maxSize);
    let estimatedWastedBytesFromTransforms = 0;
    for (const result of transformResults) {
        const pattern = getTransformPatterns().find((p) => p.name === result.name);
        if (!pattern || !pattern.estimateBytes || !content)
            continue;
        estimatedWastedBytesFromTransforms += pattern.estimateBytes(content);
    }
    const estimatedWastedBytes = estimatedWastedBytesFromPolyfills + estimatedWastedBytesFromTransforms;
    return estimatedWastedBytes;
}
var matcher = new CodePatternMatcher([
    ...getPolyfillPatterns(),
    ...getTransformPatterns()
]);
function detectLegacyJavaScript$1(content, map) {
    if (!content)
        return { matches: [], estimatedByteSavings: 0 };
    let matches = matcher.match(content);
    if (map) {
        for (const { name, modules } of polyfillModuleData) {
            if (matches.some((m) => m.name === name))
                continue;
            const source = map.sourceURLs().find((source2) => modules.some((module) => {
                return source2.endsWith(`/${module}.js`) || source2.includes(`node_modules/${module}/`);
            }));
            if (!source)
                continue;
            const mapping = map.mappings().find((m) => m.sourceURL === source);
            if (mapping) {
                matches.push({ name, line: mapping.lineNumber, column: mapping.columnNumber });
            }
            else {
                matches.push({ name, line: 0, column: 0 });
            }
        }
    }
    matches = matches.sort((a, b) => a.name > b.name ? 1 : a.name === b.name ? 0 : -1);
    return {
        matches,
        estimatedByteSavings: estimateWastedBytes(content, matches)
    };
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

var legacyJavascript = /*#__PURE__*/Object.freeze({
	__proto__: null,
	detectLegacyJavaScript: detectLegacyJavaScript$1,
	getCoreJsPolyfillData: getCoreJsPolyfillData,
	getTransformPatterns: getTransformPatterns
});

// Copyright 2025 The Chromium Authors
const { detectLegacyJavaScript } = legacyJavascript;
const UIStrings$z = {
    title: 'Legacy JavaScript',
    description: 'Polyfills and transforms enable older browsers to use new JavaScript features. However, many aren\'t necessary for modern browsers. Consider modifying your JavaScript build process to not transpile [Baseline](https://web.dev/articles/baseline-and-polyfills) features, unless you know you must support older browsers. [Learn why most sites can deploy ES6+ code without transpiling](https://developer.chrome.com/docs/performance/insights/legacy-javascript)',
    columnScript: 'Script',
    columnWastedBytes: 'Wasted bytes',
};
const str_$y = registerUIStrings('models/trace/insights/LegacyJavaScript.ts', UIStrings$z);
const i18nString$k = getLocalizedString.bind(undefined, str_$y);
const BYTE_THRESHOLD = 5000;
function finalize$6(partialModel) {
    const requests = [...partialModel.legacyJavaScriptResults.keys()].map(script => script.request).filter(e => !!e);
    return {
        insightKey: "LegacyJavaScript" ,
        strings: UIStrings$z,
        title: i18nString$k(UIStrings$z.title),
        description: i18nString$k(UIStrings$z.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/legacy-javascript',
        category: InsightCategory.ALL,
        state: requests.length ? 'fail' : 'pass',
        relatedEvents: [...new Set(requests)],
        ...partialModel,
    };
}
function isLegacyJavaScript(model) {
    return model.insightKey === "LegacyJavaScript" ;
}
function generateInsight$6(data, context) {
    const scripts = data.Scripts.scripts.filter(script => {
        if (script.frame !== context.frameId) {
            return false;
        }
        if (script.url?.startsWith('chrome-extension://')) {
            return false;
        }
        return timestampIsInBounds(context.bounds, script.ts) ||
            (script.request && eventIsInBounds(script.request, context.bounds));
    });
    const legacyJavaScriptResults = new Map();
    const wastedBytesByRequestId = new Map();
    for (const script of scripts) {
        if (!script.content || script.content.length < BYTE_THRESHOLD) {
            continue;
        }
        const result = detectLegacyJavaScript(script.content, script.sourceMap);
        if (result.estimatedByteSavings < BYTE_THRESHOLD) {
            continue;
        }
        const compressionRatio = estimateCompressionRatioForScript(script);
        const transferSize = Math.round(result.estimatedByteSavings * compressionRatio);
        result.estimatedByteSavings = transferSize;
        legacyJavaScriptResults.set(script, result);
        if (script.request) {
            const requestId = script.request.args.data.requestId;
            wastedBytesByRequestId.set(requestId, transferSize);
        }
    }
    const sorted = new Map([...legacyJavaScriptResults].sort((a, b) => b[1].estimatedByteSavings - a[1].estimatedByteSavings));
    return finalize$6({
        legacyJavaScriptResults: sorted,
        metricSavings: metricSavingsForWastedBytes(wastedBytesByRequestId, context),
        wastedBytes: wastedBytesByRequestId.values().reduce((acc, cur) => acc + cur, 0),
    });
}
function createOverlays$6(model) {
    return [...model.legacyJavaScriptResults.keys()].map(script => script.request).filter(e => !!e).map(request => {
        return {
            type: 'ENTRY_OUTLINE',
            entry: request,
            outlineReason: 'ERROR',
        };
    });
}

var LegacyJavaScript = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$z,
	createOverlays: createOverlays$6,
	generateInsight: generateInsight$6,
	i18nString: i18nString$k,
	isLegacyJavaScript: isLegacyJavaScript
});

// Copyright 2025 The Chromium Authors
const UIStrings$y = {
    title: 'Modern HTTP',
    description: 'HTTP/2 and HTTP/3 offer many benefits over HTTP/1.1, such as multiplexing. [Learn more about using modern HTTP](https://developer.chrome.com/docs/performance/insights/modern-http).',
    request: 'Request',
    protocol: 'Protocol',
    noOldProtocolRequests: 'No requests used HTTP/1.1, or its current use of HTTP/1.1 does not present a significant optimization opportunity. HTTP/1.1 requests are only flagged if six or more static assets originate from the same origin, and they are not served from a local development environment or a third-party source.'
};
const str_$x = registerUIStrings('models/trace/insights/ModernHTTP.ts', UIStrings$y);
const i18nString$j = getLocalizedString.bind(undefined, str_$x);
function isModernHTTPInsight(model) {
    return model.insightKey === "ModernHTTP" ;
}
function isMultiplexableStaticAsset(request, entityMappings, firstPartyEntity) {
    if (!STATIC_RESOURCE_TYPES.has(request.args.data.resourceType)) {
        return false;
    }
    if (request.args.data.decodedBodyLength < 100) {
        const entity = entityMappings.entityByEvent.get(request);
        if (entity) {
            if (firstPartyEntity?.name === entity.name) {
                return true;
            }
            if (!entity.isUnrecognized) {
                return false;
            }
        }
    }
    return true;
}
function determineHttp1Requests(requests, entityMappings, firstPartyEntity) {
    const http1Requests = [];
    const groupedByOrigin = new Map();
    for (const record of requests) {
        const url = new URL(record.args.data.url);
        if (!isMultiplexableStaticAsset(record, entityMappings, firstPartyEntity)) {
            continue;
        }
        if (isSyntheticNetworkRequestLocalhost(record)) {
            continue;
        }
        const originRequests = getWithDefault(groupedByOrigin, url.origin, () => []);
        originRequests.push(record);
    }
    const seenURLs = new Set();
    for (const request of requests) {
        if (seenURLs.has(request.args.data.url)) {
            continue;
        }
        if (request.args.data.fromServiceWorker) {
            continue;
        }
        const isOldHttp = /HTTP\/[01][.\d]?/i.test(request.args.data.protocol);
        if (!isOldHttp) {
            continue;
        }
        const url = new URL(request.args.data.url);
        const group = groupedByOrigin.get(url.origin) || [];
        if (group.length < 6) {
            continue;
        }
        seenURLs.add(request.args.data.url);
        http1Requests.push(request);
    }
    return http1Requests;
}
function computeWasteWithGraph(urlsToChange, graph, simulator) {
    const simulationBefore = simulator.simulate(graph);
    const originalProtocols = new Map();
    graph.traverse(node => {
        if (node.type !== 'network') {
            return;
        }
        if (!urlsToChange.has(node.request.url)) {
            return;
        }
        originalProtocols.set(node.request.requestId, node.request.protocol);
        node.request.protocol = 'h2';
    });
    const simulationAfter = simulator.simulate(graph);
    graph.traverse(node => {
        if (node.type !== 'network') {
            return;
        }
        const originalProtocol = originalProtocols.get(node.request.requestId);
        if (originalProtocol === undefined) {
            return;
        }
        node.request.protocol = originalProtocol;
    });
    const savings = simulationBefore.timeInMs - simulationAfter.timeInMs;
    return floor(savings, 1 / 10);
}
function computeMetricSavings(http1Requests, context) {
    if (!context.navigation || !context.lantern) {
        return;
    }
    const urlsToChange = new Set(http1Requests.map(r => r.args.data.url));
    const fcpGraph = context.lantern.metrics.firstContentfulPaint.optimisticGraph;
    const lcpGraph = context.lantern.metrics.largestContentfulPaint.optimisticGraph;
    return {
        FCP: computeWasteWithGraph(urlsToChange, fcpGraph, context.lantern.simulator),
        LCP: computeWasteWithGraph(urlsToChange, lcpGraph, context.lantern.simulator),
    };
}
function finalize$5(partialModel) {
    return {
        insightKey: "ModernHTTP" ,
        strings: UIStrings$y,
        title: i18nString$j(UIStrings$y.title),
        description: i18nString$j(UIStrings$y.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/modern-http',
        category: InsightCategory.LCP,
        state: partialModel.http1Requests.length > 0 ? 'fail' : 'pass',
        ...partialModel,
        relatedEvents: partialModel.http1Requests,
    };
}
function generateInsight$5(data, context) {
    const isWithinContext = (event) => eventIsInBounds(event, context.bounds);
    const contextRequests = data.NetworkRequests.byTime.filter(isWithinContext);
    const entityMappings = data.NetworkRequests.entityMappings;
    const firstPartyUrl = context.navigation?.args.data?.documentLoaderURL ?? data.Meta.mainFrameURL;
    const firstPartyEntity = getEntityForUrl(firstPartyUrl, entityMappings);
    const http1Requests = determineHttp1Requests(contextRequests, entityMappings, firstPartyEntity ?? null);
    return finalize$5({
        http1Requests,
        metricSavings: computeMetricSavings(http1Requests, context),
    });
}
function createOverlayForRequest$1(request) {
    return {
        type: 'ENTRY_OUTLINE',
        entry: request,
        outlineReason: 'ERROR',
    };
}
function createOverlays$5(model) {
    return model.http1Requests.map(req => createOverlayForRequest$1(req)) ?? [];
}

var ModernHTTP = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$y,
	createOverlayForRequest: createOverlayForRequest$1,
	createOverlays: createOverlays$5,
	determineHttp1Requests: determineHttp1Requests,
	generateInsight: generateInsight$5,
	i18nString: i18nString$j,
	isModernHTTPInsight: isModernHTTPInsight
});

// Copyright 2025 The Chromium Authors
const UIStrings$x = {
    title: 'Network dependency tree',
    description: '[Avoid chaining critical requests](https://developer.chrome.com/docs/performance/insights/network-dependency-tree) by reducing the length of chains, reducing the download size of resources, or deferring the download of unnecessary resources to improve page load.',
    warningDescription: 'Avoid chaining critical requests by reducing the length of chains, reducing the download size of resources, or deferring the download of unnecessary resources to improve page load.',
    noNetworkDependencyTree: 'No rendering tasks impacted by network dependencies',
    maxCriticalPathLatency: 'Max critical path latency:',
    columnRequest: 'Request',
    columnTime: 'Time',
    preconnectOriginsTableTitle: 'Preconnected origins',
    preconnectOriginsTableDescription: '[preconnect](https://developer.chrome.com/docs/lighthouse/performance/uses-rel-preconnect/) hints help the browser establish a connection earlier in the page load, saving time when the first request for that origin is made. The following are the origins that the page preconnected to.',
    noPreconnectOrigins: 'no origins were preconnected',
    tooManyPreconnectLinksWarning: 'More than 4 `preconnect` connections were found. These should be used sparingly and only to the most important origins.',
    unusedWarning: 'Unused preconnect. Only use `preconnect` for origins that the page is likely to request.',
    crossoriginWarning: 'Unused preconnect. Check that the `crossorigin` attribute is used properly.',
    columnSource: 'Source',
    noPreconnectCandidates: 'No additional origins are good candidates for preconnecting',
    estSavingTableTitle: 'Preconnect candidates',
    estSavingTableDescription: 'Add [preconnect](https://developer.chrome.com/docs/lighthouse/performance/uses-rel-preconnect/) hints to your most important origins, but try to use no more than 4.',
    columnOrigin: 'Origin',
    columnWastedMs: 'Est LCP savings',
};
const str_$w = registerUIStrings('models/trace/insights/NetworkDependencyTree.ts', UIStrings$x);
const i18nString$i = getLocalizedString.bind(undefined, str_$w);
const nonCriticalResourceTypes = new Set([
    "Image" ,
    "XHR" ,
    "Fetch" ,
    "EventSource" ,
]);
const PRECONNECT_SOCKET_MAX_IDLE_IN_MS = Milli(15_000);
const IGNORE_THRESHOLD_IN_MILLISECONDS = Milli(50);
const TOO_MANY_PRECONNECTS_THRESHOLD = 4;
function finalize$4(partialModel) {
    return {
        insightKey: "NetworkDependencyTree" ,
        strings: UIStrings$x,
        title: i18nString$i(UIStrings$x.title),
        description: i18nString$i(UIStrings$x.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/network-dependency-tree',
        category: InsightCategory.LCP,
        state: partialModel.fail ? 'fail' : 'pass',
        ...partialModel,
    };
}
function isCritical(request, context) {
    if (request.args.data.requestId === context.navigationId) {
        return true;
    }
    if (request.args.data.isLinkPreload) {
        return false;
    }
    const isIframe = request.args.data.resourceType === "Document"  &&
        request.args.data.frame !== context.frameId;
    if (nonCriticalResourceTypes.has(request.args.data.resourceType) || isIframe ||
        request.args.data.mimeType.startsWith('image/')) {
        return false;
    }
    const initiatorUrl = request.args.data.initiator?.url || getStackTraceTopCallFrameInEventPayload(request)?.url;
    if (!initiatorUrl) {
        return false;
    }
    const isBlocking = isSyntheticNetworkRequestEventRenderBlocking(request);
    const isHighPriority = isSyntheticNetworkRequestHighPriority(request);
    return isHighPriority || isBlocking;
}
function findMaxLeafNode(node) {
    if (node.children.length === 0) {
        return node;
    }
    let maxLeaf = node.children[0];
    for (const child of node.children) {
        const leaf = findMaxLeafNode(child);
        if (leaf.timeFromInitialRequest > maxLeaf.timeFromInitialRequest) {
            maxLeaf = leaf;
        }
    }
    return maxLeaf;
}
function sortRecursively(nodes) {
    for (const node of nodes) {
        if (node.children.length > 0) {
            node.children.sort((nodeA, nodeB) => {
                const leafA = findMaxLeafNode(nodeA);
                const leafB = findMaxLeafNode(nodeB);
                return leafB.timeFromInitialRequest - leafA.timeFromInitialRequest;
            });
            sortRecursively(node.children);
        }
    }
}
function generateNetworkDependencyTree(context) {
    const rootNodes = [];
    const relatedEvents = new Map();
    let maxTime = Micro(0);
    let fail = false;
    let longestChain = [];
    function addChain(path) {
        if (path.length === 0) {
            return;
        }
        if (path.length >= 2) {
            fail = true;
        }
        const initialRequest = path[0];
        const lastRequest = path[path.length - 1];
        const totalChainTime = Micro(lastRequest.ts + lastRequest.dur - initialRequest.ts);
        if (totalChainTime > maxTime) {
            maxTime = totalChainTime;
            longestChain = path;
        }
        let currentNodes = rootNodes;
        for (let depth = 0; depth < path.length; ++depth) {
            const request = path[depth];
            let found = currentNodes.find(node => node.request === request);
            if (!found) {
                const timeFromInitialRequest = Micro(request.ts + request.dur - initialRequest.ts);
                found = {
                    request,
                    timeFromInitialRequest,
                    children: [],
                    relatedRequests: new Set(),
                };
                currentNodes.push(found);
            }
            path.forEach(request => found?.relatedRequests.add(request));
            relatedEvents.set(request, depth < 2 ? [] : [i18nString$i(UIStrings$x.warningDescription)]);
            currentNodes = found.children;
        }
    }
    const seenNodes = new Set();
    function getNextNodes(node) {
        return node.getDependents().filter(n => n.getDependencies().every(d => seenNodes.has(d)));
    }
    context.lantern?.graph.traverse((node, traversalPath) => {
        seenNodes.add(node);
        if (node.type !== 'network') {
            return;
        }
        const networkNode = node;
        if (!isCritical(networkNode.rawRequest, context)) {
            return;
        }
        const networkPath = traversalPath.filter(node => node.type === 'network').reverse().map(node => node.rawRequest);
        if (networkPath.some(request => (!isCritical(request, context)))) {
            return;
        }
        if (node.isNonNetworkProtocol) {
            return;
        }
        addChain(networkPath);
    }, getNextNodes);
    if (longestChain.length > 0) {
        let currentNodes = rootNodes;
        for (const request of longestChain) {
            const found = currentNodes.find(node => node.request === request);
            if (found) {
                found.isLongest = true;
                currentNodes = found.children;
            }
            else {
                console.error('Some request in the longest chain is not found');
            }
        }
    }
    sortRecursively(rootNodes);
    return {
        rootNodes,
        maxTime,
        fail,
        relatedEvents,
    };
}
function getSecurityOrigin(url) {
    const parsedURL = new ParsedURL(url);
    return parsedURL.securityOrigin();
}
function handleLinkResponseHeaderPart(trimmedPart) {
    if (!trimmedPart) {
        return null;
    }
    const urlStart = trimmedPart.indexOf('<');
    const urlEnd = trimmedPart.indexOf('>');
    if (urlStart !== 0 || urlEnd === -1 || urlEnd <= urlStart) {
        return null;
    }
    const url = trimmedPart.substring(urlStart + 1, urlEnd).trim();
    if (!url) {
        return null;
    }
    const paramsString = trimmedPart.substring(urlEnd + 1).trim();
    if (paramsString) {
        const params = paramsString.split(';');
        for (const param of params) {
            const trimmedParam = param.trim();
            if (!trimmedParam) {
                continue;
            }
            const eqIndex = trimmedParam.indexOf('=');
            if (eqIndex === -1) {
                continue;
            }
            const paramName = trimmedParam.substring(0, eqIndex).trim().toLowerCase();
            let paramValue = trimmedParam.substring(eqIndex + 1).trim();
            if (paramValue.startsWith('"') && paramValue.endsWith('"')) {
                paramValue = paramValue.substring(1, paramValue.length - 1);
            }
            if (paramName === 'rel' && paramValue === 'preconnect') {
                return { url, headerText: trimmedPart };
            }
        }
    }
    return null;
}
function handleLinkResponseHeader(linkHeaderValue) {
    if (!linkHeaderValue) {
        return [];
    }
    const preconnectedOrigins = [];
    for (let i = 0; i < linkHeaderValue.length;) {
        const firstUrlEnd = linkHeaderValue.indexOf('>', i);
        if (firstUrlEnd === -1) {
            break;
        }
        const commaIndex = linkHeaderValue.indexOf(',', firstUrlEnd);
        const partEnd = commaIndex !== -1 ? commaIndex : linkHeaderValue.length;
        const part = linkHeaderValue.substring(i, partEnd);
        if (partEnd + 1 <= i) {
            console.warn('unexpected infinite loop, bailing');
            break;
        }
        i = partEnd + 1;
        const preconnectedOrigin = handleLinkResponseHeaderPart(part.trim());
        if (preconnectedOrigin) {
            preconnectedOrigins.push(preconnectedOrigin);
        }
    }
    return preconnectedOrigins;
}
function generatePreconnectedOrigins(data, context, contextRequests, preconnectCandidates) {
    const preconnectedOrigins = [];
    for (const event of data.NetworkRequests.linkPreconnectEvents) {
        preconnectedOrigins.push({
            node_id: event.args.data.node_id,
            frame: event.args.data.frame,
            url: event.args.data.url,
            unused: !contextRequests.some(request => getSecurityOrigin(event.args.data.url) === getSecurityOrigin(request.args.data.url)),
            crossorigin: preconnectCandidates.some(candidate => candidate.origin === getSecurityOrigin(event.args.data.url)),
            source: 'DOM',
        });
    }
    const documentRequest = data.NetworkRequests.byId.get(context.navigationId);
    documentRequest?.args.data.responseHeaders?.forEach(header => {
        if (header.name.toLowerCase() === 'link') {
            const preconnectedOriginsFromResponseHeader = handleLinkResponseHeader(header.value);
            preconnectedOriginsFromResponseHeader?.forEach(origin => preconnectedOrigins.push({
                url: origin.url,
                headerText: origin.headerText,
                request: documentRequest,
                unused: !contextRequests.some(request => getSecurityOrigin(origin.url) === getSecurityOrigin(request.args.data.url)),
                crossorigin: preconnectCandidates.some(candidate => candidate.origin === getSecurityOrigin(origin.url)),
                source: 'ResponseHeader',
            }));
        }
    });
    return preconnectedOrigins;
}
function hasValidTiming(request) {
    return !!request.args.data.timing && request.args.data.timing.connectEnd >= 0 &&
        request.args.data.timing.connectStart >= 0;
}
function hasAlreadyConnectedToOrigin(request) {
    const { timing } = request.args.data;
    if (!timing) {
        return false;
    }
    if (timing.dnsStart === -1 && timing.dnsEnd === -1 && timing.connectStart === -1 && timing.connectEnd === -1) {
        return true;
    }
    if (timing.dnsEnd - timing.dnsStart === 0 && timing.connectEnd - timing.connectStart === 0) {
        return true;
    }
    return false;
}
function socketStartTimeIsBelowThreshold(request, mainResource) {
    const timeSinceMainEnd = Math.max(0, request.args.data.syntheticData.sendStartTime - mainResource.args.data.syntheticData.finishTime);
    return microToMilli(timeSinceMainEnd) < PRECONNECT_SOCKET_MAX_IDLE_IN_MS;
}
function candidateRequestsByOrigin(data, mainResource, contextRequests, lcpGraphURLs) {
    const origins = new Map();
    contextRequests.forEach(request => {
        if (!hasValidTiming(request)) {
            return;
        }
        const initiator = getNetworkInitiator(data, request);
        if (initiator === mainResource) {
            return;
        }
        const url = new URL(request.args.data.url);
        if (url.origin === 'null') {
            return;
        }
        const mainOrigin = new URL(mainResource.args.data.url).origin;
        if (url.origin === mainOrigin) {
            return;
        }
        if (!lcpGraphURLs.has(request.args.data.url)) {
            return;
        }
        if (hasAlreadyConnectedToOrigin(request)) {
            return;
        }
        if (!socketStartTimeIsBelowThreshold(request, mainResource)) {
            return;
        }
        const originRequests = getWithDefault(origins, url.origin, () => []);
        originRequests.push(request);
    });
    return origins;
}
function generatePreconnectCandidates(data, context, contextRequests) {
    if (!context.lantern) {
        return [];
    }
    const documentRequest = data.NetworkRequests.byId.get(context.navigationId);
    if (!documentRequest) {
        return [];
    }
    const { rtt, additionalRttByOrigin } = context.lantern.simulator.getOptions();
    const lcpGraph = context.lantern.metrics.largestContentfulPaint.pessimisticGraph;
    const fcpGraph = context.lantern.metrics.firstContentfulPaint.pessimisticGraph;
    const lcpGraphURLs = new Set();
    lcpGraph.traverse(node => {
        if (node.type === 'network') {
            lcpGraphURLs.add(node.request.url);
        }
    });
    const fcpGraphURLs = new Set();
    fcpGraph.traverse(node => {
        if (node.type === 'network') {
            fcpGraphURLs.add(node.request.url);
        }
    });
    const groupedOrigins = candidateRequestsByOrigin(data, documentRequest, contextRequests, lcpGraphURLs);
    let preconnectCandidates = [];
    groupedOrigins.forEach(requests => {
        const firstRequestOfOrigin = requests[0];
        if (!firstRequestOfOrigin.args.data.timing) {
            return;
        }
        const firstRequestOfOriginParsedURL = new ParsedURL(firstRequestOfOrigin.args.data.url);
        const origin = firstRequestOfOriginParsedURL.securityOrigin();
        const additionalRtt = additionalRttByOrigin.get(origin) ?? 0;
        let connectionTime = Milli(rtt + additionalRtt);
        if (firstRequestOfOriginParsedURL.scheme === 'https') {
            connectionTime = Milli(connectionTime * 2);
        }
        const timeBetweenMainResourceAndDnsStart = Micro(firstRequestOfOrigin.args.data.syntheticData.sendStartTime -
            documentRequest.args.data.syntheticData.finishTime +
            milliToMicro(firstRequestOfOrigin.args.data.timing.dnsStart));
        const wastedMs = Math.min(connectionTime, microToMilli(timeBetweenMainResourceAndDnsStart));
        if (wastedMs < IGNORE_THRESHOLD_IN_MILLISECONDS) {
            return;
        }
        if (fcpGraphURLs.has(firstRequestOfOrigin.args.data.url)) ;
        preconnectCandidates.push({
            origin,
            wastedMs,
        });
    });
    preconnectCandidates = preconnectCandidates.sort((a, b) => b.wastedMs - a.wastedMs);
    return preconnectCandidates.slice(0, TOO_MANY_PRECONNECTS_THRESHOLD);
}
function isNetworkDependencyTreeInsight(model) {
    return model.insightKey === "NetworkDependencyTree" ;
}
function generateInsight$4(data, context) {
    if (!context.navigation) {
        return finalize$4({
            rootNodes: [],
            maxTime: 0,
            fail: false,
            preconnectedOrigins: [],
            preconnectCandidates: [],
        });
    }
    const { rootNodes, maxTime, fail, relatedEvents, } = generateNetworkDependencyTree(context);
    const isWithinContext = (event) => eventIsInBounds(event, context.bounds);
    const contextRequests = data.NetworkRequests.byTime.filter(isWithinContext);
    const preconnectCandidates = generatePreconnectCandidates(data, context, contextRequests);
    const preconnectedOrigins = generatePreconnectedOrigins(data, context, contextRequests, preconnectCandidates);
    return finalize$4({
        rootNodes,
        maxTime,
        fail,
        relatedEvents,
        preconnectedOrigins,
        preconnectCandidates,
    });
}
function createOverlays$4(model) {
    function walk(nodes, overlays) {
        nodes.forEach(node => {
            overlays.push({
                type: 'ENTRY_OUTLINE',
                entry: node.request,
                outlineReason: 'ERROR',
            });
            walk(node.children, overlays);
        });
    }
    const overlays = [];
    walk(model.rootNodes, overlays);
    return overlays;
}

var NetworkDependencyTree = /*#__PURE__*/Object.freeze({
	__proto__: null,
	TOO_MANY_PRECONNECTS_THRESHOLD: TOO_MANY_PRECONNECTS_THRESHOLD,
	UIStrings: UIStrings$x,
	createOverlays: createOverlays$4,
	generateInsight: generateInsight$4,
	generatePreconnectCandidates: generatePreconnectCandidates,
	generatePreconnectedOrigins: generatePreconnectedOrigins,
	handleLinkResponseHeader: handleLinkResponseHeader,
	i18nString: i18nString$i,
	isNetworkDependencyTreeInsight: isNetworkDependencyTreeInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$w = {
    title: 'Render-blocking requests',
    description: 'Requests are blocking the page\'s initial render, which may delay LCP. ' +
        '[Deferring or inlining](https://developer.chrome.com/docs/performance/insights/render-blocking) ' +
        'can move these network requests out of the critical path.',
    renderBlockingRequest: 'Request',
    duration: 'Duration',
    noRenderBlocking: 'No render-blocking requests for this navigation',
};
const str_$v = registerUIStrings('models/trace/insights/RenderBlocking.ts', UIStrings$w);
const i18nString$h = getLocalizedString.bind(undefined, str_$v);
function isRenderBlockingInsight(insight) {
    return insight.insightKey === 'RenderBlocking';
}
const MINIMUM_WASTED_MS = 50;
function getNodesAndTimingByRequestId(nodeTimings) {
    const requestIdToNode = new Map();
    for (const [node, nodeTiming] of nodeTimings) {
        if (node.type !== 'network') {
            continue;
        }
        requestIdToNode.set(node.request.requestId, { node, nodeTiming });
    }
    return requestIdToNode;
}
function estimateSavingsWithGraphs(deferredIds, lanternContext) {
    const simulator = lanternContext.simulator;
    const fcpGraph = lanternContext.metrics.firstContentfulPaint.optimisticGraph;
    const { nodeTimings } = lanternContext.simulator.simulate(fcpGraph);
    const adjustedNodeTimings = new Map(nodeTimings);
    const totalChildNetworkBytes = 0;
    const minimalFCPGraph = fcpGraph.cloneWithRelationships(node => {
        const canDeferRequest = deferredIds.has(node.id);
        return !canDeferRequest;
    });
    if (minimalFCPGraph.type !== 'network') {
        throw new Error('minimalFCPGraph not a NetworkNode');
    }
    const estimateBeforeInline = Math.max(...Array.from(Array.from(adjustedNodeTimings).map(timing => timing[1].endTime)));
    const originalTransferSize = minimalFCPGraph.request.transferSize;
    const safeTransferSize = originalTransferSize || 0;
    minimalFCPGraph.request.transferSize = safeTransferSize + totalChildNetworkBytes;
    const estimateAfterInline = simulator.simulate(minimalFCPGraph).timeInMs;
    minimalFCPGraph.request.transferSize = originalTransferSize;
    return Math.round(Math.max(estimateBeforeInline - estimateAfterInline, 0));
}
function hasImageLCP(data, context) {
    return data.LargestImagePaint.lcpRequestByNavigationId.has(context.navigationId);
}
function computeSavings(data, context, renderBlockingRequests) {
    if (!context.lantern) {
        return;
    }
    const nodesAndTimingsByRequestId = getNodesAndTimingByRequestId(context.lantern.metrics.firstContentfulPaint.optimisticEstimate.nodeTimings);
    const metricSavings = { FCP: 0, LCP: 0 };
    const requestIdToWastedMs = new Map();
    const deferredNodeIds = new Set();
    for (const request of renderBlockingRequests) {
        const nodeAndTiming = nodesAndTimingsByRequestId.get(request.args.data.requestId);
        if (!nodeAndTiming) {
            continue;
        }
        const { node, nodeTiming } = nodeAndTiming;
        node.traverse(node => deferredNodeIds.add(node.id));
        const wastedMs = Math.round(nodeTiming.duration);
        if (wastedMs < MINIMUM_WASTED_MS) {
            continue;
        }
        requestIdToWastedMs.set(node.id, wastedMs);
    }
    if (requestIdToWastedMs.size) {
        metricSavings.FCP = estimateSavingsWithGraphs(deferredNodeIds, context.lantern);
        if (!hasImageLCP(data, context)) {
            metricSavings.LCP = metricSavings.FCP;
        }
    }
    return { metricSavings, requestIdToWastedMs };
}
function finalize$3(partialModel) {
    return {
        insightKey: "RenderBlocking" ,
        strings: UIStrings$w,
        title: i18nString$h(UIStrings$w.title),
        description: i18nString$h(UIStrings$w.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/render-blocking',
        category: InsightCategory.LCP,
        state: partialModel.renderBlockingRequests.length > 0 ? 'fail' : 'pass',
        ...partialModel,
    };
}
function generateInsight$3(data, context) {
    if (!context.navigation) {
        return finalize$3({
            renderBlockingRequests: [],
        });
    }
    const firstPaintTs = data.PageLoadMetrics.metricScoresByFrameId.get(context.frameId)
        ?.get(context.navigation)
        ?.get("FP" )
        ?.event?.ts;
    if (!firstPaintTs) {
        return finalize$3({
            renderBlockingRequests: [],
            warnings: [InsightWarning.NO_FP],
        });
    }
    let renderBlockingRequests = [];
    for (const req of data.NetworkRequests.byTime) {
        if (req.args.data.frame !== context.frameId) {
            continue;
        }
        if (!isSyntheticNetworkRequestEventRenderBlocking(req)) {
            continue;
        }
        if (req.args.data.syntheticData.finishTime > firstPaintTs) {
            continue;
        }
        if (req.args.data.renderBlocking === 'in_body_parser_blocking') {
            const priority = req.args.data.priority;
            const isScript = req.args.data.resourceType === "Script" ;
            const isBlockingScript = isScript && priority === "High" ;
            if (priority !== "VeryHigh"  && !isBlockingScript) {
                continue;
            }
        }
        const navigation = getNavigationForTraceEvent(req, context.frameId, data.Meta.navigationsByFrameId);
        if (navigation === context.navigation) {
            renderBlockingRequests.push(req);
        }
    }
    const savings = computeSavings(data, context, renderBlockingRequests);
    renderBlockingRequests = renderBlockingRequests.sort((a, b) => {
        return b.dur - a.dur;
    });
    return finalize$3({
        relatedEvents: renderBlockingRequests,
        renderBlockingRequests,
        ...savings,
    });
}
function createOverlayForRequest(request) {
    return {
        type: 'ENTRY_OUTLINE',
        entry: request,
        outlineReason: 'ERROR',
    };
}
function createOverlays$3(model) {
    return model.renderBlockingRequests.map(request => createOverlayForRequest(request));
}

var RenderBlocking = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$w,
	createOverlayForRequest: createOverlayForRequest,
	createOverlays: createOverlays$3,
	generateInsight: generateInsight$3,
	i18nString: i18nString$h,
	isRenderBlockingInsight: isRenderBlockingInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$v = {
    title: 'CSS Selector costs',
    description: 'If Recalculate Style costs remain high, selector optimization can reduce them. [Optimize the selectors](https://developer.chrome.com/docs/performance/insights/slow-css-selector) with both high elapsed time and high slow-path %. Simpler selectors, fewer selectors, a smaller DOM, and a shallower DOM will all reduce matching costs.',
    matchAttempts: 'Match attempts',
    matchCount: 'Match count',
    elapsed: 'Elapsed time',
    topSelectors: 'Top selectors',
    total: 'Total',
    enableSelectorData: 'No CSS selector data was found. CSS selector stats need to be enabled in the performance panel settings.',
    topSelectorElapsedTime: 'Top selector elapsed time',
    topSelectorMatchAttempt: 'Top selector match attempt',
};
const str_$u = registerUIStrings('models/trace/insights/SlowCSSSelector.ts', UIStrings$v);
const i18nString$g = getLocalizedString.bind(undefined, str_$u);
const slowCSSSelectorThreshold = 500;
function aggregateSelectorStats(data, context) {
    const selectorMap = new Map();
    for (const [event, value] of data.dataForRecalcStyleEvent) {
        if (event.args.beginData?.frame !== context.frameId) {
            continue;
        }
        if (!eventIsInBounds(event, context.bounds)) {
            continue;
        }
        for (const timing of value.timings) {
            const key = timing[SelectorTimingsKey.Selector] + '_' + timing[SelectorTimingsKey.StyleSheetId];
            const findTiming = selectorMap.get(key);
            if (findTiming !== undefined) {
                findTiming[SelectorTimingsKey.Elapsed] += timing[SelectorTimingsKey.Elapsed];
                findTiming[SelectorTimingsKey.FastRejectCount] += timing[SelectorTimingsKey.FastRejectCount];
                findTiming[SelectorTimingsKey.MatchAttempts] += timing[SelectorTimingsKey.MatchAttempts];
                findTiming[SelectorTimingsKey.MatchCount] += timing[SelectorTimingsKey.MatchCount];
            }
            else {
                selectorMap.set(key, { ...timing });
            }
        }
    }
    return [...selectorMap.values()];
}
function finalize$2(partialModel) {
    return {
        insightKey: "SlowCSSSelector" ,
        strings: UIStrings$v,
        title: i18nString$g(UIStrings$v.title),
        description: i18nString$g(UIStrings$v.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/slow-css-selector',
        category: InsightCategory.ALL,
        state: partialModel.topSelectorElapsedMs && partialModel.topSelectorMatchAttempts ? 'informative' : 'pass',
        ...partialModel,
    };
}
function isSlowCSSSelectorInsight(model) {
    return model.insightKey === "SlowCSSSelector" ;
}
function generateInsight$2(data, context) {
    const selectorStatsData = data.SelectorStats;
    if (!selectorStatsData) {
        throw new Error('no selector stats data');
    }
    const selectorTimings = aggregateSelectorStats(selectorStatsData, context);
    let totalElapsedUs = 0;
    let totalMatchAttempts = 0;
    let totalMatchCount = 0;
    selectorTimings.map(timing => {
        totalElapsedUs += timing[SelectorTimingsKey.Elapsed];
        totalMatchAttempts += timing[SelectorTimingsKey.MatchAttempts];
        totalMatchCount += timing[SelectorTimingsKey.MatchCount];
    });
    let topSelectorElapsedMs = null;
    let topSelectorMatchAttempts = null;
    if (selectorTimings.length > 0) {
        topSelectorElapsedMs = selectorTimings.reduce((a, b) => {
            return a[SelectorTimingsKey.Elapsed] > b[SelectorTimingsKey.Elapsed] ? a : b;
        });
        if (topSelectorElapsedMs && topSelectorElapsedMs[SelectorTimingsKey.Elapsed] < slowCSSSelectorThreshold) {
            topSelectorElapsedMs = null;
        }
        topSelectorMatchAttempts = selectorTimings.reduce((a, b) => {
            return a[SelectorTimingsKey.MatchAttempts] > b[SelectorTimingsKey.MatchAttempts] ? a : b;
        });
    }
    return finalize$2({
        relatedEvents: [],
        totalElapsedMs: Milli(totalElapsedUs / 1000.0),
        totalMatchAttempts,
        totalMatchCount,
        topSelectorElapsedMs,
        topSelectorMatchAttempts,
    });
}
function createOverlays$2(_) {
    return [];
}

var SlowCSSSelector = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$v,
	createOverlays: createOverlays$2,
	generateInsight: generateInsight$2,
	i18nString: i18nString$g,
	isSlowCSSSelectorInsight: isSlowCSSSelectorInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$u = {
    title: '3rd parties',
    description: '3rd party code can significantly impact load performance. ' +
        '[Reduce and defer loading of 3rd party code](https://developer.chrome.com/docs/performance/insights/third-parties) to prioritize your page\'s content.',
    columnThirdParty: '3rd party',
    columnTransferSize: 'Transfer size',
    columnMainThreadTime: 'Main thread time',
    noThirdParties: 'No third parties found',
};
const str_$t = registerUIStrings('models/trace/insights/ThirdParties.ts', UIStrings$u);
const i18nString$f = getLocalizedString.bind(undefined, str_$t);
function getRelatedEvents(summaries, firstPartyEntity) {
    const relatedEvents = [];
    for (const summary of summaries) {
        if (summary.entity !== firstPartyEntity) {
            relatedEvents.push(...summary.relatedEvents);
        }
    }
    return relatedEvents;
}
function finalize$1(partialModel) {
    return {
        insightKey: "ThirdParties" ,
        strings: UIStrings$u,
        title: i18nString$f(UIStrings$u.title),
        description: i18nString$f(UIStrings$u.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/third-parties',
        category: InsightCategory.ALL,
        state: partialModel.entitySummaries.find(summary => summary.entity !== partialModel.firstPartyEntity) ?
            'informative' :
            'pass',
        ...partialModel,
    };
}
function isThirdPartyInsight(model) {
    return model.insightKey === "ThirdParties" ;
}
function generateInsight$1(data, context) {
    const entitySummaries = summarizeByThirdParty(data, context.bounds);
    const firstPartyUrl = context.navigation?.args.data?.documentLoaderURL ?? data.Meta.mainFrameURL;
    const firstPartyEntity = nostatsSubset.getEntity(firstPartyUrl) ||
        makeUpEntity(data.Renderer.entityMappings.createdEntityCache, firstPartyUrl);
    return finalize$1({
        relatedEvents: getRelatedEvents(entitySummaries, firstPartyEntity),
        firstPartyEntity,
        entitySummaries,
    });
}
function createOverlaysForSummary(summary) {
    const overlays = [];
    for (const event of summary.relatedEvents) {
        if (event.dur === undefined || event.dur < 1_000) {
            continue;
        }
        const overlay = {
            type: 'ENTRY_OUTLINE',
            entry: event,
            outlineReason: 'INFO',
        };
        overlays.push(overlay);
    }
    return overlays;
}
function createOverlays$1(model) {
    const overlays = [];
    const summaries = model.entitySummaries ?? [];
    for (const summary of summaries) {
        if (summary.entity === model.firstPartyEntity) {
            continue;
        }
        const summaryOverlays = createOverlaysForSummary(summary);
        overlays.push(...summaryOverlays);
    }
    return overlays;
}

var ThirdParties = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$u,
	createOverlays: createOverlays$1,
	createOverlaysForSummary: createOverlaysForSummary,
	generateInsight: generateInsight$1,
	i18nString: i18nString$f,
	isThirdPartyInsight: isThirdPartyInsight
});

// Copyright 2024 The Chromium Authors
const UIStrings$t = {
    title: 'Optimize viewport for mobile',
    description: 'Tap interactions may be [delayed by up to 300\xA0ms](https://developer.chrome.com/docs/performance/insights/viewport) if the viewport is not optimized for mobile.',
    mobileTapDelayLabel: 'Mobile tap delay',
};
const str_$s = registerUIStrings('models/trace/insights/Viewport.ts', UIStrings$t);
const i18nString$e = getLocalizedString.bind(undefined, str_$s);
function finalize(partialModel) {
    return {
        insightKey: "Viewport" ,
        strings: UIStrings$t,
        title: i18nString$e(UIStrings$t.title),
        description: i18nString$e(UIStrings$t.description),
        docs: 'https://developer.chrome.com/docs/performance/insights/viewport',
        category: InsightCategory.INP,
        state: partialModel.mobileOptimized === false ? 'fail' : 'pass',
        ...partialModel,
    };
}
function isViewportInsight(model) {
    return model.insightKey === "Viewport" ;
}
function generateInsight(data, context) {
    const viewportEvent = data.UserInteractions.parseMetaViewportEvents.find(event => {
        if (event.args.data.frame !== context.frameId) {
            return false;
        }
        return eventIsInBounds(event, context.bounds);
    });
    const compositorEvents = data.UserInteractions.beginCommitCompositorFrameEvents.filter(event => {
        if (event.args.frame !== context.frameId) {
            return false;
        }
        if (viewportEvent && event.ts < viewportEvent.ts) {
            return false;
        }
        return eventIsInBounds(event, context.bounds);
    });
    if (!compositorEvents.length) {
        return finalize({
            mobileOptimized: null,
            warnings: [InsightWarning.NO_LAYOUT],
        });
    }
    for (const event of compositorEvents) {
        if (!event.args.is_mobile_optimized) {
            const longPointerInteractions = [...data.UserInteractions.interactionsOverThreshold.values()].filter(interaction => categoryOfInteraction(interaction) === 'POINTER' &&
                interaction.inputDelay >= 50_000);
            const inputDelay = Math.max(0, ...longPointerInteractions.map(interaction => interaction.inputDelay)) / 1000;
            const inpMetricSavings = clamp$1(inputDelay, 0, 300);
            return finalize({
                mobileOptimized: false,
                viewportEvent,
                longPointerInteractions,
                metricSavings: { INP: inpMetricSavings },
            });
        }
    }
    return finalize({
        mobileOptimized: true,
        viewportEvent,
    });
}
function createOverlays(model) {
    if (!model.longPointerInteractions) {
        return [];
    }
    return model.longPointerInteractions.map(interaction => {
        const delay = Math.min(interaction.inputDelay, 300 * 1000);
        const bounds = traceWindowFromMicroSeconds(Micro(interaction.ts), Micro(interaction.ts + delay));
        return {
            type: 'TIMESPAN_BREAKDOWN',
            entry: interaction,
            sections: [{ bounds, label: i18nString$e(UIStrings$t.mobileTapDelayLabel), showDuration: true }],
            renderLocation: 'ABOVE_EVENT',
        };
    });
}

var Viewport = /*#__PURE__*/Object.freeze({
	__proto__: null,
	UIStrings: UIStrings$t,
	createOverlays: createOverlays,
	generateInsight: generateInsight,
	i18nString: i18nString$e,
	isViewportInsight: isViewportInsight
});

// Copyright 2024 The Chromium Authors

var Models = /*#__PURE__*/Object.freeze({
	__proto__: null,
	CLSCulprits: CLSCulprits,
	Cache: Cache,
	DOMSize: DOMSize,
	DocumentLatency: DocumentLatency,
	DuplicatedJavaScript: DuplicatedJavaScript,
	FontDisplay: FontDisplay,
	ForcedReflow: ForcedReflow,
	INPBreakdown: INPBreakdown,
	ImageDelivery: ImageDelivery,
	LCPBreakdown: LCPBreakdown,
	LCPDiscovery: LCPDiscovery,
	LegacyJavaScript: LegacyJavaScript,
	ModernHTTP: ModernHTTP,
	NetworkDependencyTree: NetworkDependencyTree,
	RenderBlocking: RenderBlocking,
	SlowCSSSelector: SlowCSSSelector,
	ThirdParties: ThirdParties,
	Viewport: Viewport
});

// Copyright 2024 The Chromium Authors

var insights = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Cache: Cache,
	Common: Common,
	Models: Models,
	ModernHTTP: ModernHTTP,
	Statistics: Statistics,
	Types: types$1
});

// Copyright 2024 The Chromium Authors
class LanternError extends Error {
}

// Copyright 2024 The Chromium Authors
class UrlUtils {
    static rewriteChromeInternalUrl(url) {
        if (!url?.startsWith('chrome://')) {
            return url;
        }
        if (url.endsWith('/')) {
            url = url.replace(/\/$/, '');
        }
        return url.replace(/^chrome:\/\/chrome\//, 'chrome://');
    }
    static equalWithExcludedFragments(url1, url2) {
        [url1, url2] = [url1, url2].map(this.rewriteChromeInternalUrl);
        try {
            const urla = new URL(url1);
            urla.hash = '';
            const urlb = new URL(url2);
            urlb.hash = '';
            return urla.href === urlb.href;
        }
        catch {
            return false;
        }
    }
}
const INITIAL_CWD = 14 * 1024;
const DEFAULT_SERVER_RESPONSE_PERCENTAGE = 0.4;
const SERVER_RESPONSE_PERCENTAGE_OF_TTFB = {
    Document: 0.9,
    XHR: 0.9,
    Fetch: 0.9,
};
class NetworkAnalyzer {
    static get summary() {
        return '__SUMMARY__';
    }
    static groupByOrigin(records) {
        const grouped = new Map();
        records.forEach(item => {
            const key = item.parsedURL.securityOrigin;
            const group = grouped.get(key) || [];
            group.push(item);
            grouped.set(key, group);
        });
        return grouped;
    }
    static getSummary(values) {
        values.sort((a, b) => a - b);
        let median;
        if (values.length === 0) {
            median = values[0];
        }
        else if (values.length % 2 === 0) {
            const a = values[Math.floor((values.length - 1) / 2)];
            const b = values[Math.floor((values.length - 1) / 2) + 1];
            median = (a + b) / 2;
        }
        else {
            median = values[Math.floor((values.length - 1) / 2)];
        }
        return {
            min: values[0],
            max: values[values.length - 1],
            avg: values.reduce((a, b) => a + b, 0) / values.length,
            median,
        };
    }
    static summarize(values) {
        const summaryByKey = new Map();
        const allEstimates = [];
        for (const [key, estimates] of values) {
            summaryByKey.set(key, NetworkAnalyzer.getSummary(estimates));
            allEstimates.push(...estimates);
        }
        summaryByKey.set(NetworkAnalyzer.summary, NetworkAnalyzer.getSummary(allEstimates));
        return summaryByKey;
    }
    static estimateValueByOrigin(requests, iteratee) {
        const connectionWasReused = NetworkAnalyzer.estimateIfConnectionWasReused(requests);
        const groupedByOrigin = NetworkAnalyzer.groupByOrigin(requests);
        const estimates = new Map();
        for (const [origin, originRequests] of groupedByOrigin.entries()) {
            let originEstimates = [];
            for (const request of originRequests) {
                const timing = request.timing;
                if (!timing) {
                    continue;
                }
                const value = iteratee({
                    request,
                    timing,
                    connectionReused: connectionWasReused.get(request.requestId),
                });
                if (typeof value !== 'undefined') {
                    originEstimates = originEstimates.concat(value);
                }
            }
            if (!originEstimates.length) {
                continue;
            }
            estimates.set(origin, originEstimates);
        }
        return estimates;
    }
    static estimateRTTViaConnectionTiming(info) {
        const { timing, connectionReused, request } = info;
        if (connectionReused) {
            return;
        }
        const { connectStart, sslStart, sslEnd, connectEnd } = timing;
        if (connectEnd >= 0 && connectStart >= 0 && request.protocol.startsWith('h3')) {
            return connectEnd - connectStart;
        }
        if (sslStart >= 0 && sslEnd >= 0 && sslStart !== connectStart) {
            return [connectEnd - sslStart, sslStart - connectStart];
        }
        if (connectStart >= 0 && connectEnd >= 0) {
            return connectEnd - connectStart;
        }
        return;
    }
    static estimateRTTViaDownloadTiming(info) {
        const { timing, connectionReused, request } = info;
        if (connectionReused) {
            return;
        }
        if (request.transferSize <= INITIAL_CWD) {
            return;
        }
        if (!Number.isFinite(timing.receiveHeadersEnd) || timing.receiveHeadersEnd < 0) {
            return;
        }
        const totalTime = request.networkEndTime - request.networkRequestTime;
        const downloadTimeAfterFirstByte = totalTime - timing.receiveHeadersEnd;
        const numberOfRoundTrips = Math.log2(request.transferSize / INITIAL_CWD);
        if (numberOfRoundTrips > 5) {
            return;
        }
        return downloadTimeAfterFirstByte / numberOfRoundTrips;
    }
    static estimateRTTViaSendStartTiming(info) {
        const { timing, connectionReused, request } = info;
        if (connectionReused) {
            return;
        }
        if (!Number.isFinite(timing.sendStart) || timing.sendStart < 0) {
            return;
        }
        let roundTrips = 1;
        if (!request.protocol.startsWith('h3')) {
            roundTrips += 1;
        }
        if (request.parsedURL.scheme === 'https') {
            roundTrips += 1;
        }
        return timing.sendStart / roundTrips;
    }
    static estimateRTTViaHeadersEndTiming(info) {
        const { timing, connectionReused, request } = info;
        if (!Number.isFinite(timing.receiveHeadersEnd) || timing.receiveHeadersEnd < 0) {
            return;
        }
        if (!request.resourceType) {
            return;
        }
        const serverResponseTimePercentage = SERVER_RESPONSE_PERCENTAGE_OF_TTFB[request.resourceType] || DEFAULT_SERVER_RESPONSE_PERCENTAGE;
        const estimatedServerResponseTime = timing.receiveHeadersEnd * serverResponseTimePercentage;
        let roundTrips = 1;
        if (!connectionReused) {
            roundTrips += 1;
            if (!request.protocol.startsWith('h3')) {
                roundTrips += 1;
            }
            if (request.parsedURL.scheme === 'https') {
                roundTrips += 1;
            }
        }
        return Math.max((timing.receiveHeadersEnd - estimatedServerResponseTime) / roundTrips, 3);
    }
    static estimateResponseTimeByOrigin(records, rttByOrigin) {
        return NetworkAnalyzer.estimateValueByOrigin(records, ({ request, timing }) => {
            if (request.serverResponseTime !== undefined) {
                return request.serverResponseTime;
            }
            if (!Number.isFinite(timing.receiveHeadersEnd) || timing.receiveHeadersEnd < 0) {
                return;
            }
            if (!Number.isFinite(timing.sendEnd) || timing.sendEnd < 0) {
                return;
            }
            const ttfb = timing.receiveHeadersEnd - timing.sendEnd;
            const origin = request.parsedURL.securityOrigin;
            const rtt = rttByOrigin.get(origin) || rttByOrigin.get(NetworkAnalyzer.summary) || 0;
            return Math.max(ttfb - rtt, 0);
        });
    }
    static canTrustConnectionInformation(requests) {
        const connectionIdWasStarted = new Map();
        for (const request of requests) {
            const started = connectionIdWasStarted.get(request.connectionId) || !request.connectionReused;
            connectionIdWasStarted.set(request.connectionId, started);
        }
        if (connectionIdWasStarted.size <= 1) {
            return false;
        }
        return Array.from(connectionIdWasStarted.values()).every(started => started);
    }
    static estimateIfConnectionWasReused(records, options) {
        const { forceCoarseEstimates = false } = options || {};
        if (!forceCoarseEstimates && NetworkAnalyzer.canTrustConnectionInformation(records)) {
            return new Map(records.map(request => [request.requestId, Boolean(request.connectionReused)]));
        }
        const connectionWasReused = new Map();
        const groupedByOrigin = NetworkAnalyzer.groupByOrigin(records);
        for (const originRecords of groupedByOrigin.values()) {
            const earliestReusePossible = originRecords.map(request => request.networkEndTime).reduce((a, b) => Math.min(a, b), Infinity);
            for (const request of originRecords) {
                connectionWasReused.set(request.requestId, request.networkRequestTime >= earliestReusePossible || request.protocol === 'h2');
            }
            const firstRecord = originRecords.reduce((a, b) => {
                return a.networkRequestTime > b.networkRequestTime ? b : a;
            });
            connectionWasReused.set(firstRecord.requestId, false);
        }
        return connectionWasReused;
    }
    static estimateRTTByOrigin(records, options) {
        const { forceCoarseEstimates = false,
        coarseEstimateMultiplier = 0.3, useDownloadEstimates = true, useSendStartEstimates = true, useHeadersEndEstimates = true, } = options || {};
        const connectionWasReused = NetworkAnalyzer.estimateIfConnectionWasReused(records);
        const groupedByOrigin = NetworkAnalyzer.groupByOrigin(records);
        const estimatesByOrigin = new Map();
        for (const [origin, originRequests] of groupedByOrigin.entries()) {
            const originEstimates = [];
            function collectEstimates(estimator, multiplier = 1) {
                for (const request of originRequests) {
                    const timing = request.timing;
                    if (!timing || !request.transferSize) {
                        continue;
                    }
                    const estimates = estimator({
                        request,
                        timing,
                        connectionReused: connectionWasReused.get(request.requestId),
                    });
                    if (estimates === undefined) {
                        continue;
                    }
                    if (!Array.isArray(estimates)) {
                        originEstimates.push(estimates * multiplier);
                    }
                    else {
                        originEstimates.push(...estimates.map(e => e * multiplier));
                    }
                }
            }
            if (!forceCoarseEstimates) {
                collectEstimates(this.estimateRTTViaConnectionTiming);
            }
            if (!originEstimates.length) {
                if (useDownloadEstimates) {
                    collectEstimates(this.estimateRTTViaDownloadTiming, coarseEstimateMultiplier);
                }
                if (useSendStartEstimates) {
                    collectEstimates(this.estimateRTTViaSendStartTiming, coarseEstimateMultiplier);
                }
                if (useHeadersEndEstimates) {
                    collectEstimates(this.estimateRTTViaHeadersEndTiming, coarseEstimateMultiplier);
                }
            }
            if (originEstimates.length) {
                estimatesByOrigin.set(origin, originEstimates);
            }
        }
        if (!estimatesByOrigin.size) {
            throw new LanternError('No timing information available');
        }
        return NetworkAnalyzer.summarize(estimatesByOrigin);
    }
    static estimateServerResponseTimeByOrigin(records, options) {
        let rttByOrigin = options?.rttByOrigin;
        if (!rttByOrigin) {
            rttByOrigin = new Map();
            const rttSummaryByOrigin = NetworkAnalyzer.estimateRTTByOrigin(records, options);
            for (const [origin, summary] of rttSummaryByOrigin.entries()) {
                rttByOrigin.set(origin, summary.min);
            }
        }
        const estimatesByOrigin = NetworkAnalyzer.estimateResponseTimeByOrigin(records, rttByOrigin);
        return NetworkAnalyzer.summarize(estimatesByOrigin);
    }
    static estimateThroughput(records) {
        let totalBytes = 0;
        const timeBoundaries = records
            .reduce((boundaries, request) => {
            const scheme = request.parsedURL?.scheme;
            if (scheme === 'data' || request.failed || !request.finished ||
                request.statusCode > 300 || !request.transferSize) {
                return boundaries;
            }
            totalBytes += request.transferSize;
            boundaries.push({ time: request.responseHeadersEndTime / 1000, isStart: true });
            boundaries.push({ time: request.networkEndTime / 1000, isStart: false });
            return boundaries;
        }, [])
            .sort((a, b) => a.time - b.time);
        if (!timeBoundaries.length) {
            return null;
        }
        let inflight = 0;
        let currentStart = 0;
        let totalDuration = 0;
        timeBoundaries.forEach(boundary => {
            if (boundary.isStart) {
                if (inflight === 0) {
                    currentStart = boundary.time;
                }
                inflight++;
            }
            else {
                inflight--;
                if (inflight === 0) {
                    totalDuration += boundary.time - currentStart;
                }
            }
        });
        return totalBytes * 8 / totalDuration;
    }
    static computeRTTAndServerResponseTime(records) {
        const rttByOrigin = new Map();
        for (const [origin, summary] of NetworkAnalyzer.estimateRTTByOrigin(records).entries()) {
            rttByOrigin.set(origin, summary.min);
        }
        const minimumRtt = Math.min(...Array.from(rttByOrigin.values()));
        const responseTimeSummaries = NetworkAnalyzer.estimateServerResponseTimeByOrigin(records, {
            rttByOrigin,
        });
        const additionalRttByOrigin = new Map();
        const serverResponseTimeByOrigin = new Map();
        for (const [origin, summary] of responseTimeSummaries.entries()) {
            const rttForOrigin = rttByOrigin.get(origin) || minimumRtt;
            additionalRttByOrigin.set(origin, rttForOrigin - minimumRtt);
            serverResponseTimeByOrigin.set(origin, summary.median);
        }
        return {
            rtt: minimumRtt,
            additionalRttByOrigin,
            serverResponseTimeByOrigin,
        };
    }
    static analyze(records) {
        const throughput = NetworkAnalyzer.estimateThroughput(records);
        if (throughput === null) {
            return null;
        }
        return {
            throughput,
            ...NetworkAnalyzer.computeRTTAndServerResponseTime(records),
        };
    }
    static findResourceForUrl(records, resourceUrl) {
        return records.find(request => resourceUrl.startsWith(request.url) && UrlUtils.equalWithExcludedFragments(request.url, resourceUrl));
    }
    static findLastDocumentForUrl(records, resourceUrl) {
        const matchingRequests = records.filter(request => request.resourceType === 'Document' && !request.failed &&
            resourceUrl.startsWith(request.url) && UrlUtils.equalWithExcludedFragments(request.url, resourceUrl));
        return matchingRequests[matchingRequests.length - 1];
    }
    static resolveRedirects(request) {
        while (request.redirectDestination) {
            request = request.redirectDestination;
        }
        return request;
    }
}

// Copyright 2024 The Chromium Authors

var core = /*#__PURE__*/Object.freeze({
	__proto__: null,
	LanternError: LanternError,
	NetworkAnalyzer: NetworkAnalyzer
});

// Copyright 2024 The Chromium Authors
class BaseNode {
    static types = {
        NETWORK: 'network',
        CPU: 'cpu',
    };
    _id;
    _isMainDocument;
    dependents;
    dependencies;
    constructor(id) {
        this._id = id;
        this._isMainDocument = false;
        this.dependents = [];
        this.dependencies = [];
    }
    get id() {
        return this._id;
    }
    get type() {
        throw new LanternError('Unimplemented');
    }
    get startTime() {
        throw new LanternError('Unimplemented');
    }
    get endTime() {
        throw new LanternError('Unimplemented');
    }
    setIsMainDocument(value) {
        this._isMainDocument = value;
    }
    isMainDocument() {
        return this._isMainDocument;
    }
    getDependents() {
        return this.dependents.slice();
    }
    getNumberOfDependents() {
        return this.dependents.length;
    }
    getDependencies() {
        return this.dependencies.slice();
    }
    getNumberOfDependencies() {
        return this.dependencies.length;
    }
    getRootNode() {
        let rootNode = this;
        while (rootNode.dependencies.length) {
            rootNode = rootNode.dependencies[0];
        }
        return rootNode;
    }
    addDependent(node) {
        node.addDependency(this);
    }
    addDependency(node) {
        if (node === this) {
            throw new LanternError('Cannot add dependency on itself');
        }
        if (this.dependencies.includes(node)) {
            return;
        }
        node.dependents.push(this);
        this.dependencies.push(node);
    }
    removeDependent(node) {
        node.removeDependency(this);
    }
    removeDependency(node) {
        if (!this.dependencies.includes(node)) {
            return;
        }
        const thisIndex = node.dependents.indexOf(this);
        node.dependents.splice(thisIndex, 1);
        this.dependencies.splice(this.dependencies.indexOf(node), 1);
    }
    removeAllDependencies() {
        for (const node of this.dependencies.slice()) {
            this.removeDependency(node);
        }
    }
    isDependentOn(node) {
        let isDependentOnNode = false;
        this.traverse(currentNode => {
            if (isDependentOnNode) {
                return;
            }
            isDependentOnNode = currentNode === node;
        }, currentNode => {
            if (isDependentOnNode) {
                return [];
            }
            return currentNode.getDependencies();
        });
        return isDependentOnNode;
    }
    cloneWithoutRelationships() {
        const node = new BaseNode(this.id);
        node.setIsMainDocument(this._isMainDocument);
        return node;
    }
    cloneWithRelationships(predicate) {
        const rootNode = this.getRootNode();
        const idsToIncludedClones = new Map();
        rootNode.traverse(node => {
            if (idsToIncludedClones.has(node.id)) {
                return;
            }
            if (predicate === undefined) {
                idsToIncludedClones.set(node.id, node.cloneWithoutRelationships());
                return;
            }
            if (predicate(node)) {
                node.traverse(node => idsToIncludedClones.set(node.id, node.cloneWithoutRelationships()),
                node => node.dependencies.filter(parent => !idsToIncludedClones.has(parent.id)));
            }
        });
        rootNode.traverse(originalNode => {
            const clonedNode = idsToIncludedClones.get(originalNode.id);
            if (!clonedNode) {
                return;
            }
            for (const dependency of originalNode.dependencies) {
                const clonedDependency = idsToIncludedClones.get(dependency.id);
                if (!clonedDependency) {
                    throw new LanternError('Dependency somehow not cloned');
                }
                clonedNode.addDependency(clonedDependency);
            }
        });
        const clonedThisNode = idsToIncludedClones.get(this.id);
        if (!clonedThisNode) {
            throw new LanternError('Cloned graph missing node');
        }
        return clonedThisNode;
    }
    traverse(callback, getNextNodes) {
        for (const { node, traversalPath } of this.traverseGenerator(getNextNodes)) {
            callback(node, traversalPath);
        }
    }
    *traverseGenerator(getNextNodes) {
        if (!getNextNodes) {
            getNextNodes = node => node.getDependents();
        }
        const queue = [[this]];
        const visited = new Set([this.id]);
        while (queue.length) {
            const traversalPath = queue.shift();
            const node = traversalPath[0];
            yield { node, traversalPath };
            for (const nextNode of getNextNodes(node)) {
                if (visited.has(nextNode.id)) {
                    continue;
                }
                visited.add(nextNode.id);
                queue.push([nextNode, ...traversalPath]);
            }
        }
    }
    static findCycle(node, direction = 'both') {
        if (direction === 'both') {
            return BaseNode.findCycle(node, 'dependents') || BaseNode.findCycle(node, 'dependencies');
        }
        const visited = new Set();
        const currentPath = [];
        const toVisit = [node];
        const depthAdded = new Map([[node, 0]]);
        while (toVisit.length) {
            const currentNode = toVisit.pop();
            if (currentPath.includes(currentNode)) {
                return currentPath;
            }
            if (visited.has(currentNode)) {
                continue;
            }
            while (currentPath.length > depthAdded.get(currentNode)) {
                currentPath.pop();
            }
            visited.add(currentNode);
            currentPath.push(currentNode);
            const nodesToExplore = direction === 'dependents' ? currentNode.dependents : currentNode.dependencies;
            for (const nextNode of nodesToExplore) {
                if (toVisit.includes(nextNode)) {
                    continue;
                }
                toVisit.push(nextNode);
                depthAdded.set(nextNode, currentPath.length);
            }
        }
        return null;
    }
    canDependOn(node) {
        return node.startTime <= this.startTime;
    }
}

// Copyright 2024 The Chromium Authors
class CPUNode extends BaseNode {
    _event;
    _childEvents;
    correctedEndTs;
    constructor(parentEvent, childEvents = [], correctedEndTs) {
        const nodeId = `${parentEvent.tid}.${parentEvent.ts}`;
        super(nodeId);
        this._event = parentEvent;
        this._childEvents = childEvents;
        this.correctedEndTs = correctedEndTs;
    }
    get type() {
        return BaseNode.types.CPU;
    }
    get startTime() {
        return this._event.ts;
    }
    get endTime() {
        if (this.correctedEndTs) {
            return this.correctedEndTs;
        }
        return this._event.ts + this._event.dur;
    }
    get duration() {
        return this.endTime - this.startTime;
    }
    get event() {
        return this._event;
    }
    get childEvents() {
        return this._childEvents;
    }
    didPerformLayout() {
        return this._childEvents.some(evt => evt.name === 'Layout');
    }
    getEvaluateScriptURLs() {
        const urls = new Set();
        for (const event of this._childEvents) {
            if (event.name !== 'EvaluateScript') {
                continue;
            }
            if (!event.args.data?.url) {
                continue;
            }
            urls.add(event.args.data.url);
        }
        return urls;
    }
    cloneWithoutRelationships() {
        return new CPUNode(this._event, this._childEvents, this.correctedEndTs);
    }
}

// Copyright 2024 The Chromium Authors
const NON_NETWORK_SCHEMES = [
    'blob',
    'data',
    'intent',
    'file',
    'filesystem',
    'chrome-extension',
];
function isNonNetworkProtocol(protocol) {
    const urlScheme = protocol.includes(':') ? protocol.slice(0, protocol.indexOf(':')) : protocol;
    return NON_NETWORK_SCHEMES.includes(urlScheme);
}
class NetworkNode extends BaseNode {
    _request;
    constructor(networkRequest) {
        super(networkRequest.requestId);
        this._request = networkRequest;
    }
    get type() {
        return BaseNode.types.NETWORK;
    }
    get startTime() {
        return this._request.rendererStartTime * 1000;
    }
    get endTime() {
        return this._request.networkEndTime * 1000;
    }
    get rawRequest() {
        return this._request.rawRequest;
    }
    get request() {
        return this._request;
    }
    get initiatorType() {
        return this._request.initiator.type;
    }
    get fromDiskCache() {
        return Boolean(this._request.fromDiskCache);
    }
    get isNonNetworkProtocol() {
        return isNonNetworkProtocol(this.request.protocol) ||
            isNonNetworkProtocol(this.request.parsedURL.scheme);
    }
    get isConnectionless() {
        return this.fromDiskCache || this.isNonNetworkProtocol;
    }
    hasRenderBlockingPriority() {
        const priority = this._request.priority;
        const isScript = this._request.resourceType === 'Script';
        const isDocument = this._request.resourceType === 'Document';
        const isBlockingScript = priority === 'High' && isScript;
        const isBlockingHtmlImport = priority === 'High' && isDocument;
        return priority === 'VeryHigh' || isBlockingScript || isBlockingHtmlImport;
    }
    cloneWithoutRelationships() {
        const node = new NetworkNode(this._request);
        node.setIsMainDocument(this._isMainDocument);
        return node;
    }
}

// Copyright 2024 The Chromium Authors
const SCHEDULABLE_TASK_TITLE_LH = 'RunTask';
const SCHEDULABLE_TASK_TITLE_ALT1 = 'ThreadControllerImpl::RunTask';
const SCHEDULABLE_TASK_TITLE_ALT2 = 'ThreadControllerImpl::DoWork';
const SCHEDULABLE_TASK_TITLE_ALT3 = 'TaskQueueManager::ProcessTaskFromWorkQueue';
const SIGNIFICANT_DUR_THRESHOLD_MS = 10;
const IGNORED_MIME_TYPES_REGEX = /^video/;
class PageDependencyGraph {
    static getNetworkInitiators(request) {
        if (!request.initiator) {
            return [];
        }
        if (request.initiator.url) {
            return [request.initiator.url];
        }
        if (request.initiator.type === 'script') {
            const scriptURLs = new Set();
            let stack = request.initiator.stack;
            while (stack) {
                const callFrames = stack.callFrames || [];
                for (const frame of callFrames) {
                    if (frame.url) {
                        scriptURLs.add(frame.url);
                    }
                }
                stack = stack.parent;
            }
            return Array.from(scriptURLs);
        }
        return [];
    }
    static getNetworkNodeOutput(networkRequests) {
        const nodes = [];
        const idToNodeMap = new Map();
        const urlToNodeMap = new Map();
        const frameIdToNodeMap = new Map();
        networkRequests.forEach(request => {
            if (IGNORED_MIME_TYPES_REGEX.test(request.mimeType)) {
                return;
            }
            if (request.fromWorker) {
                return;
            }
            while (idToNodeMap.has(request.requestId)) {
                request.requestId += ':duplicate';
            }
            const node = new NetworkNode(request);
            nodes.push(node);
            const urlList = urlToNodeMap.get(request.url) || [];
            urlList.push(node);
            idToNodeMap.set(request.requestId, node);
            urlToNodeMap.set(request.url, urlList);
            if (request.frameId && request.resourceType === 'Document' && request.documentURL === request.url) {
                const value = frameIdToNodeMap.has(request.frameId) ? null : node;
                frameIdToNodeMap.set(request.frameId, value);
            }
        });
        return { nodes, idToNodeMap, urlToNodeMap, frameIdToNodeMap };
    }
    static isScheduleableTask(evt) {
        return evt.name === SCHEDULABLE_TASK_TITLE_LH || evt.name === SCHEDULABLE_TASK_TITLE_ALT1 ||
            evt.name === SCHEDULABLE_TASK_TITLE_ALT2 || evt.name === SCHEDULABLE_TASK_TITLE_ALT3;
    }
    static assertHasToplevelEvents(events) {
        const hasToplevelTask = events.some(this.isScheduleableTask);
        if (!hasToplevelTask) {
            throw new LanternError('Could not find any top level events');
        }
    }
    static getCPUNodes(mainThreadEvents) {
        const nodes = [];
        let i = 0;
        PageDependencyGraph.assertHasToplevelEvents(mainThreadEvents);
        while (i < mainThreadEvents.length) {
            const evt = mainThreadEvents[i];
            i++;
            if (!PageDependencyGraph.isScheduleableTask(evt) || !evt.dur) {
                continue;
            }
            let correctedEndTs = undefined;
            const children = [];
            for (const endTime = evt.ts + evt.dur; i < mainThreadEvents.length && mainThreadEvents[i].ts < endTime; i++) {
                const event = mainThreadEvents[i];
                if (PageDependencyGraph.isScheduleableTask(event) && event.dur) {
                    correctedEndTs = event.ts - 1;
                    break;
                }
                children.push(event);
            }
            nodes.push(new CPUNode(evt, children, correctedEndTs));
        }
        return nodes;
    }
    static linkNetworkNodes(rootNode, networkNodeOutput) {
        networkNodeOutput.nodes.forEach(node => {
            const directInitiatorRequest = node.request.initiatorRequest || rootNode.request;
            const directInitiatorNode = networkNodeOutput.idToNodeMap.get(directInitiatorRequest.requestId) || rootNode;
            const canDependOnInitiator = !directInitiatorNode.isDependentOn(node) && node.canDependOn(directInitiatorNode);
            const initiators = PageDependencyGraph.getNetworkInitiators(node.request);
            if (initiators.length) {
                initiators.forEach(initiator => {
                    const parentCandidates = networkNodeOutput.urlToNodeMap.get(initiator) || [];
                    if (parentCandidates.length === 1 && parentCandidates[0].startTime <= node.startTime &&
                        !parentCandidates[0].isDependentOn(node)) {
                        node.addDependency(parentCandidates[0]);
                    }
                    else if (canDependOnInitiator) {
                        directInitiatorNode.addDependent(node);
                    }
                });
            }
            else if (canDependOnInitiator) {
                directInitiatorNode.addDependent(node);
            }
            if (node !== rootNode && node.getDependencies().length === 0 && node.canDependOn(rootNode)) {
                node.addDependency(rootNode);
            }
            if (!node.request.redirects) {
                return;
            }
            const redirects = [...node.request.redirects, node.request];
            for (let i = 1; i < redirects.length; i++) {
                const redirectNode = networkNodeOutput.idToNodeMap.get(redirects[i - 1].requestId);
                const actualNode = networkNodeOutput.idToNodeMap.get(redirects[i].requestId);
                if (actualNode && redirectNode) {
                    actualNode.addDependency(redirectNode);
                }
            }
        });
    }
    static linkCPUNodes(rootNode, networkNodeOutput, cpuNodes) {
        const linkableResourceTypes = new Set([
            'XHR',
            'Fetch',
            'Script',
        ]);
        function addDependentNetworkRequest(cpuNode, reqId) {
            const networkNode = networkNodeOutput.idToNodeMap.get(reqId);
            if (!networkNode ||
                networkNode.startTime <= cpuNode.startTime) {
                return;
            }
            const { request } = networkNode;
            const resourceType = request.resourceType || request.redirectDestination?.resourceType;
            if (!linkableResourceTypes.has(resourceType)) {
                return;
            }
            cpuNode.addDependent(networkNode);
        }
        function addDependencyOnFrame(cpuNode, frameId) {
            if (!frameId) {
                return;
            }
            const networkNode = networkNodeOutput.frameIdToNodeMap.get(frameId);
            if (!networkNode) {
                return;
            }
            if (networkNode.startTime >= cpuNode.startTime) {
                return;
            }
            cpuNode.addDependency(networkNode);
        }
        function addDependencyOnUrl(cpuNode, url) {
            if (!url) {
                return;
            }
            const minimumAllowableTimeSinceNetworkNodeEnd = -100 * 1000;
            const candidates = networkNodeOutput.urlToNodeMap.get(url) || [];
            let minCandidate = null;
            let minDistance = Infinity;
            for (const candidate of candidates) {
                if (cpuNode.startTime <= candidate.startTime) {
                    return;
                }
                const distance = cpuNode.startTime - candidate.endTime;
                if (distance >= minimumAllowableTimeSinceNetworkNodeEnd && distance < minDistance) {
                    minCandidate = candidate;
                    minDistance = distance;
                }
            }
            if (!minCandidate) {
                return;
            }
            cpuNode.addDependency(minCandidate);
        }
        const timers = new Map();
        for (const node of cpuNodes) {
            for (const evt of node.childEvents) {
                if (!evt.args.data) {
                    continue;
                }
                const argsUrl = evt.args.data.url;
                const stackTraceUrls = (evt.args.data.stackTrace || []).map(l => l.url).filter(Boolean);
                switch (evt.name) {
                    case 'TimerInstall':
                        timers.set(evt.args.data.timerId, node);
                        stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
                        break;
                    case 'TimerFire': {
                        const installer = timers.get(evt.args.data.timerId);
                        if (!installer || installer.endTime > node.startTime) {
                            break;
                        }
                        installer.addDependent(node);
                        break;
                    }
                    case 'InvalidateLayout':
                    case 'ScheduleStyleRecalculation':
                        addDependencyOnFrame(node, evt.args.data.frame);
                        stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
                        break;
                    case 'EvaluateScript':
                        addDependencyOnFrame(node, evt.args.data.frame);
                        addDependencyOnUrl(node, argsUrl);
                        stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
                        break;
                    case 'XHRReadyStateChange':
                        if (evt.args.data.readyState !== 4) {
                            break;
                        }
                        addDependencyOnUrl(node, argsUrl);
                        stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
                        break;
                    case 'FunctionCall':
                    case 'v8.compile':
                        addDependencyOnFrame(node, evt.args.data.frame);
                        addDependencyOnUrl(node, argsUrl);
                        break;
                    case 'ParseAuthorStyleSheet':
                        addDependencyOnFrame(node, evt.args.data.frame);
                        addDependencyOnUrl(node, evt.args.data.styleSheetUrl);
                        break;
                    case 'ResourceSendRequest':
                        addDependencyOnFrame(node, evt.args.data.frame);
                        addDependentNetworkRequest(node, evt.args.data.requestId);
                        stackTraceUrls.forEach(url => addDependencyOnUrl(node, url));
                        break;
                }
            }
            if (node.getNumberOfDependencies() === 0 && node.canDependOn(rootNode)) {
                node.addDependency(rootNode);
            }
        }
        const minimumEvtDur = SIGNIFICANT_DUR_THRESHOLD_MS * 1000;
        let foundFirstLayout = false;
        let foundFirstPaint = false;
        let foundFirstParse = false;
        for (const node of cpuNodes) {
            let isFirst = false;
            if (!foundFirstLayout && node.childEvents.some(evt => evt.name === 'Layout')) {
                isFirst = foundFirstLayout = true;
            }
            if (!foundFirstPaint && node.childEvents.some(evt => evt.name === 'Paint')) {
                isFirst = foundFirstPaint = true;
            }
            if (!foundFirstParse && node.childEvents.some(evt => evt.name === 'ParseHTML')) {
                isFirst = foundFirstParse = true;
            }
            if (isFirst || node.duration >= minimumEvtDur) {
                continue;
            }
            if (node.getNumberOfDependencies() === 1 || node.getNumberOfDependents() <= 1) {
                PageDependencyGraph.pruneNode(node);
            }
        }
    }
    static pruneNode(node) {
        const dependencies = node.getDependencies();
        const dependents = node.getDependents();
        for (const dependency of dependencies) {
            node.removeDependency(dependency);
            for (const dependent of dependents) {
                dependency.addDependent(dependent);
            }
        }
        for (const dependent of dependents) {
            node.removeDependent(dependent);
        }
    }
    static debugNormalizeRequests(lanternRequests) {
        for (const request of lanternRequests) {
            request.rendererStartTime = Math.round(request.rendererStartTime * 1000) / 1000;
            request.networkRequestTime = Math.round(request.networkRequestTime * 1000) / 1000;
            request.responseHeadersEndTime = Math.round(request.responseHeadersEndTime * 1000) / 1000;
            request.networkEndTime = Math.round(request.networkEndTime * 1000) / 1000;
        }
        for (const r of lanternRequests) {
            delete r.rawRequest;
            if (r.initiatorRequest) {
                r.initiatorRequest = { id: r.initiatorRequest.requestId };
            }
            if (r.redirectDestination) {
                r.redirectDestination = { id: r.redirectDestination.requestId };
            }
            if (r.redirectSource) {
                r.redirectSource = { id: r.redirectSource.requestId };
            }
            if (r.redirects) {
                r.redirects = r.redirects.map(r2 => r2.requestId);
            }
        }
        const requests = lanternRequests
            .map(r => ({
            requestId: r.requestId,
            connectionId: r.connectionId,
            connectionReused: r.connectionReused,
            url: r.url,
            protocol: r.protocol,
            parsedURL: r.parsedURL,
            documentURL: r.documentURL,
            rendererStartTime: r.rendererStartTime,
            networkRequestTime: r.networkRequestTime,
            responseHeadersEndTime: r.responseHeadersEndTime,
            networkEndTime: r.networkEndTime,
            transferSize: r.transferSize,
            resourceSize: r.resourceSize,
            fromDiskCache: r.fromDiskCache,
            fromMemoryCache: r.fromMemoryCache,
            finished: r.finished,
            statusCode: r.statusCode,
            redirectSource: r.redirectSource,
            redirectDestination: r.redirectDestination,
            redirects: r.redirects,
            failed: r.failed,
            initiator: r.initiator,
            timing: r.timing ? {
                requestTime: r.timing.requestTime,
                proxyStart: r.timing.proxyStart,
                proxyEnd: r.timing.proxyEnd,
                dnsStart: r.timing.dnsStart,
                dnsEnd: r.timing.dnsEnd,
                connectStart: r.timing.connectStart,
                connectEnd: r.timing.connectEnd,
                sslStart: r.timing.sslStart,
                sslEnd: r.timing.sslEnd,
                workerStart: r.timing.workerStart,
                workerReady: r.timing.workerReady,
                workerFetchStart: r.timing.workerFetchStart,
                workerRespondWithSettled: r.timing.workerRespondWithSettled,
                sendStart: r.timing.sendStart,
                sendEnd: r.timing.sendEnd,
                pushStart: r.timing.pushStart,
                pushEnd: r.timing.pushEnd,
                receiveHeadersStart: r.timing.receiveHeadersStart,
                receiveHeadersEnd: r.timing.receiveHeadersEnd,
            } :
                r.timing,
            resourceType: r.resourceType,
            mimeType: r.mimeType,
            priority: r.priority,
            initiatorRequest: r.initiatorRequest,
            frameId: r.frameId,
            fromWorker: r.fromWorker,
            isLinkPreload: r.isLinkPreload,
            serverResponseTime: r.serverResponseTime,
        }))
            .filter(r => !r.fromWorker);
        const debug = requests;
        console.log(debug);
    }
    static createGraph(mainThreadEvents, networkRequests, url) {
        const networkNodeOutput = PageDependencyGraph.getNetworkNodeOutput(networkRequests);
        const cpuNodes = PageDependencyGraph.getCPUNodes(mainThreadEvents);
        const { requestedUrl, mainDocumentUrl } = url;
        if (!requestedUrl) {
            throw new LanternError('requestedUrl is required to get the root request');
        }
        if (!mainDocumentUrl) {
            throw new LanternError('mainDocumentUrl is required to get the main resource');
        }
        const rootRequest = NetworkAnalyzer.findResourceForUrl(networkRequests, requestedUrl);
        if (!rootRequest) {
            throw new LanternError('rootRequest not found');
        }
        const rootNode = networkNodeOutput.idToNodeMap.get(rootRequest.requestId);
        if (!rootNode) {
            throw new LanternError('rootNode not found');
        }
        const mainDocumentRequest = NetworkAnalyzer.findLastDocumentForUrl(networkRequests, mainDocumentUrl);
        if (!mainDocumentRequest) {
            throw new LanternError('mainDocumentRequest not found');
        }
        const mainDocumentNode = networkNodeOutput.idToNodeMap.get(mainDocumentRequest.requestId);
        if (!mainDocumentNode) {
            throw new LanternError('mainDocumentNode not found');
        }
        PageDependencyGraph.linkNetworkNodes(rootNode, networkNodeOutput);
        PageDependencyGraph.linkCPUNodes(rootNode, networkNodeOutput, cpuNodes);
        mainDocumentNode.setIsMainDocument(true);
        if (NetworkNode.findCycle(rootNode)) {
            throw new LanternError('Invalid dependency graph created, cycle detected');
        }
        return rootNode;
    }
    static printGraph(rootNode, widthInCharacters = 80) {
        function padRight(str, target, padChar = ' ') {
            return str + padChar.repeat(Math.max(target - str.length, 0));
        }
        const nodes = [];
        rootNode.traverse(node => nodes.push(node));
        nodes.sort((a, b) => a.startTime - b.startTime);
        const nodeToLabel = new Map();
        rootNode.traverse(node => {
            const ascii = 65 + nodeToLabel.size;
            let label;
            if (ascii > 90) {
                label = `Z${ascii - 90}`;
            }
            else {
                label = String.fromCharCode(ascii);
            }
            nodeToLabel.set(node, label);
        });
        const min = nodes[0].startTime;
        const max = nodes.reduce((max, node) => Math.max(max, node.endTime), 0);
        const totalTime = max - min;
        const timePerCharacter = totalTime / widthInCharacters;
        nodes.forEach(node => {
            const offset = Math.round((node.startTime - min) / timePerCharacter);
            const length = Math.ceil((node.endTime - node.startTime) / timePerCharacter);
            const bar = padRight('', offset) + padRight('', length, '=');
            const displayName = node.request ? node.request.url : node.type;
            console.log(padRight(bar, widthInCharacters), `| ${displayName.slice(0, 50)}`);
        });
        console.log();
        nodes.forEach(node => {
            const displayName = node.request ? node.request.url : node.type;
            console.log(nodeToLabel.get(node), displayName.slice(0, widthInCharacters - 5));
            for (const child of node.dependents) {
                const displayName = child.request ? child.request.url : child.type;
                console.log('  ->', nodeToLabel.get(child), displayName.slice(0, widthInCharacters - 10));
            }
            console.log();
        });
        const cyclePath = NetworkNode.findCycle(rootNode);
        console.log('Cycle?', cyclePath ? 'yes' : 'no');
        if (cyclePath) {
            const path = [...cyclePath];
            path.push(path[0]);
            console.log(path.map(node => nodeToLabel.get(node)).join(' -> '));
        }
    }
}

// Copyright 2024 The Chromium Authors

var graph = /*#__PURE__*/Object.freeze({
	__proto__: null,
	BaseNode: BaseNode,
	CPUNode: CPUNode,
	NetworkNode: NetworkNode,
	PageDependencyGraph: PageDependencyGraph
});

// Copyright 2024 The Chromium Authors
class Metric {
    static getScriptUrls(dependencyGraph, treatNodeAsRenderBlocking) {
        const scriptUrls = new Set();
        dependencyGraph.traverse(node => {
            if (node.type !== BaseNode.types.NETWORK) {
                return;
            }
            if (node.request.resourceType !== 'Script') {
                return;
            }
            if (treatNodeAsRenderBlocking?.(node)) {
                scriptUrls.add(node.request.url);
            }
        });
        return scriptUrls;
    }
    static get coefficients() {
        throw new LanternError('coefficients unimplemented!');
    }
    static getScaledCoefficients(_rttMs) {
        return this.coefficients;
    }
    static getOptimisticGraph(_dependencyGraph, _processedNavigation) {
        throw new LanternError('Optimistic graph unimplemented!');
    }
    static getPessimisticGraph(_dependencyGraph, _processedNavigation) {
        throw new LanternError('Pessmistic graph unimplemented!');
    }
    static getEstimateFromSimulation(simulationResult, _extras) {
        return simulationResult;
    }
    static compute(data, extras) {
        const { simulator, graph, processedNavigation } = data;
        const metricName = this.name.replace('Lantern', '');
        const optimisticGraph = this.getOptimisticGraph(graph, processedNavigation);
        const pessimisticGraph = this.getPessimisticGraph(graph, processedNavigation);
        let simulateOptions = { label: `optimistic${metricName}` };
        const optimisticSimulation = simulator.simulate(optimisticGraph, simulateOptions);
        simulateOptions = { label: `pessimistic${metricName}` };
        const pessimisticSimulation = simulator.simulate(pessimisticGraph, simulateOptions);
        const optimisticEstimate = this.getEstimateFromSimulation(optimisticSimulation, { ...extras, optimistic: true });
        const pessimisticEstimate = this.getEstimateFromSimulation(pessimisticSimulation, { ...extras, optimistic: false });
        const coefficients = this.getScaledCoefficients(simulator.rtt);
        const interceptMultiplier = coefficients.intercept > 0 ? Math.min(1, optimisticEstimate.timeInMs / 1000) : 1;
        const timing = coefficients.intercept * interceptMultiplier +
            coefficients.optimistic * optimisticEstimate.timeInMs + coefficients.pessimistic * pessimisticEstimate.timeInMs;
        return {
            timing,
            optimisticEstimate,
            pessimisticEstimate,
            optimisticGraph,
            pessimisticGraph,
        };
    }
}

// Copyright 2024 The Chromium Authors
class FirstContentfulPaint extends Metric {
    static get coefficients() {
        return {
            intercept: 0,
            optimistic: 0.5,
            pessimistic: 0.5,
        };
    }
    static getRenderBlockingNodeData(graph$1, { cutoffTimestamp, treatNodeAsRenderBlocking, additionalCpuNodesToTreatAsRenderBlocking }) {
        const scriptUrlToNodeMap = new Map();
        const cpuNodes = [];
        graph$1.traverse(node => {
            if (node.type === BaseNode.types.CPU) {
                if (node.startTime <= cutoffTimestamp) {
                    cpuNodes.push(node);
                }
                const scriptUrls = node.getEvaluateScriptURLs();
                for (const url of scriptUrls) {
                    const existing = scriptUrlToNodeMap.get(url) || node;
                    scriptUrlToNodeMap.set(url, node.startTime < existing.startTime ? node : existing);
                }
            }
        });
        cpuNodes.sort((a, b) => a.startTime - b.startTime);
        const possiblyRenderBlockingScriptUrls = Metric.getScriptUrls(graph$1, node => {
            return node.endTime <= cutoffTimestamp && treatNodeAsRenderBlocking(node);
        });
        const definitelyNotRenderBlockingScriptUrls = new Set();
        const renderBlockingCpuNodeIds = new Set();
        for (const url of possiblyRenderBlockingScriptUrls) {
            const cpuNodeForUrl = scriptUrlToNodeMap.get(url);
            if (!cpuNodeForUrl) {
                continue;
            }
            if (cpuNodes.includes(cpuNodeForUrl)) {
                renderBlockingCpuNodeIds.add(cpuNodeForUrl.id);
                continue;
            }
            definitelyNotRenderBlockingScriptUrls.add(url);
        }
        const firstLayout = cpuNodes.find(node => node.didPerformLayout());
        if (firstLayout) {
            renderBlockingCpuNodeIds.add(firstLayout.id);
        }
        const firstPaint = cpuNodes.find(node => node.childEvents.some(e => e.name === 'Paint'));
        if (firstPaint) {
            renderBlockingCpuNodeIds.add(firstPaint.id);
        }
        const firstParse = cpuNodes.find(node => node.childEvents.some(e => e.name === 'ParseHTML'));
        if (firstParse) {
            renderBlockingCpuNodeIds.add(firstParse.id);
        }
        if (additionalCpuNodesToTreatAsRenderBlocking) {
            cpuNodes.filter(additionalCpuNodesToTreatAsRenderBlocking).forEach(node => renderBlockingCpuNodeIds.add(node.id));
        }
        return {
            definitelyNotRenderBlockingScriptUrls,
            renderBlockingCpuNodeIds,
        };
    }
    static getFirstPaintBasedGraph(dependencyGraph, { cutoffTimestamp, treatNodeAsRenderBlocking, additionalCpuNodesToTreatAsRenderBlocking }) {
        const rbData = this.getRenderBlockingNodeData(dependencyGraph, {
            cutoffTimestamp,
            treatNodeAsRenderBlocking,
            additionalCpuNodesToTreatAsRenderBlocking,
        });
        const { definitelyNotRenderBlockingScriptUrls, renderBlockingCpuNodeIds } = rbData;
        return dependencyGraph.cloneWithRelationships(node => {
            if (node.type === BaseNode.types.NETWORK) {
                const endedAfterPaint = node.endTime > cutoffTimestamp || node.startTime > cutoffTimestamp;
                if (endedAfterPaint && !node.isMainDocument()) {
                    return false;
                }
                const url = node.request.url;
                if (definitelyNotRenderBlockingScriptUrls.has(url)) {
                    return false;
                }
                return treatNodeAsRenderBlocking(node);
            }
            return renderBlockingCpuNodeIds.has(node.id);
        });
    }
    static getOptimisticGraph(dependencyGraph, processedNavigation) {
        return this.getFirstPaintBasedGraph(dependencyGraph, {
            cutoffTimestamp: processedNavigation.timestamps.firstContentfulPaint,
            treatNodeAsRenderBlocking: node => node.hasRenderBlockingPriority() && node.initiatorType !== 'script',
        });
    }
    static getPessimisticGraph(dependencyGraph, processedNavigation) {
        return this.getFirstPaintBasedGraph(dependencyGraph, {
            cutoffTimestamp: processedNavigation.timestamps.firstContentfulPaint,
            treatNodeAsRenderBlocking: node => node.hasRenderBlockingPriority(),
        });
    }
}

// Copyright 2024 The Chromium Authors
const CRITICAL_LONG_TASK_THRESHOLD = 20;
class Interactive extends Metric {
    static get coefficients() {
        return {
            intercept: 0,
            optimistic: 0.45,
            pessimistic: 0.55,
        };
    }
    static getOptimisticGraph(dependencyGraph) {
        const minimumCpuTaskDuration = CRITICAL_LONG_TASK_THRESHOLD * 1000;
        return dependencyGraph.cloneWithRelationships(node => {
            if (node.type === BaseNode.types.CPU) {
                return node.duration > minimumCpuTaskDuration;
            }
            const isImage = node.request.resourceType === 'Image';
            const isScript = node.request.resourceType === 'Script';
            return (!isImage && (isScript || node.request.priority === 'High' || node.request.priority === 'VeryHigh'));
        });
    }
    static getPessimisticGraph(dependencyGraph) {
        return dependencyGraph;
    }
    static getEstimateFromSimulation(simulationResult, extras) {
        if (!extras.lcpResult) {
            throw new LanternError('missing lcpResult');
        }
        const lastTaskAt = Interactive.getLastLongTaskEndTime(simulationResult.nodeTimings);
        const minimumTime = extras.optimistic ? extras.lcpResult.optimisticEstimate.timeInMs :
            extras.lcpResult.pessimisticEstimate.timeInMs;
        return {
            timeInMs: Math.max(minimumTime, lastTaskAt),
            nodeTimings: simulationResult.nodeTimings,
        };
    }
    static compute(data, extras) {
        const lcpResult = extras?.lcpResult;
        if (!lcpResult) {
            throw new LanternError('LCP is required to calculate the Interactive metric');
        }
        const metricResult = super.compute(data, extras);
        metricResult.timing = Math.max(metricResult.timing, lcpResult.timing);
        return metricResult;
    }
    static getLastLongTaskEndTime(nodeTimings, duration = 50) {
        return Array.from(nodeTimings.entries())
            .filter(([node, timing]) => {
            if (node.type !== BaseNode.types.CPU) {
                return false;
            }
            return timing.duration > duration;
        })
            .map(([_, timing]) => timing.endTime)
            .reduce((max, x) => Math.max(max || 0, x || 0), 0);
    }
}

// Copyright 2024 The Chromium Authors
class LargestContentfulPaint extends Metric {
    static get coefficients() {
        return {
            intercept: 0,
            optimistic: 0.5,
            pessimistic: 0.5,
        };
    }
    static isNotLowPriorityImageNode(node) {
        if (node.type !== 'network') {
            return true;
        }
        const isImage = node.request.resourceType === 'Image';
        const isLowPriority = node.request.priority === 'Low' || node.request.priority === 'VeryLow';
        return !isImage || !isLowPriority;
    }
    static getOptimisticGraph(dependencyGraph, processedNavigation) {
        const lcp = processedNavigation.timestamps.largestContentfulPaint;
        if (!lcp) {
            throw new LanternError('NO_LCP');
        }
        return FirstContentfulPaint.getFirstPaintBasedGraph(dependencyGraph, {
            cutoffTimestamp: lcp,
            treatNodeAsRenderBlocking: LargestContentfulPaint.isNotLowPriorityImageNode,
        });
    }
    static getPessimisticGraph(dependencyGraph, processedNavigation) {
        const lcp = processedNavigation.timestamps.largestContentfulPaint;
        if (!lcp) {
            throw new LanternError('NO_LCP');
        }
        return FirstContentfulPaint.getFirstPaintBasedGraph(dependencyGraph, {
            cutoffTimestamp: lcp,
            treatNodeAsRenderBlocking: _ => true,
            additionalCpuNodesToTreatAsRenderBlocking: node => node.didPerformLayout(),
        });
    }
    static getEstimateFromSimulation(simulationResult) {
        const nodeTimesNotOffscreenImages = Array.from(simulationResult.nodeTimings.entries())
            .filter(entry => LargestContentfulPaint.isNotLowPriorityImageNode(entry[0]))
            .map(entry => entry[1].endTime);
        return {
            timeInMs: Math.max(...nodeTimesNotOffscreenImages),
            nodeTimings: simulationResult.nodeTimings,
        };
    }
    static compute(data, extras) {
        const fcpResult = extras?.fcpResult;
        if (!fcpResult) {
            throw new LanternError('FCP is required to calculate the LCP metric');
        }
        const metricResult = super.compute(data, extras);
        metricResult.timing = Math.max(metricResult.timing, fcpResult.timing);
        return metricResult;
    }
}

// Copyright 2024 The Chromium Authors
class MaxPotentialFID extends Metric {
    static get coefficients() {
        return {
            intercept: 0,
            optimistic: 0.5,
            pessimistic: 0.5,
        };
    }
    static getOptimisticGraph(dependencyGraph) {
        return dependencyGraph;
    }
    static getPessimisticGraph(dependencyGraph) {
        return dependencyGraph;
    }
    static getEstimateFromSimulation(simulation, extras) {
        if (!extras.fcpResult) {
            throw new LanternError('missing fcpResult');
        }
        const fcpTimeInMs = extras.optimistic ? extras.fcpResult.pessimisticEstimate.timeInMs :
            extras.fcpResult.optimisticEstimate.timeInMs;
        const timings = MaxPotentialFID.getTimingsAfterFCP(simulation.nodeTimings, fcpTimeInMs);
        return {
            timeInMs: Math.max(...timings.map(timing => timing.duration), 16),
            nodeTimings: simulation.nodeTimings,
        };
    }
    static compute(data, extras) {
        const fcpResult = extras?.fcpResult;
        if (!fcpResult) {
            throw new LanternError('FCP is required to calculate the Max Potential FID metric');
        }
        return super.compute(data, extras);
    }
    static getTimingsAfterFCP(nodeTimings, fcpTimeInMs) {
        return Array.from(nodeTimings.entries())
            .filter(([node, timing]) => node.type === BaseNode.types.CPU && timing.endTime > fcpTimeInMs)
            .map(([_, timing]) => timing);
    }
}

// Copyright 2024 The Chromium Authors
const mobileSlow4GRtt = 150;
class SpeedIndex extends Metric {
    static get coefficients() {
        return {
            intercept: 0,
            optimistic: 1.4,
            pessimistic: 0.4,
        };
    }
    static getScaledCoefficients(rttMs) {
        const defaultCoefficients = this.coefficients;
        const defaultRttExcess = mobileSlow4GRtt - 30;
        const multiplier = Math.max((rttMs - 30) / defaultRttExcess, 0);
        return {
            intercept: defaultCoefficients.intercept * multiplier,
            optimistic: 0.5 + (defaultCoefficients.optimistic - 0.5) * multiplier,
            pessimistic: 0.5 + (defaultCoefficients.pessimistic - 0.5) * multiplier,
        };
    }
    static getOptimisticGraph(dependencyGraph) {
        return dependencyGraph;
    }
    static getPessimisticGraph(dependencyGraph) {
        return dependencyGraph;
    }
    static getEstimateFromSimulation(simulationResult, extras) {
        if (!extras.fcpResult) {
            throw new LanternError('missing fcpResult');
        }
        if (extras.observedSpeedIndex === undefined) {
            throw new LanternError('missing observedSpeedIndex');
        }
        const fcpTimeInMs = extras.fcpResult.pessimisticEstimate.timeInMs;
        const estimate = extras.optimistic ?
            extras.observedSpeedIndex :
            SpeedIndex.computeLayoutBasedSpeedIndex(simulationResult.nodeTimings, fcpTimeInMs);
        return {
            timeInMs: estimate,
            nodeTimings: simulationResult.nodeTimings,
        };
    }
    static compute(data, extras) {
        const fcpResult = extras?.fcpResult;
        if (!fcpResult) {
            throw new LanternError('FCP is required to calculate the SpeedIndex metric');
        }
        const metricResult = super.compute(data, extras);
        metricResult.timing = Math.max(metricResult.timing, fcpResult.timing);
        return metricResult;
    }
    static computeLayoutBasedSpeedIndex(nodeTimings, fcpTimeInMs) {
        const layoutWeights = [];
        for (const [node, timing] of nodeTimings.entries()) {
            if (node.type !== BaseNode.types.CPU) {
                continue;
            }
            if (node.childEvents.some(x => x.name === 'Layout')) {
                const timingWeight = Math.max(Math.log2(timing.endTime - timing.startTime), 0);
                layoutWeights.push({ time: timing.endTime, weight: timingWeight });
            }
        }
        const totalWeightedTime = layoutWeights.map(evt => evt.weight * Math.max(evt.time, fcpTimeInMs)).reduce((a, b) => a + b, 0);
        const totalWeight = layoutWeights.map(evt => evt.weight).reduce((a, b) => a + b, 0);
        if (!totalWeight) {
            return fcpTimeInMs;
        }
        return totalWeightedTime / totalWeight;
    }
}

// Copyright 2024 The Chromium Authors
const BLOCKING_TIME_THRESHOLD = 50;
function calculateTbtImpactForEvent(event, startTimeMs, endTimeMs, topLevelEvent) {
    let threshold = BLOCKING_TIME_THRESHOLD;
    if (topLevelEvent) {
        threshold *= (event.duration / topLevelEvent.duration);
    }
    if (event.duration < threshold) {
        return 0;
    }
    if (event.end < startTimeMs) {
        return 0;
    }
    if (event.start > endTimeMs) {
        return 0;
    }
    const clippedStart = Math.max(event.start, startTimeMs);
    const clippedEnd = Math.min(event.end, endTimeMs);
    const clippedDuration = clippedEnd - clippedStart;
    if (clippedDuration < threshold) {
        return 0;
    }
    return clippedDuration - threshold;
}
function calculateSumOfBlockingTime(topLevelEvents, startTimeMs, endTimeMs) {
    if (endTimeMs <= startTimeMs) {
        return 0;
    }
    let sumBlockingTime = 0;
    for (const event of topLevelEvents) {
        sumBlockingTime += calculateTbtImpactForEvent(event, startTimeMs, endTimeMs);
    }
    return sumBlockingTime;
}

var TBTUtils = /*#__PURE__*/Object.freeze({
	__proto__: null,
	BLOCKING_TIME_THRESHOLD: BLOCKING_TIME_THRESHOLD,
	calculateSumOfBlockingTime: calculateSumOfBlockingTime,
	calculateTbtImpactForEvent: calculateTbtImpactForEvent
});

// Copyright 2024 The Chromium Authors
class TotalBlockingTime extends Metric {
    static get coefficients() {
        return {
            intercept: 0,
            optimistic: 0.5,
            pessimistic: 0.5,
        };
    }
    static getOptimisticGraph(dependencyGraph) {
        return dependencyGraph;
    }
    static getPessimisticGraph(dependencyGraph) {
        return dependencyGraph;
    }
    static getEstimateFromSimulation(simulation, extras) {
        if (!extras.fcpResult) {
            throw new LanternError('missing fcpResult');
        }
        if (!extras.interactiveResult) {
            throw new LanternError('missing interactiveResult');
        }
        const fcpTimeInMs = extras.optimistic ? extras.fcpResult.pessimisticEstimate.timeInMs :
            extras.fcpResult.optimisticEstimate.timeInMs;
        const interactiveTimeMs = extras.optimistic ? extras.interactiveResult.optimisticEstimate.timeInMs :
            extras.interactiveResult.pessimisticEstimate.timeInMs;
        const minDurationMs = BLOCKING_TIME_THRESHOLD;
        const events = TotalBlockingTime.getTopLevelEvents(simulation.nodeTimings, minDurationMs);
        return {
            timeInMs: calculateSumOfBlockingTime(events, fcpTimeInMs, interactiveTimeMs),
            nodeTimings: simulation.nodeTimings,
        };
    }
    static compute(data, extras) {
        const fcpResult = extras?.fcpResult;
        if (!fcpResult) {
            throw new LanternError('FCP is required to calculate the TBT metric');
        }
        const interactiveResult = extras?.fcpResult;
        if (!interactiveResult) {
            throw new LanternError('Interactive is required to calculate the TBT metric');
        }
        return super.compute(data, extras);
    }
    static getTopLevelEvents(nodeTimings, minDurationMs) {
        const events = [];
        for (const [node, timing] of nodeTimings.entries()) {
            if (node.type !== BaseNode.types.CPU) {
                continue;
            }
            if (timing.duration < minDurationMs) {
                continue;
            }
            events.push({
                start: timing.startTime,
                end: timing.endTime,
                duration: timing.duration,
            });
        }
        return events;
    }
}

// Copyright 2024 The Chromium Authors

var metrics$1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	FirstContentfulPaint: FirstContentfulPaint,
	Interactive: Interactive,
	LargestContentfulPaint: LargestContentfulPaint,
	MaxPotentialFID: MaxPotentialFID,
	Metric: Metric,
	SpeedIndex: SpeedIndex,
	TBTUtils: TBTUtils,
	TotalBlockingTime: TotalBlockingTime
});

// Copyright 2024 The Chromium Authors
const INITIAL_CONGESTION_WINDOW = 10;
const TCP_SEGMENT_SIZE = 1460;
class TCPConnection {
    warmed;
    ssl;
    h2;
    rtt;
    throughput;
    serverLatency;
    _congestionWindow;
    h2OverflowBytesDownloaded;
    constructor(rtt, throughput, serverLatency = 0, ssl = true, h2 = false) {
        this.warmed = false;
        this.ssl = ssl;
        this.h2 = h2;
        this.rtt = rtt;
        this.throughput = throughput;
        this.serverLatency = serverLatency;
        this._congestionWindow = INITIAL_CONGESTION_WINDOW;
        this.h2OverflowBytesDownloaded = 0;
    }
    static maximumSaturatedConnections(rtt, availableThroughput) {
        const roundTripsPerSecond = 1000 / rtt;
        const bytesPerRoundTrip = TCP_SEGMENT_SIZE;
        const bytesPerSecond = roundTripsPerSecond * bytesPerRoundTrip;
        const minimumThroughputRequiredPerRequest = bytesPerSecond * 8;
        return Math.floor(availableThroughput / minimumThroughputRequiredPerRequest);
    }
    computeMaximumCongestionWindowInSegments() {
        const bytesPerSecond = this.throughput / 8;
        const secondsPerRoundTrip = this.rtt / 1000;
        const bytesPerRoundTrip = bytesPerSecond * secondsPerRoundTrip;
        return Math.floor(bytesPerRoundTrip / TCP_SEGMENT_SIZE);
    }
    setThroughput(throughput) {
        this.throughput = throughput;
    }
    setCongestionWindow(congestion) {
        this._congestionWindow = congestion;
    }
    setWarmed(warmed) {
        this.warmed = warmed;
    }
    isH2() {
        return this.h2;
    }
    get congestionWindow() {
        return this._congestionWindow;
    }
    setH2OverflowBytesDownloaded(bytes) {
        if (!this.h2) {
            return;
        }
        this.h2OverflowBytesDownloaded = bytes;
    }
    clone() {
        return Object.assign(new TCPConnection(this.rtt, this.throughput), this);
    }
    simulateDownloadUntil(bytesToDownload, options) {
        const { timeAlreadyElapsed = 0, maximumTimeToElapse = Infinity, dnsResolutionTime = 0 } = options || {};
        if (this.warmed && this.h2) {
            bytesToDownload -= this.h2OverflowBytesDownloaded;
        }
        const twoWayLatency = this.rtt;
        const oneWayLatency = twoWayLatency / 2;
        const maximumCongestionWindow = this.computeMaximumCongestionWindowInSegments();
        let handshakeAndRequest = oneWayLatency;
        if (!this.warmed) {
            handshakeAndRequest =
                dnsResolutionTime +
                    oneWayLatency +
                    oneWayLatency +
                    oneWayLatency +
                    (this.ssl ? twoWayLatency : 0);
        }
        let roundTrips = Math.ceil(handshakeAndRequest / twoWayLatency);
        let timeToFirstByte = handshakeAndRequest + this.serverLatency + oneWayLatency;
        if (this.warmed && this.h2) {
            timeToFirstByte = 0;
        }
        const timeElapsedForTTFB = Math.max(timeToFirstByte - timeAlreadyElapsed, 0);
        const maximumDownloadTimeToElapse = maximumTimeToElapse - timeElapsedForTTFB;
        let congestionWindow = Math.min(this._congestionWindow, maximumCongestionWindow);
        let totalBytesDownloaded = 0;
        if (timeElapsedForTTFB > 0) {
            totalBytesDownloaded = congestionWindow * TCP_SEGMENT_SIZE;
        }
        else {
            roundTrips = 0;
        }
        let downloadTimeElapsed = 0;
        let bytesRemaining = bytesToDownload - totalBytesDownloaded;
        while (bytesRemaining > 0 && downloadTimeElapsed <= maximumDownloadTimeToElapse) {
            roundTrips++;
            downloadTimeElapsed += twoWayLatency;
            congestionWindow = Math.max(Math.min(maximumCongestionWindow, congestionWindow * 2), 1);
            const bytesDownloadedInWindow = congestionWindow * TCP_SEGMENT_SIZE;
            totalBytesDownloaded += bytesDownloadedInWindow;
            bytesRemaining -= bytesDownloadedInWindow;
        }
        const timeElapsed = timeElapsedForTTFB + downloadTimeElapsed;
        const extraBytesDownloaded = this.h2 ? Math.max(totalBytesDownloaded - bytesToDownload, 0) : 0;
        const bytesDownloaded = Math.max(Math.min(totalBytesDownloaded, bytesToDownload), 0);
        let connectionTiming;
        if (!this.warmed) {
            connectionTiming = {
                dnsResolutionTime,
                connectionTime: handshakeAndRequest - dnsResolutionTime,
                sslTime: this.ssl ? twoWayLatency : undefined,
                timeToFirstByte,
            };
        }
        else if (this.h2) {
            connectionTiming = {
                timeToFirstByte,
            };
        }
        else {
            connectionTiming = {
                connectionTime: handshakeAndRequest,
                timeToFirstByte,
            };
        }
        return {
            roundTrips,
            timeElapsed,
            bytesDownloaded,
            extraBytesDownloaded,
            congestionWindow,
            connectionTiming,
        };
    }
}

// Copyright 2024 The Chromium Authors
const DEFAULT_SERVER_RESPONSE_TIME = 30;
const TLS_SCHEMES = ['https', 'wss'];
const CONNECTIONS_PER_ORIGIN = 6;
class ConnectionPool {
    options;
    records;
    connectionsByOrigin;
    connectionsByRequest;
    _connectionsInUse;
    connectionReusedByRequestId;
    constructor(records, options) {
        this.options = options;
        this.records = records;
        this.connectionsByOrigin = new Map();
        this.connectionsByRequest = new Map();
        this._connectionsInUse = new Set();
        this.connectionReusedByRequestId = NetworkAnalyzer.estimateIfConnectionWasReused(records, {
            forceCoarseEstimates: true,
        });
        this.initializeConnections();
    }
    connectionsInUse() {
        return Array.from(this._connectionsInUse);
    }
    initializeConnections() {
        const connectionReused = this.connectionReusedByRequestId;
        const additionalRttByOrigin = this.options.additionalRttByOrigin;
        const serverResponseTimeByOrigin = this.options.serverResponseTimeByOrigin;
        const recordsByOrigin = NetworkAnalyzer.groupByOrigin(this.records);
        for (const [origin, requests] of recordsByOrigin.entries()) {
            const connections = [];
            const additionalRtt = additionalRttByOrigin.get(origin) || 0;
            const responseTime = serverResponseTimeByOrigin.get(origin) || DEFAULT_SERVER_RESPONSE_TIME;
            for (const request of requests) {
                if (connectionReused.get(request.requestId)) {
                    continue;
                }
                const isTLS = TLS_SCHEMES.includes(request.parsedURL.scheme);
                const isH2 = request.protocol === 'h2';
                const connection = new TCPConnection(this.options.rtt + additionalRtt, this.options.throughput, responseTime, isTLS, isH2);
                connections.push(connection);
            }
            if (!connections.length) {
                throw new LanternError(`Could not find a connection for origin: ${origin}`);
            }
            const minConnections = connections[0].isH2() ? 1 : CONNECTIONS_PER_ORIGIN;
            while (connections.length < minConnections) {
                connections.push(connections[0].clone());
            }
            this.connectionsByOrigin.set(origin, connections);
        }
    }
    findAvailableConnectionWithLargestCongestionWindow(connections) {
        let maxConnection = null;
        for (let i = 0; i < connections.length; i++) {
            const connection = connections[i];
            if (this._connectionsInUse.has(connection)) {
                continue;
            }
            const currentMax = (maxConnection?.congestionWindow) || -Infinity;
            if (connection.congestionWindow > currentMax) {
                maxConnection = connection;
            }
        }
        return maxConnection;
    }
    acquire(request) {
        if (this.connectionsByRequest.has(request)) {
            throw new LanternError('Record already has a connection');
        }
        const origin = request.parsedURL.securityOrigin;
        const connections = this.connectionsByOrigin.get(origin) || [];
        const connectionToUse = this.findAvailableConnectionWithLargestCongestionWindow(connections);
        if (!connectionToUse) {
            return null;
        }
        this._connectionsInUse.add(connectionToUse);
        this.connectionsByRequest.set(request, connectionToUse);
        return connectionToUse;
    }
    acquireActiveConnectionFromRequest(request) {
        const activeConnection = this.connectionsByRequest.get(request);
        if (!activeConnection) {
            throw new LanternError('Could not find an active connection for request');
        }
        return activeConnection;
    }
    release(request) {
        const connection = this.connectionsByRequest.get(request);
        this.connectionsByRequest.delete(request);
        if (connection) {
            this._connectionsInUse.delete(connection);
        }
    }
}

// Copyright 2024 The Chromium Authors
const DEVTOOLS_RTT_ADJUSTMENT_FACTOR = 3.75;
const DEVTOOLS_THROUGHPUT_ADJUSTMENT_FACTOR = 0.9;
const throttling = {
    DEVTOOLS_RTT_ADJUSTMENT_FACTOR,
    DEVTOOLS_THROUGHPUT_ADJUSTMENT_FACTOR,
    mobileSlow4G: {
        rttMs: 150,
        throughputKbps: 1.6 * 1024,
        requestLatencyMs: 150 * DEVTOOLS_RTT_ADJUSTMENT_FACTOR,
        downloadThroughputKbps: 1.6 * 1024 * DEVTOOLS_THROUGHPUT_ADJUSTMENT_FACTOR,
        uploadThroughputKbps: 750 * DEVTOOLS_THROUGHPUT_ADJUSTMENT_FACTOR,
        cpuSlowdownMultiplier: 4,
    },
    mobileRegular3G: {
        rttMs: 300,
        throughputKbps: 700,
        requestLatencyMs: 300 * DEVTOOLS_RTT_ADJUSTMENT_FACTOR,
        downloadThroughputKbps: 700 * DEVTOOLS_THROUGHPUT_ADJUSTMENT_FACTOR,
        uploadThroughputKbps: 700 * DEVTOOLS_THROUGHPUT_ADJUSTMENT_FACTOR,
        cpuSlowdownMultiplier: 4,
    },
    desktopDense4G: {
        rttMs: 40,
        throughputKbps: 10 * 1024,
        cpuSlowdownMultiplier: 1,
        requestLatencyMs: 0,
        downloadThroughputKbps: 0,
        uploadThroughputKbps: 0,
    },
};
const Constants = { throttling };

// Copyright 2024 The Chromium Authors
const DNS_RESOLUTION_RTT_MULTIPLIER = 2;
class DNSCache {
    static rttMultiplier = DNS_RESOLUTION_RTT_MULTIPLIER;
    rtt;
    resolvedDomainNames;
    constructor({ rtt }) {
        this.rtt = rtt;
        this.resolvedDomainNames = new Map();
    }
    getTimeUntilResolution(request, options) {
        const { requestedAt = 0, shouldUpdateCache = false } = options || {};
        const domain = request.parsedURL.host;
        const cacheEntry = this.resolvedDomainNames.get(domain);
        let timeUntilResolved = this.rtt * DNSCache.rttMultiplier;
        if (cacheEntry) {
            const timeUntilCachedIsResolved = Math.max(cacheEntry.resolvedAt - requestedAt, 0);
            timeUntilResolved = Math.min(timeUntilCachedIsResolved, timeUntilResolved);
        }
        const resolvedAt = requestedAt + timeUntilResolved;
        if (shouldUpdateCache) {
            this.updateCacheResolvedAtIfNeeded(request, resolvedAt);
        }
        return timeUntilResolved;
    }
    updateCacheResolvedAtIfNeeded(request, resolvedAt) {
        const domain = request.parsedURL.host;
        const cacheEntry = this.resolvedDomainNames.get(domain) || { resolvedAt };
        cacheEntry.resolvedAt = Math.min(cacheEntry.resolvedAt, resolvedAt);
        this.resolvedDomainNames.set(domain, cacheEntry);
    }
    setResolvedAt(domain, resolvedAt) {
        this.resolvedDomainNames.set(domain, { resolvedAt });
    }
}

// Copyright 2024 The Chromium Authors
class SimulatorTimingMap {
    nodeTimings;
    constructor() {
        this.nodeTimings = new Map();
    }
    getNodes() {
        return Array.from(this.nodeTimings.keys());
    }
    setReadyToStart(node, values) {
        this.nodeTimings.set(node, values);
    }
    setInProgress(node, values) {
        const nodeTiming = {
            ...this.getQueued(node),
            startTime: values.startTime,
            timeElapsed: 0,
        };
        this.nodeTimings.set(node, node.type === BaseNode.types.NETWORK ? { ...nodeTiming, timeElapsedOvershoot: 0, bytesDownloaded: 0 } :
            nodeTiming);
    }
    setCompleted(node, values) {
        const nodeTiming = {
            ...this.getInProgress(node),
            endTime: values.endTime,
            connectionTiming: values.connectionTiming,
        };
        this.nodeTimings.set(node, nodeTiming);
    }
    setCpu(node, values) {
        const nodeTiming = {
            ...this.getCpuStarted(node),
            timeElapsed: values.timeElapsed,
        };
        this.nodeTimings.set(node, nodeTiming);
    }
    setCpuEstimated(node, values) {
        const nodeTiming = {
            ...this.getCpuStarted(node),
            estimatedTimeElapsed: values.estimatedTimeElapsed,
        };
        this.nodeTimings.set(node, nodeTiming);
    }
    setNetwork(node, values) {
        const nodeTiming = {
            ...this.getNetworkStarted(node),
            timeElapsed: values.timeElapsed,
            timeElapsedOvershoot: values.timeElapsedOvershoot,
            bytesDownloaded: values.bytesDownloaded,
        };
        this.nodeTimings.set(node, nodeTiming);
    }
    setNetworkEstimated(node, values) {
        const nodeTiming = {
            ...this.getNetworkStarted(node),
            estimatedTimeElapsed: values.estimatedTimeElapsed,
        };
        this.nodeTimings.set(node, nodeTiming);
    }
    getQueued(node) {
        const timing = this.nodeTimings.get(node);
        if (!timing) {
            throw new LanternError(`Node ${node.id} not yet queued`);
        }
        return timing;
    }
    getCpuStarted(node) {
        const timing = this.nodeTimings.get(node);
        if (!timing) {
            throw new LanternError(`Node ${node.id} not yet queued`);
        }
        if (!('startTime' in timing)) {
            throw new LanternError(`Node ${node.id} not yet started`);
        }
        if ('bytesDownloaded' in timing) {
            throw new LanternError(`Node ${node.id} timing not valid`);
        }
        return timing;
    }
    getNetworkStarted(node) {
        const timing = this.nodeTimings.get(node);
        if (!timing) {
            throw new LanternError(`Node ${node.id} not yet queued`);
        }
        if (!('startTime' in timing)) {
            throw new LanternError(`Node ${node.id} not yet started`);
        }
        if (!('bytesDownloaded' in timing)) {
            throw new LanternError(`Node ${node.id} timing not valid`);
        }
        return timing;
    }
    getInProgress(node) {
        const timing = this.nodeTimings.get(node);
        if (!timing) {
            throw new LanternError(`Node ${node.id} not yet queued`);
        }
        if (!('startTime' in timing)) {
            throw new LanternError(`Node ${node.id} not yet started`);
        }
        if (!('estimatedTimeElapsed' in timing)) {
            throw new LanternError(`Node ${node.id} not yet in progress`);
        }
        return timing;
    }
    getCompleted(node) {
        const timing = this.nodeTimings.get(node);
        if (!timing) {
            throw new LanternError(`Node ${node.id} not yet queued`);
        }
        if (!('startTime' in timing)) {
            throw new LanternError(`Node ${node.id} not yet started`);
        }
        if (!('estimatedTimeElapsed' in timing)) {
            throw new LanternError(`Node ${node.id} not yet in progress`);
        }
        if (!('endTime' in timing)) {
            throw new LanternError(`Node ${node.id} not yet completed`);
        }
        return timing;
    }
}

// Copyright 2024 The Chromium Authors
const defaultThrottling = Constants.throttling.mobileSlow4G;
const DEFAULT_MAXIMUM_CONCURRENT_REQUESTS = 10;
const DEFAULT_LAYOUT_TASK_MULTIPLIER = 0.5;
const DEFAULT_MAXIMUM_CPU_TASK_DURATION = 10000;
const NodeState = {
    NotReadyToStart: 0,
    ReadyToStart: 1,
    InProgress: 2,
    Complete: 3,
};
const PriorityStartTimePenalty = {
    VeryHigh: 0,
    High: 0.25,
    Medium: 0.5,
    Low: 1,
    VeryLow: 2,
};
const ALL_SIMULATION_NODE_TIMINGS = new Map();
class Simulator {
    static createSimulator(settings) {
        const { throttlingMethod, throttling, precomputedLanternData, networkAnalysis } = settings;
        const options = {
            additionalRttByOrigin: networkAnalysis.additionalRttByOrigin,
            serverResponseTimeByOrigin: networkAnalysis.serverResponseTimeByOrigin,
            observedThroughput: networkAnalysis.throughput,
        };
        if (precomputedLanternData) {
            options.additionalRttByOrigin = new Map(Object.entries(precomputedLanternData.additionalRttByOrigin));
            options.serverResponseTimeByOrigin = new Map(Object.entries(precomputedLanternData.serverResponseTimeByOrigin));
        }
        switch (throttlingMethod) {
            case 'provided':
                options.rtt = networkAnalysis.rtt;
                options.throughput = networkAnalysis.throughput;
                options.cpuSlowdownMultiplier = 1;
                options.layoutTaskMultiplier = 1;
                break;
            case 'devtools':
                if (throttling) {
                    options.rtt = throttling.requestLatencyMs / Constants.throttling.DEVTOOLS_RTT_ADJUSTMENT_FACTOR;
                    options.throughput =
                        throttling.downloadThroughputKbps * 1024 / Constants.throttling.DEVTOOLS_THROUGHPUT_ADJUSTMENT_FACTOR;
                }
                options.cpuSlowdownMultiplier = 1;
                options.layoutTaskMultiplier = 1;
                break;
            case 'simulate':
                if (throttling) {
                    options.rtt = throttling.rttMs;
                    options.throughput = throttling.throughputKbps * 1024;
                    options.cpuSlowdownMultiplier = throttling.cpuSlowdownMultiplier;
                }
                break;
        }
        return new Simulator(options);
    }
    options;
    _rtt;
    throughput;
    maximumConcurrentRequests;
    cpuSlowdownMultiplier;
    layoutTaskMultiplier;
    cachedNodeListByStartPosition;
    nodeTimings;
    numberInProgressByType;
    nodes;
    dns;
    connectionPool;
    constructor(options) {
        this.options = Object.assign({
            rtt: defaultThrottling.rttMs,
            throughput: defaultThrottling.throughputKbps * 1024,
            maximumConcurrentRequests: DEFAULT_MAXIMUM_CONCURRENT_REQUESTS,
            cpuSlowdownMultiplier: defaultThrottling.cpuSlowdownMultiplier,
            layoutTaskMultiplier: DEFAULT_LAYOUT_TASK_MULTIPLIER,
            additionalRttByOrigin: new Map(),
            serverResponseTimeByOrigin: new Map(),
        }, options);
        this._rtt = this.options.rtt;
        this.throughput = this.options.throughput;
        this.maximumConcurrentRequests = Math.max(Math.min(TCPConnection.maximumSaturatedConnections(this._rtt, this.throughput), this.options.maximumConcurrentRequests), 1);
        this.cpuSlowdownMultiplier = this.options.cpuSlowdownMultiplier;
        this.layoutTaskMultiplier = this.cpuSlowdownMultiplier * this.options.layoutTaskMultiplier;
        this.cachedNodeListByStartPosition = [];
        this.nodeTimings = new SimulatorTimingMap();
        this.numberInProgressByType = new Map();
        this.nodes = {};
        this.dns = new DNSCache({ rtt: this._rtt });
        this.connectionPool = null;
        if (!Number.isFinite(this._rtt)) {
            throw new LanternError(`Invalid rtt ${this._rtt}`);
        }
        if (!Number.isFinite(this.throughput)) {
            throw new LanternError(`Invalid throughput ${this.throughput}`);
        }
    }
    get rtt() {
        return this._rtt;
    }
    initializeConnectionPool(graph$1) {
        const records = [];
        graph$1.getRootNode().traverse(node => {
            if (node.type === BaseNode.types.NETWORK) {
                records.push(node.request);
            }
        });
        this.connectionPool = new ConnectionPool(records, this.options);
    }
    initializeAuxiliaryData() {
        this.nodeTimings = new SimulatorTimingMap();
        this.numberInProgressByType = new Map();
        this.nodes = {};
        this.cachedNodeListByStartPosition = [];
        for (const state of Object.values(NodeState)) {
            this.nodes[state] = new Set();
        }
    }
    numberInProgress(type) {
        return this.numberInProgressByType.get(type) || 0;
    }
    markNodeAsReadyToStart(node, queuedTime) {
        const nodeStartPosition = Simulator.computeNodeStartPosition(node);
        const firstNodeIndexWithGreaterStartPosition = this.cachedNodeListByStartPosition.findIndex(candidate => Simulator.computeNodeStartPosition(candidate) > nodeStartPosition);
        const insertionIndex = firstNodeIndexWithGreaterStartPosition === -1 ? this.cachedNodeListByStartPosition.length :
            firstNodeIndexWithGreaterStartPosition;
        this.cachedNodeListByStartPosition.splice(insertionIndex, 0, node);
        this.nodes[NodeState.ReadyToStart].add(node);
        this.nodes[NodeState.NotReadyToStart].delete(node);
        this.nodeTimings.setReadyToStart(node, { queuedTime });
    }
    markNodeAsInProgress(node, startTime) {
        const indexOfNodeToStart = this.cachedNodeListByStartPosition.indexOf(node);
        this.cachedNodeListByStartPosition.splice(indexOfNodeToStart, 1);
        this.nodes[NodeState.InProgress].add(node);
        this.nodes[NodeState.ReadyToStart].delete(node);
        this.numberInProgressByType.set(node.type, this.numberInProgress(node.type) + 1);
        this.nodeTimings.setInProgress(node, { startTime });
    }
    markNodeAsComplete(node, endTime, connectionTiming) {
        this.nodes[NodeState.Complete].add(node);
        this.nodes[NodeState.InProgress].delete(node);
        this.numberInProgressByType.set(node.type, this.numberInProgress(node.type) - 1);
        this.nodeTimings.setCompleted(node, { endTime, connectionTiming });
        for (const dependent of node.getDependents()) {
            const dependencies = dependent.getDependencies();
            if (dependencies.some(dep => !this.nodes[NodeState.Complete].has(dep))) {
                continue;
            }
            this.markNodeAsReadyToStart(dependent, endTime);
        }
    }
    acquireConnection(request) {
        return this.connectionPool.acquire(request);
    }
    getNodesSortedByStartPosition() {
        return Array.from(this.cachedNodeListByStartPosition);
    }
    startNodeIfPossible(node, totalElapsedTime) {
        if (node.type === BaseNode.types.CPU) {
            if (this.numberInProgress(node.type) === 0) {
                this.markNodeAsInProgress(node, totalElapsedTime);
            }
            return;
        }
        if (node.type !== BaseNode.types.NETWORK) {
            throw new LanternError('Unsupported');
        }
        if (!node.isConnectionless) {
            const numberOfActiveRequests = this.numberInProgress(node.type);
            if (numberOfActiveRequests >= this.maximumConcurrentRequests) {
                return;
            }
            const connection = this.acquireConnection(node.request);
            if (!connection) {
                return;
            }
        }
        this.markNodeAsInProgress(node, totalElapsedTime);
    }
    updateNetworkCapacity() {
        const inFlight = this.numberInProgress(BaseNode.types.NETWORK);
        if (inFlight === 0) {
            return;
        }
        for (const connection of this.connectionPool.connectionsInUse()) {
            connection.setThroughput(this.throughput / inFlight);
        }
    }
    estimateTimeRemaining(node) {
        if (node.type === BaseNode.types.CPU) {
            return this.estimateCPUTimeRemaining(node);
        }
        if (node.type === BaseNode.types.NETWORK) {
            return this.estimateNetworkTimeRemaining(node);
        }
        throw new LanternError('Unsupported');
    }
    estimateCPUTimeRemaining(cpuNode) {
        const timingData = this.nodeTimings.getCpuStarted(cpuNode);
        const multiplier = cpuNode.didPerformLayout() ? this.layoutTaskMultiplier : this.cpuSlowdownMultiplier;
        const totalDuration = Math.min(Math.round(cpuNode.duration / 1000 * multiplier), DEFAULT_MAXIMUM_CPU_TASK_DURATION);
        const estimatedTimeElapsed = totalDuration - timingData.timeElapsed;
        this.nodeTimings.setCpuEstimated(cpuNode, { estimatedTimeElapsed });
        return estimatedTimeElapsed;
    }
    estimateNetworkTimeRemaining(networkNode) {
        const request = networkNode.request;
        const timingData = this.nodeTimings.getNetworkStarted(networkNode);
        let timeElapsed = 0;
        if (networkNode.fromDiskCache) {
            const sizeInMb = (request.resourceSize || 0) / 1024 / 1024;
            timeElapsed = 8 + 20 * sizeInMb - timingData.timeElapsed;
        }
        else if (networkNode.isNonNetworkProtocol) {
            const sizeInMb = (request.resourceSize || 0) / 1024 / 1024;
            timeElapsed = 2 + 10 * sizeInMb - timingData.timeElapsed;
        }
        else {
            const connection = this.connectionPool.acquireActiveConnectionFromRequest(request);
            const dnsResolutionTime = this.dns.getTimeUntilResolution(request, {
                requestedAt: timingData.startTime,
                shouldUpdateCache: true,
            });
            const timeAlreadyElapsed = timingData.timeElapsed;
            const calculation = connection.simulateDownloadUntil(request.transferSize - timingData.bytesDownloaded, { timeAlreadyElapsed, dnsResolutionTime, maximumTimeToElapse: Infinity });
            timeElapsed = calculation.timeElapsed;
        }
        const estimatedTimeElapsed = timeElapsed + timingData.timeElapsedOvershoot;
        this.nodeTimings.setNetworkEstimated(networkNode, { estimatedTimeElapsed });
        return estimatedTimeElapsed;
    }
    findNextNodeCompletionTime() {
        let minimumTime = Infinity;
        for (const node of this.nodes[NodeState.InProgress]) {
            minimumTime = Math.min(minimumTime, this.estimateTimeRemaining(node));
        }
        return minimumTime;
    }
    updateProgressMadeInTimePeriod(node, timePeriodLength, totalElapsedTime) {
        const timingData = this.nodeTimings.getInProgress(node);
        const isFinished = timingData.estimatedTimeElapsed === timePeriodLength;
        if (node.type === BaseNode.types.CPU || node.isConnectionless) {
            if (isFinished) {
                this.markNodeAsComplete(node, totalElapsedTime);
            }
            else {
                timingData.timeElapsed += timePeriodLength;
            }
            return;
        }
        if (node.type !== BaseNode.types.NETWORK) {
            throw new LanternError('Unsupported');
        }
        if (!('bytesDownloaded' in timingData)) {
            throw new LanternError('Invalid timing data');
        }
        const request = node.request;
        const connection = this.connectionPool.acquireActiveConnectionFromRequest(request);
        const dnsResolutionTime = this.dns.getTimeUntilResolution(request, {
            requestedAt: timingData.startTime,
            shouldUpdateCache: true,
        });
        const calculation = connection.simulateDownloadUntil(request.transferSize - timingData.bytesDownloaded, {
            dnsResolutionTime,
            timeAlreadyElapsed: timingData.timeElapsed,
            maximumTimeToElapse: timePeriodLength - timingData.timeElapsedOvershoot,
        });
        connection.setCongestionWindow(calculation.congestionWindow);
        connection.setH2OverflowBytesDownloaded(calculation.extraBytesDownloaded);
        if (isFinished) {
            connection.setWarmed(true);
            this.connectionPool.release(request);
            this.markNodeAsComplete(node, totalElapsedTime, calculation.connectionTiming);
        }
        else {
            timingData.timeElapsed += calculation.timeElapsed;
            timingData.timeElapsedOvershoot += calculation.timeElapsed - timePeriodLength;
            timingData.bytesDownloaded += calculation.bytesDownloaded;
        }
    }
    computeFinalNodeTimings() {
        const completeNodeTimingEntries = this.nodeTimings.getNodes().map(node => {
            return [node, this.nodeTimings.getCompleted(node)];
        });
        completeNodeTimingEntries.sort((a, b) => a[1].startTime - b[1].startTime);
        const nodeTimingEntries = completeNodeTimingEntries.map(([node, timing]) => {
            return [
                node,
                {
                    startTime: timing.startTime,
                    endTime: timing.endTime,
                    duration: timing.endTime - timing.startTime,
                },
            ];
        });
        return {
            nodeTimings: new Map(nodeTimingEntries),
            completeNodeTimings: new Map(completeNodeTimingEntries),
        };
    }
    getOptions() {
        return this.options;
    }
    simulate(graph$1, options) {
        if (BaseNode.findCycle(graph$1)) {
            throw new LanternError('Cannot simulate graph with cycle');
        }
        options = Object.assign({
            label: undefined,
        }, options);
        this.dns = new DNSCache({ rtt: this._rtt });
        this.initializeConnectionPool(graph$1);
        this.initializeAuxiliaryData();
        const nodesNotReadyToStart = this.nodes[NodeState.NotReadyToStart];
        const nodesReadyToStart = this.nodes[NodeState.ReadyToStart];
        const nodesInProgress = this.nodes[NodeState.InProgress];
        const rootNode = graph$1.getRootNode();
        rootNode.traverse(node => nodesNotReadyToStart.add(node));
        let totalElapsedTime = 0;
        let iteration = 0;
        this.markNodeAsReadyToStart(rootNode, totalElapsedTime);
        while (nodesReadyToStart.size || nodesInProgress.size) {
            for (const node of this.getNodesSortedByStartPosition()) {
                this.startNodeIfPossible(node, totalElapsedTime);
            }
            if (!nodesInProgress.size) {
                throw new LanternError('Failed to start a node');
            }
            this.updateNetworkCapacity();
            const minimumTime = this.findNextNodeCompletionTime();
            totalElapsedTime += minimumTime;
            if (!Number.isFinite(minimumTime) || iteration > 100000) {
                throw new LanternError('Simulation failed, depth exceeded');
            }
            iteration++;
            for (const node of nodesInProgress) {
                this.updateProgressMadeInTimePeriod(node, minimumTime, totalElapsedTime);
            }
        }
        const { nodeTimings, completeNodeTimings } = this.computeFinalNodeTimings();
        ALL_SIMULATION_NODE_TIMINGS.set(options.label || 'unlabeled', completeNodeTimings);
        return {
            timeInMs: totalElapsedTime,
            nodeTimings,
        };
    }
    computeWastedMsFromWastedBytes(wastedBytes) {
        const { throughput, observedThroughput } = this.options;
        const bitsPerSecond = throughput === 0 ? observedThroughput : throughput;
        if (bitsPerSecond === 0) {
            return 0;
        }
        const wastedBits = wastedBytes * 8;
        const wastedMs = wastedBits / bitsPerSecond * 1000;
        return Math.round(wastedMs / 10) * 10;
    }
    static get allNodeTimings() {
        return ALL_SIMULATION_NODE_TIMINGS;
    }
    static computeNodeStartPosition(node) {
        if (node.type === 'cpu') {
            return node.startTime;
        }
        return node.startTime + (PriorityStartTimePenalty[node.request.priority] * 1000 * 1000 || 0);
    }
}

// Copyright 2024 The Chromium Authors

var simulation = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ConnectionPool: ConnectionPool,
	Constants: Constants,
	DNSCache: DNSCache,
	Simulator: Simulator,
	SimulatorTimingMap: SimulatorTimingMap,
	TCPConnection: TCPConnection
});

// Copyright 2024 The Chromium Authors
const NetworkRequestTypes = {
    XHR: 'XHR',
    Fetch: 'Fetch',
    EventSource: 'EventSource',
    Script: 'Script',
    Stylesheet: 'Stylesheet',
    Image: 'Image',
    Media: 'Media',
    Font: 'Font',
    Document: 'Document',
    TextTrack: 'TextTrack',
    WebSocket: 'WebSocket',
    Other: 'Other',
    Manifest: 'Manifest',
    SignedExchange: 'SignedExchange',
    Ping: 'Ping',
    Preflight: 'Preflight',
    CSPViolationReport: 'CSPViolationReport',
    Prefetch: 'Prefetch',
    FedCM: 'FedCM',
};

// Copyright 2024 The Chromium Authors

var types = /*#__PURE__*/Object.freeze({
	__proto__: null,
	NetworkRequestTypes: NetworkRequestTypes
});

// Copyright 2024 The Chromium Authors

var lantern = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Core: core,
	Graph: graph,
	Metrics: metrics$1,
	Simulation: simulation,
	Types: types
});

// Copyright 2024 The Chromium Authors
function createProcessedNavigation(data, frameId, navigation) {
    const scoresByNav = data.PageLoadMetrics.metricScoresByFrameId.get(frameId);
    if (!scoresByNav) {
        throw new LanternError('missing metric scores for frame');
    }
    const scores = scoresByNav.get(navigation);
    if (!scores) {
        throw new LanternError('missing metric scores for specified navigation');
    }
    const getTimestampOrUndefined = (metric) => {
        const metricScore = scores.get(metric);
        if (!metricScore?.event) {
            return;
        }
        return metricScore.event.ts;
    };
    const getTimestamp = (metric) => {
        const metricScore = scores.get(metric);
        if (!metricScore?.event) {
            throw new LanternError(`missing metric: ${metric}`);
        }
        return metricScore.event.ts;
    };
    return {
        timestamps: {
            firstContentfulPaint: getTimestamp("FCP" ),
            largestContentfulPaint: getTimestampOrUndefined("LCP" ),
        },
    };
}
function createParsedUrl(url) {
    if (typeof url === 'string') {
        url = new URL(url);
    }
    return {
        scheme: url.protocol.split(':')[0],
        host: url.hostname,
        securityOrigin: url.origin,
    };
}
function findWorkerThreads(trace) {
    const workerThreads = new Map();
    const workerCreationEvents = ['ServiceWorker thread', 'DedicatedWorker thread'];
    for (const event of trace.traceEvents) {
        if (event.name !== 'thread_name' || !event.args.name) {
            continue;
        }
        if (!workerCreationEvents.includes(event.args.name)) {
            continue;
        }
        const tids = workerThreads.get(event.pid);
        if (tids) {
            tids.push(event.tid);
        }
        else {
            workerThreads.set(event.pid, [event.tid]);
        }
    }
    return workerThreads;
}
function createLanternRequest(parsedTrace, workerThreads, request) {
    if (request.args.data.hasResponse && request.args.data.connectionId === undefined) {
        throw new LanternError('Trace is too old');
    }
    let url;
    try {
        url = new URL(request.args.data.url);
    }
    catch {
        return;
    }
    const timing = request.args.data.timing ? {
        workerFetchStart: -1,
        workerRespondWithSettled: -1,
        receiveHeadersStart: -1,
        ...request.args.data.timing,
    } :
        undefined;
    const networkRequestTime = timing ? timing.requestTime * 1000 : request.args.data.syntheticData.downloadStart / 1000;
    let fromWorker = false;
    const tids = workerThreads.get(request.pid);
    if (tids?.includes(request.tid)) {
        fromWorker = true;
    }
    if (parsedTrace.Workers.workerIdByThread.has(request.tid)) {
        fromWorker = true;
    }
    const initiator = request.args.data.initiator ?? { type: "other"  };
    if (request.args.data.stackTrace) {
        const callFrames = request.args.data.stackTrace.map(f => {
            return {
                scriptId: String(f.scriptId),
                url: f.url,
                lineNumber: f.lineNumber - 1,
                columnNumber: f.columnNumber - 1,
                functionName: f.functionName,
            };
        });
        initiator.stack = { callFrames };
    }
    let resourceType = request.args.data.resourceType;
    if (request.args.data.initiator?.fetchType === 'xmlhttprequest') {
        resourceType = 'XHR';
    }
    else if (request.args.data.initiator?.fetchType === 'fetch') {
        resourceType = 'Fetch';
    }
    let resourceSize = request.args.data.decodedBodyLength ?? 0;
    if (url.protocol === 'data:' && resourceSize === 0) {
        const commaIndex = url.pathname.indexOf(',');
        if (url.pathname.substring(0, commaIndex).includes(';base64')) {
            resourceSize = atob(url.pathname.substring(commaIndex + 1)).length;
        }
        else {
            resourceSize = url.pathname.length - commaIndex - 1;
        }
    }
    return {
        rawRequest: request,
        requestId: request.args.data.requestId,
        connectionId: request.args.data.connectionId ?? 0,
        connectionReused: request.args.data.connectionReused ?? false,
        url: request.args.data.url,
        protocol: request.args.data.protocol,
        parsedURL: createParsedUrl(url),
        documentURL: request.args.data.requestingFrameUrl,
        rendererStartTime: request.ts / 1000,
        networkRequestTime,
        responseHeadersEndTime: request.args.data.syntheticData.downloadStart / 1000,
        networkEndTime: request.args.data.syntheticData.finishTime / 1000,
        transferSize: request.args.data.encodedDataLength,
        resourceSize,
        fromDiskCache: request.args.data.syntheticData.isDiskCached,
        fromMemoryCache: request.args.data.syntheticData.isMemoryCached,
        isLinkPreload: request.args.data.isLinkPreload,
        finished: request.args.data.finished,
        failed: request.args.data.failed,
        statusCode: request.args.data.statusCode,
        initiator,
        timing,
        resourceType,
        mimeType: request.args.data.mimeType,
        priority: request.args.data.priority,
        frameId: request.args.data.frame,
        fromWorker,
        serverResponseTime: request.args.data.lrServerResponseTime,
    };
}
function chooseInitiatorRequest(request, requestsByURL) {
    if (request.redirectSource) {
        return request.redirectSource;
    }
    const initiatorURL = PageDependencyGraph.getNetworkInitiators(request)[0];
    let candidates = requestsByURL.get(initiatorURL) || [];
    candidates = candidates.filter(c => {
        return c.responseHeadersEndTime <= request.rendererStartTime && c.finished && !c.failed;
    });
    if (candidates.length > 1) {
        const nonPrefetchCandidates = candidates.filter(cand => cand.resourceType !== NetworkRequestTypes.Other);
        if (nonPrefetchCandidates.length) {
            candidates = nonPrefetchCandidates;
        }
    }
    if (candidates.length > 1) {
        const sameFrameCandidates = candidates.filter(cand => cand.frameId === request.frameId);
        if (sameFrameCandidates.length) {
            candidates = sameFrameCandidates;
        }
    }
    if (candidates.length > 1 && request.initiator.type === 'parser') {
        const documentCandidates = candidates.filter(cand => cand.resourceType === NetworkRequestTypes.Document);
        if (documentCandidates.length) {
            candidates = documentCandidates;
        }
    }
    if (candidates.length > 1) {
        const linkPreloadCandidates = candidates.filter(c => c.isLinkPreload);
        if (linkPreloadCandidates.length) {
            const nonPreloadCandidates = candidates.filter(c => !c.isLinkPreload);
            const allPreloaded = nonPreloadCandidates.every(c => c.fromDiskCache || c.fromMemoryCache);
            if (nonPreloadCandidates.length && allPreloaded) {
                candidates = linkPreloadCandidates;
            }
        }
    }
    return candidates.length === 1 ? candidates[0] : null;
}
function linkInitiators(lanternRequests) {
    const requestsByURL = new Map();
    for (const request of lanternRequests) {
        const requests = requestsByURL.get(request.url) || [];
        requests.push(request);
        requestsByURL.set(request.url, requests);
    }
    for (const request of lanternRequests) {
        const initiatorRequest = chooseInitiatorRequest(request, requestsByURL);
        if (initiatorRequest) {
            request.initiatorRequest = initiatorRequest;
        }
    }
}
function createNetworkRequests(trace, data, startTime = 0, endTime = Number.POSITIVE_INFINITY) {
    const workerThreads = findWorkerThreads(trace);
    const lanternRequestsNoRedirects = [];
    for (const request of data.NetworkRequests.byTime) {
        if (request.ts >= startTime && request.ts < endTime) {
            const lanternRequest = createLanternRequest(data, workerThreads, request);
            if (lanternRequest) {
                lanternRequestsNoRedirects.push(lanternRequest);
            }
        }
    }
    const lanternRequests = [];
    for (const request of [...lanternRequestsNoRedirects]) {
        if (!request.rawRequest) {
            continue;
        }
        const redirects = request.rawRequest.args.data.redirects;
        if (!redirects.length) {
            lanternRequests.push(request);
            continue;
        }
        const requestChain = [];
        for (const redirect of redirects) {
            const redirectedRequest = structuredClone(request);
            redirectedRequest.networkRequestTime = redirect.ts / 1000;
            redirectedRequest.rendererStartTime = redirectedRequest.networkRequestTime;
            redirectedRequest.networkEndTime = (redirect.ts + redirect.dur) / 1000;
            redirectedRequest.responseHeadersEndTime = redirectedRequest.networkEndTime;
            redirectedRequest.timing = {
                requestTime: redirectedRequest.networkRequestTime / 1000,
                receiveHeadersStart: redirectedRequest.responseHeadersEndTime,
                receiveHeadersEnd: redirectedRequest.responseHeadersEndTime,
                proxyStart: -1,
                proxyEnd: -1,
                dnsStart: -1,
                dnsEnd: -1,
                connectStart: -1,
                connectEnd: -1,
                sslStart: -1,
                sslEnd: -1,
                sendStart: -1,
                sendEnd: -1,
                workerStart: -1,
                workerReady: -1,
                workerFetchStart: -1,
                workerRespondWithSettled: -1,
                pushStart: -1,
                pushEnd: -1,
            };
            redirectedRequest.url = redirect.url;
            redirectedRequest.parsedURL = createParsedUrl(redirect.url);
            redirectedRequest.statusCode = 302;
            redirectedRequest.resourceType = undefined;
            redirectedRequest.transferSize = 400;
            requestChain.push(redirectedRequest);
            lanternRequests.push(redirectedRequest);
        }
        requestChain.push(request);
        lanternRequests.push(request);
        for (let i = 0; i < requestChain.length; i++) {
            const request = requestChain[i];
            if (i > 0) {
                request.redirectSource = requestChain[i - 1];
                request.redirects = requestChain.slice(0, i);
            }
            if (i !== requestChain.length - 1) {
                request.redirectDestination = requestChain[i + 1];
            }
        }
        for (let i = 1; i < requestChain.length; i++) {
            requestChain[i].requestId = `${requestChain[i - 1].requestId}:redirect`;
        }
    }
    linkInitiators(lanternRequests);
    return lanternRequests;
}
function collectMainThreadEvents(trace, data) {
    const Meta = data.Meta;
    const mainFramePids = Meta.mainFrameNavigations.length ? new Set(Meta.mainFrameNavigations.map(nav => nav.pid)) :
        Meta.topLevelRendererIds;
    const rendererPidToTid = new Map();
    for (const pid of mainFramePids) {
        const threads = Meta.threadsInProcess.get(pid) ?? [];
        let found = false;
        for (const [tid, thread] of threads) {
            if (thread.args.name === 'CrRendererMain') {
                rendererPidToTid.set(pid, tid);
                found = true;
                break;
            }
        }
        if (found) {
            continue;
        }
        for (const [tid, thread] of threads) {
            if (thread.args.name === 'CrBrowserMain') {
                rendererPidToTid.set(pid, tid);
                found = true;
                break;
            }
        }
    }
    return trace.traceEvents.filter(e => rendererPidToTid.get(e.pid) === e.tid);
}
function createGraph(requests, trace, data, url) {
    const mainThreadEvents = collectMainThreadEvents(trace, data);
    if (!url) {
        url = {
            requestedUrl: requests[0].url,
            mainDocumentUrl: '',
        };
        let request = requests[0];
        while (request.redirectDestination) {
            request = request.redirectDestination;
        }
        url.mainDocumentUrl = request.url;
    }
    return PageDependencyGraph.createGraph(mainThreadEvents, requests, url);
}

var LanternComputationData = /*#__PURE__*/Object.freeze({
	__proto__: null,
	createGraph: createGraph,
	createNetworkRequests: createNetworkRequests,
	createProcessedNavigation: createProcessedNavigation
});

// Copyright 2023 The Chromium Authors
var _a$2;
class TraceParseProgressEvent extends Event {
    data;
    static eventName = 'traceparseprogress';
    constructor(data, init = { bubbles: true }) {
        super(TraceParseProgressEvent.eventName, init);
        this.data = data;
    }
}
function calculateProgress(value, phase) {
    if (phase === 0.8 ) {
        return (value * (0.8  - 0.2 )) + 0.2 ;
    }
    return value * phase;
}
class TraceProcessor extends EventTarget {
    #traceHandlers;
    #status = "IDLE" ;
    #modelConfiguration = defaults();
    #data = null;
    #insights = null;
    static createWithAllHandlers() {
        return new _a$2(ModelHandlers, defaults());
    }
    static getInsightRunners() {
        return { ...Models };
    }
    constructor(traceHandlers, modelConfiguration) {
        super();
        this.#verifyHandlers(traceHandlers);
        this.#traceHandlers = {
            Meta: MetaHandler,
            ...traceHandlers,
        };
        if (modelConfiguration) {
            this.#modelConfiguration = modelConfiguration;
        }
        this.#passConfigToHandlers();
    }
    #passConfigToHandlers() {
        for (const handler of Object.values(this.#traceHandlers)) {
            if ('handleUserConfig' in handler && handler.handleUserConfig) {
                handler.handleUserConfig(this.#modelConfiguration);
            }
        }
    }
    #verifyHandlers(providedHandlers) {
        if (Object.keys(providedHandlers).length === Object.keys(ModelHandlers).length) {
            return;
        }
        const requiredHandlerKeys = new Set();
        for (const [handlerName, handler] of Object.entries(providedHandlers)) {
            requiredHandlerKeys.add(handlerName);
            const deps = 'deps' in handler ? handler.deps() : [];
            for (const depName of deps) {
                requiredHandlerKeys.add(depName);
            }
        }
        const providedHandlerKeys = new Set(Object.keys(providedHandlers));
        requiredHandlerKeys.delete('Meta');
        for (const requiredKey of requiredHandlerKeys) {
            if (!providedHandlerKeys.has(requiredKey)) {
                throw new Error(`Required handler ${requiredKey} not provided.`);
            }
        }
    }
    reset() {
        if (this.#status === "PARSING" ) {
            throw new Error('Trace processor can\'t reset while parsing.');
        }
        const handlers = Object.values(this.#traceHandlers);
        for (const handler of handlers) {
            handler.reset();
        }
        this.#data = null;
        this.#insights = null;
        this.#status = "IDLE" ;
    }
    async parse(traceEvents, options) {
        if (this.#status !== "IDLE" ) {
            throw new Error(`Trace processor can't start parsing when not idle. Current state: ${this.#status}`);
        }
        if (typeof options.isCPUProfile === 'undefined' && options.metadata) {
            options.isCPUProfile = options.metadata.dataOrigin === "CPUProfile" ;
        }
        options.logger?.start('total');
        try {
            this.#status = "PARSING" ;
            options.logger?.start('parse');
            await this.#computeParsedTrace(traceEvents, options);
            options.logger?.end('parse');
            if (this.#data && !options.isCPUProfile) {
                options.logger?.start('insights');
                this.#computeInsights(this.#data, traceEvents, options);
                options.logger?.end('insights');
            }
            this.#status = "FINISHED_PARSING" ;
        }
        catch (e) {
            this.#status = "ERRORED_WHILE_PARSING" ;
            throw e;
        }
        finally {
            options.logger?.end('total');
        }
    }
    async #computeParsedTrace(traceEvents, options) {
        const eventsPerChunk = 50_000;
        const sortedHandlers = [...sortHandlers(this.#traceHandlers).entries()];
        for (const [, handler] of sortedHandlers) {
            handler.reset();
        }
        options.logger?.start('parse:handleEvent');
        for (let i = 0; i < traceEvents.length; ++i) {
            if (i % eventsPerChunk === 0 && i) {
                const percent = calculateProgress(i / traceEvents.length, 0.2 );
                this.dispatchEvent(new TraceParseProgressEvent({ percent }));
                await new Promise(resolve => setTimeout(resolve, 0));
            }
            const event = traceEvents[i];
            for (let j = 0; j < sortedHandlers.length; ++j) {
                const [, handler] = sortedHandlers[j];
                handler.handleEvent(event);
            }
        }
        options.logger?.end('parse:handleEvent');
        const finalizeOptions = {
            ...options,
            allTraceEvents: traceEvents,
        };
        for (let i = 0; i < sortedHandlers.length; i++) {
            const [name, handler] = sortedHandlers[i];
            if (handler.finalize) {
                options.logger?.start(`parse:${name}:finalize`);
                await new Promise(resolve => setTimeout(resolve, 0));
                await handler.finalize(finalizeOptions);
                options.logger?.end(`parse:${name}:finalize`);
            }
            const percent = calculateProgress(i / sortedHandlers.length, 0.8 );
            this.dispatchEvent(new TraceParseProgressEvent({ percent }));
        }
        options.logger?.start('parse:handler.data()');
        const parsedTrace = {};
        for (const [name, handler] of Object.entries(this.#traceHandlers)) {
            Object.assign(parsedTrace, { [name]: handler.data() });
        }
        options.logger?.end('parse:handler.data()');
        this.dispatchEvent(new TraceParseProgressEvent({ percent: 1  }));
        this.#data = parsedTrace;
    }
    get data() {
        if (this.#status !== "FINISHED_PARSING" ) {
            return null;
        }
        return this.#data;
    }
    get insights() {
        if (this.#status !== "FINISHED_PARSING" ) {
            return null;
        }
        return this.#insights;
    }
    #createLanternContext(data, traceEvents, frameId, navigation, options) {
        if (!data.NetworkRequests || !data.Workers || !data.PageLoadMetrics) {
            return;
        }
        if (!data.NetworkRequests.byTime.length) {
            throw new LanternError('No network requests found in trace');
        }
        const navStarts = data.Meta.navigationsByFrameId.get(frameId);
        const navStartIndex = navStarts?.findIndex(n => n === navigation);
        if (!navStarts || navStartIndex === undefined || navStartIndex === -1) {
            throw new LanternError('Could not find navigation start');
        }
        const startTime = navStarts[navStartIndex].ts;
        const endTime = navStartIndex + 1 < navStarts.length ? navStarts[navStartIndex + 1].ts : Number.POSITIVE_INFINITY;
        const boundedTraceEvents = traceEvents.filter(e => e.ts >= startTime && e.ts < endTime);
        const trace = {
            traceEvents: boundedTraceEvents,
        };
        const requests = createNetworkRequests(trace, data, startTime, endTime);
        const graph = createGraph(requests, trace, data);
        const processedNavigation = createProcessedNavigation(data, frameId, navigation);
        const networkAnalysis = NetworkAnalyzer.analyze(requests);
        if (!networkAnalysis) {
            return;
        }
        const lanternSettings = {
            networkAnalysis,
            throttlingMethod: 'provided',
            ...options.lanternSettings,
        };
        const simulator = Simulator.createSimulator(lanternSettings);
        const computeData = { graph, simulator, processedNavigation };
        const fcpResult = FirstContentfulPaint.compute(computeData);
        const lcpResult = LargestContentfulPaint.compute(computeData, { fcpResult });
        const interactiveResult = Interactive.compute(computeData, { lcpResult });
        const tbtResult = TotalBlockingTime.compute(computeData, { fcpResult, interactiveResult });
        const metrics = {
            firstContentfulPaint: fcpResult,
            interactive: interactiveResult,
            largestContentfulPaint: lcpResult,
            totalBlockingTime: tbtResult,
        };
        return { requests, graph, simulator, metrics };
    }
    sortInsightSet(insightSet, metadata) {
        const baselineOrder = {
            INPBreakdown: null,
            LCPBreakdown: null,
            LCPDiscovery: null,
            CLSCulprits: null,
            RenderBlocking: null,
            NetworkDependencyTree: null,
            ImageDelivery: null,
            DocumentLatency: null,
            FontDisplay: null,
            Viewport: null,
            DOMSize: null,
            ThirdParties: null,
            DuplicatedJavaScript: null,
            SlowCSSSelector: null,
            ForcedReflow: null,
            Cache: null,
            ModernHTTP: null,
            LegacyJavaScript: null,
        };
        const weights = calculateMetricWeightsForSorting(insightSet, metadata);
        const observedLcpMicro = getLCP(insightSet)?.value;
        const observedLcp = observedLcpMicro ? microToMilli(observedLcpMicro) : Milli(0);
        const observedCls = getCLS(insightSet).value;
        const observedInpMicro = getINP(insightSet)?.value;
        const observedInp = observedInpMicro ? microToMilli(observedInpMicro) : Milli(200);
        const observedLcpScore = observedLcp !== undefined ? evaluateLCPMetricScore(observedLcp) : undefined;
        const observedInpScore = evaluateINPMetricScore(observedInp);
        const observedClsScore = evaluateCLSMetricScore(observedCls);
        const insightToSortingRank = new Map();
        for (const [name, insight] of Object.entries(insightSet.model)) {
            const lcp = insight.metricSavings?.LCP ?? 0;
            const inp = insight.metricSavings?.INP ?? 0;
            const cls = insight.metricSavings?.CLS ?? 0;
            const lcpPostSavings = observedLcp !== undefined ? Math.max(0, observedLcp - lcp) : undefined;
            const inpPostSavings = Math.max(0, observedInp - inp);
            const clsPostSavings = Math.max(0, observedCls - cls);
            let score = 0;
            if (weights.lcp && lcp && observedLcpScore !== undefined && lcpPostSavings !== undefined) {
                score += weights.lcp * (evaluateLCPMetricScore(lcpPostSavings) - observedLcpScore);
            }
            if (weights.inp && inp && observedInpScore !== undefined) {
                score += weights.inp * (evaluateINPMetricScore(inpPostSavings) - observedInpScore);
            }
            if (weights.cls && cls && observedClsScore !== undefined) {
                score += weights.cls * (evaluateCLSMetricScore(clsPostSavings) - observedClsScore);
            }
            insightToSortingRank.set(name, score);
        }
        const baselineOrderKeys = Object.keys(baselineOrder);
        const orderedKeys = Object.keys(insightSet.model);
        orderedKeys.sort((a, b) => {
            const a1 = baselineOrderKeys.indexOf(a);
            const b1 = baselineOrderKeys.indexOf(b);
            if (a1 >= 0 && b1 >= 0) {
                return a1 - b1;
            }
            if (a1 >= 0) {
                return -1;
            }
            if (b1 >= 0) {
                return 1;
            }
            return 0;
        });
        orderedKeys.sort((a, b) => (insightToSortingRank.get(b) ?? 0) - (insightToSortingRank.get(a) ?? 0));
        const newModel = {};
        for (const key of orderedKeys) {
            const model = insightSet.model[key];
            newModel[key] = model;
        }
        insightSet.model = newModel;
    }
    #computeInsightSet(data, context) {
        const logger = context.options.logger;
        if (!this.#insights) {
            this.#insights = new Map();
        }
        let id, urlString, navigation;
        if (context.navigation) {
            id = `NAVIGATION_${this.#insights.size}`;
            urlString = data.Meta.finalDisplayUrlByNavigationId.get(context.navigationId) ?? data.Meta.mainFrameURL;
            navigation = context.navigation;
        }
        else {
            id = NO_NAVIGATION;
            urlString = data.Meta.finalDisplayUrlByNavigationId.get('') ?? data.Meta.mainFrameURL;
        }
        const insightSetModel = {};
        const insightSetModelErrors = {};
        for (const [name, insight] of Object.entries(_a$2.getInsightRunners())) {
            try {
                logger?.start(`insights:${name}`);
                const model = insight.generateInsight(data, context);
                model.frameId = context.frameId;
                const navId = context.navigation?.args.data?.navigationId;
                if (navId) {
                    model.navigation = context.navigation;
                }
                model.createOverlays = () => {
                    return insight.createOverlays(model);
                };
                Object.assign(insightSetModel, { [name]: model });
            }
            catch (err) {
                Object.assign(insightSetModelErrors, { [name]: err });
            }
            finally {
                logger?.end(`insights:${name}`);
            }
        }
        const isNavigation = id === NO_NAVIGATION;
        const trivialThreshold = milliToMicro(Milli(5000));
        const everyInsightPasses = Object.values(insightSetModel).every(model => model && model.state === 'pass');
        const noLcp = !insightSetModel.LCPBreakdown?.lcpEvent;
        const noInp = !insightSetModel.INPBreakdown?.longestInteractionEvent;
        const noLayoutShifts = insightSetModel.CLSCulprits?.shifts?.size === 0;
        const shouldExclude = isNavigation && context.bounds.range < trivialThreshold && everyInsightPasses && noLcp &&
            noInp && noLayoutShifts;
        if (shouldExclude) {
            return;
        }
        let url;
        try {
            url = new URL(urlString);
        }
        catch {
            return;
        }
        const insightSet = {
            id,
            url,
            navigation,
            frameId: context.frameId,
            bounds: context.bounds,
            model: insightSetModel,
            modelErrors: insightSetModelErrors,
        };
        this.#insights.set(insightSet.id, insightSet);
        this.sortInsightSet(insightSet, context.options.metadata ?? null);
    }
    #computeInsights(data, traceEvents, options) {
        this.#insights = new Map();
        const navigations = data.Meta.mainFrameNavigations.filter(navigation => navigation.args.frame && navigation.args.data?.navigationId);
        this.#computeInsightsForInitialTracePeriod(data, navigations, options);
        for (const [index, navigation] of navigations.entries()) {
            const min = navigation.ts;
            const max = index + 1 < navigations.length ? navigations[index + 1].ts : data.Meta.traceBounds.max;
            const bounds = traceWindowFromMicroSeconds(min, max);
            this.#computeInsightsForNavigation(navigation, bounds, data, traceEvents, options);
        }
    }
    #computeInsightsForInitialTracePeriod(data, navigations, options) {
        const bounds = navigations.length > 0 ?
            traceWindowFromMicroSeconds(data.Meta.traceBounds.min, navigations[0].ts) :
            data.Meta.traceBounds;
        const context = {
            options,
            bounds,
            frameId: data.Meta.mainFrameId,
        };
        this.#computeInsightSet(data, context);
    }
    #computeInsightsForNavigation(navigation, bounds, data, traceEvents, options) {
        const frameId = navigation.args.frame;
        const navigationId = navigation.args.data?.navigationId;
        let lantern$1;
        try {
            options.logger?.start('insights:createLanternContext');
            lantern$1 = this.#createLanternContext(data, traceEvents, frameId, navigation, options);
        }
        catch (e) {
            const expectedErrors = [
                'mainDocumentRequest not found',
                'missing metric scores for main frame',
                'missing metric: FCP',
                'missing metric: LCP',
                'No network requests found in trace',
                'Trace is too old',
            ];
            if (!(e instanceof LanternError)) {
                console.error(e);
            }
            else if (!expectedErrors.some(err => e.message === err)) {
                console.error(e);
            }
        }
        finally {
            options.logger?.end('insights:createLanternContext');
        }
        const context = {
            options,
            bounds,
            frameId,
            navigation,
            navigationId,
            lantern: lantern$1,
        };
        this.#computeInsightSet(data, context);
    }
}
_a$2 = TraceProcessor;
function sortHandlers(traceHandlers) {
    const sortedMap = new Map();
    const visited = new Set();
    const visitHandler = (handlerName) => {
        if (sortedMap.has(handlerName)) {
            return;
        }
        if (visited.has(handlerName)) {
            let stackPath = '';
            for (const handler of visited) {
                if (stackPath || handler === handlerName) {
                    stackPath += `${handler}->`;
                }
            }
            stackPath += handlerName;
            throw new Error(`Found dependency cycle in trace event handlers: ${stackPath}`);
        }
        visited.add(handlerName);
        const handler = traceHandlers[handlerName];
        if (!handler) {
            return;
        }
        const deps = handler.deps?.();
        if (deps) {
            deps.forEach(visitHandler);
        }
        sortedMap.set(handlerName, handler);
    };
    for (const handlerName of Object.keys(traceHandlers)) {
        visitHandler(handlerName);
    }
    return sortedMap;
}

var Processor = /*#__PURE__*/Object.freeze({
	__proto__: null,
	TraceParseProgressEvent: TraceParseProgressEvent,
	TraceProcessor: TraceProcessor,
	sortHandlers: sortHandlers
});

// Copyright 2022 The Chromium Authors
class Model extends EventTarget {
    #traces = [];
    #nextNumberByDomain = new Map();
    #recordingsAvailable = [];
    #lastRecordingIndex = 0;
    #processor;
    #config = defaults();
    static createWithAllHandlers(config) {
        return new Model(ModelHandlers, config);
    }
    static createWithSubsetOfHandlers(traceHandlers, config) {
        return new Model(traceHandlers, config);
    }
    constructor(handlers, config) {
        super();
        if (config) {
            this.#config = config;
        }
        this.#processor = new TraceProcessor(handlers, this.#config);
    }
    async parse(traceEvents, config = {}) {
        if (config.showAllEvents === undefined) {
            config.showAllEvents = this.#config.showAllEvents;
        }
        const metadata = config.metadata || {};
        const onTraceUpdate = (event) => {
            const { data } = event;
            this.dispatchEvent(new ModelUpdateEvent({ type: "PROGRESS_UPDATE" , data }));
        };
        this.#processor.addEventListener(TraceParseProgressEvent.eventName, onTraceUpdate);
        const syntheticEventsManager = SyntheticEventsManager.createAndActivate(traceEvents);
        try {
            await this.#processor.parse(traceEvents, config);
            if (!this.#processor.data) {
                throw new Error('processor did not parse trace');
            }
            const file = this.#storeAndCreateParsedTraceFile(syntheticEventsManager, traceEvents, metadata, this.#processor.data, this.#processor.insights);
            this.#traces.push(file);
        }
        catch (e) {
            throw e;
        }
        finally {
            this.#processor.removeEventListener(TraceParseProgressEvent.eventName, onTraceUpdate);
            this.dispatchEvent(new ModelUpdateEvent({ type: "COMPLETE" , data: 'done' }));
        }
    }
    #storeAndCreateParsedTraceFile(syntheticEventsManager, traceEvents, metadata, data, traceInsights) {
        this.#lastRecordingIndex++;
        let recordingName = `Trace ${this.#lastRecordingIndex}`;
        const origin = extractOriginFromTrace(data.Meta.mainFrameURL);
        if (origin) {
            const nextSequenceForDomain = getWithDefault(this.#nextNumberByDomain, origin, () => 1);
            recordingName = `${origin} (${nextSequenceForDomain})`;
            this.#nextNumberByDomain.set(origin, nextSequenceForDomain + 1);
        }
        this.#recordingsAvailable.push(recordingName);
        return {
            traceEvents,
            metadata,
            data,
            insights: traceInsights,
            syntheticEventsManager,
        };
    }
    lastTraceIndex() {
        return this.size() - 1;
    }
    parsedTrace(index = this.#traces.length - 1) {
        return this.#traces.at(index) ?? null;
    }
    overrideModifications(index, newModifications) {
        if (this.#traces[index]) {
            this.#traces[index].metadata.modifications = newModifications;
        }
    }
    syntheticTraceEventsManager(index = this.#traces.length - 1) {
        return this.#traces.at(index)?.syntheticEventsManager ?? null;
    }
    size() {
        return this.#traces.length;
    }
    deleteTraceByIndex(recordingIndex) {
        this.#traces.splice(recordingIndex, 1);
        this.#recordingsAvailable.splice(recordingIndex, 1);
    }
    getRecordingsAvailable() {
        return this.#recordingsAvailable;
    }
    resetProcessor() {
        this.#processor.reset();
    }
}
class ModelUpdateEvent extends Event {
    data;
    static eventName = 'modelupdate';
    constructor(data) {
        super(ModelUpdateEvent.eventName);
        this.data = data;
    }
}
function isModelUpdateDataComplete(eventData) {
    return eventData.type === "COMPLETE" ;
}

var ModelImpl = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Model: Model,
	ModelUpdateEvent: ModelUpdateEvent,
	isModelUpdateDataComplete: isModelUpdateDataComplete
});

// Copyright 2023 The Chromium Authors
const UIStrings$s = {
    loading: 'Loading',
    experience: 'Experience',
    scripting: 'Scripting',
    rendering: 'Rendering',
    painting: 'Painting',
    gpu: 'GPU',
    async: 'Async',
    system: 'System',
    idle: 'Idle',
    task: 'Task',
    consoleTaskRun: 'Run console task',
    other: 'Other',
    animation: 'Animation',
    event: 'Event',
    requestMainThreadFrame: 'Request main thread frame',
    frameStart: 'Frame start',
    onMessage: 'On message',
    schedulePostMessage: 'Schedule postMessage',
    messaging: 'Messaging',
    frameStartMainThread: 'Frame start (main thread)',
    drawFrame: 'Draw frame',
    profilingOverhead: 'Profiling overhead',
    hitTest: 'Hit test',
    scheduleStyleRecalculation: 'Schedule style recalculation',
    recalculateStyle: 'Recalculate style',
    invalidateLayout: 'Invalidate Layout',
    layerize: 'Layerize',
    layout: 'Layout',
    paintSetup: 'Paint setup',
    paintImage: 'Paint image',
    prePaint: 'Pre-paint',
    updateLayer: 'Update layer',
    updateLayerTree: 'Update layer tree',
    paint: 'Paint',
    rasterizePaint: 'Rasterize paint',
    scroll: 'Scroll',
    commit: 'Commit',
    compositeLayers: 'Composite layers',
    computeIntersections: 'Compute intersections',
    parseHtml: 'Parse HTML',
    parseStylesheet: 'Parse stylesheet',
    installTimer: 'Install timer',
    removeTimer: 'Remove timer',
    timerFired: 'Timer fired',
    xhrReadyStateChange: '`XHR` `readyState` change',
    xhrLoad: '`XHR` load',
    compileScript: 'Compile script',
    cacheScript: 'Cache script code',
    compileCode: 'Compile code',
    optimizeCode: 'Optimize code',
    evaluateScript: 'Evaluate script',
    compileModule: 'Compile module',
    cacheModule: 'Cache module code',
    evaluateModule: 'Evaluate module',
    streamingCompileTask: 'Streaming compile task',
    waitingForNetwork: 'Waiting for network',
    parseAndCompile: 'Parse and compile',
    deserializeCodeCache: 'Deserialize code cache',
    streamingWasmResponse: 'Streaming Wasm response',
    compiledWasmModule: 'Compiled Wasm module',
    cachedWasmModule: 'Cached Wasm module',
    wasmModuleCacheHit: 'Wasm module cache hit',
    wasmModuleCacheInvalid: 'Wasm module cache invalid',
    frameStartedLoading: 'Frame started loading',
    onloadEvent: 'Onload event',
    domcontentloadedEvent: 'DOMContentLoaded event',
    firstPaint: 'First Paint',
    firstContentfulPaint: 'First Contentful Paint',
    largestContentfulPaint: 'Largest Contentful Paint',
    softLargestContentfulPaint: 'Soft Largest Contentful Paint',
    timestamp: 'Timestamp',
    consoleTime: 'Console time',
    userTiming: 'User timing',
    willSendRequest: 'Will send request',
    sendRequest: 'Send request',
    receiveResponse: 'Receive response',
    finishLoading: 'Finish loading',
    receiveData: 'Receive data',
    runMicrotasks: 'Run microtasks',
    functionCall: 'Function call',
    gcEvent: 'GC event',
    majorGc: 'Major GC',
    minorGc: 'Minor GC',
    requestAnimationFrame: 'Request animation frame',
    cancelAnimationFrame: 'Cancel animation frame',
    animationFrameFired: 'Animation frame fired',
    requestIdleCallback: 'Request idle callback',
    cancelIdleCallback: 'Cancel idle callback',
    fireIdleCallback: 'Fire idle callback',
    createWebsocket: 'Create WebSocket',
    sendWebsocketHandshake: 'Send WebSocket handshake',
    receiveWebsocketHandshake: 'Receive WebSocket handshake',
    wsMessageReceived: 'Receive WebSocket message',
    wsMessageSent: 'Send WebSocket message',
    destroyWebsocket: 'Destroy WebSocket',
    embedderCallback: 'Embedder callback',
    imageDecode: 'Image decode',
    domGc: 'DOM GC',
    cppGc: 'C++ GC',
    encrypt: 'Encrypt',
    encryptReply: 'Encrypt reply',
    decrypt: 'Decrypt',
    decryptReply: 'Decrypt reply',
    digest: 'Digest',
    digestReply: 'Digest reply',
    sign: 'Sign',
    signReply: 'Sign reply',
    verify: 'Verify',
    verifyReply: 'Verify reply',
    asyncTask: 'Async task',
    layoutShift: 'Layout shift',
    layoutShiftCluster: 'Layout shift cluster',
    eventTiming: 'Event timing',
    jsFrame: 'JS frame',
    rasterizing: 'Rasterizing',
    drawing: 'Drawing',
    schedulePostTaskCallback: 'Schedule postTask',
    runPostTaskCallback: 'Fire postTask',
    abortPostTaskCallback: 'Cancel postTask',
};
var EventCategory;
(function (EventCategory) {
    EventCategory["DRAWING"] = "drawing";
    EventCategory["RASTERIZING"] = "rasterizing";
    EventCategory["LAYOUT"] = "layout";
    EventCategory["LOADING"] = "loading";
    EventCategory["EXPERIENCE"] = "experience";
    EventCategory["SCRIPTING"] = "scripting";
    EventCategory["MESSAGING"] = "messaging";
    EventCategory["RENDERING"] = "rendering";
    EventCategory["PAINTING"] = "painting";
    EventCategory["GPU"] = "gpu";
    EventCategory["ASYNC"] = "async";
    EventCategory["OTHER"] = "other";
    EventCategory["IDLE"] = "idle";
})(EventCategory || (EventCategory = {}));
let mainEventCategories;
const str_$r = registerUIStrings('models/trace/Styles.ts', UIStrings$s);
const i18nString$d = getLocalizedString.bind(undefined, str_$r);
class TimelineRecordStyle {
    title;
    category;
    hidden;
    constructor(title, category, hidden = false) {
        this.title = title;
        this.category = category;
        this.hidden = hidden;
    }
}
class TimelineCategory {
    name;
    title;
    visible;
    #hidden;
    #cssVariable;
    constructor(name, title, visible, cssVariable) {
        this.name = name;
        this.title = title;
        this.visible = visible;
        this.#cssVariable = cssVariable;
        this.hidden = false;
    }
    get hidden() {
        return Boolean(this.#hidden);
    }
    get cssVariable() {
        return this.#cssVariable;
    }
    getCSSValue() {
        return `var(${this.#cssVariable})`;
    }
    set hidden(hidden) {
        this.#hidden = hidden;
    }
}
let categoryStyles;
let eventStylesMap;
function getEventStyle(eventName) {
    return maybeInitSylesMap()[eventName];
}
function stringIsEventCategory(it) {
    return Object.values(EventCategory).includes(it);
}
function getCategoryStyles() {
    if (categoryStyles) {
        return categoryStyles;
    }
    categoryStyles = {
        loading: new TimelineCategory(EventCategory.LOADING, i18nString$d(UIStrings$s.loading), true, '--app-color-loading'),
        experience: new TimelineCategory(EventCategory.EXPERIENCE, i18nString$d(UIStrings$s.experience), false, '--app-color-rendering'),
        messaging: new TimelineCategory(EventCategory.MESSAGING, i18nString$d(UIStrings$s.messaging), true, '--app-color-messaging'),
        scripting: new TimelineCategory(EventCategory.SCRIPTING, i18nString$d(UIStrings$s.scripting), true, '--app-color-scripting'),
        rendering: new TimelineCategory(EventCategory.RENDERING, i18nString$d(UIStrings$s.rendering), true, '--app-color-rendering'),
        painting: new TimelineCategory(EventCategory.PAINTING, i18nString$d(UIStrings$s.painting), true, '--app-color-painting'),
        gpu: new TimelineCategory(EventCategory.GPU, i18nString$d(UIStrings$s.gpu), false, '--app-color-painting'),
        async: new TimelineCategory(EventCategory.ASYNC, i18nString$d(UIStrings$s.async), false, '--app-color-async'),
        other: new TimelineCategory(EventCategory.OTHER, i18nString$d(UIStrings$s.system), false, '--app-color-system'),
        idle: new TimelineCategory(EventCategory.IDLE, i18nString$d(UIStrings$s.idle), false, '--app-color-idle'),
        layout: new TimelineCategory(EventCategory.LAYOUT, i18nString$d(UIStrings$s.layout), false, '--app-color-loading'),
        rasterizing: new TimelineCategory(EventCategory.RASTERIZING, i18nString$d(UIStrings$s.rasterizing), false, '--app-color-scripting'),
        drawing: new TimelineCategory(EventCategory.DRAWING, i18nString$d(UIStrings$s.drawing), false, '--app-color-rendering'),
    };
    return categoryStyles;
}
function maybeInitSylesMap() {
    if (eventStylesMap) {
        return eventStylesMap;
    }
    const defaultCategoryStyles = getCategoryStyles();
    eventStylesMap = {
        ["RunTask" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.task), defaultCategoryStyles.other),
        ["ProfileCall" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.jsFrame), defaultCategoryStyles.scripting),
        ["JSSample" ]: new TimelineRecordStyle("JSSample" , defaultCategoryStyles.scripting),
        ["Program" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.other), defaultCategoryStyles.other),
        ["CpuProfiler::StartProfiling" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.profilingOverhead), defaultCategoryStyles.other),
        ["Animation" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.animation), defaultCategoryStyles.rendering),
        ["EventDispatch" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.event), defaultCategoryStyles.scripting),
        ["RequestMainThreadFrame" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.requestMainThreadFrame), defaultCategoryStyles.rendering, true),
        ["BeginFrame" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.frameStart), defaultCategoryStyles.rendering, true),
        ["BeginMainThreadFrame" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.frameStartMainThread), defaultCategoryStyles.rendering, true),
        ["DrawFrame" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.drawFrame), defaultCategoryStyles.rendering, true),
        ["HitTest" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.hitTest), defaultCategoryStyles.rendering),
        ["ScheduleStyleRecalculation" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.scheduleStyleRecalculation), defaultCategoryStyles.rendering),
        ["UpdateLayoutTree" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.recalculateStyle), defaultCategoryStyles.rendering),
        ["InvalidateLayout" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.invalidateLayout), defaultCategoryStyles.rendering, true),
        ["Layerize" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.layerize), defaultCategoryStyles.rendering),
        ["Layout" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.layout), defaultCategoryStyles.rendering),
        ["PaintSetup" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.paintSetup), defaultCategoryStyles.painting),
        ["PaintImage" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.paintImage), defaultCategoryStyles.painting, true),
        ["UpdateLayer" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.updateLayer), defaultCategoryStyles.painting, true),
        ["UpdateLayerTree" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.updateLayerTree), defaultCategoryStyles.rendering),
        ["Paint" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.paint), defaultCategoryStyles.painting),
        ["PrePaint" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.prePaint), defaultCategoryStyles.rendering),
        ["RasterTask" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.rasterizePaint), defaultCategoryStyles.painting),
        ["ScrollLayer" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.scroll), defaultCategoryStyles.rendering),
        ["Commit" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.commit), defaultCategoryStyles.painting),
        ["CompositeLayers" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.compositeLayers), defaultCategoryStyles.painting),
        ["ComputeIntersections" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.computeIntersections), defaultCategoryStyles.rendering),
        ["ParseHTML" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.parseHtml), defaultCategoryStyles.loading),
        ["ParseAuthorStyleSheet" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.parseStylesheet), defaultCategoryStyles.loading),
        ["TimerInstall" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.installTimer), defaultCategoryStyles.scripting),
        ["TimerRemove" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.removeTimer), defaultCategoryStyles.scripting),
        ["TimerFire" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.timerFired), defaultCategoryStyles.scripting),
        ["XHRReadyStateChange" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.xhrReadyStateChange), defaultCategoryStyles.scripting),
        ["XHRLoad" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.xhrLoad), defaultCategoryStyles.scripting),
        ["v8.compile" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.compileScript), defaultCategoryStyles.scripting),
        ["v8.produceCache" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.cacheScript), defaultCategoryStyles.scripting),
        ["V8.CompileCode" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.compileCode), defaultCategoryStyles.scripting),
        ["V8.OptimizeCode" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.optimizeCode), defaultCategoryStyles.scripting),
        ["EvaluateScript" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.evaluateScript), defaultCategoryStyles.scripting),
        ["V8.CompileModule" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.compileModule), defaultCategoryStyles.scripting),
        ["v8.produceModuleCache" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.cacheModule), defaultCategoryStyles.scripting),
        ["v8.evaluateModule" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.evaluateModule), defaultCategoryStyles.scripting),
        ["v8.parseOnBackground" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.streamingCompileTask), defaultCategoryStyles.other),
        ["v8.parseOnBackgroundWaiting" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.waitingForNetwork), defaultCategoryStyles.idle),
        ["v8.parseOnBackgroundParsing" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.parseAndCompile), defaultCategoryStyles.scripting),
        ["v8.deserializeOnBackground" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.deserializeCodeCache), defaultCategoryStyles.scripting),
        ["V8.FinalizeDeserialization" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.profilingOverhead), defaultCategoryStyles.other),
        ["v8.wasm.streamFromResponseCallback" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.streamingWasmResponse), defaultCategoryStyles.scripting),
        ["v8.wasm.compiledModule" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.compiledWasmModule), defaultCategoryStyles.scripting),
        ["v8.wasm.cachedModule" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.cachedWasmModule), defaultCategoryStyles.scripting),
        ["v8.wasm.moduleCacheHit" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.wasmModuleCacheHit), defaultCategoryStyles.scripting),
        ["v8.wasm.moduleCacheInvalid" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.wasmModuleCacheInvalid), defaultCategoryStyles.scripting),
        ["FrameStartedLoading" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.frameStartedLoading), defaultCategoryStyles.loading, true),
        ["MarkLoad" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.onloadEvent), defaultCategoryStyles.scripting, true),
        ["MarkDOMContent" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.domcontentloadedEvent), defaultCategoryStyles.scripting, true),
        ["firstPaint" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.firstPaint), defaultCategoryStyles.painting, true),
        ["firstContentfulPaint" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.firstContentfulPaint), defaultCategoryStyles.rendering, true),
        ["largestContentfulPaint::Candidate" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.largestContentfulPaint), defaultCategoryStyles.rendering, true),
        ["largestContentfulPaint::CandidateForSoftNavigation" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.softLargestContentfulPaint), defaultCategoryStyles.rendering, true),
        ["TimeStamp" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.timestamp), defaultCategoryStyles.scripting),
        ["ConsoleTime" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.consoleTime), defaultCategoryStyles.scripting),
        ["UserTiming" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.userTiming), defaultCategoryStyles.scripting),
        ["ResourceWillSendRequest" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.willSendRequest), defaultCategoryStyles.loading),
        ["ResourceSendRequest" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.sendRequest), defaultCategoryStyles.loading),
        ["ResourceReceiveResponse" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.receiveResponse), defaultCategoryStyles.loading),
        ["ResourceFinish" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.finishLoading), defaultCategoryStyles.loading),
        ["ResourceReceivedData" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.receiveData), defaultCategoryStyles.loading),
        ["RunMicrotasks" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.runMicrotasks), defaultCategoryStyles.scripting),
        ["FunctionCall" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.functionCall), defaultCategoryStyles.scripting),
        ["GCEvent" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.gcEvent), defaultCategoryStyles.scripting),
        ["MajorGC" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.majorGc), defaultCategoryStyles.scripting),
        ["MinorGC" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.minorGc), defaultCategoryStyles.scripting),
        ["CppGC.IncrementalSweep" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.cppGc), defaultCategoryStyles.scripting),
        ["RequestAnimationFrame" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.requestAnimationFrame), defaultCategoryStyles.scripting),
        ["CancelAnimationFrame" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.cancelAnimationFrame), defaultCategoryStyles.scripting),
        ["FireAnimationFrame" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.animationFrameFired), defaultCategoryStyles.scripting),
        ["RequestIdleCallback" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.requestIdleCallback), defaultCategoryStyles.scripting),
        ["CancelIdleCallback" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.cancelIdleCallback), defaultCategoryStyles.scripting),
        ["FireIdleCallback" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.fireIdleCallback), defaultCategoryStyles.scripting),
        ["WebSocketCreate" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.createWebsocket), defaultCategoryStyles.scripting),
        ["WebSocketSendHandshakeRequest" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.sendWebsocketHandshake), defaultCategoryStyles.scripting),
        ["WebSocketReceiveHandshakeResponse" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.receiveWebsocketHandshake), defaultCategoryStyles.scripting),
        ["WebSocketDestroy" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.destroyWebsocket), defaultCategoryStyles.scripting),
        ["WebSocketSend" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.wsMessageSent), defaultCategoryStyles.scripting),
        ["WebSocketReceive" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.wsMessageReceived), defaultCategoryStyles.scripting),
        ["EmbedderCallback" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.embedderCallback), defaultCategoryStyles.scripting),
        ["Decode Image" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.imageDecode), defaultCategoryStyles.painting),
        ["GPUTask" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.gpu), defaultCategoryStyles.gpu),
        ["BlinkGC.AtomicPhase" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.domGc), defaultCategoryStyles.scripting),
        ["DoEncrypt" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.encrypt), defaultCategoryStyles.scripting),
        ["DoEncryptReply" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.encryptReply), defaultCategoryStyles.scripting),
        ["DoDecrypt" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.decrypt), defaultCategoryStyles.scripting),
        ["DoDecryptReply" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.decryptReply), defaultCategoryStyles.scripting),
        ["DoDigest" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.digest), defaultCategoryStyles.scripting),
        ["DoDigestReply" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.digestReply), defaultCategoryStyles.scripting),
        ["DoSign" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.sign), defaultCategoryStyles.scripting),
        ["DoSignReply" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.signReply), defaultCategoryStyles.scripting),
        ["DoVerify" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.verify), defaultCategoryStyles.scripting),
        ["DoVerifyReply" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.verifyReply), defaultCategoryStyles.scripting),
        ["AsyncTask" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.asyncTask), defaultCategoryStyles.async),
        ["LayoutShift" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.layoutShift), defaultCategoryStyles.experience,
        true),
        ["SyntheticLayoutShift" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.layoutShift), defaultCategoryStyles.experience),
        ["SyntheticLayoutShiftCluster" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.layoutShiftCluster), defaultCategoryStyles.experience),
        ["EventTiming" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.eventTiming), defaultCategoryStyles.experience),
        ["HandlePostMessage" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.onMessage), defaultCategoryStyles.messaging),
        ["SchedulePostMessage" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.schedulePostMessage), defaultCategoryStyles.messaging),
        ["SchedulePostTaskCallback" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.schedulePostTaskCallback), defaultCategoryStyles.scripting),
        ["RunPostTaskCallback" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.runPostTaskCallback), defaultCategoryStyles.scripting),
        ["AbortPostTaskCallback" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.abortPostTaskCallback), defaultCategoryStyles.scripting),
        ["V8Console::runTask" ]: new TimelineRecordStyle(i18nString$d(UIStrings$s.consoleTaskRun), defaultCategoryStyles.scripting),
    };
    const visibleEventStyles = Object.entries(eventStylesMap).filter(([, style]) => style.hidden === false).map(([key,]) => key);
    const visibleTraceEventsComplete = visibleEventStyles.every(eventType => {
        return VISIBLE_TRACE_EVENT_TYPES.has(eventType);
    });
    const eventStylesMapKeys = Object.keys(eventStylesMap);
    const eventStylesComplete = Array.from(VISIBLE_TRACE_EVENT_TYPES).every(eventType => {
        return eventStylesMapKeys.includes(eventType);
    });
    if (!visibleTraceEventsComplete || !eventStylesComplete) {
        throw new Error('eventStylesMap and VISIBLE_TRACE_EVENT_TYPES are out of sync!');
    }
    return eventStylesMap;
}
function setEventStylesMap(eventStyles) {
    eventStylesMap = eventStyles;
}
function setCategories(cats) {
    categoryStyles = cats;
}
function visibleTypes() {
    const eventStyles = maybeInitSylesMap();
    const result = [];
    for (const name in eventStyles) {
        const nameAsKey = name;
        if (!eventStyles[nameAsKey]?.hidden) {
            result.push(name);
        }
    }
    return result;
}
function getTimelineMainEventCategories() {
    if (mainEventCategories) {
        return mainEventCategories;
    }
    mainEventCategories = [
        EventCategory.IDLE,
        EventCategory.LOADING,
        EventCategory.PAINTING,
        EventCategory.RENDERING,
        EventCategory.SCRIPTING,
        EventCategory.OTHER,
    ];
    return mainEventCategories;
}
function setTimelineMainEventCategories(categories) {
    mainEventCategories = categories;
}
function markerDetailsForEvent(event) {
    let title = '';
    let color = 'var(--color-text-primary)';
    if (isFirstContentfulPaint(event)) {
        color = 'var(--sys-color-green-bright)';
        title = "FCP" ;
    }
    if (isAnyLargestContentfulPaintCandidate(event)) {
        color = 'var(--sys-color-green)';
        title = isSoftLargestContentfulPaintCandidate(event) ?
            "LCP*"  :
            "LCP" ;
    }
    if (isNavigationStart(event) || isSoftNavigationStart(event)) {
        color = 'var(--color-text-primary)';
        title = isSoftNavigationStart(event) ? "Nav*"  :
            "Nav" ;
    }
    if (isMarkDOMContent(event)) {
        color = 'var(--color-text-disabled)';
        title = "DCL" ;
    }
    if (isMarkLoad(event)) {
        color = 'var(--color-text-disabled)';
        title = "L" ;
    }
    return { color, title };
}

var Styles = /*#__PURE__*/Object.freeze({
	__proto__: null,
	get EventCategory () { return EventCategory; },
	TimelineCategory: TimelineCategory,
	TimelineRecordStyle: TimelineRecordStyle,
	getCategoryStyles: getCategoryStyles,
	getEventStyle: getEventStyle,
	getTimelineMainEventCategories: getTimelineMainEventCategories,
	markerDetailsForEvent: markerDetailsForEvent,
	maybeInitSylesMap: maybeInitSylesMap,
	setCategories: setCategories,
	setEventStylesMap: setEventStylesMap,
	setTimelineMainEventCategories: setTimelineMainEventCategories,
	stringIsEventCategory: stringIsEventCategory,
	visibleTypes: visibleTypes
});

// Copyright 2024 The Chromium Authors
const UIStrings$r = {
    anonymous: '(anonymous)',
    eventDispatchS: 'Event: {PH1}',
    frame: 'Frame',
    wsConnectionOpened: 'WebSocket opened',
    wsConnectionOpenedWithUrl: 'WebSocket opened: {PH1}',
    wsConnectionClosed: 'WebSocket closed',
    layoutShift: 'Layout shift',
};
const str_$q = registerUIStrings('models/trace/Name.ts', UIStrings$r);
const i18nString$c = getLocalizedString.bind(undefined, str_$q);
function forEntry(entry, parsedTrace) {
    if (isProfileCall(entry)) {
        if (parsedTrace) {
            const potentialCallName = getProfileCallFunctionName(parsedTrace.data.Samples, entry);
            if (potentialCallName) {
                return potentialCallName;
            }
        }
        return entry.callFrame.functionName || i18nString$c(UIStrings$r.anonymous);
    }
    if (isLegacyTimelineFrame(entry)) {
        return lockedString(UIStrings$r.frame);
    }
    if (isDispatch(entry)) {
        return i18nString$c(UIStrings$r.eventDispatchS, { PH1: entry.args.data.type });
    }
    if (isSyntheticNetworkRequest(entry)) {
        const parsedURL = new ParsedURL(entry.args.data.url);
        const text = parsedURL.isValid ? `${parsedURL.displayName} (${parsedURL.host})` : entry.args.data.url || 'Network request';
        return text;
    }
    if (isWebSocketCreate(entry)) {
        if (entry.args.data.url) {
            return i18nString$c(UIStrings$r.wsConnectionOpenedWithUrl, { PH1: entry.args.data.url });
        }
        return i18nString$c(UIStrings$r.wsConnectionOpened);
    }
    if (isWebSocketDestroy(entry)) {
        return i18nString$c(UIStrings$r.wsConnectionClosed);
    }
    if (isSyntheticInteraction(entry)) {
        return nameForInteractionEvent(entry);
    }
    if (isSyntheticLayoutShift(entry)) {
        return i18nString$c(UIStrings$r.layoutShift);
    }
    if (isSyntheticAnimation(entry) && entry.args.data.beginEvent.args.data.displayName) {
        return entry.args.data.beginEvent.args.data.displayName;
    }
    const eventStyleCustomName = getEventStyle(entry.name)?.title;
    return eventStyleCustomName || entry.name;
}
function nameForInteractionEvent(event) {
    const category = categoryOfInteraction(event);
    if (category === 'OTHER') {
        return 'Other';
    }
    if (category === 'KEYBOARD') {
        return 'Keyboard';
    }
    if (category === 'POINTER') {
        return 'Pointer';
    }
    return event.type;
}

var Name = /*#__PURE__*/Object.freeze({
	__proto__: null,
	forEntry: forEntry
});

// Copyright 2022 The Chromium Authors

var trace = /*#__PURE__*/Object.freeze({
	__proto__: null,
	EntityMapper: EntityMapper$1,
	EventsSerializer: EventsSerializer$1,
	Extras: extras,
	Handlers: handlers,
	Helpers: helpers,
	Insights: insights,
	Lantern: lantern,
	LanternComputationData: LanternComputationData,
	Name: Name,
	Processor: Processor,
	Styles: Styles,
	TraceModel: ModelImpl,
	Types: types$3
});

// Copyright 2025 The Chromium Authors
let instance = null;
class Prototypes {
    constructor() {
    }
    static instance() {
        if (instance) {
            return instance;
        }
        instance = new Prototypes();
        return instance;
    }
    isEnabled(setting) {
        const greendevFlagEnabled = Boolean(hostConfig.devToolsGreenDevUi?.enabled);
        return greendevFlagEnabled && this.settings()[setting].get();
    }
    settings() {
        const settings = Settings.instance();
        const aiAnnotations = settings.createSetting('greendev-ai-annotations-enabled', false, "Local" );
        const copyToGemini = settings.createSetting('greendev-copy-to-gemini-enabled', false, "Local" );
        const breakpointDebuggerAgent = settings.createSetting('greendev-breakpoint-debugger-agent-enabled', false, "Local" );
        return { aiAnnotations, copyToGemini, breakpointDebuggerAgent };
    }
}

// Copyright 2025 The Chromium Authors
var AnnotationType;
(function (AnnotationType) {
    AnnotationType[AnnotationType["ELEMENT_NODE"] = 0] = "ELEMENT_NODE";
    AnnotationType[AnnotationType["STYLE_RULE"] = 1] = "STYLE_RULE";
    AnnotationType[AnnotationType["NETWORK_REQUEST"] = 2] = "NETWORK_REQUEST";
    AnnotationType[AnnotationType["NETWORK_REQUEST_SUBPANEL_HEADERS"] = 3] = "NETWORK_REQUEST_SUBPANEL_HEADERS";
})(AnnotationType || (AnnotationType = {}));

// Copyright 2025 The Chromium Authors
class AnnotationRepository {
    static #instance = null;
    static #hasRepliedGreenDevDisabled = false;
    static #hasShownFlagWarning = false;
    #events = new ObjectWrapper();
    #annotationData = [];
    #nextId = 0;
    static instance() {
        if (!AnnotationRepository.#instance) {
            AnnotationRepository.#instance = new AnnotationRepository();
        }
        return AnnotationRepository.#instance;
    }
    static annotationsEnabled() {
        const enabled = Prototypes.instance().isEnabled('aiAnnotations');
        if (!enabled) {
            this.#hasRepliedGreenDevDisabled = true;
        }
        else if (this.#hasRepliedGreenDevDisabled && !this.#hasShownFlagWarning) {
            console.warn('Flag controlling GreenDev has flipped from false to true. ' +
                'Only some callers will expect GreenDev to be enabled, which can lead to unexpected results.');
            this.#hasShownFlagWarning = true;
        }
        return Boolean(enabled);
    }
    addEventListener(eventType, listener, thisObject) {
        if (!AnnotationRepository.annotationsEnabled()) {
            console.warn('Received request to add event listener with annotations disabled');
        }
        return this.#events.addEventListener(eventType, listener, thisObject);
    }
    getAnnotationDataByType(type) {
        if (!AnnotationRepository.annotationsEnabled()) {
            console.warn('Received query for annotation types with annotations disabled');
            return [];
        }
        const annotations = this.#annotationData.filter(annotation => annotation.type === type);
        return annotations;
    }
    getAnnotationDataById(id) {
        if (!AnnotationRepository.annotationsEnabled()) {
            console.warn('Received query for annotation type with annotations disabled');
            return undefined;
        }
        return this.#annotationData.find(annotation => annotation.id === id);
    }
    #getExistingAnnotation(type, anchor) {
        const annotations = this.getAnnotationDataByType(type);
        const annotation = annotations.find(annotation => {
            if (typeof anchor === 'string') {
                return annotation.lookupId === anchor;
            }
            switch (type) {
                case AnnotationType.ELEMENT_NODE: {
                    const elementAnnotation = annotation;
                    return elementAnnotation.anchor === anchor;
                }
                case AnnotationType.NETWORK_REQUEST_SUBPANEL_HEADERS: {
                    const networkRequestDetailsAnnotation = annotation;
                    return networkRequestDetailsAnnotation.anchor === anchor;
                }
                default:
                    console.warn('[AnnotationRepository] Unknown AnnotationType', type);
                    return false;
            }
        });
        return annotation;
    }
    #updateExistingAnnotationLabel(label, type, anchor) {
        const annotation = this.#getExistingAnnotation(type, anchor);
        if (annotation) {
            annotation.message = label;
            return true;
        }
        return false;
    }
    addElementsAnnotation(label, anchor, anchorToString) {
        if (!AnnotationRepository.annotationsEnabled()) {
            console.warn('Received annotation registration with annotations disabled');
            return;
        }
        if (this.#updateExistingAnnotationLabel(label, AnnotationType.ELEMENT_NODE, anchor)) {
            return;
        }
        const annotationData = {
            id: this.#nextId++,
            type: AnnotationType.ELEMENT_NODE,
            message: label,
            lookupId: typeof anchor === 'string' ? anchor : '',
            anchor: typeof anchor !== 'string' ? anchor : undefined,
            anchorToString,
        };
        this.#annotationData.push(annotationData);
        console.log('[AnnotationRepository] Added element annotation:', label, {
            annotationData,
            annotations: this.#annotationData.length,
        });
        this.#events.dispatchEventToListeners("AnnotationAdded" , annotationData);
    }
    addNetworkRequestAnnotation(label, anchor, anchorToString) {
        if (!AnnotationRepository.annotationsEnabled()) {
            console.warn('Received annotation registration with annotations disabled');
            return;
        }
        if (this.#updateExistingAnnotationLabel(label, AnnotationType.NETWORK_REQUEST_SUBPANEL_HEADERS, anchor)) {
            return;
        }
        const annotationData = {
            id: this.#nextId++,
            type: AnnotationType.NETWORK_REQUEST,
            message: '',
            lookupId: typeof anchor === 'string' ? anchor : '',
            anchor: typeof anchor !== 'string' ? anchor : undefined,
            anchorToString,
        };
        this.#annotationData.push(annotationData);
        console.log('[AnnotationRepository] Added annotation:', label, {
            annotationData,
            annotations: this.#annotationData.length,
        });
        this.#events.dispatchEventToListeners("AnnotationAdded" , annotationData);
        const annotationDetailsData = {
            id: this.#nextId++,
            type: AnnotationType.NETWORK_REQUEST_SUBPANEL_HEADERS,
            message: label,
            lookupId: typeof anchor === 'string' ? anchor : '',
            anchor: typeof anchor !== 'string' ? anchor : undefined,
            anchorToString,
        };
        this.#annotationData.push(annotationDetailsData);
        this.#events.dispatchEventToListeners("AnnotationAdded" , annotationDetailsData);
    }
    deleteAllAnnotations() {
        this.#annotationData = [];
        this.#events.dispatchEventToListeners("AllAnnotationsDeleted" );
        console.log('[AnnotationRepository] Deleting all annotations');
    }
    deleteAnnotation(id) {
        const index = this.#annotationData.findIndex(annotation => annotation.id === id);
        if (index === -1) {
            console.warn(`[AnnotationRepository] Could not find annotation with id ${id}`);
            return;
        }
        this.#annotationData.splice(index, 1);
        this.#events.dispatchEventToListeners("AnnotationDeleted" , { id });
        console.log(`[AnnotationRepository] Deleted annotation with id ${id}`);
    }
}

// Copyright 2013 The Chromium Authors
class Size {
    width;
    height;
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }
    clipTo(size) {
        if (!size) {
            return this;
        }
        return new Size(Math.min(this.width, size.width), Math.min(this.height, size.height));
    }
    scale(scale) {
        return new Size(this.width * scale, this.height * scale);
    }
    isEqual(size) {
        return size !== null && this.width === size.width && this.height === size.height;
    }
    widthToMax(size) {
        return new Size(Math.max(this.width, (typeof size === 'number' ? size : size.width)), this.height);
    }
    addWidth(size) {
        return new Size(this.width + (typeof size === 'number' ? size : size.width), this.height);
    }
    heightToMax(size) {
        return new Size(this.width, Math.max(this.height, (typeof size === 'number' ? size : size.height)));
    }
    addHeight(size) {
        return new Size(this.width, this.height + (typeof size === 'number' ? size : size.height));
    }
}

// Copyright 2014 The Chromium Authors
const UIStrings$q = {
    laptopWithTouch: 'Laptop with touch',
    laptopWithHiDPIScreen: 'Laptop with HiDPI screen',
    laptopWithMDPIScreen: 'Laptop with MDPI screen',
};
const str_$p = registerUIStrings('models/emulation/EmulatedDevices.ts', UIStrings$q);
const i18nLazyString$b = getLazilyComputedLocalizedString.bind(undefined, str_$p);
const Horizontal = 'horizontal';
const Vertical = 'vertical';
const HorizontalSpanned = 'horizontal-spanned';
const VerticalSpanned = 'vertical-spanned';
var Type$1;
(function (Type) {
    Type["Phone"] = "phone";
    Type["Tablet"] = "tablet";
    Type["Notebook"] = "notebook";
    Type["Desktop"] = "desktop";
    Type["Unknown"] = "unknown";
})(Type$1 || (Type$1 = {}));
var Show;
(function (Show) {
    Show["Always"] = "Always";
    Show["Default"] = "Default";
    Show["Never"] = "Never";
})(Show || (Show = {}));
[
    {
        'order': 10,
        'show-by-default': true,
        'title': 'iPhone SE',
        'screen': {
            'horizontal': {
                'width': 667,
                'height': 375,
            },
            'device-pixel-ratio': 2,
            'vertical': {
                'width': 375,
                'height': 667,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '18.5', 'architecture': '', 'model': 'iPhone', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 12,
        'show-by-default': true,
        'title': 'iPhone XR',
        'screen': {
            'horizontal': {
                'width': 896,
                'height': 414,
            },
            'device-pixel-ratio': 2,
            'vertical': {
                'width': 414,
                'height': 896,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '18.5', 'architecture': '', 'model': 'iPhone', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 14,
        'show-by-default': true,
        'title': 'iPhone 12 Pro',
        'screen': {
            'horizontal': {
                'width': 844,
                'height': 390,
            },
            'device-pixel-ratio': 3,
            'vertical': {
                'width': 390,
                'height': 844,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '18.5', 'architecture': '', 'model': 'iPhone', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 15,
        'show-by-default': true,
        'title': 'iPhone 14 Pro Max',
        'screen': {
            'horizontal': {
                'width': 932,
                'height': 430,
            },
            'device-pixel-ratio': 3,
            'vertical': {
                'width': 430,
                'height': 932,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '18.5', 'architecture': '', 'model': 'iPhone', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 16,
        'show-by-default': false,
        'title': 'Pixel 3 XL',
        'screen': {
            'horizontal': {
                'width': 786,
                'height': 393,
            },
            'device-pixel-ratio': 2.75,
            'vertical': {
                'width': 393,
                'height': 786,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 11; Pixel 3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '11', 'architecture': '', 'model': 'Pixel 3', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 18,
        'show-by-default': true,
        'title': 'Pixel 7',
        'screen': {
            'horizontal': {
                'width': 915,
                'height': 412,
            },
            'device-pixel-ratio': 2.625,
            'vertical': {
                'width': 412,
                'height': 915,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '13', 'architecture': '', 'model': 'Pixel 5', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 20,
        'show-by-default': true,
        'title': 'Samsung Galaxy S8+',
        'screen': {
            'horizontal': {
                'width': 740,
                'height': 360,
            },
            'device-pixel-ratio': 4,
            'vertical': {
                'width': 360,
                'height': 740,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '8.0.0', 'architecture': '', 'model': 'SM-G955U', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 24,
        'show-by-default': true,
        'title': 'Samsung Galaxy S20 Ultra',
        'screen': {
            'horizontal': {
                'width': 915,
                'height': 412,
            },
            'device-pixel-ratio': 3.5,
            'vertical': {
                'width': 412,
                'height': 915,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 13; SM-G981B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '13', 'architecture': '', 'model': 'SM-G981B', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 26,
        'show-by-default': true,
        'title': 'iPad Mini',
        'screen': {
            'horizontal': {
                'width': 1024,
                'height': 768,
            },
            'device-pixel-ratio': 2,
            'vertical': {
                'width': 768,
                'height': 1024,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '18.5', 'architecture': '', 'model': 'iPad', 'mobile': true },
        'type': 'tablet',
    },
    {
        'order': 28,
        'show-by-default': true,
        'title': 'iPad Air',
        'screen': {
            'horizontal': {
                'width': 1180,
                'height': 820,
            },
            'device-pixel-ratio': 2,
            'vertical': {
                'width': 820,
                'height': 1180,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '18.5', 'architecture': '', 'model': 'iPad', 'mobile': true },
        'type': 'tablet',
    },
    {
        'order': 29,
        'show-by-default': true,
        'title': 'iPad Pro',
        'screen': {
            'horizontal': {
                'width': 1366,
                'height': 1024,
            },
            'device-pixel-ratio': 2,
            'vertical': {
                'width': 1024,
                'height': 1366,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '18.5', 'architecture': '', 'model': 'iPad', 'mobile': true },
        'type': 'tablet',
    },
    {
        'order': 30,
        'show-by-default': true,
        'title': 'Surface Pro 7',
        'screen': {
            'horizontal': {
                'width': 1368,
                'height': 912,
            },
            'device-pixel-ratio': 2,
            'vertical': {
                'width': 912,
                'height': 1368,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36',
        'type': 'tablet',
    },
    {
        'order': 32,
        'show-by-default': true,
        'dual-screen': true,
        'title': 'Surface Duo',
        'screen': {
            'horizontal': { 'width': 720, 'height': 540 },
            'device-pixel-ratio': 2.5,
            'vertical': { 'width': 540, 'height': 720 },
            'vertical-spanned': {
                'width': 1114,
                'height': 720,
                'hinge': { 'width': 34, 'height': 720, 'x': 540, 'y': 0, 'contentColor': { 'r': 38, 'g': 38, 'b': 38, 'a': 1 } },
            },
            'horizontal-spanned': {
                'width': 720,
                'height': 1114,
                'hinge': { 'width': 720, 'height': 34, 'x': 0, 'y': 540, 'contentColor': { 'r': 38, 'g': 38, 'b': 38, 'a': 1 } },
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 11.0; Surface Duo) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '11.0', 'architecture': '', 'model': 'Surface Duo', 'mobile': true },
        'type': 'phone',
        'modes': [
            { 'title': 'default', 'orientation': 'vertical', 'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 } },
            { 'title': 'default', 'orientation': 'horizontal', 'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 } },
            { 'title': 'spanned', 'orientation': 'vertical-spanned', 'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 } },
            {
                'title': 'spanned',
                'orientation': 'horizontal-spanned',
                'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 },
            },
        ],
    },
    {
        'order': 34,
        'show-by-default': true,
        'foldable-screen': true,
        'title': 'Galaxy Z Fold 5',
        'screen': {
            'horizontal': { 'width': 882, 'height': 344 },
            'device-pixel-ratio': 2.625,
            'vertical': { 'width': 344, 'height': 882 },
            'vertical-spanned': {
                'width': 690,
                'height': 829,
                'hinge': {
                    'width': 0,
                    'height': 829,
                    'x': 345,
                    'y': 0,
                    'contentColor': { 'r': 38, 'g': 38, 'b': 38, 'a': 0.2 },
                    'outlineColor': { 'r': 38, 'g': 38, 'b': 38, 'a': 0.7 },
                },
            },
            'horizontal-spanned': {
                'width': 829,
                'height': 690,
                'hinge': {
                    'width': 829,
                    'height': 0,
                    'x': 0,
                    'y': 345,
                    'contentColor': { 'r': 38, 'g': 38, 'b': 38, 'a': 0.2 },
                    'outlineColor': { 'r': 38, 'g': 38, 'b': 38, 'a': 0.7 },
                },
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '10.0', 'architecture': '', 'model': 'SM-F946U', 'mobile': true },
        'type': 'phone',
        'modes': [
            { 'title': 'default', 'orientation': 'vertical', 'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 } },
            { 'title': 'default', 'orientation': 'horizontal', 'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 } },
            { 'title': 'spanned', 'orientation': 'vertical-spanned', 'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 } },
            {
                'title': 'spanned',
                'orientation': 'horizontal-spanned',
                'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 },
            },
        ],
    },
    {
        'order': 35,
        'show-by-default': true,
        'foldable-screen': true,
        'title': 'Asus Zenbook Fold',
        'screen': {
            'horizontal': { 'width': 1280, 'height': 853 },
            'device-pixel-ratio': 1.5,
            'vertical': { 'width': 853, 'height': 1280 },
            'vertical-spanned': {
                'width': 1706,
                'height': 1280,
                'hinge': {
                    'width': 107,
                    'height': 1280,
                    'x': 800,
                    'y': 0,
                    'contentColor': { 'r': 38, 'g': 38, 'b': 38, 'a': 0.2 },
                    'outlineColor': { 'r': 38, 'g': 38, 'b': 38, 'a': 0.7 },
                },
            },
            'horizontal-spanned': {
                'width': 1280,
                'height': 1706,
                'hinge': {
                    'width': 1706,
                    'height': 107,
                    'x': 0,
                    'y': 800,
                    'contentColor': { 'r': 38, 'g': 38, 'b': 38, 'a': 0.2 },
                    'outlineColor': { 'r': 38, 'g': 38, 'b': 38, 'a': 0.7 },
                },
            },
        },
        'capabilities': ['touch'],
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36',
        'user-agent-metadata': { 'platform': 'Windows', 'platformVersion': '11.0', 'architecture': '', 'model': 'UX9702AA', 'mobile': false },
        'type': 'tablet',
        'modes': [
            { 'title': 'default', 'orientation': 'vertical', 'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 } },
            { 'title': 'default', 'orientation': 'horizontal', 'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 } },
            {
                'title': 'spanned',
                'orientation': 'vertical-spanned',
                'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 },
            },
            {
                'title': 'spanned',
                'orientation': 'horizontal-spanned',
                'insets': { 'left': 0, 'top': 0, 'right': 0, 'bottom': 0 },
            },
        ],
    },
    {
        'order': 36,
        'show-by-default': true,
        'title': 'Samsung Galaxy A51/71',
        'screen': {
            'horizontal': {
                'width': 914,
                'height': 412,
            },
            'device-pixel-ratio': 2.625,
            'vertical': {
                'width': 412,
                'height': 914,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '8.0.0', 'architecture': '', 'model': 'SM-G955U', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 52,
        'show-by-default': true,
        'title': 'Nest Hub Max',
        'screen': {
            'horizontal': {
                'outline': {
                    'image': '@url(optimized/google-nest-hub-max-horizontal.avif)',
                    'insets': { 'left': 92, 'top': 96, 'right': 91, 'bottom': 248 },
                },
                'width': 1280,
                'height': 800,
            },
            'device-pixel-ratio': 2,
            'vertical': {
                'width': 1280,
                'height': 800,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (X11; Linux aarch64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36 CrKey/1.54.250320',
        'type': 'tablet',
        'modes': [{ 'title': 'default', 'orientation': 'horizontal' }],
    },
    {
        'order': 50,
        'show-by-default': true,
        'title': 'Nest Hub',
        'screen': {
            'horizontal': {
                'outline': {
                    'image': '@url(optimized/google-nest-hub-horizontal.avif)',
                    'insets': { 'left': 82, 'top': 74, 'right': 83, 'bottom': 222 },
                },
                'width': 1024,
                'height': 600,
            },
            'device-pixel-ratio': 2,
            'vertical': {
                'width': 1024,
                'height': 600,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36 CrKey/1.54.248666',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '', 'architecture': '', 'model': '', 'mobile': false },
        'type': 'tablet',
        'modes': [{ 'title': 'default', 'orientation': 'horizontal' }],
    },
    {
        'order': 129,
        'show-by-default': false,
        'title': 'iPhone 4',
        'screen': {
            'horizontal': { 'width': 480, 'height': 320 },
            'device-pixel-ratio': 2,
            'vertical': { 'width': 320, 'height': 480 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '7.1.2', 'architecture': '', 'model': 'iPhone', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 130,
        'show-by-default': false,
        'title': 'iPhone 5/SE',
        'screen': {
            'horizontal': {
                'outline': {
                    'image': '@url(optimized/iPhone5-landscape.avif)',
                    'insets': { 'left': 115, 'top': 25, 'right': 115, 'bottom': 28 },
                },
                'width': 568,
                'height': 320,
            },
            'device-pixel-ratio': 2,
            'vertical': {
                'outline': {
                    'image': '@url(optimized/iPhone5-portrait.avif)',
                    'insets': { 'left': 29, 'top': 105, 'right': 25, 'bottom': 111 },
                },
                'width': 320,
                'height': 568,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '10.3.1', 'architecture': '', 'model': 'iPhone', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 131,
        'show-by-default': false,
        'title': 'iPhone 6/7/8',
        'screen': {
            'horizontal': {
                'outline': {
                    'image': '@url(optimized/iPhone6-landscape.avif)',
                    'insets': { 'left': 106, 'top': 28, 'right': 106, 'bottom': 28 },
                },
                'width': 667,
                'height': 375,
            },
            'device-pixel-ratio': 2,
            'vertical': {
                'outline': {
                    'image': '@url(optimized/iPhone6-portrait.avif)',
                    'insets': { 'left': 28, 'top': 105, 'right': 28, 'bottom': 105 },
                },
                'width': 375,
                'height': 667,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '13.2.3', 'architecture': '', 'model': 'iPhone', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 132,
        'show-by-default': false,
        'title': 'iPhone 6/7/8 Plus',
        'screen': {
            'horizontal': {
                'outline': {
                    'image': '@url(optimized/iPhone6Plus-landscape.avif)',
                    'insets': { 'left': 109, 'top': 29, 'right': 109, 'bottom': 27 },
                },
                'width': 736,
                'height': 414,
            },
            'device-pixel-ratio': 3,
            'vertical': {
                'outline': {
                    'image': '@url(optimized/iPhone6Plus-portrait.avif)',
                    'insets': { 'left': 26, 'top': 107, 'right': 30, 'bottom': 111 },
                },
                'width': 414,
                'height': 736,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '13.2.3', 'architecture': '', 'model': 'iPhone', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 133,
        'show-by-default': false,
        'title': 'iPhone X',
        'screen': {
            'horizontal': { 'width': 812, 'height': 375 },
            'device-pixel-ratio': 3,
            'vertical': { 'width': 375, 'height': 812 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '13.2.3', 'architecture': '', 'model': 'iPhone', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'BlackBerry Z30',
        'screen': {
            'horizontal': { 'width': 640, 'height': 360 },
            'device-pixel-ratio': 2,
            'vertical': { 'width': 360, 'height': 640 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+',
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Nexus 4',
        'screen': {
            'horizontal': { 'width': 640, 'height': 384 },
            'device-pixel-ratio': 2,
            'vertical': { 'width': 384, 'height': 640 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '4.4.2', 'architecture': '', 'model': 'Nexus 4', 'mobile': true },
        'type': 'phone',
    },
    {
        'title': 'Nexus 5',
        'type': 'phone',
        'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '6.0', 'architecture': '', 'model': 'Nexus 5', 'mobile': true },
        'capabilities': ['touch', 'mobile'],
        'show-by-default': false,
        'screen': {
            'device-pixel-ratio': 3,
            'vertical': { 'width': 360, 'height': 640 },
            'horizontal': { 'width': 640, 'height': 360 },
        },
        'modes': [
            {
                'title': 'default',
                'orientation': 'vertical',
                'insets': { 'left': 0, 'top': 25, 'right': 0, 'bottom': 48 },
                'image': '@url(optimized/google-nexus-5-vertical-default-1x.avif) 1x, @url(optimized/google-nexus-5-vertical-default-2x.avif) 2x',
            },
            {
                'title': 'navigation bar',
                'orientation': 'vertical',
                'insets': { 'left': 0, 'top': 80, 'right': 0, 'bottom': 48 },
                'image': '@url(optimized/google-nexus-5-vertical-navigation-1x.avif) 1x, @url(optimized/google-nexus-5-vertical-navigation-2x.avif) 2x',
            },
            {
                'title': 'keyboard',
                'orientation': 'vertical',
                'insets': { 'left': 0, 'top': 80, 'right': 0, 'bottom': 312 },
                'image': '@url(optimized/google-nexus-5-vertical-keyboard-1x.avif) 1x, @url(optimized/google-nexus-5-vertical-keyboard-2x.avif) 2x',
            },
            {
                'title': 'default',
                'orientation': 'horizontal',
                'insets': { 'left': 0, 'top': 25, 'right': 42, 'bottom': 0 },
                'image': '@url(optimized/google-nexus-5-horizontal-default-1x.avif) 1x, @url(optimized/google-nexus-5-horizontal-default-2x.avif) 2x',
            },
            {
                'title': 'navigation bar',
                'orientation': 'horizontal',
                'insets': { 'left': 0, 'top': 80, 'right': 42, 'bottom': 0 },
                'image': '@url(optimized/google-nexus-5-horizontal-navigation-1x.avif) 1x, @url(optimized/google-nexus-5-horizontal-navigation-2x.avif) 2x',
            },
            {
                'title': 'keyboard',
                'orientation': 'horizontal',
                'insets': { 'left': 0, 'top': 80, 'right': 42, 'bottom': 202 },
                'image': '@url(optimized/google-nexus-5-horizontal-keyboard-1x.avif) 1x, @url(optimized/google-nexus-5-horizontal-keyboard-2x.avif) 2x',
            },
        ],
    },
    {
        'title': 'Nexus 5X',
        'type': 'phone',
        'user-agent': 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '8.0.0', 'architecture': '', 'model': 'Nexus 5X', 'mobile': true },
        'capabilities': ['touch', 'mobile'],
        'show-by-default': false,
        'screen': {
            'device-pixel-ratio': 2.625,
            'vertical': {
                'outline': {
                    'image': '@url(optimized/Nexus5X-portrait.avif)',
                    'insets': { 'left': 18, 'top': 88, 'right': 22, 'bottom': 98 },
                },
                'width': 412,
                'height': 732,
            },
            'horizontal': {
                'outline': {
                    'image': '@url(optimized/Nexus5X-landscape.avif)',
                    'insets': { 'left': 88, 'top': 21, 'right': 98, 'bottom': 19 },
                },
                'width': 732,
                'height': 412,
            },
        },
        'modes': [
            {
                'title': 'default',
                'orientation': 'vertical',
                'insets': { 'left': 0, 'top': 24, 'right': 0, 'bottom': 48 },
                'image': '@url(optimized/google-nexus-5x-vertical-default-1x.avif) 1x, @url(optimized/google-nexus-5x-vertical-default-2x.avif) 2x',
            },
            {
                'title': 'navigation bar',
                'orientation': 'vertical',
                'insets': { 'left': 0, 'top': 80, 'right': 0, 'bottom': 48 },
                'image': '@url(optimized/google-nexus-5x-vertical-navigation-1x.avif) 1x, @url(optimized/google-nexus-5x-vertical-navigation-2x.avif) 2x',
            },
            {
                'title': 'keyboard',
                'orientation': 'vertical',
                'insets': { 'left': 0, 'top': 80, 'right': 0, 'bottom': 342 },
                'image': '@url(optimized/google-nexus-5x-vertical-keyboard-1x.avif) 1x, @url(optimized/google-nexus-5x-vertical-keyboard-2x.avif) 2x',
            },
            {
                'title': 'default',
                'orientation': 'horizontal',
                'insets': { 'left': 0, 'top': 24, 'right': 48, 'bottom': 0 },
                'image': '@url(optimized/google-nexus-5x-horizontal-default-1x.avif) 1x, @url(optimized/google-nexus-5x-horizontal-default-2x.avif) 2x',
            },
            {
                'title': 'navigation bar',
                'orientation': 'horizontal',
                'insets': { 'left': 0, 'top': 80, 'right': 48, 'bottom': 0 },
                'image': '@url(optimized/google-nexus-5x-horizontal-navigation-1x.avif) 1x, @url(optimized/google-nexus-5x-horizontal-navigation-2x.avif) 2x',
            },
            {
                'title': 'keyboard',
                'orientation': 'horizontal',
                'insets': { 'left': 0, 'top': 80, 'right': 48, 'bottom': 222 },
                'image': '@url(optimized/google-nexus-5x-horizontal-keyboard-1x.avif) 1x, @url(optimized/google-nexus-5x-horizontal-keyboard-2x.avif) 2x',
            },
        ],
    },
    {
        'show-by-default': false,
        'title': 'Nexus 6',
        'screen': {
            'horizontal': { 'width': 732, 'height': 412 },
            'device-pixel-ratio': 3.5,
            'vertical': { 'width': 412, 'height': 732 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '7.1.1', 'architecture': '', 'model': 'Nexus 6', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Nexus 6P',
        'screen': {
            'horizontal': {
                'outline': {
                    'image': '@url(optimized/Nexus6P-landscape.avif)',
                    'insets': { 'left': 94, 'top': 17, 'right': 88, 'bottom': 17 },
                },
                'width': 732,
                'height': 412,
            },
            'device-pixel-ratio': 3.5,
            'vertical': {
                'outline': {
                    'image': '@url(optimized/Nexus6P-portrait.avif)',
                    'insets': { 'left': 16, 'top': 94, 'right': 16, 'bottom': 88 },
                },
                'width': 412,
                'height': 732,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '8.0.0', 'architecture': '', 'model': 'Nexus 6P', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 120,
        'show-by-default': false,
        'title': 'Pixel 2',
        'screen': {
            'horizontal': { 'width': 731, 'height': 411 },
            'device-pixel-ratio': 2.625,
            'vertical': { 'width': 411, 'height': 731 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '8.0', 'architecture': '', 'model': 'Pixel 2', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 121,
        'show-by-default': false,
        'title': 'Pixel 2 XL',
        'screen': {
            'horizontal': { 'width': 823, 'height': 411 },
            'device-pixel-ratio': 3.5,
            'vertical': { 'width': 411, 'height': 823 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '8.0.0', 'architecture': '', 'model': 'Pixel 2 XL', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Pixel 3',
        'screen': {
            'horizontal': { 'width': 786, 'height': 393 },
            'device-pixel-ratio': 2.75,
            'vertical': { 'width': 393, 'height': 786 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '9', 'architecture': '', 'model': 'Pixel 3', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Pixel 4',
        'screen': {
            'horizontal': { 'width': 745, 'height': 353 },
            'device-pixel-ratio': 3,
            'vertical': { 'width': 353, 'height': 745 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '10', 'architecture': '', 'model': 'Pixel 4', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'LG Optimus L70',
        'screen': {
            'horizontal': { 'width': 640, 'height': 384 },
            'device-pixel-ratio': 1.25,
            'vertical': { 'width': 384, 'height': 640 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '4.4.2', 'architecture': '', 'model': 'LGMS323', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Nokia N9',
        'screen': {
            'horizontal': { 'width': 854, 'height': 480 },
            'device-pixel-ratio': 1,
            'vertical': { 'width': 480, 'height': 854 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13',
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Nokia Lumia 520',
        'screen': {
            'horizontal': { 'width': 533, 'height': 320 },
            'device-pixel-ratio': 1.5,
            'vertical': { 'width': 320, 'height': 533 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)',
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Microsoft Lumia 550',
        'screen': {
            'horizontal': { 'width': 640, 'height': 360 },
            'device-pixel-ratio': 2,
            'vertical': { 'width': 640, 'height': 360 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36 Edge/14.14263',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '4.2.1', 'architecture': '', 'model': 'Lumia 550', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Microsoft Lumia 950',
        'screen': {
            'horizontal': { 'width': 640, 'height': 360 },
            'device-pixel-ratio': 4,
            'vertical': { 'width': 360, 'height': 640 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36 Edge/14.14263',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '4.2.1', 'architecture': '', 'model': 'Lumia 950', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Galaxy S III',
        'screen': {
            'horizontal': { 'width': 640, 'height': 360 },
            'device-pixel-ratio': 2,
            'vertical': { 'width': 360, 'height': 640 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '4.0', 'architecture': '', 'model': 'GT-I9300', 'mobile': true },
        'type': 'phone',
    },
    {
        'order': 110,
        'show-by-default': false,
        'title': 'Galaxy S5',
        'screen': {
            'horizontal': { 'width': 640, 'height': 360 },
            'device-pixel-ratio': 3,
            'vertical': { 'width': 360, 'height': 640 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '5.0', 'architecture': '', 'model': 'SM-G900P', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Galaxy S8',
        'screen': {
            'horizontal': { 'width': 740, 'height': 360 },
            'device-pixel-ratio': 3,
            'vertical': { 'width': 360, 'height': 740 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '7.0', 'architecture': '', 'model': 'SM-G950U', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Galaxy S9+',
        'screen': {
            'horizontal': { 'width': 658, 'height': 320 },
            'device-pixel-ratio': 4.5,
            'vertical': { 'width': 320, 'height': 658 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '8.0.0', 'architecture': '', 'model': 'SM-G965U', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Galaxy Tab S4',
        'screen': {
            'horizontal': { 'width': 1138, 'height': 712 },
            'device-pixel-ratio': 2.25,
            'vertical': { 'width': 712, 'height': 1138 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '8.1.0', 'architecture': '', 'model': 'SM-T837A', 'mobile': false },
        'type': 'phone',
    },
    {
        'order': 1,
        'show-by-default': false,
        'title': 'JioPhone 2',
        'screen': {
            'horizontal': { 'width': 320, 'height': 240 },
            'device-pixel-ratio': 1,
            'vertical': { 'width': 240, 'height': 320 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5',
        'user-agent-metadata': {
            'platform': 'Android',
            'platformVersion': '',
            'architecture': '',
            'model': 'LYF/F300B/LYF-F300B-001-01-15-130718-i',
            'mobile': true,
        },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Kindle Fire HDX',
        'screen': {
            'horizontal': { 'width': 1280, 'height': 800 },
            'device-pixel-ratio': 2,
            'vertical': { 'width': 800, 'height': 1280 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true',
        'type': 'tablet',
    },
    {
        'order': 140,
        'show-by-default': false,
        'title': 'iPad',
        'screen': {
            'horizontal': {
                'outline': {
                    'image': '@url(optimized/iPad-landscape.avif)',
                    'insets': { 'left': 112, 'top': 56, 'right': 116, 'bottom': 52 },
                },
                'width': 1024,
                'height': 768,
            },
            'device-pixel-ratio': 2,
            'vertical': {
                'outline': {
                    'image': '@url(optimized/iPad-portrait.avif)',
                    'insets': { 'left': 52, 'top': 114, 'right': 55, 'bottom': 114 },
                },
                'width': 768,
                'height': 1024,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '11.0', 'architecture': '', 'model': 'iPad', 'mobile': true },
        'type': 'tablet',
    },
    {
        'order': 141,
        'show-by-default': false,
        'title': 'iPad Pro',
        'screen': {
            'horizontal': { 'width': 1366, 'height': 1024 },
            'device-pixel-ratio': 2,
            'vertical': { 'width': 1024, 'height': 1366 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',
        'user-agent-metadata': { 'platform': 'iOS', 'platformVersion': '11.0', 'architecture': '', 'model': 'iPad', 'mobile': true },
        'type': 'tablet',
    },
    {
        'show-by-default': false,
        'title': 'Blackberry PlayBook',
        'screen': {
            'horizontal': { 'width': 1024, 'height': 600 },
            'device-pixel-ratio': 1,
            'vertical': { 'width': 600, 'height': 1024 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+',
        'type': 'tablet',
    },
    {
        'show-by-default': false,
        'title': 'Nexus 10',
        'screen': {
            'horizontal': { 'width': 1280, 'height': 800 },
            'device-pixel-ratio': 2,
            'vertical': { 'width': 800, 'height': 1280 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '6.0.1', 'architecture': '', 'model': 'Nexus 10', 'mobile': false },
        'type': 'tablet',
    },
    {
        'show-by-default': false,
        'title': 'Nexus 7',
        'screen': {
            'horizontal': { 'width': 960, 'height': 600 },
            'device-pixel-ratio': 2,
            'vertical': { 'width': 600, 'height': 960 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '6.0.1', 'architecture': '', 'model': 'Nexus 7', 'mobile': false },
        'type': 'tablet',
    },
    {
        'show-by-default': false,
        'title': 'Galaxy Note 3',
        'screen': {
            'horizontal': { 'width': 640, 'height': 360 },
            'device-pixel-ratio': 3,
            'vertical': { 'width': 360, 'height': 640 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '4.3', 'architecture': '', 'model': 'SM-N900T', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Galaxy Note II',
        'screen': {
            'horizontal': { 'width': 640, 'height': 360 },
            'device-pixel-ratio': 2,
            'vertical': { 'width': 360, 'height': 640 },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '4.1', 'architecture': '', 'model': 'GT-N7100', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': i18nLazyString$b(UIStrings$q.laptopWithTouch),
        'screen': {
            'horizontal': { 'width': 1280, 'height': 950 },
            'device-pixel-ratio': 1,
            'vertical': { 'width': 950, 'height': 1280 },
        },
        'capabilities': ['touch'],
        'user-agent': '',
        'type': 'notebook',
        'modes': [{ 'title': 'default', 'orientation': 'horizontal' }],
    },
    {
        'show-by-default': false,
        'title': i18nLazyString$b(UIStrings$q.laptopWithHiDPIScreen),
        'screen': {
            'horizontal': { 'width': 1440, 'height': 900 },
            'device-pixel-ratio': 2,
            'vertical': { 'width': 900, 'height': 1440 },
        },
        'capabilities': [],
        'user-agent': '',
        'type': 'notebook',
        'modes': [{ 'title': 'default', 'orientation': 'horizontal' }],
    },
    {
        'show-by-default': false,
        'title': i18nLazyString$b(UIStrings$q.laptopWithMDPIScreen),
        'screen': {
            'horizontal': { 'width': 1280, 'height': 800 },
            'device-pixel-ratio': 1,
            'vertical': { 'width': 800, 'height': 1280 },
        },
        'capabilities': [],
        'user-agent': '',
        'type': 'notebook',
        'modes': [{ 'title': 'default', 'orientation': 'horizontal' }],
    },
    {
        'show-by-default': false,
        'title': 'Moto G4',
        'screen': {
            'horizontal': {
                'outline': {
                    'image': '@url(optimized/MotoG4-landscape.avif)',
                    'insets': { 'left': 91, 'top': 30, 'right': 74, 'bottom': 30 },
                },
                'width': 640,
                'height': 360,
            },
            'device-pixel-ratio': 3,
            'vertical': {
                'outline': {
                    'image': '@url(optimized/MotoG4-portrait.avif)',
                    'insets': { 'left': 30, 'top': 91, 'right': 30, 'bottom': 74 },
                },
                'width': 360,
                'height': 640,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '6.0.1', 'architecture': '', 'model': 'Moto G (4)', 'mobile': true },
        'type': 'phone',
    },
    {
        'show-by-default': false,
        'title': 'Moto G Power',
        'screen': {
            'device-pixel-ratio': 1.75,
            'horizontal': {
                'width': 823,
                'height': 412,
            },
            'vertical': {
                'width': 412,
                'height': 823,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 11; moto g power (2022)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36',
        'user-agent-metadata': {
            'platform': 'Android',
            'platformVersion': '11',
            'architecture': '',
            'model': 'moto g power (2022)',
            'mobile': true,
        },
        'type': 'phone',
    },
    {
        'order': 200,
        'show-by-default': false,
        'title': 'Facebook on Android',
        'screen': {
            'horizontal': {
                'width': 892,
                'height': 412,
            },
            'device-pixel-ratio': 3.5,
            'vertical': {
                'width': 412,
                'height': 892,
            },
        },
        'capabilities': ['touch', 'mobile'],
        'user-agent': 'Mozilla/5.0 (Linux; Android 12; Pixel 6 Build/SQ3A.220705.004; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/%s Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/407.0.0.0.65;]',
        'user-agent-metadata': { 'platform': 'Android', 'platformVersion': '12', 'architecture': '', 'model': 'Pixel 6', 'mobile': true },
        'type': 'phone',
    },
];

// Copyright 2015 The Chromium Authors
const UIStrings$p = {
    widthCannotBeEmpty: 'Width cannot be empty.',
    widthMustBeANumber: 'Width must be a number.',
    widthMustBeLessThanOrEqualToS: 'Width must be less than or equal to {PH1}.',
    widthMustBeGreaterThanOrEqualToS: 'Width must be greater than or equal to {PH1}.',
    heightCannotBeEmpty: 'Height cannot be empty.',
    heightMustBeANumber: 'Height must be a number.',
    heightMustBeLessThanOrEqualToS: 'Height must be less than or equal to {PH1}.',
    heightMustBeGreaterThanOrEqualTo: 'Height must be greater than or equal to {PH1}.',
    devicePixelRatioMustBeANumberOr: 'Device pixel ratio must be a number or blank.',
    devicePixelRatioMustBeLessThanOr: 'Device pixel ratio must be less than or equal to {PH1}.',
    devicePixelRatioMustBeGreater: 'Device pixel ratio must be greater than or equal to {PH1}.',
};
const str_$o = registerUIStrings('models/emulation/DeviceModeModel.ts', UIStrings$p);
const i18nString$b = getLocalizedString.bind(undefined, str_$o);
let deviceModeModelInstance;
class DeviceModeModel extends ObjectWrapper {
    #screenRect;
    #visiblePageRect;
    #availableSize;
    #preferredSize;
    #initialized;
    #appliedDeviceSize;
    #appliedDeviceScaleFactor;
    #appliedUserAgentType;
    #scaleSetting;
    #scale;
    #widthSetting;
    #heightSetting;
    #uaSetting;
    #deviceScaleFactorSetting;
    #deviceOutlineSetting;
    #toolbarControlsEnabledSetting;
    #type;
    #device;
    #mode;
    #fitScale;
    #touchEnabled;
    #touchMobile;
    #emulationModel;
    #onModelAvailable;
    #outlineRect;
    #screenOrientationLocked;
    constructor() {
        super();
        this.#screenRect = new Rect(0, 0, 1, 1);
        this.#visiblePageRect = new Rect(0, 0, 1, 1);
        this.#availableSize = new Size(1, 1);
        this.#preferredSize = new Size(1, 1);
        this.#initialized = false;
        this.#appliedDeviceSize = new Size(1, 1);
        this.#appliedDeviceScaleFactor = globalThis.devicePixelRatio;
        this.#appliedUserAgentType = "Desktop" ;
        this.#scaleSetting = Settings.instance().createSetting('emulation.device-scale', 1);
        if (!this.#scaleSetting.get()) {
            this.#scaleSetting.set(1);
        }
        this.#scaleSetting.addChangeListener(this.scaleSettingChanged, this);
        this.#scale = 1;
        this.#widthSetting = Settings.instance().createSetting('emulation.device-width', 400);
        if (this.#widthSetting.get() < MinDeviceSize) {
            this.#widthSetting.set(MinDeviceSize);
        }
        if (this.#widthSetting.get() > MaxDeviceSize) {
            this.#widthSetting.set(MaxDeviceSize);
        }
        this.#widthSetting.addChangeListener(this.widthSettingChanged, this);
        this.#heightSetting = Settings.instance().createSetting('emulation.device-height', 0);
        if (this.#heightSetting.get() && this.#heightSetting.get() < MinDeviceSize) {
            this.#heightSetting.set(MinDeviceSize);
        }
        if (this.#heightSetting.get() > MaxDeviceSize) {
            this.#heightSetting.set(MaxDeviceSize);
        }
        this.#heightSetting.addChangeListener(this.heightSettingChanged, this);
        this.#uaSetting = Settings.instance().createSetting('emulation.device-ua', "Mobile" );
        this.#uaSetting.addChangeListener(this.uaSettingChanged, this);
        this.#deviceScaleFactorSetting =
            Settings.instance().createSetting('emulation.device-scale-factor', 0);
        this.#deviceScaleFactorSetting.addChangeListener(this.deviceScaleFactorSettingChanged, this);
        this.#deviceOutlineSetting = Settings.instance().moduleSetting('emulation.show-device-outline');
        this.#deviceOutlineSetting.addChangeListener(this.deviceOutlineSettingChanged, this);
        this.#toolbarControlsEnabledSetting = Settings.instance().createSetting('emulation.toolbar-controls-enabled', true, "Session" );
        this.#type = Type.None;
        this.#device = null;
        this.#mode = null;
        this.#fitScale = 1;
        this.#touchEnabled = false;
        this.#touchMobile = false;
        this.#emulationModel = null;
        this.#onModelAvailable = null;
        this.#screenOrientationLocked = false;
        TargetManager.instance().observeModels(EmulationModel, this);
    }
    static instance(opts) {
        if (!deviceModeModelInstance || opts?.forceNew) {
            deviceModeModelInstance = new DeviceModeModel();
        }
        return deviceModeModelInstance;
    }
    static tryInstance(opts) {
        try {
            return this.instance(opts);
        }
        catch {
            return null;
        }
    }
    static widthValidator(value) {
        let valid = false;
        let errorMessage;
        if (!value) {
            errorMessage = i18nString$b(UIStrings$p.widthCannotBeEmpty);
        }
        else if (!/^[\d]+$/.test(value)) {
            errorMessage = i18nString$b(UIStrings$p.widthMustBeANumber);
        }
        else if (Number(value) > MaxDeviceSize) {
            errorMessage = i18nString$b(UIStrings$p.widthMustBeLessThanOrEqualToS, { PH1: MaxDeviceSize });
        }
        else if (Number(value) < MinDeviceSize) {
            errorMessage = i18nString$b(UIStrings$p.widthMustBeGreaterThanOrEqualToS, { PH1: MinDeviceSize });
        }
        else {
            valid = true;
        }
        return { valid, errorMessage };
    }
    static heightValidator(value) {
        let valid = false;
        let errorMessage;
        if (!value) {
            errorMessage = i18nString$b(UIStrings$p.heightCannotBeEmpty);
        }
        else if (!/^[\d]+$/.test(value)) {
            errorMessage = i18nString$b(UIStrings$p.heightMustBeANumber);
        }
        else if (Number(value) > MaxDeviceSize) {
            errorMessage = i18nString$b(UIStrings$p.heightMustBeLessThanOrEqualToS, { PH1: MaxDeviceSize });
        }
        else if (Number(value) < MinDeviceSize) {
            errorMessage = i18nString$b(UIStrings$p.heightMustBeGreaterThanOrEqualTo, { PH1: MinDeviceSize });
        }
        else {
            valid = true;
        }
        return { valid, errorMessage };
    }
    static scaleValidator(value) {
        let valid = false;
        let errorMessage;
        const parsedValue = Number(value.trim());
        if (!value) {
            valid = true;
        }
        else if (Number.isNaN(parsedValue)) {
            errorMessage = i18nString$b(UIStrings$p.devicePixelRatioMustBeANumberOr);
        }
        else if (Number(value) > MaxDeviceScaleFactor) {
            errorMessage = i18nString$b(UIStrings$p.devicePixelRatioMustBeLessThanOr, { PH1: MaxDeviceScaleFactor });
        }
        else if (Number(value) < MinDeviceScaleFactor) {
            errorMessage = i18nString$b(UIStrings$p.devicePixelRatioMustBeGreater, { PH1: MinDeviceScaleFactor });
        }
        else {
            valid = true;
        }
        return { valid, errorMessage };
    }
    get scaleSettingInternal() {
        return this.#scaleSetting;
    }
    setAvailableSize(availableSize, preferredSize) {
        this.#availableSize = availableSize;
        this.#preferredSize = preferredSize;
        this.#initialized = true;
        this.calculateAndEmulate(false);
    }
    emulate(type, device, mode, scale) {
        const resetPageScaleFactor = this.#type !== type || this.#device !== device || this.#mode !== mode;
        this.#type = type;
        if (type === Type.Device && device && mode) {
            console.assert(Boolean(device) && Boolean(mode), 'Must pass device and mode for device emulation');
            this.#mode = mode;
            this.#device = device;
            if (this.#initialized) {
                const orientation = device.orientationByName(mode.orientation);
                this.#scaleSetting.set(scale ||
                    this.calculateFitScale(orientation.width, orientation.height, this.currentOutline(), this.currentInsets()));
            }
        }
        else {
            this.#device = null;
            this.#mode = null;
        }
        if (type !== Type.None) {
            userMetrics.actionTaken(Action.DeviceModeEnabled);
        }
        this.calculateAndEmulate(resetPageScaleFactor);
    }
    setWidth(width) {
        const max = Math.min(MaxDeviceSize, this.preferredScaledWidth());
        width = Math.max(Math.min(width, max), 1);
        this.#widthSetting.set(width);
    }
    setWidthAndScaleToFit(width) {
        width = Math.max(Math.min(width, MaxDeviceSize), 1);
        this.#scaleSetting.set(this.calculateFitScale(width, this.#heightSetting.get()));
        this.#widthSetting.set(width);
    }
    setHeight(height) {
        const max = Math.min(MaxDeviceSize, this.preferredScaledHeight());
        height = Math.max(Math.min(height, max), 0);
        if (height === this.preferredScaledHeight()) {
            height = 0;
        }
        this.#heightSetting.set(height);
    }
    setHeightAndScaleToFit(height) {
        height = Math.max(Math.min(height, MaxDeviceSize), 0);
        this.#scaleSetting.set(this.calculateFitScale(this.#widthSetting.get(), height));
        this.#heightSetting.set(height);
    }
    setScale(scale) {
        this.#scaleSetting.set(scale);
    }
    device() {
        return this.#device;
    }
    mode() {
        return this.#mode;
    }
    type() {
        return this.#type;
    }
    screenImage() {
        return (this.#device && this.#mode) ? this.#device.modeImage(this.#mode) : '';
    }
    outlineImage() {
        return (this.#device && this.#mode && this.#deviceOutlineSetting.get()) ? this.#device.outlineImage(this.#mode) :
            '';
    }
    outlineRect() {
        return this.#outlineRect || null;
    }
    screenRect() {
        return this.#screenRect;
    }
    visiblePageRect() {
        return this.#visiblePageRect;
    }
    scale() {
        return this.#scale;
    }
    fitScale() {
        return this.#fitScale;
    }
    appliedDeviceSize() {
        return this.#appliedDeviceSize;
    }
    appliedDeviceScaleFactor() {
        return this.#appliedDeviceScaleFactor;
    }
    appliedUserAgentType() {
        return this.#appliedUserAgentType;
    }
    isFullHeight() {
        return !this.#heightSetting.get();
    }
    isMobile() {
        switch (this.#type) {
            case Type.Device:
                return this.#device ? this.#device.mobile() : false;
            case Type.None:
                return false;
            case Type.Responsive:
                return this.#uaSetting.get() === "Mobile"  || this.#uaSetting.get() === "Mobile (no touch)" ;
        }
        return false;
    }
    enabledSetting() {
        return Settings.instance().createSetting('emulation.show-device-mode', false);
    }
    scaleSetting() {
        return this.#scaleSetting;
    }
    uaSetting() {
        return this.#uaSetting;
    }
    deviceScaleFactorSetting() {
        return this.#deviceScaleFactorSetting;
    }
    deviceOutlineSetting() {
        return this.#deviceOutlineSetting;
    }
    toolbarControlsEnabledSetting() {
        return this.#toolbarControlsEnabledSetting;
    }
    reset() {
        this.#deviceScaleFactorSetting.set(0);
        this.#scaleSetting.set(1);
        this.setWidth(400);
        this.setHeight(0);
        this.#uaSetting.set("Mobile" );
    }
    modelAdded(emulationModel) {
        if (emulationModel.target() === TargetManager.instance().primaryPageTarget() &&
            emulationModel.supportsDeviceEmulation()) {
            this.#emulationModel = emulationModel;
            if (this.#onModelAvailable) {
                const callback = this.#onModelAvailable;
                this.#onModelAvailable = null;
                callback();
            }
            emulationModel.addEventListener("ScreenOrientationLockChanged" , this.onScreenOrientationLockChanged, this);
            const resourceTreeModel = emulationModel.target().model(ResourceTreeModel);
            if (resourceTreeModel) {
                resourceTreeModel.addEventListener(Events$6.FrameResized, this.onFrameChange, this);
                resourceTreeModel.addEventListener(Events$6.FrameNavigated, this.onFrameChange, this);
            }
        }
        else {
            void emulationModel.emulateTouch(this.#touchEnabled, this.#touchMobile);
        }
    }
    modelRemoved(emulationModel) {
        if (this.#emulationModel === emulationModel) {
            emulationModel.removeEventListener("ScreenOrientationLockChanged" , this.onScreenOrientationLockChanged, this);
            this.#emulationModel = null;
            this.#screenOrientationLocked = false;
            this.dispatchEventToListeners("Updated" );
        }
    }
    inspectedURL() {
        return this.#emulationModel ? this.#emulationModel.target().inspectedURL() : null;
    }
    onFrameChange() {
        const overlayModel = this.#emulationModel ? this.#emulationModel.overlayModel() : null;
        if (!overlayModel) {
            return;
        }
        this.showHingeIfApplicable(overlayModel);
    }
    onScreenOrientationLockChanged(event) {
        this.#screenOrientationLocked = event.data.locked;
        if (event.data.locked && event.data.orientation) {
            this.applyOrientationLock(event.data.orientation);
        }
        this.dispatchEventToListeners("Updated" );
    }
    applyOrientationLock(orientation) {
        const wantsLandscape = orientation.type === "landscapePrimary"  ||
            orientation.type === "landscapeSecondary" ;
        if (this.#type === Type.Device && this.#device && this.#mode) {
            const isCurrentlyLandscape = this.#mode.orientation === Horizontal || this.#mode.orientation === HorizontalSpanned;
            if (wantsLandscape !== isCurrentlyLandscape) {
                const rotationPartner = this.#device.getRotationPartner(this.#mode);
                if (rotationPartner) {
                    this.emulate(this.#type, this.#device, rotationPartner);
                }
            }
        }
        else if (this.#type === Type.Responsive) {
            const appliedSize = this.appliedDeviceSize();
            const isCurrentlyLandscape = appliedSize.width > appliedSize.height;
            if (wantsLandscape !== isCurrentlyLandscape) {
                this.setSizeAndScaleToFit(appliedSize.height, appliedSize.width);
            }
        }
    }
    isScreenOrientationLocked() {
        return this.#screenOrientationLocked;
    }
    scaleSettingChanged() {
        this.calculateAndEmulate(false);
    }
    widthSettingChanged() {
        this.calculateAndEmulate(false);
    }
    heightSettingChanged() {
        this.calculateAndEmulate(false);
    }
    uaSettingChanged() {
        this.calculateAndEmulate(true);
    }
    deviceScaleFactorSettingChanged() {
        this.calculateAndEmulate(false);
    }
    deviceOutlineSettingChanged() {
        this.calculateAndEmulate(false);
    }
    preferredScaledWidth() {
        return Math.floor(this.#preferredSize.width / (this.#scaleSetting.get() || 1));
    }
    preferredScaledHeight() {
        return Math.floor(this.#preferredSize.height / (this.#scaleSetting.get() || 1));
    }
    currentOutline() {
        let outline = new Insets(0, 0, 0, 0);
        if (this.#type !== Type.Device || !this.#device || !this.#mode) {
            return outline;
        }
        const orientation = this.#device.orientationByName(this.#mode.orientation);
        if (this.#deviceOutlineSetting.get()) {
            outline = orientation.outlineInsets || outline;
        }
        return outline;
    }
    currentInsets() {
        if (this.#type !== Type.Device || !this.#mode) {
            return new Insets(0, 0, 0, 0);
        }
        return this.#mode.insets;
    }
    getScreenOrientationType() {
        if (!this.#mode) {
            throw new Error('Mode required to get orientation type.');
        }
        switch (this.#mode.orientation) {
            case VerticalSpanned:
            case Vertical:
                return "portraitPrimary" ;
            case HorizontalSpanned:
            case Horizontal:
            default:
                return "landscapePrimary" ;
        }
    }
    calculateAndEmulate(resetPageScaleFactor) {
        if (!this.#emulationModel) {
            this.#onModelAvailable = this.calculateAndEmulate.bind(this, resetPageScaleFactor);
        }
        const mobile = this.isMobile();
        const overlayModel = this.#emulationModel ? this.#emulationModel.overlayModel() : null;
        if (overlayModel) {
            this.showHingeIfApplicable(overlayModel);
        }
        if (this.#type === Type.Device && this.#device && this.#mode) {
            const orientation = this.#device.orientationByName(this.#mode.orientation);
            const outline = this.currentOutline();
            const insets = this.currentInsets();
            this.#fitScale = this.calculateFitScale(orientation.width, orientation.height, outline, insets);
            if (mobile) {
                this.#appliedUserAgentType = this.#device.touch() ? "Mobile"  : "Mobile (no touch)" ;
            }
            else {
                this.#appliedUserAgentType = this.#device.touch() ? "Desktop (touch)"  : "Desktop" ;
            }
            this.applyDeviceMetrics(new Size(orientation.width, orientation.height), insets, outline, this.#scaleSetting.get(), this.#device.deviceScaleFactor, mobile, this.getScreenOrientationType(), resetPageScaleFactor);
            this.applyUserAgent(this.#device.userAgent, this.#device.userAgentMetadata);
            this.applyTouch(this.#device.touch(), mobile);
        }
        else if (this.#type === Type.None) {
            this.#fitScale = this.calculateFitScale(this.#availableSize.width, this.#availableSize.height);
            this.#appliedUserAgentType = "Desktop" ;
            this.applyDeviceMetrics(this.#availableSize, new Insets(0, 0, 0, 0), new Insets(0, 0, 0, 0), 1, 0, mobile, null, resetPageScaleFactor);
            this.applyUserAgent('', null);
            this.applyTouch(false, false);
        }
        else if (this.#type === Type.Responsive) {
            let screenWidth = this.#widthSetting.get();
            if (!screenWidth || screenWidth > this.preferredScaledWidth()) {
                screenWidth = this.preferredScaledWidth();
            }
            let screenHeight = this.#heightSetting.get();
            if (!screenHeight || screenHeight > this.preferredScaledHeight()) {
                screenHeight = this.preferredScaledHeight();
            }
            const defaultDeviceScaleFactor = mobile ? defaultMobileScaleFactor : 0;
            this.#fitScale = this.calculateFitScale(this.#widthSetting.get(), this.#heightSetting.get());
            this.#appliedUserAgentType = this.#uaSetting.get();
            this.applyDeviceMetrics(new Size(screenWidth, screenHeight), new Insets(0, 0, 0, 0), new Insets(0, 0, 0, 0), this.#scaleSetting.get(), this.#deviceScaleFactorSetting.get() || defaultDeviceScaleFactor, mobile, screenHeight >= screenWidth ? "portraitPrimary"  :
                "landscapePrimary" , resetPageScaleFactor);
            this.applyUserAgent(mobile ? defaultMobileUserAgent : '', mobile ? defaultMobileUserAgentMetadata : null);
            this.applyTouch(this.#uaSetting.get() === "Desktop (touch)"  || this.#uaSetting.get() === "Mobile" , this.#uaSetting.get() === "Mobile" );
        }
        if (overlayModel) {
            overlayModel.setShowViewportSizeOnResize(this.#type === Type.None);
        }
        this.dispatchEventToListeners("Updated" );
    }
    calculateFitScale(screenWidth, screenHeight, outline, insets) {
        const outlineWidth = outline ? outline.left + outline.right : 0;
        const outlineHeight = outline ? outline.top + outline.bottom : 0;
        const insetsWidth = insets ? insets.left + insets.right : 0;
        const insetsHeight = insets ? insets.top + insets.bottom : 0;
        let scale = Math.min(screenWidth ? this.#preferredSize.width / (screenWidth + outlineWidth) : 1, screenHeight ? this.#preferredSize.height / (screenHeight + outlineHeight) : 1);
        scale = Math.min(Math.floor(scale * 100), 100);
        let sharpScale = scale;
        while (sharpScale > scale * 0.7) {
            let sharp = true;
            if (screenWidth) {
                sharp = sharp && Number.isInteger((screenWidth - insetsWidth) * sharpScale / 100);
            }
            if (screenHeight) {
                sharp = sharp && Number.isInteger((screenHeight - insetsHeight) * sharpScale / 100);
            }
            if (sharp) {
                return sharpScale / 100;
            }
            sharpScale -= 1;
        }
        return scale / 100;
    }
    setSizeAndScaleToFit(width, height) {
        this.#scaleSetting.set(this.calculateFitScale(width, height));
        this.setWidth(width);
        this.setHeight(height);
    }
    applyUserAgent(userAgent, userAgentMetadata) {
        MultitargetNetworkManager.instance().setUserAgentOverride(userAgent, userAgentMetadata);
    }
    applyDeviceMetrics(screenSize, insets, outline, scale, deviceScaleFactor, mobile, screenOrientation, resetPageScaleFactor) {
        screenSize.width = Math.max(1, Math.floor(screenSize.width));
        screenSize.height = Math.max(1, Math.floor(screenSize.height));
        let pageWidth = screenSize.width - insets.left - insets.right;
        let pageHeight = screenSize.height - insets.top - insets.bottom;
        const positionX = insets.left;
        const positionY = insets.top;
        const screenOrientationAngle = screenOrientation === "landscapePrimary"  ? 90 : 0;
        this.#appliedDeviceSize = screenSize;
        this.#appliedDeviceScaleFactor = deviceScaleFactor || window.devicePixelRatio;
        this.#screenRect = new Rect(Math.max(0, (this.#availableSize.width - screenSize.width * scale) / 2), outline.top * scale, screenSize.width * scale, screenSize.height * scale);
        this.#outlineRect = new Rect(this.#screenRect.left - outline.left * scale, 0, (outline.left + screenSize.width + outline.right) * scale, (outline.top + screenSize.height + outline.bottom) * scale);
        this.#visiblePageRect = new Rect(positionX * scale, positionY * scale, Math.min(pageWidth * scale, this.#availableSize.width - this.#screenRect.left - positionX * scale), Math.min(pageHeight * scale, this.#availableSize.height - this.#screenRect.top - positionY * scale));
        this.#scale = scale;
        const displayFeature = this.getDisplayFeature();
        if (!displayFeature) {
            if (scale === 1 && this.#availableSize.width >= screenSize.width &&
                this.#availableSize.height >= screenSize.height) {
                pageWidth = 0;
                pageHeight = 0;
            }
            if (this.#visiblePageRect.width === pageWidth * scale && this.#visiblePageRect.height === pageHeight * scale &&
                Number.isInteger(pageWidth * scale) && Number.isInteger(pageHeight * scale)) {
                pageWidth = 0;
                pageHeight = 0;
            }
        }
        if (!this.#emulationModel) {
            return;
        }
        if (resetPageScaleFactor) {
            void this.#emulationModel.resetPageScaleFactor();
        }
        if (pageWidth || pageHeight || mobile || deviceScaleFactor || scale !== 1 || screenOrientation || displayFeature) {
            const metrics = {
                width: pageWidth,
                height: pageHeight,
                deviceScaleFactor,
                mobile,
                scale,
                screenWidth: screenSize.width,
                screenHeight: screenSize.height,
                positionX,
                positionY,
                dontSetVisibleSize: true,
            };
            if (displayFeature) {
                metrics.displayFeature = displayFeature;
                metrics.devicePosture = { type: "folded"  };
            }
            else {
                metrics.devicePosture = { type: "continuous"  };
            }
            if (screenOrientation) {
                metrics.screenOrientation = { type: screenOrientation, angle: screenOrientationAngle };
            }
            void this.#emulationModel.emulateDevice(metrics);
        }
        else {
            void this.#emulationModel.emulateDevice(null);
        }
    }
    exitHingeMode() {
        const overlayModel = this.#emulationModel ? this.#emulationModel.overlayModel() : null;
        if (overlayModel) {
            overlayModel.showHingeForDualScreen(null);
        }
    }
    async captureScreenshot(fullSize, clip) {
        const screenCaptureModel = this.#emulationModel ? this.#emulationModel.target().model(ScreenCaptureModel) : null;
        if (!screenCaptureModel) {
            return null;
        }
        let screenshotMode;
        if (clip) {
            screenshotMode = "fromClip" ;
        }
        else if (fullSize) {
            screenshotMode = "fullpage" ;
        }
        else {
            screenshotMode = "fromViewport" ;
        }
        const overlayModel = this.#emulationModel ? this.#emulationModel.overlayModel() : null;
        if (overlayModel) {
            overlayModel.setShowViewportSizeOnResize(false);
        }
        const screenshot = await screenCaptureModel.captureScreenshot("png" , 100, screenshotMode, clip);
        const deviceMetrics = {
            width: 0,
            height: 0,
            deviceScaleFactor: 0,
            mobile: false,
        };
        if (fullSize && this.#emulationModel) {
            if (this.#device && this.#mode) {
                const orientation = this.#device.orientationByName(this.#mode.orientation);
                deviceMetrics.width = orientation.width;
                deviceMetrics.height = orientation.height;
                const dispFeature = this.getDisplayFeature();
                if (dispFeature) {
                    deviceMetrics.displayFeature = dispFeature;
                }
            }
            else {
                deviceMetrics.width = 0;
                deviceMetrics.height = 0;
            }
            await this.#emulationModel.emulateDevice(deviceMetrics);
        }
        this.calculateAndEmulate(false);
        return screenshot;
    }
    applyTouch(touchEnabled, mobile) {
        this.#touchEnabled = touchEnabled;
        this.#touchMobile = mobile;
        for (const emulationModel of TargetManager.instance().models(EmulationModel)) {
            void emulationModel.emulateTouch(touchEnabled, mobile);
        }
    }
    showHingeIfApplicable(overlayModel) {
        const orientation = (this.#device && this.#mode) ? this.#device.orientationByName(this.#mode.orientation) : null;
        if (orientation?.hinge) {
            overlayModel.showHingeForDualScreen(orientation.hinge);
            return;
        }
        overlayModel.showHingeForDualScreen(null);
    }
    getDisplayFeatureOrientation() {
        if (!this.#mode) {
            throw new Error('Mode required to get display feature orientation.');
        }
        switch (this.#mode.orientation) {
            case VerticalSpanned:
            case Vertical:
                return "vertical" ;
            case HorizontalSpanned:
            case Horizontal:
            default:
                return "horizontal" ;
        }
    }
    getDisplayFeature() {
        if (!this.#device || !this.#mode ||
            (this.#mode.orientation !== VerticalSpanned && this.#mode.orientation !== HorizontalSpanned)) {
            return null;
        }
        const orientation = this.#device.orientationByName(this.#mode.orientation);
        if (!orientation?.hinge) {
            return null;
        }
        const hinge = orientation.hinge;
        return {
            orientation: this.getDisplayFeatureOrientation(),
            offset: (this.#mode.orientation === VerticalSpanned) ? hinge.x : hinge.y,
            maskLength: (this.#mode.orientation === VerticalSpanned) ? hinge.width : hinge.height,
        };
    }
}
class Insets {
    left;
    top;
    right;
    bottom;
    constructor(left, top, right, bottom) {
        this.left = left;
        this.top = top;
        this.right = right;
        this.bottom = bottom;
    }
    isEqual(insets) {
        return insets !== null && this.left === insets.left && this.top === insets.top && this.right === insets.right &&
            this.bottom === insets.bottom;
    }
}
class Rect {
    left;
    top;
    width;
    height;
    constructor(left, top, width, height) {
        this.left = left;
        this.top = top;
        this.width = width;
        this.height = height;
    }
    isEqual(rect) {
        return rect !== null && this.left === rect.left && this.top === rect.top && this.width === rect.width &&
            this.height === rect.height;
    }
    scale(scale) {
        return new Rect(this.left * scale, this.top * scale, this.width * scale, this.height * scale);
    }
    relativeTo(origin) {
        return new Rect(this.left - origin.left, this.top - origin.top, this.width, this.height);
    }
    rebaseTo(origin) {
        return new Rect(this.left + origin.left, this.top + origin.top, this.width, this.height);
    }
}
var Type;
(function (Type) {
    Type["None"] = "None";
    Type["Responsive"] = "Responsive";
    Type["Device"] = "Device";
})(Type || (Type = {}));
const MinDeviceSize = 50;
const MaxDeviceSize = 9999;
const MinDeviceScaleFactor = 0;
const MaxDeviceScaleFactor = 10;
const mobileUserAgent = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36';
const defaultMobileUserAgent = MultitargetNetworkManager.patchUserAgentWithChromeVersion(mobileUserAgent);
const defaultMobileUserAgentMetadata = {
    platform: 'Android',
    platformVersion: '6.0',
    architecture: '',
    model: 'Nexus 5',
    mobile: true,
};
const defaultMobileScaleFactor = 2;

// Copyright 2024 The Chromium Authors
const UIStrings$o = {
    fieldOverrideWarning: 'Field metrics are configured for a different URL than the current page.',
};
const str_$n = registerUIStrings('models/crux-manager/CrUXManager.ts', UIStrings$o);
const i18nString$a = getLocalizedString.bind(undefined, str_$n);
const CRUX_API_KEY = 'AIzaSyCCSOx25vrb5z0tbedCB3_JRzzbVW6Uwgw';
const DEFAULT_ENDPOINT = `https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=${CRUX_API_KEY}`;
let cruxManagerInstance;
const DEVICE_SCOPE_LIST = ['ALL', 'DESKTOP', 'PHONE'];
const pageScopeList = ['origin', 'url'];
const metrics = [
    'first_contentful_paint',
    'largest_contentful_paint',
    'cumulative_layout_shift',
    'interaction_to_next_paint',
    'round_trip_time',
    'form_factors',
    'largest_contentful_paint_image_time_to_first_byte',
    'largest_contentful_paint_image_resource_load_delay',
    'largest_contentful_paint_image_resource_load_duration',
    'largest_contentful_paint_image_element_render_delay',
];
class CrUXManager extends ObjectWrapper {
    #originCache = new Map();
    #urlCache = new Map();
    #mainDocumentUrl;
    #configSetting;
    #endpoint = DEFAULT_ENDPOINT;
    #pageResult;
    fieldDeviceOption = 'AUTO';
    fieldPageScope = 'url';
    constructor() {
        super();
        const useSessionStorage = hostConfig.isOffTheRecord === true;
        const storageTypeForConsent = useSessionStorage ? "Session"  : "Global" ;
        this.#configSetting = Settings.instance().createSetting('field-data', { enabled: false, override: '', originMappings: [], overrideEnabled: false }, storageTypeForConsent);
        this.#configSetting.addChangeListener(() => {
            void this.refresh();
        });
        TargetManager.instance().addModelListener(ResourceTreeModel, Events$6.FrameNavigated, this.#onFrameNavigated, this);
    }
    static instance(opts = { forceNew: null }) {
        const { forceNew } = opts;
        if (!cruxManagerInstance || forceNew) {
            cruxManagerInstance = new CrUXManager();
        }
        return cruxManagerInstance;
    }
    get pageResult() {
        return this.#pageResult;
    }
    getConfigSetting() {
        return this.#configSetting;
    }
    isEnabled() {
        return this.#configSetting.get().enabled;
    }
    async getFieldDataForPage(pageUrl) {
        const pageResult = {
            'origin-ALL': null,
            'origin-DESKTOP': null,
            'origin-PHONE': null,
            'origin-TABLET': null,
            'url-ALL': null,
            'url-DESKTOP': null,
            'url-PHONE': null,
            'url-TABLET': null,
            warnings: [],
            normalizedUrl: '',
        };
        try {
            const normalizedUrl = this.#normalizeUrl(pageUrl);
            pageResult.normalizedUrl = normalizedUrl.href;
            const promises = [];
            for (const pageScope of pageScopeList) {
                for (const deviceScope of DEVICE_SCOPE_LIST) {
                    const promise = this.#getScopedData(normalizedUrl, pageScope, deviceScope).then(response => {
                        pageResult[`${pageScope}-${deviceScope}`] = response;
                    });
                    promises.push(promise);
                }
            }
            await Promise.all(promises);
        }
        catch (err) {
            console.error(err);
        }
        finally {
            return pageResult;
        }
    }
    #getMappedUrl(unmappedUrl) {
        try {
            const unmapped = new URL(unmappedUrl);
            const mappings = this.#configSetting.get().originMappings || [];
            const mapping = mappings.find(m => m.developmentOrigin === unmapped.origin);
            if (!mapping) {
                return unmappedUrl;
            }
            const mapped = new URL(mapping.productionOrigin);
            mapped.pathname = unmapped.pathname;
            return mapped.href;
        }
        catch {
            return unmappedUrl;
        }
    }
    async getFieldDataForCurrentPageForTesting() {
        return await this.#getFieldDataForCurrentPage();
    }
    async #getFieldDataForCurrentPage() {
        const currentUrl = this.#mainDocumentUrl || await this.#getInspectedURL();
        const normalizedUrl = this.#configSetting.get().overrideEnabled ? this.#configSetting.get().override || '' :
            this.#getMappedUrl(currentUrl);
        const result = await this.getFieldDataForPage(normalizedUrl);
        if (currentUrl !== normalizedUrl) {
            result.warnings.push(i18nString$a(UIStrings$o.fieldOverrideWarning));
        }
        return result;
    }
    async #getInspectedURL() {
        const targetManager = TargetManager.instance();
        let inspectedURL = targetManager.inspectedURL();
        if (!inspectedURL) {
            inspectedURL = await new Promise(resolve => {
                function handler(event) {
                    const newInspectedURL = event.data.inspectedURL();
                    if (newInspectedURL) {
                        resolve(newInspectedURL);
                        targetManager.removeEventListener("InspectedURLChanged" , handler);
                    }
                }
                targetManager.addEventListener("InspectedURLChanged" , handler);
            });
        }
        return inspectedURL;
    }
    async #onFrameNavigated(event) {
        if (!event.data.isPrimaryFrame()) {
            return;
        }
        this.#mainDocumentUrl = event.data.url;
        await this.refresh();
    }
    async refresh() {
        this.#pageResult = undefined;
        this.dispatchEventToListeners("field-data-changed" , undefined);
        if (!this.#configSetting.get().enabled) {
            return;
        }
        this.#pageResult = await this.#getFieldDataForCurrentPage();
        this.dispatchEventToListeners("field-data-changed" , this.#pageResult);
    }
    #normalizeUrl(inputUrl) {
        const normalizedUrl = new URL(inputUrl);
        normalizedUrl.hash = '';
        normalizedUrl.search = '';
        return normalizedUrl;
    }
    async #getScopedData(normalizedUrl, pageScope, deviceScope) {
        const { origin, href: url, hostname } = normalizedUrl;
        if (hostname === 'localhost' || hostname === '127.0.0.1' || !origin.startsWith('http')) {
            return null;
        }
        const cache = pageScope === 'origin' ? this.#originCache : this.#urlCache;
        const cacheKey = pageScope === 'origin' ? `${origin}-${deviceScope}` : `${url}-${deviceScope}`;
        const cachedResponse = cache.get(cacheKey);
        if (cachedResponse !== undefined) {
            return cachedResponse;
        }
        try {
            const formFactor = deviceScope === 'ALL' ? undefined : deviceScope;
            const result = pageScope === 'origin' ? await this.#makeRequest({ origin, metrics, formFactor }) :
                await this.#makeRequest({ url, metrics, formFactor });
            cache.set(cacheKey, result);
            return result;
        }
        catch (err) {
            console.error(err);
            return null;
        }
    }
    async #makeRequest(request) {
        const body = JSON.stringify(request);
        const response = await fetch(this.#endpoint, {
            method: 'POST',
            body,
        });
        if (!response.ok && response.status !== 404) {
            throw new Error(`Failed to fetch data from CrUX server (Status code: ${response.status})`);
        }
        const responseData = await response.json();
        if (response.status === 404) {
            if (responseData?.error?.status === 'NOT_FOUND') {
                return null;
            }
            throw new Error(`Failed to fetch data from CrUX server (Status code: ${response.status})`);
        }
        if (!('record' in responseData)) {
            throw new Error(`Failed to find data in CrUX response: ${JSON.stringify(responseData)}`);
        }
        return responseData;
    }
    #getAutoDeviceScope() {
        const emulationModel = DeviceModeModel.tryInstance();
        if (emulationModel === null) {
            return 'ALL';
        }
        if (emulationModel.isMobile()) {
            if (this.#pageResult?.[`${this.fieldPageScope}-PHONE`]) {
                return 'PHONE';
            }
            return 'ALL';
        }
        if (this.#pageResult?.[`${this.fieldPageScope}-DESKTOP`]) {
            return 'DESKTOP';
        }
        return 'ALL';
    }
    resolveDeviceOptionToScope(option) {
        return option === 'AUTO' ? this.#getAutoDeviceScope() : option;
    }
    getSelectedDeviceScope() {
        return this.resolveDeviceOptionToScope(this.fieldDeviceOption);
    }
    getSelectedScope() {
        return { pageScope: this.fieldPageScope, deviceScope: this.getSelectedDeviceScope() };
    }
    getSelectedFieldResponse() {
        const pageScope = this.fieldPageScope;
        const deviceScope = this.getSelectedDeviceScope();
        return this.getFieldResponse(pageScope, deviceScope);
    }
    getSelectedFieldMetricData(fieldMetric) {
        return this.getSelectedFieldResponse()?.record.metrics[fieldMetric];
    }
    getFieldResponse(pageScope, deviceScope) {
        return this.#pageResult?.[`${pageScope}-${deviceScope}`];
    }
    setEndpointForTesting(endpoint) {
        this.#endpoint = endpoint;
    }
}

// Copyright 2022 The Chromium Authors
async function getTextFor(contentProvider) {
    const contentData = await contentProvider.requestContentData();
    if (ContentData.isError(contentData) || !contentData.isTextContent) {
        return null;
    }
    return contentData.textObj;
}
async function getFunctionNameFromScopeStart(script, lineNumber, columnNumber) {
    const sourceMap = script.sourceMap();
    if (!sourceMap) {
        return null;
    }
    const scopeName = sourceMap.findOriginalFunctionName({ line: lineNumber, column: columnNumber });
    if (scopeName !== null) {
        return scopeName;
    }
    const mappingEntry = sourceMap.findEntry(lineNumber, columnNumber);
    if (!mappingEntry?.sourceURL) {
        return null;
    }
    const name = mappingEntry.name;
    if (!name) {
        return null;
    }
    const text = await getTextFor(script);
    if (!text) {
        return null;
    }
    const openRange = new TextRange(lineNumber, columnNumber, lineNumber, columnNumber + 1);
    if (text.extract(openRange) !== '(') {
        return null;
    }
    return name;
}
async function resolveProfileFrameFunctionName({ scriptId, lineNumber, columnNumber }, target) {
    if (!target || lineNumber === undefined || columnNumber === undefined || scriptId === undefined) {
        return null;
    }
    const debuggerModel = target.model(DebuggerModel);
    const script = debuggerModel?.scriptForId(String(scriptId));
    if (!debuggerModel || !script) {
        return null;
    }
    const debuggerWorkspaceBinding = DebuggerWorkspaceBinding.instance();
    const location = new Location$1(debuggerModel, scriptId, lineNumber, columnNumber);
    const functionInfoFromPlugin = await debuggerWorkspaceBinding.pluginManager.getFunctionInfo(script, location);
    if (functionInfoFromPlugin && 'frames' in functionInfoFromPlugin) {
        const last = functionInfoFromPlugin.frames.at(-1);
        if (last?.name) {
            return last.name;
        }
    }
    return await getFunctionNameFromScopeStart(script, lineNumber, columnNumber);
}

// Copyright 2023 The Chromium Authors
var _a$1;
class SourceMappingsUpdated extends Event {
    static eventName = 'sourcemappingsupdated';
    constructor() {
        super(SourceMappingsUpdated.eventName, { composed: true, bubbles: true });
    }
}
const resolvedCodeLocationDataNames = new Map();
class SourceMapsResolver extends EventTarget {
    executionContextNamesByOrigin = new Map();
    #parsedTrace;
    #entityMapper = null;
    #isResolving = false;
    #debuggerModelsToListen = new Set();
    constructor(parsedTrace, entityMapper) {
        super();
        this.#parsedTrace = parsedTrace;
        this.#entityMapper = entityMapper ?? null;
    }
    static clearResolvedNodeNames() {
        resolvedCodeLocationDataNames.clear();
    }
    static keyForCodeLocation(callFrame) {
        return `${callFrame.url}$$$${callFrame.scriptId}$$$${callFrame.functionName}$$$${callFrame.lineNumber}$$$${callFrame.columnNumber}`;
    }
    static resolvedCodeLocationForCallFrame(callFrame) {
        const codeLocationKey = this.keyForCodeLocation(callFrame);
        return resolvedCodeLocationDataNames.get(codeLocationKey) ?? null;
    }
    static resolvedCodeLocationForEntry(entry) {
        let callFrame = null;
        if (isProfileCall(entry)) {
            callFrame = entry.callFrame;
        }
        else {
            const topCallFrame = getStackTraceTopCallFrameInEventPayload(entry);
            if (!topCallFrame) {
                return null;
            }
            callFrame = topCallFrame;
        }
        return _a$1.resolvedCodeLocationForCallFrame(callFrame);
    }
    static resolvedURLForEntry(parsedTrace, entry) {
        const resolvedCallFrameURL = _a$1.resolvedCodeLocationForEntry(entry)?.devtoolsLocation?.uiSourceCode.url();
        if (resolvedCallFrameURL) {
            return resolvedCallFrameURL;
        }
        const url = getNonResolvedURL(entry, parsedTrace.data);
        if (url) {
            return WorkspaceImpl.instance().uiSourceCodeForURL(url)?.url() ?? url;
        }
        return null;
    }
    static codeLocationForEntry(parsedTrace, entry) {
        const uiLocation = _a$1.resolvedCodeLocationForEntry(entry)?.devtoolsLocation;
        if (uiLocation) {
            return { url: uiLocation.uiSourceCode.url(), line: uiLocation.lineNumber, column: uiLocation.columnNumber };
        }
        const rawCallFrame = rawCallFrameForEntry(entry);
        if (rawCallFrame) {
            const line = rawCallFrame.lineNumber >= 0 ? rawCallFrame.lineNumber : undefined;
            const column = rawCallFrame.columnNumber >= 0 ? rawCallFrame.columnNumber : undefined;
            return { url: rawCallFrame.url, line, column };
        }
        let url = getNonResolvedURL(entry, parsedTrace.data);
        if (url) {
            url = WorkspaceImpl.instance().uiSourceCodeForURL(url)?.url() ?? url;
        }
        if (url) {
            return { url };
        }
        return null;
    }
    static storeResolvedCodeDataForCallFrame(callFrame, resolvedCodeLocationData) {
        const keyForCallFrame = this.keyForCodeLocation(callFrame);
        resolvedCodeLocationDataNames.set(keyForCallFrame, resolvedCodeLocationData);
    }
    async install() {
        for (const threadToProfileMap of this.#parsedTrace.data.Samples.profilesInProcess.values()) {
            for (const [tid, profile] of threadToProfileMap) {
                const nodes = profile.parsedProfile.nodes();
                if (!nodes || nodes.length === 0) {
                    continue;
                }
                const target = this.#targetForThread(tid);
                const debuggerModel = target?.model(DebuggerModel);
                if (!debuggerModel) {
                    continue;
                }
                for (const node of nodes) {
                    const script = debuggerModel.scriptForId(String(node.callFrame.scriptId));
                    const shouldListenToSourceMap = !script || script.sourceMapURL;
                    if (!shouldListenToSourceMap) {
                        continue;
                    }
                    this.#debuggerModelsToListen.add(debuggerModel);
                }
            }
        }
        for (const debuggerModel of this.#debuggerModelsToListen) {
            debuggerModel.sourceMapManager().addEventListener(Events$b.SourceMapAttached, this.#onAttachedSourceMap, this);
        }
        this.#updateExtensionNames();
        await this.#resolveMappingsForProfileNodes();
    }
    uninstall() {
        for (const debuggerModel of this.#debuggerModelsToListen) {
            debuggerModel.sourceMapManager().removeEventListener(Events$b.SourceMapAttached, this.#onAttachedSourceMap, this);
        }
        this.#debuggerModelsToListen.clear();
    }
    async #resolveMappingsForProfileNodes() {
        let updatedMappings = false;
        for (const [, threadsInProcess] of this.#parsedTrace.data.Samples.profilesInProcess) {
            for (const [tid, threadProfile] of threadsInProcess) {
                const nodes = threadProfile.parsedProfile.nodes() ?? [];
                const target = this.#targetForThread(tid);
                if (!target) {
                    continue;
                }
                for (const node of nodes) {
                    const resolvedFunctionName = await resolveProfileFrameFunctionName(node.callFrame, target);
                    updatedMappings ||= Boolean(resolvedFunctionName);
                    node.setOriginalFunctionName(resolvedFunctionName);
                    const debuggerModel = target.model(DebuggerModel);
                    const script = debuggerModel?.scriptForId(node.scriptId) || null;
                    const location = debuggerModel &&
                        new Location$1(debuggerModel, node.callFrame.scriptId, node.callFrame.lineNumber, node.callFrame.columnNumber);
                    const uiLocation = location &&
                        await DebuggerWorkspaceBinding.instance().rawLocationToUILocation(location);
                    updatedMappings ||= Boolean(uiLocation);
                    if (uiLocation?.uiSourceCode.url() && this.#entityMapper) {
                        this.#entityMapper.updateSourceMapEntities(node.callFrame, uiLocation.uiSourceCode.url());
                    }
                    _a$1.storeResolvedCodeDataForCallFrame(node.callFrame, { name: resolvedFunctionName, devtoolsLocation: uiLocation, script });
                }
            }
        }
        if (!updatedMappings) {
            return;
        }
        this.dispatchEvent(new SourceMappingsUpdated());
    }
    #onAttachedSourceMap() {
        if (this.#isResolving) {
            return;
        }
        this.#isResolving = true;
        setTimeout(async () => {
            this.#isResolving = false;
            await this.#resolveMappingsForProfileNodes();
        }, 500);
    }
    #targetForThread(tid) {
        const maybeWorkerId = this.#parsedTrace.data.Workers.workerIdByThread.get(tid);
        if (maybeWorkerId) {
            return TargetManager.instance().targetById(maybeWorkerId);
        }
        return TargetManager.instance().primaryPageTarget();
    }
    #updateExtensionNames() {
        for (const runtimeModel of TargetManager.instance().models(RuntimeModel)) {
            for (const context of runtimeModel.executionContexts()) {
                this.executionContextNamesByOrigin.set(context.origin, context.name);
            }
        }
        this.#entityMapper?.updateExtensionEntitiesWithName(this.executionContextNamesByOrigin);
    }
}
_a$1 = SourceMapsResolver;

// Copyright 2024 The Chromium Authors
function depthFirstWalk(nodes, callback) {
    for (const node of nodes) {
        if (callback?.(node)) {
            break;
        }
        depthFirstWalk(node.children().values(), callback);
    }
}
class AICallTree {
    selectedNode;
    rootNode;
    parsedTrace;
    #eventsSerializer = new EventsSerializer();
    constructor(selectedNode, rootNode, parsedTrace) {
        this.selectedNode = selectedNode;
        this.rootNode = rootNode;
        this.parsedTrace = parsedTrace;
    }
    static findEventsForThread({ thread, parsedTrace, bounds }) {
        const threadEvents = parsedTrace.data.Renderer.processes.get(thread.pid)?.threads.get(thread.tid)?.entries;
        if (!threadEvents) {
            return null;
        }
        return threadEvents.filter(e => eventIsInBounds(e, bounds));
    }
    static findMainThreadTasks({ thread, parsedTrace, bounds }) {
        const threadEvents = parsedTrace.data.Renderer.processes.get(thread.pid)?.threads.get(thread.tid)?.entries;
        if (!threadEvents) {
            return null;
        }
        return threadEvents.filter(isRunTask)
            .filter(e => eventIsInBounds(e, bounds));
    }
    static fromTimeOnThread({ thread, parsedTrace, bounds }) {
        const overlappingEvents = this.findEventsForThread({ thread, parsedTrace, bounds });
        if (!overlappingEvents) {
            return null;
        }
        const visibleEventsFilter = new VisibleEventsFilter(visibleTypes());
        const minDuration = Micro(bounds.range * 0.005);
        const minDurationFilter = new MinDurationFilter(minDuration);
        const compileCodeFilter = new ExcludeCompileCodeFilter();
        const rootNode = new TopDownRootNode(overlappingEvents, {
            filters: [minDurationFilter, compileCodeFilter, visibleEventsFilter],
            startTime: microToMilli(bounds.min),
            endTime: microToMilli(bounds.max),
            doNotAggregate: true,
            includeInstantEvents: true,
        });
        const instance = new AICallTree(null , rootNode, parsedTrace);
        return instance;
    }
    static fromEvent(selectedEvent, parsedTrace) {
        if (isPerformanceMark(selectedEvent)) {
            return null;
        }
        const threads = threadsInTrace(parsedTrace.data);
        const thread = threads.find(t => t.pid === selectedEvent.pid && t.tid === selectedEvent.tid);
        if (!thread) {
            return null;
        }
        if (thread.type !== "MAIN_THREAD"  &&
            thread.type !== "CPU_PROFILE" ) {
            return null;
        }
        const data = parsedTrace.data;
        if (!data.Renderer.entryToNode.has(selectedEvent) && !data.Samples.entryToNode.has(selectedEvent)) {
            return null;
        }
        const showAllEvents = parsedTrace.data.Meta.config.showAllEvents;
        const { startTime, endTime } = eventTimingsMilliSeconds(selectedEvent);
        const selectedEventBounds = traceWindowFromMicroSeconds(milliToMicro(startTime), milliToMicro(endTime));
        let threadEvents = data.Renderer.processes.get(selectedEvent.pid)?.threads.get(selectedEvent.tid)?.entries;
        if (!threadEvents) {
            threadEvents = data.Samples.profilesInProcess.get(selectedEvent.pid)?.get(selectedEvent.tid)?.profileCalls;
        }
        if (!threadEvents) {
            console.warn(`AICallTree: could not find thread for selected entry: ${selectedEvent}`);
            return null;
        }
        const overlappingEvents = threadEvents.filter(e => eventIsInBounds(e, selectedEventBounds));
        const filters = [new SelectedEventDurationFilter(selectedEvent), new ExcludeCompileCodeFilter(selectedEvent)];
        if (!showAllEvents) {
            filters.push(new VisibleEventsFilter(visibleTypes()));
        }
        const rootNode = new TopDownRootNode(overlappingEvents, {
            filters,
            startTime,
            endTime,
            includeInstantEvents: true,
        });
        let selectedNode = null;
        depthFirstWalk([rootNode].values(), node => {
            if (node.event === selectedEvent) {
                selectedNode = node;
                return true;
            }
            return;
        });
        if (selectedNode === null) {
            console.warn(`Selected event ${selectedEvent} not found within its own tree.`);
            return null;
        }
        const instance = new AICallTree(selectedNode, rootNode, parsedTrace);
        return instance;
    }
    breadthFirstWalk(nodes, serializeNodeCallback) {
        const queue = Array.from(nodes);
        let nodeIndex = 1;
        let nodesAddedToQueueCount = queue.length;
        let currentNode = queue.shift();
        while (currentNode) {
            if (currentNode.children().size > 0) {
                serializeNodeCallback(currentNode, nodeIndex, nodesAddedToQueueCount + 1);
            }
            else {
                serializeNodeCallback(currentNode, nodeIndex);
            }
            queue.push(...Array.from(currentNode.children().values()));
            nodesAddedToQueueCount += currentNode.children().size;
            currentNode = queue.shift();
            nodeIndex++;
        }
    }
    serialize(headerLevel = 1) {
        const header = '#'.repeat(headerLevel);
        const allUrls = [];
        let nodesStr = '';
        this.breadthFirstWalk(this.rootNode.children().values(), (node, nodeId, childStartingNode) => {
            nodesStr +=
                '\n' + this.stringifyNode(node, nodeId, this.parsedTrace, this.selectedNode, allUrls, childStartingNode);
        });
        let output = '';
        if (allUrls.length) {
            output += `\n${header} All URLs:\n\n` + allUrls.map((url, index) => `  * ${index}: ${url}`).join('\n');
        }
        output += `\n\n${header} Call tree:\n${nodesStr}`;
        return output;
    }
    stringifyNode(node, nodeId, parsedTrace, selectedNode, allUrls, childStartingNodeIndex) {
        const event = node.event;
        if (!event) {
            throw new Error('Event required');
        }
        const idStr = String(nodeId);
        const eventKey = this.#eventsSerializer.keyForEvent(node.event);
        const name = forEntry(event, parsedTrace);
        const roundToTenths = (num) => {
            if (!num) {
                return '';
            }
            return String(Math.round(num * 10) / 10);
        };
        const durationStr = roundToTenths(node.totalTime);
        const selfTimeStr = roundToTenths(node.selfTime);
        const location = SourceMapsResolver.codeLocationForEntry(parsedTrace, event);
        const url = location?.url;
        let urlIndexStr = '';
        if (url) {
            const existingIndex = allUrls.indexOf(url);
            if (existingIndex === -1) {
                urlIndexStr = String(allUrls.push(url) - 1);
            }
            else {
                urlIndexStr = String(existingIndex);
            }
        }
        const children = Array.from(node.children().values());
        let childRangeStr = '';
        if (childStartingNodeIndex) {
            childRangeStr = (children.length === 1) ? String(childStartingNodeIndex) :
                `${childStartingNodeIndex}-${childStartingNodeIndex + children.length}`;
        }
        const selectedMarker = selectedNode?.event === node.event ? 'S' : '';
        let line = idStr;
        line += ';' + eventKey;
        line += ';' + name;
        line += ';' + durationStr;
        line += ';' + selfTimeStr;
        line += ';' + urlIndexStr;
        line += ';' + childRangeStr;
        line += ';' + (location?.line ?? '');
        line += ';' + (location?.column ?? '');
        if (selectedMarker) {
            line += ';' + selectedMarker;
        }
        return line;
    }
    topCallFramesBySelfTime(limit) {
        const functionNodesByCallFrame = new Map();
        this.breadthFirstWalk(this.rootNode.children().values(), node => {
            if (isProfileCall(node.event)) {
                const callFrame = node.event.callFrame;
                const callFrameKey = `${callFrame.scriptId}:${callFrame.lineNumber}:${callFrame.columnNumber}`;
                const array = functionNodesByCallFrame.get(callFrameKey) ?? [];
                array.push(node);
                functionNodesByCallFrame.set(callFrameKey, array);
            }
        });
        return [...functionNodesByCallFrame.values()]
            .map(nodes => {
            return {
                callFrame: nodes[0].event.callFrame,
                selfTime: nodes.reduce((total, cur) => total + cur.selfTime, 0),
            };
        })
            .sort((a, b) => b.selfTime - a.selfTime)
            .slice(0, limit)
            .map(({ callFrame }) => callFrame);
    }
    topCallFrameByTotalTime() {
        let topChild = null;
        let topProfileCallEvent = null;
        for (const child of this.rootNode.children().values()) {
            if (isProfileCall(child.event)) {
                if (!topChild || child.totalTime > topChild.totalTime) {
                    topChild = child;
                    topProfileCallEvent = child.event;
                }
            }
        }
        return topProfileCallEvent?.callFrame ?? null;
    }
    logDebug() {
        const str = this.serialize();
        console.log('🎆', str);
        if (str.length > 45_000) {
            console.warn('Output will likely not fit in the context window. Expect an AIDA error.');
        }
    }
}
class ExcludeCompileCodeFilter extends TraceFilter {
    #selectedEvent = null;
    constructor(selectedEvent) {
        super();
        this.#selectedEvent = selectedEvent ?? null;
    }
    accept(event) {
        if (this.#selectedEvent && event === this.#selectedEvent) {
            return true;
        }
        return event.name !== "V8.CompileCode" ;
    }
}
class SelectedEventDurationFilter extends TraceFilter {
    #minDuration;
    #selectedEvent;
    constructor(selectedEvent) {
        super();
        this.#minDuration = Micro((selectedEvent.dur ?? 1) * 0.005);
        this.#selectedEvent = selectedEvent;
    }
    accept(event) {
        if (event === this.#selectedEvent) {
            return true;
        }
        return event.dur ? event.dur >= this.#minDuration : false;
    }
}
class MinDurationFilter extends TraceFilter {
    #minDuration;
    constructor(minDuration) {
        super();
        this.#minDuration = minDuration;
    }
    accept(event) {
        return event.dur ? event.dur >= this.#minDuration : false;
    }
}

// Copyright 2025 The Chromium Authors
class AIQueries {
    static findMainThread(navigationId, parsedTrace) {
        let mainThreadPID = null;
        let mainThreadTID = null;
        if (navigationId) {
            const navigation = parsedTrace.data.Meta.navigationsByNavigationId.get(navigationId);
            if (navigation?.args.data?.isOutermostMainFrame) {
                mainThreadPID = navigation.pid;
                mainThreadTID = navigation.tid;
            }
        }
        const threads = threadsInTrace(parsedTrace.data);
        const thread = threads.find(thread => {
            if (!thread.processIsOnMainFrame) {
                return false;
            }
            if (mainThreadPID && mainThreadTID) {
                return thread.pid === mainThreadPID && thread.tid === mainThreadTID;
            }
            return thread.type === "MAIN_THREAD" ;
        });
        return thread ?? null;
    }
    static mainThreadActivityBottomUpSingleNavigation(navigationId, bounds, parsedTrace) {
        const thread = this.findMainThread(navigationId, parsedTrace);
        if (!thread) {
            return null;
        }
        const events = AICallTree.findEventsForThread({ thread, parsedTrace, bounds });
        if (!events) {
            return null;
        }
        const visibleEvents = VISIBLE_TRACE_EVENT_TYPES.values().toArray();
        const filter = new VisibleEventsFilter(visibleEvents.concat(["SyntheticNetworkRequest" ]));
        const startTime = microToMilli(bounds.min);
        const endTime = microToMilli(bounds.max);
        return new BottomUpRootNode(events, {
            textFilter: new ExclusiveNameFilter([]),
            filters: [filter],
            startTime,
            endTime,
        });
    }
    static mainThreadActivityBottomUp(bounds, parsedTrace) {
        const threads = [];
        if (parsedTrace.insights) {
            for (const insightSet of parsedTrace.insights?.values()) {
                const thread = this.findMainThread(insightSet.navigation?.args.data?.navigationId, parsedTrace);
                if (thread) {
                    threads.push(thread);
                }
            }
        }
        else {
            const navigationId = parsedTrace.data.Meta.mainFrameNavigations[0].args.data?.navigationId;
            const thread = this.findMainThread(navigationId, parsedTrace);
            if (thread) {
                threads.push(thread);
            }
        }
        if (threads.length === 0) {
            return null;
        }
        const threadEvents = [...new Set(threads)].map(thread => AICallTree.findEventsForThread({ thread, parsedTrace, bounds }) ?? []);
        const events = threadEvents.flat();
        if (events.length === 0) {
            return null;
        }
        const visibleEvents = VISIBLE_TRACE_EVENT_TYPES.values().toArray();
        const filter = new VisibleEventsFilter(visibleEvents.concat(["SyntheticNetworkRequest" ]));
        const startTime = microToMilli(bounds.min);
        const endTime = microToMilli(bounds.max);
        return new BottomUpRootNode(events, {
            textFilter: new ExclusiveNameFilter([]),
            filters: [filter],
            startTime,
            endTime,
        });
    }
    static mainThreadActivityTopDown(navigationId, bounds, parsedTrace) {
        const thread = this.findMainThread(navigationId, parsedTrace);
        if (!thread) {
            return null;
        }
        return AICallTree.fromTimeOnThread({
            thread: {
                pid: thread.pid,
                tid: thread.tid,
            },
            parsedTrace,
            bounds,
        });
    }
    static longestTasks(navigationId, bounds, parsedTrace, limit = 3) {
        const thread = this.findMainThread(navigationId, parsedTrace);
        if (!thread) {
            return null;
        }
        const tasks = AICallTree.findMainThreadTasks({ thread, parsedTrace, bounds });
        if (!tasks) {
            return null;
        }
        const topTasks = tasks.filter(e => e.name === 'RunTask').sort((a, b) => b.dur - a.dur).slice(0, limit);
        return topTasks
            .map(task => {
            const tree = AICallTree.fromEvent(task, parsedTrace);
            if (tree) {
                tree.selectedNode = null;
            }
            return tree;
        })
            .filter(tree => !!tree);
    }
}

// Copyright 2011 The Chromium Authors
const UIStrings$n = {
    anonymous: '<anonymous>',
};
const str_$m = registerUIStrings('models/logs/NetworkLog.ts', UIStrings$n);
const i18nString$9 = getLocalizedString.bind(undefined, str_$m);
let networkLogInstance;
class NetworkLog extends ObjectWrapper {
    #requests = [];
    #sentNetworkRequests = [];
    #receivedNetworkResponses = [];
    #requestsSet = new Set();
    #requestsMap = new Map();
    #pageLoadForManager = new Map();
    #unresolvedPreflightRequests = new Map();
    #modelListeners = new WeakMap();
    #initiatorData = new WeakMap();
    #isRecording = true;
    constructor() {
        super();
        TargetManager.instance().observeModels(NetworkManager, this);
        const recordLogSetting = Settings.instance().moduleSetting('network-log.record-log');
        recordLogSetting.addChangeListener(() => {
            const preserveLogSetting = Settings.instance().moduleSetting('network-log.preserve-log');
            if (!preserveLogSetting.get() && recordLogSetting.get()) {
                this.reset(true);
            }
            this.setIsRecording((recordLogSetting.get()));
        }, this);
    }
    static instance() {
        if (!networkLogInstance) {
            networkLogInstance = new NetworkLog();
        }
        return networkLogInstance;
    }
    static removeInstance() {
        networkLogInstance = undefined;
    }
    modelAdded(networkManager) {
        const eventListeners = [];
        eventListeners.push(networkManager.addEventListener(Events$c.RequestStarted, this.onRequestStarted, this));
        eventListeners.push(networkManager.addEventListener(Events$c.RequestUpdated, this.onRequestUpdated, this));
        eventListeners.push(networkManager.addEventListener(Events$c.RequestRedirected, this.onRequestRedirect, this));
        eventListeners.push(networkManager.addEventListener(Events$c.RequestFinished, this.onRequestUpdated, this));
        eventListeners.push(networkManager.addEventListener(Events$c.MessageGenerated, this.networkMessageGenerated.bind(this, networkManager)));
        eventListeners.push(networkManager.addEventListener(Events$c.ResponseReceived, this.onResponseReceived, this));
        const resourceTreeModel = networkManager.target().model(ResourceTreeModel);
        if (resourceTreeModel) {
            eventListeners.push(resourceTreeModel.addEventListener(Events$6.WillReloadPage, this.willReloadPage, this));
            eventListeners.push(resourceTreeModel.addEventListener(Events$6.PrimaryPageChanged, this.onPrimaryPageChanged, this));
            eventListeners.push(resourceTreeModel.addEventListener(Events$6.Load, this.onLoad, this));
            eventListeners.push(resourceTreeModel.addEventListener(Events$6.DOMContentLoaded, this.onDOMContentLoaded.bind(this, resourceTreeModel)));
        }
        this.#modelListeners.set(networkManager, eventListeners);
    }
    modelRemoved(networkManager) {
        this.removeNetworkManagerListeners(networkManager);
    }
    removeNetworkManagerListeners(networkManager) {
        removeEventListeners(this.#modelListeners.get(networkManager) || []);
    }
    setIsRecording(enabled) {
        if (this.#isRecording === enabled) {
            return;
        }
        this.#isRecording = enabled;
        if (enabled) {
            TargetManager.instance().observeModels(NetworkManager, this);
        }
        else {
            TargetManager.instance().unobserveModels(NetworkManager, this);
            TargetManager.instance()
                .models(NetworkManager)
                .forEach(this.removeNetworkManagerListeners.bind(this));
        }
    }
    requestForURL(url) {
        return this.#requests.find(request => request.url() === url) || null;
    }
    originalRequestForURL(url) {
        return this.#sentNetworkRequests.find(request => request.url === url) || null;
    }
    originalResponseForURL(url) {
        return this.#receivedNetworkResponses.find(response => response.url === url) || null;
    }
    requests() {
        return this.#requests;
    }
    requestByManagerAndId(networkManager, requestId) {
        for (let i = this.#requests.length - 1; i >= 0; i--) {
            const request = this.#requests[i];
            if (requestId === request.requestId() &&
                networkManager === NetworkManager.forRequest(request)) {
                return request;
            }
        }
        return null;
    }
    requestByManagerAndURL(networkManager, url) {
        for (const request of this.#requests) {
            if (url === request.url() && networkManager === NetworkManager.forRequest(request)) {
                return request;
            }
        }
        return null;
    }
    initializeInitiatorSymbolIfNeeded(request) {
        let initiatorInfo = this.#initiatorData.get(request);
        if (initiatorInfo) {
            return initiatorInfo;
        }
        initiatorInfo = {
            info: null,
            chain: null,
        };
        this.#initiatorData.set(request, initiatorInfo);
        return initiatorInfo;
    }
    static initiatorInfoForRequest(request, existingInitiatorData) {
        const initiatorInfo = existingInitiatorData || {
            info: null};
        let type = "other" ;
        let url = EmptyUrlString;
        let lineNumber = undefined;
        let columnNumber = undefined;
        let scriptId = null;
        let initiatorStack = null;
        let initiatorRequest = null;
        const initiator = request.initiator();
        const redirectSource = request.redirectSource();
        if (redirectSource) {
            type = "redirect" ;
            url = redirectSource.url();
        }
        else if (initiator) {
            if (initiator.type === "parser" ) {
                type = "parser" ;
                url = initiator.url ? initiator.url : url;
                lineNumber = initiator.lineNumber;
                columnNumber = initiator.columnNumber;
            }
            else if (initiator.type === "script" ) {
                for (let stack = initiator.stack; stack;) {
                    const topFrame = stack.callFrames.length ? stack.callFrames[0] : null;
                    if (!topFrame) {
                        stack = stack.parent;
                        continue;
                    }
                    type = "script" ;
                    url = (topFrame.url || i18nString$9(UIStrings$n.anonymous));
                    lineNumber = topFrame.lineNumber;
                    columnNumber = topFrame.columnNumber;
                    scriptId = topFrame.scriptId;
                    break;
                }
                if (!initiator.stack && initiator.url) {
                    type = "script" ;
                    url = initiator.url;
                    lineNumber = initiator.lineNumber;
                }
                if (initiator.stack?.callFrames?.length) {
                    initiatorStack = initiator.stack;
                }
            }
            else if (initiator.type === "preload" ) {
                type = "preload" ;
            }
            else if (initiator.type === "preflight" ) {
                type = "preflight" ;
                initiatorRequest = request.preflightInitiatorRequest();
            }
            else if (initiator.type === "SignedExchange" ) {
                type = "signedExchange" ;
                url = initiator.url || EmptyUrlString;
            }
        }
        initiatorInfo.info = { type, url, lineNumber, columnNumber, scriptId, stack: initiatorStack, initiatorRequest };
        return initiatorInfo.info;
    }
    initiatorInfoForRequest(request) {
        const initiatorInfo = this.initializeInitiatorSymbolIfNeeded(request);
        if (initiatorInfo.info) {
            return initiatorInfo.info;
        }
        return NetworkLog.initiatorInfoForRequest(request, initiatorInfo);
    }
    initiatorGraphForRequest(request) {
        const initiated = new Map();
        const networkManager = NetworkManager.forRequest(request);
        for (const otherRequest of this.#requests) {
            const otherRequestManager = NetworkManager.forRequest(otherRequest);
            if (networkManager === otherRequestManager && this.initiatorChain(otherRequest).has(request)) {
                const initiatorRequest = this.initiatorRequest(otherRequest);
                if (initiatorRequest) {
                    initiated.set(otherRequest, initiatorRequest);
                }
            }
        }
        return { initiators: this.initiatorChain(request), initiated };
    }
    initiatorChain(request) {
        const initiatorDataForRequest = this.initializeInitiatorSymbolIfNeeded(request);
        let initiatorChainCache = initiatorDataForRequest.chain;
        if (initiatorChainCache) {
            return initiatorChainCache;
        }
        initiatorChainCache = new Set();
        let checkRequest = request;
        while (checkRequest) {
            const initiatorData = this.initializeInitiatorSymbolIfNeeded(checkRequest);
            if (initiatorData.chain) {
                initiatorChainCache = initiatorChainCache.union(initiatorData.chain);
                break;
            }
            if (initiatorChainCache.has(checkRequest)) {
                break;
            }
            initiatorChainCache.add(checkRequest);
            checkRequest = this.initiatorRequest(checkRequest);
        }
        initiatorDataForRequest.chain = initiatorChainCache;
        return initiatorChainCache;
    }
    initiatorRequest(request) {
        const initiatorData = this.initializeInitiatorSymbolIfNeeded(request);
        if (initiatorData.request !== undefined) {
            return initiatorData.request;
        }
        const url = this.initiatorInfoForRequest(request).url;
        const networkManager = NetworkManager.forRequest(request);
        initiatorData.request = networkManager ? this.requestByManagerAndURL(networkManager, url) : null;
        return initiatorData.request;
    }
    willReloadPage() {
        if (!Settings.instance().moduleSetting('network-log.preserve-log').get()) {
            this.reset(true);
        }
    }
    onPrimaryPageChanged(event) {
        const mainFrame = event.data.frame;
        const manager = mainFrame.resourceTreeModel().target().model(NetworkManager);
        if (!manager || mainFrame.resourceTreeModel().target().parentTarget()?.type() === Type$2.FRAME) {
            return;
        }
        if (mainFrame.url !== mainFrame.unreachableUrl() && schemeIs(mainFrame.url, 'chrome-error:')) {
            return;
        }
        const preserveLog = Settings.instance().moduleSetting('network-log.preserve-log').get();
        const oldRequests = this.#requests;
        const oldManagerRequests = this.#requests.filter(request => NetworkManager.forRequest(request) === manager);
        const oldRequestsSet = this.#requestsSet;
        this.#requests = [];
        this.#sentNetworkRequests = [];
        this.#receivedNetworkResponses = [];
        this.#requestsSet = new Set();
        this.#requestsMap.clear();
        this.#unresolvedPreflightRequests.clear();
        this.dispatchEventToListeners(Events.Reset, { clearIfPreserved: !preserveLog });
        let currentPageLoad = null;
        const requestsToAdd = [];
        for (const request of oldManagerRequests) {
            if (event.data.type !== "Activation"  &&
                request.loaderId !== mainFrame.loaderId) {
                continue;
            }
            if (!currentPageLoad) {
                currentPageLoad = new PageLoad(request);
                let redirectSource = request.redirectSource();
                while (redirectSource) {
                    requestsToAdd.push(redirectSource);
                    redirectSource = redirectSource.redirectSource();
                }
            }
            requestsToAdd.push(request);
        }
        const serviceWorkerRequestsToAdd = [];
        for (const swRequest of oldRequests) {
            if (!swRequest.initiatedByServiceWorker()) {
                continue;
            }
            const keepRequest = requestsToAdd.some(request => request.url() === swRequest.url() && request.issueTime() <= swRequest.issueTime());
            if (keepRequest) {
                serviceWorkerRequestsToAdd.push(swRequest);
            }
        }
        requestsToAdd.push(...serviceWorkerRequestsToAdd);
        for (const request of requestsToAdd) {
            currentPageLoad?.bindRequest(request);
            oldRequestsSet.delete(request);
            this.addRequest(request);
        }
        if (preserveLog) {
            for (const request of oldRequestsSet) {
                this.addRequest(request, true);
                request.preserved = true;
            }
        }
        if (currentPageLoad) {
            this.#pageLoadForManager.set(manager, currentPageLoad);
        }
    }
    addRequest(request, preserveLog) {
        this.#requests.push(request);
        this.#requestsSet.add(request);
        const requestList = this.#requestsMap.get(request.requestId());
        if (!requestList) {
            this.#requestsMap.set(request.requestId(), [request]);
        }
        else {
            requestList.push(request);
        }
        this.tryResolvePreflightRequests(request);
        this.dispatchEventToListeners(Events.RequestAdded, { request, preserveLog });
    }
    removeRequest(request) {
        const index = this.#requests.indexOf(request);
        if (index > -1) {
            this.#requests.splice(index, 1);
        }
        this.#requestsSet.delete(request);
        this.#requestsMap.delete(request.requestId());
        this.dispatchEventToListeners(Events.RequestRemoved, { request });
    }
    tryResolvePreflightRequests(request) {
        if (request.isPreflightRequest()) {
            const initiator = request.initiator();
            if (initiator?.requestId) {
                const [initiatorRequest] = this.requestsForId(initiator.requestId);
                if (initiatorRequest) {
                    request.setPreflightInitiatorRequest(initiatorRequest);
                    initiatorRequest.setPreflightRequest(request);
                }
                else {
                    this.#unresolvedPreflightRequests.set(initiator.requestId, request);
                }
            }
        }
        else {
            const preflightRequest = this.#unresolvedPreflightRequests.get(request.requestId());
            if (preflightRequest) {
                this.#unresolvedPreflightRequests.delete(request.requestId());
                request.setPreflightRequest(preflightRequest);
                preflightRequest.setPreflightInitiatorRequest(request);
                const data = this.#initiatorData.get(preflightRequest);
                if (data) {
                    data.info = null;
                }
                this.dispatchEventToListeners(Events.RequestUpdated, { request: preflightRequest });
            }
        }
    }
    importRequests(requests) {
        this.reset(true);
        this.#requests = [];
        this.#sentNetworkRequests = [];
        this.#receivedNetworkResponses = [];
        this.#requestsSet.clear();
        this.#requestsMap.clear();
        this.#unresolvedPreflightRequests.clear();
        for (const request of requests) {
            this.addRequest(request);
        }
    }
    onRequestStarted(event) {
        const { request, originalRequest } = event.data;
        if (originalRequest) {
            this.#sentNetworkRequests.push(originalRequest);
        }
        this.#requestsSet.add(request);
        const manager = NetworkManager.forRequest(request);
        const pageLoad = manager ? this.#pageLoadForManager.get(manager) : null;
        if (pageLoad) {
            pageLoad.bindRequest(request);
        }
        this.addRequest(request);
    }
    onResponseReceived(event) {
        const response = event.data.response;
        this.#receivedNetworkResponses.push(response);
    }
    onRequestUpdated(event) {
        const request = event.data;
        if (!this.#requestsSet.has(request)) {
            return;
        }
        this.dispatchEventToListeners(Events.RequestUpdated, { request });
    }
    onRequestRedirect(event) {
        this.#initiatorData.delete(event.data);
    }
    onDOMContentLoaded(resourceTreeModel, event) {
        const networkManager = resourceTreeModel.target().model(NetworkManager);
        const pageLoad = networkManager ? this.#pageLoadForManager.get(networkManager) : null;
        if (pageLoad) {
            pageLoad.contentLoadTime = event.data;
        }
    }
    onLoad(event) {
        const networkManager = event.data.resourceTreeModel.target().model(NetworkManager);
        const pageLoad = networkManager ? this.#pageLoadForManager.get(networkManager) : null;
        if (pageLoad) {
            pageLoad.loadTime = event.data.loadTime;
        }
    }
    reset(clearIfPreserved) {
        this.#requests = [];
        this.#sentNetworkRequests = [];
        this.#receivedNetworkResponses = [];
        this.#requestsSet.clear();
        this.#requestsMap.clear();
        this.#unresolvedPreflightRequests.clear();
        const managers = new Set(TargetManager.instance().models(NetworkManager));
        for (const manager of this.#pageLoadForManager.keys()) {
            if (!managers.has(manager)) {
                this.#pageLoadForManager.delete(manager);
            }
        }
        this.dispatchEventToListeners(Events.Reset, { clearIfPreserved });
    }
    networkMessageGenerated(networkManager, event) {
        const { message, warning, requestId } = event.data;
        const consoleMessage = new ConsoleMessage(networkManager.target().model(RuntimeModel), "network" , warning ? "warning"  : "info" , message);
        this.associateConsoleMessageWithRequest(consoleMessage, requestId);
        networkManager.target().model(ConsoleModel)?.addMessage(consoleMessage);
    }
    associateConsoleMessageWithRequest(consoleMessage, requestId) {
        const target = consoleMessage.target();
        const networkManager = target ? target.model(NetworkManager) : null;
        if (!networkManager) {
            return;
        }
        const request = this.requestByManagerAndId(networkManager, requestId);
        if (!request) {
            return;
        }
        consoleMessageToRequest.set(consoleMessage, request);
        const initiator = request.initiator();
        if (initiator) {
            consoleMessage.stackTrace = initiator.stack || undefined;
            if (initiator.url) {
                consoleMessage.url = initiator.url;
                consoleMessage.line = initiator.lineNumber || 0;
            }
        }
    }
    static requestForConsoleMessage(consoleMessage) {
        return consoleMessageToRequest.get(consoleMessage) || null;
    }
    requestsForId(requestId) {
        return this.#requestsMap.get(requestId) || [];
    }
}
const consoleMessageToRequest = new WeakMap();
var Events;
(function (Events) {
    Events["Reset"] = "Reset";
    Events["RequestAdded"] = "RequestAdded";
    Events["RequestUpdated"] = "RequestUpdated";
    Events["RequestRemoved"] = "RequestRemoved";
})(Events || (Events = {}));

// Copyright 2021 The Chromium Authors
/*
 * Copyright (C) 2007, 2008 Apple Inc.  All rights reserved.
 * Copyright (C) 2008, 2009 Anthony Ricaud <rik@webkit.org>
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
const UIStrings$m = {
    sLatencySDownloadSTotal: '{PH1} latency, {PH2} download ({PH3} total)',
    sLatency: '{PH1} latency',
    sDownload: '{PH1} download',
    sFromServiceworker: '{PH1} (from `ServiceWorker`)',
    sFromCache: '{PH1} (from cache)',
};
const str_$l = registerUIStrings('models/network_time_calculator/NetworkTimeCalculator.ts', UIStrings$m);
getLocalizedString.bind(undefined, str_$l);

// Copyright 2025 The Chromium Authors
function calculateRequestTimeRanges(request, navigationStart) {
    const result = [];
    function addRange(name, start, end) {
        if (start < Number.MAX_VALUE && start <= end) {
            result.push({ name, start, end });
        }
    }
    function firstPositive(numbers) {
        for (let i = 0; i < numbers.length; ++i) {
            if (numbers[i] > 0) {
                return numbers[i];
            }
        }
        return undefined;
    }
    function addOffsetRange(name, start, end) {
        if (start >= 0 && end >= 0) {
            addRange(name, startTime + (start / 1000), startTime + (end / 1000));
        }
    }
    function addMaybeNegativeOffsetRange(name, start, end) {
        addRange(name, startTime + (start / 1000), startTime + (end / 1000));
    }
    const timing = request.timing;
    if (!timing) {
        const start = request.issueTime() !== -1 ? request.issueTime() : request.startTime !== -1 ? request.startTime : 0;
        const hasDifferentIssueAndStartTime = request.issueTime() !== -1 && request.startTime !== -1 && request.issueTime() !== request.startTime;
        const middle = (request.responseReceivedTime === -1) ?
            (hasDifferentIssueAndStartTime ? request.startTime : Number.MAX_VALUE) :
            request.responseReceivedTime;
        const end = (request.endTime === -1) ? Number.MAX_VALUE : request.endTime;
        addRange("total" , start, end);
        addRange("blocking" , start, middle);
        const state = request.responseReceivedTime === -1 ? "connecting"  : "receiving" ;
        addRange(state, middle, end);
        return result;
    }
    const issueTime = request.issueTime();
    const startTime = timing.requestTime;
    const endTime = firstPositive([request.endTime, request.responseReceivedTime]) || startTime;
    addRange("total" , issueTime < startTime ? issueTime : startTime, endTime);
    if (timing.pushStart) {
        const pushEnd = timing.pushEnd || endTime;
        if (pushEnd > navigationStart) {
            addRange("push" , Math.max(timing.pushStart, navigationStart), pushEnd);
        }
    }
    if (issueTime < startTime) {
        addRange("queueing" , issueTime, startTime);
    }
    const responseReceived = (request.responseReceivedTime - startTime) * 1000;
    if (request.fetchedViaServiceWorker) {
        addOffsetRange("blocking" , 0, timing.workerStart);
        addOffsetRange("serviceworker-preparation" , timing.workerStart, timing.workerReady);
        addOffsetRange("serviceworker-respondwith" , timing.workerFetchStart, timing.workerRespondWithSettled);
        addOffsetRange("serviceworker" , timing.workerReady, timing.sendEnd);
        addOffsetRange("waiting" , timing.sendEnd, responseReceived);
    }
    else if (!timing.pushStart) {
        const blockingEnd = firstPositive([timing.dnsStart, timing.connectStart, timing.sendStart, responseReceived]) || 0;
        addOffsetRange("blocking" , 0, blockingEnd);
        addOffsetRange("proxy" , timing.proxyStart, timing.proxyEnd);
        addOffsetRange("dns" , timing.dnsStart, timing.dnsEnd);
        addOffsetRange("connecting" , timing.connectStart, timing.connectEnd);
        addOffsetRange("ssl" , timing.sslStart, timing.sslEnd);
        addOffsetRange("sending" , timing.sendStart, timing.sendEnd);
        addOffsetRange("waiting" , Math.max(timing.sendEnd, timing.connectEnd, timing.dnsEnd, timing.proxyEnd, blockingEnd), responseReceived);
    }
    const { serviceWorkerRouterInfo } = request;
    if (serviceWorkerRouterInfo) {
        if (timing.workerRouterEvaluationStart) {
            let routerEvaluationEnd = timing.sendStart;
            if (serviceWorkerRouterInfo?.matchedSourceType === "cache"  &&
                timing.workerCacheLookupStart) {
                routerEvaluationEnd = timing.workerCacheLookupStart;
            }
            else if (serviceWorkerRouterInfo?.actualSourceType === "fetch-event" ) {
                routerEvaluationEnd = timing.workerStart;
            }
            addMaybeNegativeOffsetRange("serviceworker-routerevaluation" , timing.workerRouterEvaluationStart, routerEvaluationEnd);
        }
        if (timing.workerCacheLookupStart) {
            let cacheLookupEnd = timing.sendStart;
            if (serviceWorkerRouterInfo?.actualSourceType === "cache" ) {
                cacheLookupEnd = timing.receiveHeadersStart;
            }
            addMaybeNegativeOffsetRange("serviceworker-cachelookup" , timing.workerCacheLookupStart, cacheLookupEnd);
        }
    }
    if (request.endTime !== -1) {
        addRange(timing.pushStart ? "receiving-push"  : "receiving" , request.responseReceivedTime, endTime);
    }
    return result;
}

// Copyright 2025 The Chromium Authors
const defaultTimeFormatterOptions = {
    style: 'unit',
    unitDisplay: 'narrow',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
};
const defaultByteFormatterOptions = {
    style: 'unit',
    unitDisplay: 'narrow',
    minimumFractionDigits: 0,
    maximumFractionDigits: 1,
};
const timeFormatters = {
    milli: new Intl.NumberFormat('en-US', {
        ...defaultTimeFormatterOptions,
        unit: 'millisecond',
    }),
    milliWithPrecision: new Intl.NumberFormat('en-US', {
        ...defaultTimeFormatterOptions,
        maximumFractionDigits: 1,
        unit: 'millisecond',
    }),
    second: new Intl.NumberFormat('en-US', {
        ...defaultTimeFormatterOptions,
        maximumFractionDigits: 1,
        unit: 'second',
    }),
    micro: new Intl.NumberFormat('en-US', {
        ...defaultTimeFormatterOptions,
        unit: 'microsecond',
    }),
};
const byteFormatters = {
    bytes: new Intl.NumberFormat('en-US', {
        ...defaultByteFormatterOptions,
        minimumFractionDigits: 0,
        maximumFractionDigits: 0,
        unit: 'byte',
    }),
    kilobytes: new Intl.NumberFormat('en-US', {
        ...defaultByteFormatterOptions,
        unit: 'kilobyte',
    }),
    megabytes: new Intl.NumberFormat('en-US', {
        ...defaultByteFormatterOptions,
        unit: 'megabyte',
    }),
};
function numberIsTooLarge(x) {
    return !Number.isFinite(x) || x === Number.MAX_VALUE;
}
function seconds(x) {
    if (numberIsTooLarge(x)) {
        return '-';
    }
    if (x === 0) {
        return formatAndEnsureSpace(timeFormatters.second, x);
    }
    const asMilli = x * 1_000;
    if (asMilli < 1) {
        return micros(x * 1_000_000);
    }
    if (asMilli < 1_000) {
        return millis(asMilli);
    }
    return formatAndEnsureSpace(timeFormatters.second, x);
}
function millis(x) {
    if (numberIsTooLarge(x)) {
        return '-';
    }
    if (x < 1) {
        return formatAndEnsureSpace(timeFormatters.milliWithPrecision, x);
    }
    return formatAndEnsureSpace(timeFormatters.milli, x);
}
function micros(x) {
    if (numberIsTooLarge(x)) {
        return '-';
    }
    if (x < 100) {
        return formatAndEnsureSpace(timeFormatters.micro, x);
    }
    const asMilli = x / 1_000;
    return millis(asMilli);
}
function bytes(x) {
    if (x < 1_000) {
        return formatAndEnsureSpace(byteFormatters.bytes, x);
    }
    const kilobytes = x / 1_000;
    if (kilobytes < 1_000) {
        return formatAndEnsureSpace(byteFormatters.kilobytes, kilobytes);
    }
    const megabytes = kilobytes / 1_000;
    return formatAndEnsureSpace(byteFormatters.megabytes, megabytes);
}
function formatAndEnsureSpace(formatter, value, separator = '\xA0') {
    const parts = formatter.formatToParts(value);
    let hasSpace = false;
    for (const part of parts) {
        if (part.type === 'literal') {
            if (part.value === ' ') {
                hasSpace = true;
                part.value = separator;
            }
            else if (part.value === separator) {
                hasSpace = true;
            }
        }
    }
    if (hasSpace) {
        return parts.map(part => part.value).join('');
    }
    const unitIndex = parts.findIndex(part => part.type === 'unit');
    if (unitIndex === -1) {
        return parts.map(part => part.value).join('');
    }
    if (unitIndex === 0) {
        return parts[0].value + separator + parts.slice(1).map(part => part.value).join('');
    }
    return parts.slice(0, unitIndex).map(part => part.value).join('') + separator +
        parts.slice(unitIndex).map(part => part.value).join('');
}

// Copyright 2025 The Chromium Authors
var _a;
const MAX_HEADERS_SIZE = 1000;
const MAX_BODY_SIZE = 10000;
function sanitizeHeaders(headers) {
    return headers.map(header => {
        if (NetworkRequestFormatter.allowHeader(header.name)) {
            return header;
        }
        return { name: header.name, value: '<redacted>' };
    });
}
class NetworkRequestFormatter {
    #calculator;
    #request;
    static allowHeader(headerName) {
        return allowedHeaders.has(headerName.toLowerCase().trim());
    }
    static formatHeaders(title, headers, addListPrefixToEachLine) {
        return formatLines(title, sanitizeHeaders(headers).map(header => {
            const prefix = addListPrefixToEachLine ? '- ' : '';
            return prefix + header.name + ': ' + header.value + '\n';
        }), MAX_HEADERS_SIZE);
    }
    static async formatBody(title, request, maxBodySize) {
        const data = await request.requestContentData();
        if (ContentData.isError(data)) {
            return '';
        }
        if (data.isEmpty) {
            return `${title}\n<empty response>`;
        }
        if (data.isTextContent) {
            const dataAsText = data.text;
            if (dataAsText.length > maxBodySize) {
                return `${title}\n${dataAsText.substring(0, maxBodySize) + '... <truncated>'}`;
            }
            return `${title}\n${dataAsText}`;
        }
        return `${title}\n<binary data>`;
    }
    static formatInitiatorUrl(initiatorUrl, allowedOrigin) {
        const initiatorOrigin = new URL(initiatorUrl).origin;
        if (initiatorOrigin === allowedOrigin) {
            return initiatorUrl;
        }
        return '<redacted cross-origin initiator URL>';
    }
    static formatStatus(status) {
        let responseStatus = '';
        if (status.statusCode) {
            responseStatus = `Response status: ${status.statusCode} ${status.statusText}\n`;
        }
        const flags = [];
        flags.push(status.finished ? 'finished' : 'pending');
        if (status.failed) {
            flags.push('failed');
        }
        if (status.canceled) {
            flags.push('canceled');
        }
        if (status.preserved) {
            flags.push('preserved');
        }
        const requestStatus = flags.length > 0 ? `Network request status: ${flags.join(', ')}\n` : '';
        return `${responseStatus}${requestStatus}`;
    }
    static formatFailureReasons(reasons) {
        const lines = [];
        if (reasons.blockedReason) {
            lines.push(`Blocked reason: ${reasons.blockedReason}`);
        }
        if (reasons.corsErrorStatus) {
            lines.push(`CORS error: ${reasons.corsErrorStatus.corsError} ${reasons.corsErrorStatus.failedParameter}`);
        }
        if (reasons.localizedFailDescription) {
            lines.push(`Fail description: ${reasons.localizedFailDescription}`);
        }
        return lines.length > 0 ? `${lines.join('\n')}\n` : '';
    }
    constructor(request, calculator) {
        this.#request = request;
        this.#calculator = calculator;
    }
    formatRequestHeaders() {
        return _a.formatHeaders('Request headers:', this.#request.requestHeaders());
    }
    formatResponseHeaders() {
        return _a.formatHeaders('Response headers:', this.#request.responseHeaders);
    }
    async formatResponseBody() {
        return await _a.formatBody('Response body:', this.#request, MAX_BODY_SIZE);
    }
    async formatNetworkRequest() {
        let responseBody = await this.formatResponseBody();
        if (responseBody) {
            responseBody = `\n\n${responseBody}`;
        }
        return `Request: ${this.#request.url()}
${AnnotationRepository.annotationsEnabled() ? `\nRequest ID: ${this.#request.requestId()}\n` : ''}
${this.formatRequestHeaders()}

${this.formatResponseHeaders()}${responseBody}

${this.formatStatus()}${this.formatFailureReasons()}
Request timing:\n${this.formatNetworkRequestTiming()}

Request initiator chain:\n${this.formatRequestInitiatorChain()}`;
    }
    formatStatus() {
        return _a.formatStatus({
            statusCode: this.#request.statusCode,
            statusText: this.#request.statusText,
            failed: this.#request.failed,
            canceled: this.#request.canceled,
            preserved: this.#request.preserved,
            finished: this.#request.finished,
        });
    }
    formatFailureReasons() {
        return _a.formatFailureReasons({
            blockedReason: this.#request.blockedReason(),
            corsErrorStatus: this.#request.corsErrorStatus(),
            localizedFailDescription: this.#request.localizedFailDescription,
        });
    }
    formatRequestInitiatorChain() {
        const allowedOrigin = new URL(this.#request.url()).origin;
        let initiatorChain = '';
        let lineStart = '- URL: ';
        const graph = NetworkLog.instance().initiatorGraphForRequest(this.#request);
        for (const initiator of Array.from(graph.initiators).reverse()) {
            initiatorChain = initiatorChain + lineStart +
                _a.formatInitiatorUrl(initiator.url(), allowedOrigin) + '\n';
            lineStart = '\t' + lineStart;
            if (initiator === this.#request) {
                initiatorChain =
                    this.#formatRequestInitiated(graph.initiated, this.#request, initiatorChain, lineStart, allowedOrigin);
            }
        }
        return initiatorChain.trim();
    }
    formatNetworkRequestTiming() {
        const results = calculateRequestTimeRanges(this.#request, this.#calculator.minimumBoundary());
        const getDuration = (name) => {
            const result = results.find(r => r.name === name);
            if (!result) {
                return;
            }
            return seconds(result.end - result.start);
        };
        const labels = [
            {
                label: 'Queued at (timestamp)',
                value: seconds(this.#request.issueTime() - this.#calculator.zeroTime()),
            },
            {
                label: 'Started at (timestamp)',
                value: seconds(this.#request.startTime - this.#calculator.zeroTime()),
            },
            {
                label: 'Queueing (duration)',
                value: getDuration('queueing'),
            },
            {
                label: 'Connection start (stalled) (duration)',
                value: getDuration('blocking'),
            },
            {
                label: 'Request sent (duration)',
                value: getDuration('sending'),
            },
            {
                label: 'Waiting for server response (duration)',
                value: getDuration('waiting'),
            },
            {
                label: 'Content download (duration)',
                value: getDuration('receiving'),
            },
            {
                label: 'Duration (duration)',
                value: getDuration('total'),
            },
        ];
        return labels.filter(label => !!label.value).map(label => `${label.label}: ${label.value}`).join('\n');
    }
    #formatRequestInitiated(initiated, parentRequest, initiatorChain, lineStart, allowedOrigin) {
        const visited = new Set();
        visited.add(this.#request);
        for (const [keyRequest, initiatedRequest] of initiated.entries()) {
            if (initiatedRequest === parentRequest) {
                if (!visited.has(keyRequest)) {
                    visited.add(keyRequest);
                    initiatorChain = initiatorChain + lineStart +
                        _a.formatInitiatorUrl(keyRequest.url(), allowedOrigin) + '\n';
                    initiatorChain =
                        this.#formatRequestInitiated(initiated, keyRequest, initiatorChain, '\t' + lineStart, allowedOrigin);
                }
            }
        }
        return initiatorChain;
    }
}
_a = NetworkRequestFormatter;
const allowedHeaders = new Set([
    ':authority',
    ':method',
    ':path',
    ':scheme',
    'a-im',
    'accept-ch',
    'accept-charset',
    'accept-datetime',
    'accept-encoding',
    'accept-language',
    'accept-patch',
    'accept-ranges',
    'accept',
    'access-control-allow-credentials',
    'access-control-allow-headers',
    'access-control-allow-methods',
    'access-control-allow-origin',
    'access-control-expose-headers',
    'access-control-max-age',
    'access-control-request-headers',
    'access-control-request-method',
    'age',
    'allow',
    'alt-svc',
    'cache-control',
    'connection',
    'content-disposition',
    'content-encoding',
    'content-language',
    'content-location',
    'content-range',
    'content-security-policy',
    'content-type',
    'correlation-id',
    'date',
    'delta-base',
    'dnt',
    'expect-ct',
    'expect',
    'expires',
    'forwarded',
    'front-end-https',
    'host',
    'http2-settings',
    'if-modified-since',
    'if-range',
    'if-unmodified-source',
    'im',
    'last-modified',
    'link',
    'location',
    'max-forwards',
    'nel',
    'origin',
    'permissions-policy',
    'pragma',
    'preference-applied',
    'proxy-connection',
    'public-key-pins',
    'range',
    'referer',
    'refresh',
    'report-to',
    'retry-after',
    'save-data',
    'sec-gpc',
    'server',
    'status',
    'strict-transport-security',
    'te',
    'timing-allow-origin',
    'tk',
    'trailer',
    'transfer-encoding',
    'upgrade-insecure-requests',
    'upgrade',
    'user-agent',
    'vary',
    'via',
    'warning',
    'www-authenticate',
    'x-att-deviceid',
    'x-content-duration',
    'x-content-security-policy',
    'x-content-type-options',
    'x-correlation-id',
    'x-forwarded-for',
    'x-forwarded-host',
    'x-forwarded-proto',
    'x-frame-options',
    'x-http-method-override',
    'x-powered-by',
    'x-redirected-by',
    'x-request-id',
    'x-requested-with',
    'x-ua-compatible',
    'x-wap-profile',
    'x-webkit-csp',
    'x-xss-protection',
]);
function formatLines(title, lines, maxLength) {
    let result = '';
    for (const line of lines) {
        if (result.length + line.length > maxLength) {
            break;
        }
        result += line;
    }
    result = result.trim();
    return result && title ? title + '\n' + result : result;
}

// Copyright 2025 The Chromium Authors
class PerformanceTraceFormatter {
    #focus;
    #parsedTrace;
    #insightSet;
    #eventsSerializer;
    #formattedFunctionCodes = new Set();
    resolveFunctionCode;
    constructor(focus) {
        this.#focus = focus;
        this.#parsedTrace = focus.parsedTrace;
        this.#insightSet = focus.primaryInsightSet;
        this.#eventsSerializer = focus.eventsSerializer;
    }
    serializeEvent(event) {
        const key = this.#eventsSerializer.keyForEvent(event);
        return `(eventKey: ${key}, ts: ${event.ts})`;
    }
    serializeBounds(bounds) {
        return `{min: ${bounds.min}, max: ${bounds.max}}`;
    }
    #getCruxTraceSummary(insightSet) {
        if (insightSet === null) {
            return [];
        }
        try {
            const cruxScope = CrUXManager.instance().getSelectedScope();
            const parts = [];
            const fieldMetrics = getFieldMetricsForInsightSet(insightSet, this.#parsedTrace.metadata, cruxScope);
            const fieldLcp = fieldMetrics?.lcp;
            const fieldInp = fieldMetrics?.inp;
            const fieldCls = fieldMetrics?.cls;
            if (fieldLcp || fieldInp || fieldCls) {
                parts.push('Metrics (field / real users):');
                const serializeFieldMetricTimingResult = (fieldMetric) => {
                    return `${Math.round(fieldMetric.value / 1000)} ms (scope: ${fieldMetric.pageScope})`;
                };
                const serializeFieldMetricNumberResult = (fieldMetric) => {
                    return `${fieldMetric.value.toFixed(2)} (scope: ${fieldMetric.pageScope})`;
                };
                if (fieldLcp) {
                    parts.push(`  - LCP: ${serializeFieldMetricTimingResult(fieldLcp)}`);
                    const fieldLcpBreakdown = fieldMetrics?.lcpBreakdown;
                    if (fieldLcpBreakdown &&
                        (fieldLcpBreakdown.ttfb || fieldLcpBreakdown.loadDelay || fieldLcpBreakdown.loadDuration ||
                            fieldLcpBreakdown.renderDelay)) {
                        parts.push('  - LCP breakdown:');
                        if (fieldLcpBreakdown.ttfb) {
                            parts.push(`    - TTFB: ${serializeFieldMetricTimingResult(fieldLcpBreakdown.ttfb)}`);
                        }
                        if (fieldLcpBreakdown.loadDelay) {
                            parts.push(`    - Load delay: ${serializeFieldMetricTimingResult(fieldLcpBreakdown.loadDelay)}`);
                        }
                        if (fieldLcpBreakdown.loadDuration) {
                            parts.push(`    - Load duration: ${serializeFieldMetricTimingResult(fieldLcpBreakdown.loadDuration)}`);
                        }
                        if (fieldLcpBreakdown.renderDelay) {
                            parts.push(`    - Render delay: ${serializeFieldMetricTimingResult(fieldLcpBreakdown.renderDelay)}`);
                        }
                    }
                }
                if (fieldInp) {
                    parts.push(`  - INP: ${serializeFieldMetricTimingResult(fieldInp)}`);
                }
                if (fieldCls) {
                    parts.push(`  - CLS: ${serializeFieldMetricNumberResult(fieldCls)}`);
                }
                parts.push('  - The above data is from CrUX–Chrome User Experience Report. It\'s how the page performs for real users.');
                parts.push('  - The values shown above are the p75 measure of all real Chrome users');
                parts.push('  - The scope indicates if the data came from the entire origin, or a specific url');
                parts.push('  - Lab metrics describe how this specific page load performed, while field metrics are an aggregation ' +
                    'of results from real-world users. Best practice is to prioritize metrics that are bad in field data. ' +
                    'Lab metrics may be better or worse than fields metrics depending on the developer\'s machine, network, or the ' +
                    'actions performed while tracing.');
            }
            return parts;
        }
        catch {
            return [];
        }
    }
    formatTraceSummary() {
        const parsedTrace = this.#parsedTrace;
        const traceMetadata = this.#parsedTrace.metadata;
        const data = parsedTrace.data;
        const parts = [];
        parts.push(`URL: ${data.Meta.mainFrameURL}`);
        parts.push(`Trace bounds: ${this.serializeBounds(data.Meta.traceBounds)}`);
        parts.push('CPU throttling: ' + (traceMetadata.cpuThrottling ? `${traceMetadata.cpuThrottling}x` : 'none'));
        parts.push(`Network throttling: ${traceMetadata.networkThrottling ?? 'none'}`);
        parts.push('\n# Available insight sets\n');
        parts.push('The following is a list of insight sets. An insight set covers a specific part of the trace, split by navigations. The insights within each insight set are specific to that part of the trace. Be sure to consider the insight set id and bounds when calling functions. If no specific insight set or navigation is mentioned, assume the user is referring to the first one.');
        for (const insightSet of parsedTrace.insights?.values() ?? []) {
            const lcp = getLCP(insightSet);
            const cls = getCLS(insightSet);
            const inp = getINP(insightSet);
            parts.push(`\n## insight set id: ${insightSet.id}\n`);
            parts.push(`URL: ${insightSet.url}`);
            parts.push(`Bounds: ${this.serializeBounds(insightSet.bounds)}`);
            if (lcp || cls || inp) {
                parts.push('Metrics (lab / observed):');
                if (lcp) {
                    const nodeId = insightSet.model.LCPBreakdown?.lcpEvent?.args.data?.nodeId;
                    const nodeIdText = nodeId !== undefined ? `, nodeId: ${nodeId}` : '';
                    parts.push(`  - LCP: ${Math.round(lcp.value / 1000)} ms, event: ${this.serializeEvent(lcp.event)}${nodeIdText}`);
                    const subparts = insightSet.model.LCPBreakdown?.subparts;
                    if (subparts) {
                        const serializeSubpart = (subpart) => {
                            return `${micros(subpart.range)}, bounds: ${this.serializeBounds(subpart)}`;
                        };
                        parts.push('  - LCP breakdown:');
                        parts.push(`    - TTFB: ${serializeSubpart(subparts.ttfb)}`);
                        if (subparts.loadDelay !== undefined) {
                            parts.push(`    - Load delay: ${serializeSubpart(subparts.loadDelay)}`);
                        }
                        if (subparts.loadDuration !== undefined) {
                            parts.push(`    - Load duration: ${serializeSubpart(subparts.loadDuration)}`);
                        }
                        parts.push(`    - Render delay: ${serializeSubpart(subparts.renderDelay)}`);
                    }
                }
                if (inp) {
                    parts.push(`  - INP: ${Math.round(inp.value / 1000)} ms, event: ${this.serializeEvent(inp.event)}`);
                }
                if (cls) {
                    const eventText = cls.worstClusterEvent ? `, event: ${this.serializeEvent(cls.worstClusterEvent)}` : '';
                    parts.push(`  - CLS: ${cls.value.toFixed(2)}${eventText}`);
                    if (AnnotationRepository.annotationsEnabled()) {
                        const worstClusterEvent = cls.worstClusterEvent;
                        const layoutShiftData = worstClusterEvent?.worstShiftEvent?.args?.data;
                        if (layoutShiftData?.impacted_nodes && layoutShiftData.impacted_nodes?.length > 0) {
                            AnnotationRepository.instance().addElementsAnnotation('This element is impacted by a layout shift', layoutShiftData.impacted_nodes[0].node_id.toString());
                        }
                    }
                }
            }
            else {
                parts.push('Metrics (lab / observed): n/a');
            }
            const cruxParts = insightSet && this.#getCruxTraceSummary(insightSet);
            if (cruxParts?.length) {
                parts.push(...cruxParts);
            }
            else {
                parts.push('Metrics (field / real users): n/a – no data for this page in CrUX');
            }
            parts.push('Available insights:');
            for (const [insightName, model] of Object.entries(insightSet.model)) {
                if (model.state === 'pass') {
                    continue;
                }
                const formatter = new PerformanceInsightFormatter(this.#focus, model);
                if (!formatter.insightIsSupported()) {
                    continue;
                }
                const insightBounds$1 = insightBounds(model, insightSet.bounds);
                const insightParts = [
                    `insight name: ${insightName}`,
                    `description: ${model.description}`,
                    `relevant trace bounds: ${this.serializeBounds(insightBounds$1)}`,
                ];
                const metricSavingsText = formatter.estimatedSavings();
                if (metricSavingsText) {
                    insightParts.push(`estimated metric savings: ${metricSavingsText}`);
                }
                if (model.wastedBytes) {
                    insightParts.push(`estimated wasted bytes: ${bytes(model.wastedBytes)}`);
                }
                for (const suggestion of formatter.getSuggestions()) {
                    insightParts.push(`example question: ${suggestion.title}`);
                }
                const insightPartsText = insightParts.join('\n    ');
                parts.push(`  - ${insightPartsText}`);
            }
        }
        return parts.join('\n');
    }
    async #formatFactByInsightSet(options) {
        const { insights, title, description, empty, cb } = options;
        const lines = [`# ${title}\n`];
        if (description) {
            lines.push(`${description}\n`);
        }
        if (insights?.size) {
            const multipleInsightSets = insights.size > 1;
            for (const insightSet of insights.values()) {
                if (multipleInsightSets) {
                    lines.push(`## insight set id: ${insightSet.id}\n`);
                }
                lines.push((await cb(insightSet) ?? empty) + '\n');
            }
        }
        else {
            lines.push(empty + '\n');
        }
        return lines.join('\n');
    }
    formatCriticalRequests() {
        const parsedTrace = this.#parsedTrace;
        return this.#formatFactByInsightSet({
            insights: parsedTrace.insights,
            title: 'Critical network requests',
            empty: 'none',
            cb: async (insightSet) => {
                const criticalRequests = [];
                const walkRequest = (node) => {
                    criticalRequests.push(node.request);
                    node.children.forEach(walkRequest);
                };
                insightSet.model.NetworkDependencyTree?.rootNodes.forEach(walkRequest);
                return criticalRequests.length ? this.formatNetworkRequests(criticalRequests, { verbose: false }) : null;
            },
        });
    }
    async #serializeBottomUpRootNode(rootNode, limit) {
        const topNodes = [...rootNode.children().values()]
            .filter(n => n.totalTime >= 1)
            .sort((a, b) => b.selfTime - a.selfTime)
            .slice(0, limit);
        const callFrames = [];
        function nodeToText(node) {
            const event = node.event;
            let frame;
            if (isProfileCall(event)) {
                frame = event.callFrame;
                if (node.selfTime >= 100 && callFrames.length < 3) {
                    callFrames.push(frame);
                }
            }
            else {
                frame = getStackTraceTopCallFrameInEventPayload(event);
            }
            let source = forEntry(event);
            if (frame?.url) {
                source += ` (url: ${frame.url}`;
                if (frame.lineNumber !== -1) {
                    source += `, line: ${frame.lineNumber}`;
                }
                if (frame.columnNumber !== -1) {
                    source += `, column: ${frame.columnNumber}`;
                }
                source += ')';
            }
            return `- self: ${millis(node.selfTime)}, total: ${millis(node.totalTime)}, source: ${source}`;
        }
        return topNodes.map(node => nodeToText.call(this, node)).join('\n') +
            await this.#serializeRelevantFunctions(callFrames);
    }
    #getSerializeBottomUpRootNodeFormat(limit) {
        return `This is the bottom-up summary for the entire trace. Only the top ${limit} activities (sorted by self time) are shown. An activity is all the aggregated time spent on the same type of work. For example, it can be all the time spent in a specific JavaScript function, or all the time spent in a specific browser rendering stage (like layout, v8 compile, parsing html). "Self time" represents the aggregated time spent directly in an activity, across all occurrences. "Total time" represents the aggregated time spent in an activity or any of its children.`;
    }
    formatMainThreadBottomUpSummary() {
        const parsedTrace = this.#parsedTrace;
        const limit = 10;
        return this.#formatFactByInsightSet({
            insights: parsedTrace.insights,
            title: 'Main thread bottom-up summary',
            description: this.#getSerializeBottomUpRootNodeFormat(limit),
            empty: 'no activity',
            cb: async (insightSet) => {
                const rootNode = AIQueries.mainThreadActivityBottomUpSingleNavigation(insightSet.navigation?.args.data?.navigationId, insightSet.bounds, parsedTrace);
                return rootNode ? await this.#serializeBottomUpRootNode(rootNode, limit) : null;
            },
        });
    }
    #formatThirdPartyEntitySummaries(summaries) {
        const topMainThreadTimeEntries = summaries.toSorted((a, b) => b.mainThreadTime - a.mainThreadTime).slice(0, 5);
        if (!topMainThreadTimeEntries.length) {
            return '';
        }
        const listText = topMainThreadTimeEntries
            .map(s => {
            const transferSize = `${bytes(s.transferSize)}`;
            return `- name: ${s.entity.name}, main thread time: ${millis(s.mainThreadTime)}, network transfer size: ${transferSize}`;
        })
            .join('\n');
        return listText;
    }
    formatThirdPartySummary() {
        const parsedTrace = this.#parsedTrace;
        return this.#formatFactByInsightSet({
            insights: parsedTrace.insights,
            title: '3rd party summary',
            empty: 'no 3rd parties',
            cb: async (insightSet) => {
                const thirdPartySummaries = summarizeByThirdParty(parsedTrace.data, insightSet.bounds);
                return thirdPartySummaries.length ? this.#formatThirdPartyEntitySummaries(thirdPartySummaries) : null;
            },
        });
    }
    formatLongestTasks() {
        const parsedTrace = this.#parsedTrace;
        return this.#formatFactByInsightSet({
            insights: parsedTrace.insights,
            title: 'Longest tasks',
            empty: 'none',
            cb: async (insightSet) => {
                const longestTaskTrees = AIQueries.longestTasks(insightSet.navigation?.args.data?.navigationId, insightSet.bounds, parsedTrace, 3);
                if (!longestTaskTrees?.length) {
                    return null;
                }
                return longestTaskTrees
                    .map(tree => {
                    const time = millis(tree.rootNode.totalTime);
                    return `- total time: ${time}, event: ${this.serializeEvent(tree.rootNode.event)}`;
                })
                    .join('\n');
            },
        });
    }
    #serializeRelatedInsightsForEvents(events) {
        if (!events.length) {
            return '';
        }
        const insightNameToRelatedEvents = new Map();
        if (this.#insightSet) {
            for (const model of Object.values(this.#insightSet.model)) {
                if (!model.relatedEvents) {
                    continue;
                }
                const modeRelatedEvents = Array.isArray(model.relatedEvents) ? model.relatedEvents : [...model.relatedEvents.keys()];
                if (!modeRelatedEvents.length) {
                    continue;
                }
                const relatedEvents = modeRelatedEvents.filter(e => events.includes(e));
                if (relatedEvents.length) {
                    insightNameToRelatedEvents.set(model.insightKey, relatedEvents);
                }
            }
        }
        if (!insightNameToRelatedEvents.size) {
            return '';
        }
        const results = [];
        for (const [insightKey, events] of insightNameToRelatedEvents) {
            const eventsString = events.slice(0, 5).map(e => forEntry(e) + ' ' + this.serializeEvent(e)).join(', ');
            results.push(`- ${insightKey}: ${eventsString}`);
        }
        return results.join('\n');
    }
    async formatMainThreadTrackSummary(bounds) {
        if (!this.#parsedTrace.insights) {
            return 'No main thread activity found';
        }
        const results = [];
        const insightSet = this.#parsedTrace.insights?.values().find(insightSet => boundsIncludeTimeRange({ bounds, timeRange: insightSet.bounds }));
        const topDownTree = AIQueries.mainThreadActivityTopDown(insightSet?.navigation?.args.data?.navigationId, bounds, this.#parsedTrace);
        if (topDownTree) {
            results.push('# Top-down main thread summary');
            results.push(await this.formatCallTree(topDownTree, 2 ));
        }
        const bottomUpRootNode = AIQueries.mainThreadActivityBottomUp(bounds, this.#parsedTrace);
        if (bottomUpRootNode) {
            results.push('# Bottom-up main thread summary');
            const limit = 20;
            results.push(this.#getSerializeBottomUpRootNodeFormat(limit));
            results.push(await this.#serializeBottomUpRootNode(bottomUpRootNode, limit));
        }
        const thirdPartySummaries = summarizeByThirdParty(this.#parsedTrace.data, bounds);
        if (thirdPartySummaries.length) {
            results.push('# Third parties');
            results.push(this.#formatThirdPartyEntitySummaries(thirdPartySummaries));
        }
        const relatedInsightsText = this.#serializeRelatedInsightsForEvents([...topDownTree?.rootNode.events ?? [], ...bottomUpRootNode?.events ?? []]);
        if (relatedInsightsText) {
            results.push('# Related insights');
            results.push('Here are all the insights that contain some related event from the main thread in the given range.');
            results.push(relatedInsightsText);
        }
        if (!results.length) {
            return 'No main thread activity found';
        }
        return results.join('\n\n');
    }
    formatNetworkTrackSummary(bounds) {
        const results = [];
        const requests = this.#parsedTrace.data.NetworkRequests.byTime.filter(request => eventIsInBounds(request, bounds));
        const requestsText = this.formatNetworkRequests(requests, { verbose: false });
        results.push('# Network requests summary');
        results.push(requestsText || 'No requests in the given bounds');
        const relatedInsightsText = this.#serializeRelatedInsightsForEvents(requests);
        if (relatedInsightsText) {
            results.push('# Related insights');
            results.push('Here are all the insights that contain some related request from the given range.');
            results.push(relatedInsightsText);
        }
        return results.join('\n\n');
    }
    async formatCallTree(tree, headerLevel = 1) {
        let result = `${tree.serialize(headerLevel)}\n\nIMPORTANT: Never show eventKey to the user.\n`;
        const relevantCallFrames = [];
        if (tree.selectedNode && isProfileCall(tree.selectedNode.event)) {
            relevantCallFrames.push(tree.selectedNode.event.callFrame);
        }
        const topCallFrameByTotalTime = tree.topCallFrameByTotalTime();
        if (topCallFrameByTotalTime) {
            relevantCallFrames.push(topCallFrameByTotalTime);
        }
        relevantCallFrames.push(...tree.topCallFramesBySelfTime(3));
        result += await this.#serializeRelevantFunctions(relevantCallFrames);
        return result;
    }
    formatNetworkRequests(requests, options) {
        if (requests.length === 0) {
            return '';
        }
        let verbose;
        if (options?.verbose !== undefined) {
            verbose = options.verbose;
        }
        else {
            verbose = requests.length === 1;
        }
        if (verbose) {
            return requests.map(request => this.#networkRequestVerbosely(request, options)).join('\n');
        }
        return this.#networkRequestsArrayCompressed(requests);
    }
    #getOrAssignUrlIndex(urlIdToIndex, url) {
        let index = urlIdToIndex.get(url);
        if (index !== undefined) {
            return index;
        }
        index = urlIdToIndex.size;
        urlIdToIndex.set(url, index);
        return index;
    }
    #getInitiatorChain(parsedTrace, request) {
        const initiators = [];
        let cur = request;
        while (cur) {
            const initiator = getNetworkInitiator(parsedTrace.data, cur);
            if (initiator) {
                if (initiators.includes(initiator)) {
                    return [];
                }
                initiators.unshift(initiator);
            }
            cur = initiator;
        }
        return initiators;
    }
    #networkRequestVerbosely(request, options) {
        const { url, requestId, statusCode, initialPriority, priority, fromServiceWorker, mimeType, responseHeaders, syntheticData, protocol } = request.args.data;
        const parsedTrace = this.#parsedTrace;
        const titlePrefix = `## ${options?.customTitle ?? 'Network request'}`;
        const navigationForEvent = getNavigationForTraceEvent(request, request.args.data.frame, parsedTrace.data.Meta.navigationsByFrameId);
        const baseTime = navigationForEvent?.ts ?? parsedTrace.data.Meta.traceBounds.min;
        const startTimesForLifecycle = {
            queuedAt: request.ts - baseTime,
            requestSentAt: syntheticData.sendStartTime - baseTime,
            downloadCompletedAt: syntheticData.finishTime - baseTime,
            processingCompletedAt: request.ts + request.dur - baseTime,
        };
        const mainThreadProcessingDuration = startTimesForLifecycle.processingCompletedAt - startTimesForLifecycle.downloadCompletedAt;
        const downloadTime = syntheticData.finishTime - syntheticData.downloadStart;
        const renderBlocking = isSyntheticNetworkRequestEventRenderBlocking(request);
        const initiator = getNetworkInitiator(parsedTrace.data, request);
        const priorityLines = [];
        if (initialPriority === priority) {
            priorityLines.push(`Priority: ${priority}`);
        }
        else {
            priorityLines.push(`Initial priority: ${initialPriority}`);
            priorityLines.push(`Final priority: ${priority}`);
        }
        const redirects = request.args.data.redirects.map((redirect, index) => {
            const startTime = redirect.ts - baseTime;
            return `#### Redirect ${index + 1}: ${redirect.url}
- Start time: ${micros(startTime)}
- Duration: ${micros(redirect.dur)}`;
        });
        const initiators = this.#getInitiatorChain(parsedTrace, request);
        const initiatorUrls = initiators.map(initiator => initiator.args.data.url);
        const eventKey = this.#eventsSerializer.keyForEvent(request);
        const eventKeyLine = eventKey ? `eventKey: ${eventKey}\n` : '';
        return `${titlePrefix}: ${url}${AnnotationRepository.annotationsEnabled() ? `\nrequestId: ${requestId}` : ''}
${eventKeyLine}Timings:
- Queued at: ${micros(startTimesForLifecycle.queuedAt)}
- Request sent at: ${micros(startTimesForLifecycle.requestSentAt)}
- Download complete at: ${micros(startTimesForLifecycle.downloadCompletedAt)}
- Main thread processing completed at: ${micros(startTimesForLifecycle.processingCompletedAt)}
Durations:
- Download time: ${micros(downloadTime)}
- Main thread processing time: ${micros(mainThreadProcessingDuration)}
- Total duration: ${micros(request.dur)}${initiator ? `\nInitiator: ${initiator.args.data.url}` : ''}
Redirects:${redirects.length ? '\n' + redirects.join('\n') : ' no redirects'}
Status code: ${statusCode}
MIME Type: ${mimeType}
Protocol: ${protocol}
${priorityLines.join('\n')}
Render-blocking: ${renderBlocking ? 'Yes' : 'No'}
From a service worker: ${fromServiceWorker ? 'Yes' : 'No'}
Initiators (root request to the request that directly loaded this one): ${initiatorUrls.join(', ') || 'none'}
${NetworkRequestFormatter.formatHeaders('Response headers', responseHeaders ?? [], true)}`;
    }
    #networkRequestsArrayCompressed(requests) {
        const networkDataString = `
Network requests data:

`;
        const urlIdToIndex = new Map();
        const allRequestsText = requests
            .map(request => {
            const urlIndex = this.#getOrAssignUrlIndex(urlIdToIndex, request.args.data.url);
            return this.#networkRequestCompressedFormat(urlIndex, request, urlIdToIndex);
        })
            .join('\n');
        const urlsMapString = 'allUrls = ' +
            `[${Array.from(urlIdToIndex.entries())
                .map(([url, index]) => {
                return `${index}: ${url}`;
            })
                .join(', ')}]`;
        return networkDataString + '\n\n' + urlsMapString + '\n\n' + allRequestsText;
    }
    static callFrameDataFormatDescription = `Each call frame is presented in the following format:

'id;eventKey;name;duration;selfTime;urlIndex;childRange;[line];[column];[S]'

Key definitions:

* id: A unique numerical identifier for the call frame. Never mention this id in the output to the user.
* eventKey: String that uniquely identifies this event in the flame chart.
* name: A concise string describing the call frame (e.g., 'Evaluate Script', 'render', 'fetchData').
* duration: The total execution time of the call frame, including its children.
* selfTime: The time spent directly within the call frame, excluding its children's execution.
* urlIndex: Index referencing the "All URLs" list. Empty if no specific script URL is associated.
* childRange: Specifies the direct children of this node using their IDs. If empty ('' or 'S' at the end), the node has no children. If a single number (e.g., '4'), the node has one child with that ID. If in the format 'firstId-lastId' (e.g., '4-5'), it indicates a consecutive range of child IDs from 'firstId' to 'lastId', inclusive.
* line: An optional field for a call frame's line number. This is where the function is defined.
* column: An optional field for a call frame's column number. This is where the function is defined.
* S: _Optional_. The letter 'S' terminates the line if that call frame was selected by the user.

Example Call Tree:

1;r-123;main;500;100;0;1;;
2;r-124;update;200;50;;3;0;1;
3;p-49575-15428179-2834-374;animate;150;20;0;4-5;0;1;S
4;p-49575-15428179-3505-1162;calculatePosition;80;80;0;1;;
5;p-49575-15428179-5391-2767;applyStyles;50;50;0;1;;
`;
    static networkDataFormatDescription = `Network requests are formatted like this:
\`urlIndex;eventKey;queuedTime;requestSentTime;downloadCompleteTime;processingCompleteTime;totalDuration;downloadDuration;mainThreadProcessingDuration;statusCode;mimeType;priority;initialPriority;finalPriority;renderBlocking;protocol;fromServiceWorker;initiators;redirects:[[redirectUrlIndex|startTime|duration]];responseHeaders:[header1Value|header2Value|...]\`

- \`urlIndex\`: Numerical index for the request's URL, referencing the "All URLs" list.
- \`eventKey\`: String that uniquely identifies this request's trace event.
Timings (all in milliseconds, relative to navigation start):
- \`queuedTime\`: When the request was queued.
- \`requestSentTime\`: When the request was sent.
- \`downloadCompleteTime\`: When the download completed.
- \`processingCompleteTime\`: When main thread processing finished.
Durations (all in milliseconds):
- \`totalDuration\`: Total time from the request being queued until its main thread processing completed.
- \`downloadDuration\`: Time spent actively downloading the resource.
- \`mainThreadProcessingDuration\`: Time spent on the main thread after the download completed.
- \`statusCode\`: The HTTP status code of the response (e.g., 200, 404).
- \`mimeType\`: The MIME type of the resource (e.g., "text/html", "application/javascript").
- \`priority\`: The final network request priority (e.g., "VeryHigh", "Low").
- \`initialPriority\`: The initial network request priority.
- \`finalPriority\`: The final network request priority (redundant if \`priority\` is always final, but kept for clarity if \`initialPriority\` and \`priority\` differ).
- \`renderBlocking\`: 't' if the request was render-blocking, 'f' otherwise.
- \`protocol\`: The network protocol used (e.g., "h2", "http/1.1").
- \`fromServiceWorker\`: 't' if the request was served from a service worker, 'f' otherwise.
- \`initiators\`: A list (separated by ,) of URL indices for the initiator chain of this request. Listed in order starting from the root request to the request that directly loaded this one. This represents the network dependencies necessary to load this request. If there is no initiator, this is empty.
- \`redirects\`: A comma-separated list of redirects, enclosed in square brackets. Each redirect is formatted as
\`[redirectUrlIndex|startTime|duration]\`, where: \`redirectUrlIndex\`: Numerical index for the redirect's URL. \`startTime\`: The start time of the redirect in milliseconds, relative to navigation start. \`duration\`: The duration of the redirect in milliseconds.
- \`responseHeaders\`: A list (separated by '|') of values for specific, pre-defined response headers, enclosed in square brackets.
The order of headers corresponds to an internal fixed list. If a header is not present, its value will be empty.
`;
    #networkRequestCompressedFormat(urlIndex, request, urlIdToIndex) {
        const { statusCode, initialPriority, priority, fromServiceWorker, mimeType, responseHeaders, syntheticData, protocol, } = request.args.data;
        const parsedTrace = this.#parsedTrace;
        const navigationForEvent = getNavigationForTraceEvent(request, request.args.data.frame, parsedTrace.data.Meta.navigationsByFrameId);
        const baseTime = navigationForEvent?.ts ?? parsedTrace.data.Meta.traceBounds.min;
        const queuedTime = micros(request.ts - baseTime);
        const requestSentTime = micros(syntheticData.sendStartTime - baseTime);
        const downloadCompleteTime = micros(syntheticData.finishTime - baseTime);
        const processingCompleteTime = micros(request.ts + request.dur - baseTime);
        const totalDuration = micros(request.dur);
        const downloadDuration = micros(syntheticData.finishTime - syntheticData.downloadStart);
        const mainThreadProcessingDuration = micros(request.ts + request.dur - syntheticData.finishTime);
        const renderBlocking = isSyntheticNetworkRequestEventRenderBlocking(request) ? 't' : 'f';
        const finalPriority = priority;
        const headerValues = responseHeaders
            ?.map(header => {
            const value = NetworkRequestFormatter.allowHeader(header.name) ? header.value : '<redacted>';
            return `${header.name}: ${value}`;
        })
            .join('|');
        const redirects = request.args.data.redirects
            .map(redirect => {
            const urlIndex = this.#getOrAssignUrlIndex(urlIdToIndex, redirect.url);
            const redirectStartTime = micros(redirect.ts - baseTime);
            const redirectDuration = micros(redirect.dur);
            return `[${urlIndex}|${redirectStartTime}|${redirectDuration}]`;
        })
            .join(',');
        const initiators = this.#getInitiatorChain(parsedTrace, request);
        const initiatorUrlIndices = initiators.map(initiator => this.#getOrAssignUrlIndex(urlIdToIndex, initiator.args.data.url));
        const parts = [
            urlIndex,
            this.#eventsSerializer.keyForEvent(request) ?? '',
            queuedTime,
            requestSentTime,
            downloadCompleteTime,
            processingCompleteTime,
            totalDuration,
            downloadDuration,
            mainThreadProcessingDuration,
            statusCode,
            mimeType,
            priority,
            initialPriority,
            finalPriority,
            renderBlocking,
            protocol,
            fromServiceWorker ? 't' : 'f',
            initiatorUrlIndices.join(','),
            `[${redirects}]`,
            `[${headerValues ?? ''}]`,
        ];
        return parts.join(';');
    }
    resolveFunctionCodeAtLocation(url, line, column) {
        if (!this.resolveFunctionCode) {
            throw new Error('missing resolveFunctionCode');
        }
        return this.resolveFunctionCode(url, line, column);
    }
    formatFunctionCode(code) {
        return this.#getFormattedFunctionCodeExplainer() + '\n\n' + this.#formatFunctionCode(code);
    }
    #getFormattedFunctionCodeExplainer() {
        return 'The following are markdown block(s) of code that ran in the page, each representing a separate function. <FUNCTION_START> and <FUNCTION_END> marks the exact function declaration, and everything outside that is provided for additional context. Comments at the end of each line indicate the runtime performance cost of that code. Do not show the user the function markers or the additional context.';
    }
    #functionCodeToKey(code) {
        return code.functionBounds.uiSourceCode.url() + ':' + code.functionBounds.range.toString();
    }
    #hasFormattedFunctionCode(code) {
        return this.#formattedFunctionCodes.has(this.#functionCodeToKey(code));
    }
    #formatFunctionCode(code) {
        this.#formattedFunctionCodes.add(this.#functionCodeToKey(code));
        const { startLine, startColumn } = code.range;
        const { startLine: contextStartLine, startColumn: contextStartColumn, endLine: contextEndLine, endColumn: contextEndColumn } = code.rangeWithContext;
        const name = code.functionBounds.name || '(anonymous)';
        const url = code.functionBounds.uiSourceCode.url();
        const parts = [];
        parts.push(`${name} @ ${url}:${startLine}:${startColumn}. With added context, chunk is from ${contextStartLine}:${contextStartColumn} to ${contextEndLine}:${contextEndColumn}`);
        parts.push('```');
        parts.push(code.codeWithContext);
        parts.push('```');
        return parts.join('\n');
    }
    async #serializeRelevantFunctions(callFrames) {
        const resolveFunctionCode = this.resolveFunctionCode;
        if (!resolveFunctionCode) {
            return '';
        }
        const functionCodeStrings = [];
        const functionCodes = await Promise.all(callFrames.map(frame => resolveFunctionCode(frame.url, frame.lineNumber, frame.columnNumber)));
        for (const code of functionCodes) {
            if (code && !this.#hasFormattedFunctionCode(code)) {
                functionCodeStrings.push(this.#formatFunctionCode(code));
            }
        }
        if (!functionCodeStrings.length) {
            return '';
        }
        return '\n' + [
            this.#getFormattedFunctionCodeExplainer(),
            functionCodeStrings.length > 1 ? `Here are ${functionCodeStrings.length} relevant functions:` :
                `Here is a relevant function:`,
            ...functionCodeStrings,
        ].join('\n\n');
    }
}

// Copyright 2025 The Chromium Authors
function getLCPData(parsedTrace, frameId, navigation) {
    const navMetrics = parsedTrace.data.PageLoadMetrics.metricScoresByFrameId.get(frameId)?.get(navigation);
    if (!navMetrics) {
        return null;
    }
    const metric = navMetrics.get("LCP" );
    if (!metric || !metricIsLCP(metric)) {
        return null;
    }
    const lcpEvent = metric?.event;
    if (!lcpEvent || !isAnyLargestContentfulPaintCandidate(lcpEvent)) {
        return null;
    }
    const navigationId = navigation.args.data?.navigationId;
    return {
        lcpEvent,
        lcpRequest: navigationId ? parsedTrace.data.LargestImagePaint.lcpRequestByNavigationId.get(navigationId) :
            undefined,
        metricScore: metric,
    };
}
class PerformanceInsightFormatter {
    #traceFormatter;
    #insight;
    #parsedTrace;
    constructor(focus, insight) {
        this.#traceFormatter = new PerformanceTraceFormatter(focus);
        this.#insight = insight;
        this.#parsedTrace = focus.parsedTrace;
    }
    #formatMilli(x) {
        if (x === undefined) {
            return '';
        }
        return millis(x);
    }
    #formatMicro(x) {
        if (x === undefined) {
            return '';
        }
        return this.#formatMilli(microToMilli(x));
    }
    #formatRequestUrl(request) {
        return `${request.args.data.url} ${this.#traceFormatter.serializeEvent(request)}`;
    }
    #formatScriptUrl(script) {
        if (script.request) {
            return this.#formatRequestUrl(script.request);
        }
        return script.url ?? script.sourceUrl ?? script.scriptId;
    }
    #formatUrl(url) {
        const request = this.#parsedTrace.data.NetworkRequests.byTime.find(request => request.args.data.url === url);
        if (request) {
            return this.#formatRequestUrl(request);
        }
        return url;
    }
    #lcpMetricSharedContext() {
        if (!this.#insight.navigation) {
            return '';
        }
        if (!this.#insight.frameId || !this.#insight.navigation) {
            return '';
        }
        const data = getLCPData(this.#parsedTrace, this.#insight.frameId, this.#insight.navigation);
        if (!data) {
            return '';
        }
        const { metricScore, lcpRequest, lcpEvent } = data;
        const theLcpElement = lcpEvent.args.data?.nodeName ?
            `The LCP element (${lcpEvent.args.data.nodeName}, nodeId: ${lcpEvent.args.data.nodeId})` :
            'The LCP element';
        const parts = [
            `The Largest Contentful Paint (LCP) time for this navigation was ${this.#formatMicro(metricScore.timing)}.`,
        ];
        if (lcpRequest) {
            parts.push(`${theLcpElement} is an image fetched from ${this.#formatRequestUrl(lcpRequest)}.`);
            const request = this.#traceFormatter.formatNetworkRequests([lcpRequest], { verbose: true, customTitle: 'LCP resource network request' });
            parts.push(request);
        }
        else {
            parts.push(`${theLcpElement} is text and was not fetched from the network.`);
        }
        return parts.join('\n');
    }
    insightIsSupported() {
        return this.#description().length > 0;
    }
    getSuggestions() {
        switch (this.#insight.insightKey) {
            case 'CLSCulprits':
                return [
                    { title: 'Help me optimize my CLS score' },
                    { title: 'How can I prevent layout shifts on this page?' },
                ];
            case 'DocumentLatency':
                return [
                    { title: 'How do I decrease the initial loading time of my page?' },
                    { title: 'Did anything slow down the request for this document?' },
                ];
            case 'DOMSize':
                return [{ title: 'How can I reduce the size of my DOM?' }];
            case 'DuplicatedJavaScript':
                return [
                    { title: 'How do I deduplicate the identified scripts in my bundle?' },
                    { title: 'Which duplicated JavaScript modules are the most problematic?' }
                ];
            case 'FontDisplay':
                return [
                    { title: 'How can I update my CSS to avoid layout shifts caused by incorrect `font-display` properties?' }
                ];
            case 'ForcedReflow':
                return [
                    { title: 'How can I avoid forced reflows and layout thrashing?' },
                    { title: 'What is forced reflow and why is it problematic?' }
                ];
            case 'ImageDelivery':
                return [
                    { title: 'What should I do to improve and optimize the time taken to fetch and display images on the page?' },
                    { title: 'Are all images on my site optimized?' },
                ];
            case 'INPBreakdown':
                return [
                    { title: 'Suggest fixes for my longest interaction' }, { title: 'Why is a large INP score problematic?' },
                    { title: 'What\'s the biggest contributor to my longest interaction?' }
                ];
            case 'LCPDiscovery':
                return [
                    { title: 'Suggest fixes to reduce my LCP' }, { title: 'What can I do to reduce my LCP discovery time?' },
                    { title: 'Why is LCP discovery time important?' }
                ];
            case 'LCPBreakdown':
                return [
                    { title: 'Help me optimize my LCP score' }, { title: 'Which LCP phase was most problematic?' },
                    { title: 'What can I do to reduce the LCP time for this page load?' }
                ];
            case 'NetworkDependencyTree':
                return [{ title: 'How do I optimize my network dependency tree?' }];
            case 'RenderBlocking':
                return [
                    { title: 'Show me the most impactful render-blocking requests that I should focus on' },
                    { title: 'How can I reduce the number of render-blocking requests?' }
                ];
            case 'SlowCSSSelector':
                return [{ title: 'How can I optimize my CSS to increase the performance of CSS selectors?' }];
            case 'ThirdParties':
                return [{ title: 'Which third parties are having the largest impact on my page performance?' }];
            case 'Cache':
                return [{ title: 'What caching strategies can I apply to improve my page performance?' }];
            case 'Viewport':
                return [{ title: 'How do I make sure my page is optimized for mobile viewing?' }];
            case 'ModernHTTP':
                return [
                    { title: 'Is my site using the best HTTP practices?' },
                    { title: 'Which resources are not using a modern HTTP protocol?' },
                ];
            case 'LegacyJavaScript':
                return [
                    { title: 'Is my site polyfilling modern JavaScript features?' },
                    { title: 'How can I reduce the amount of legacy JavaScript on my page?' },
                ];
            default:
                throw new Error(`Unknown insight key '${this.#insight.insightKey}'`);
        }
    }
    formatCacheInsight(insight) {
        if (insight.requests.length === 0) {
            return UIStrings$K.noRequestsToCache + '.';
        }
        let output = 'The following resources were associated with ineffficient cache policies:\n';
        for (const entry of insight.requests) {
            output += `\n- ${this.#formatRequestUrl(entry.request)}`;
            output += `\n  - Cache Time to Live (TTL): ${entry.ttl} seconds`;
            output += `\n  - Wasted bytes: ${bytes(entry.wastedBytes)}`;
        }
        output += '\n\n' + UIStrings$K.description;
        return output;
    }
    #formatLayoutShift(shift, index, rootCauses) {
        const baseTime = this.#parsedTrace.data.Meta.traceBounds.min;
        const potentialRootCauses = [];
        if (rootCauses) {
            rootCauses.iframes.forEach(iframe => potentialRootCauses.push(`- An iframe (id: ${iframe.frame}, url: ${iframe.url ?? 'unknown'} was injected into the page)`));
            rootCauses.webFonts.forEach(req => {
                potentialRootCauses.push(`- A font that was loaded over the network: ${this.#formatRequestUrl(req)}.`);
            });
            rootCauses.nonCompositedAnimations.forEach(nonCompositedFailure => {
                potentialRootCauses.push('- A non-composited animation:');
                const animationInfoOutput = [];
                potentialRootCauses.push(`- non-composited animation: \`${nonCompositedFailure.name || '(unnamed)'}\``);
                if (nonCompositedFailure.name) {
                    animationInfoOutput.push(`Animation name: ${nonCompositedFailure.name}`);
                }
                if (nonCompositedFailure.unsupportedProperties) {
                    animationInfoOutput.push('Unsupported CSS properties:');
                    animationInfoOutput.push('- ' + nonCompositedFailure.unsupportedProperties.join(', '));
                }
                animationInfoOutput.push('Failure reasons:');
                animationInfoOutput.push('  - ' + nonCompositedFailure.failureReasons.join(', '));
                potentialRootCauses.push(animationInfoOutput.map(l => ' '.repeat(4) + l).join('\n'));
            });
            rootCauses.unsizedImages.forEach(img => {
                const url = img.paintImageEvent.args.data.url;
                const nodeName = img.paintImageEvent.args.data.nodeName;
                const extraText = url ? `url: ${this.#formatUrl(url)}` : `id: ${img.backendNodeId}`;
                potentialRootCauses.push(`- An unsized image (${nodeName}) (${extraText}).`);
            });
        }
        const rootCauseText = potentialRootCauses.length ? `- Potential root causes:\n  ${potentialRootCauses.join('\n')}` :
            '- No potential root causes identified';
        const startTime = microToMilli(Micro(shift.ts - baseTime));
        const impactedNodeNames = shift.rawSourceEvent.args.data?.impacted_nodes?.map(n => n.debug_name).filter(name => name !== undefined) ?? [];
        const impactedNodeText = impactedNodeNames.length ? `\n- Impacted elements:\n  - ${impactedNodeNames.join('\n  - ')}\n` : '';
        return `### Layout shift ${index + 1}:${impactedNodeText}
- Start time: ${millis(startTime)}
- Score: ${shift.args.data?.weighted_score_delta.toFixed(4)}
${rootCauseText}`;
    }
    formatClsCulpritsInsight(insight) {
        const { worstCluster, shifts } = insight;
        if (!worstCluster) {
            return 'No layout shifts were found.';
        }
        const baseTime = this.#parsedTrace.data.Meta.traceBounds.min;
        const clusterTimes = {
            start: worstCluster.ts - baseTime,
            end: worstCluster.ts + worstCluster.dur - baseTime,
        };
        const shiftsFormatted = worstCluster.events.map((layoutShift, index) => {
            return this.#formatLayoutShift(layoutShift, index, shifts.get(layoutShift));
        });
        return `The worst layout shift cluster was the cluster that started at ${this.#formatMicro(clusterTimes.start)} and ended at ${this.#formatMicro(clusterTimes.end)}, with a duration of ${this.#formatMicro(worstCluster.dur)}.
The score for this cluster is ${worstCluster.clusterCumulativeScore.toFixed(4)}.

Layout shifts in this cluster:
${shiftsFormatted.join('\n')}`;
    }
    formatDocumentLatencyInsight(insight) {
        if (!insight.data) {
            return '';
        }
        const { checklist, documentRequest } = insight.data;
        if (!documentRequest) {
            return '';
        }
        const checklistBulletPoints = [];
        checklistBulletPoints.push({
            name: 'The request was not redirected',
            passed: checklist.noRedirects.value,
        });
        checklistBulletPoints.push({
            name: 'Server responded quickly',
            passed: checklist.serverResponseIsFast.value,
        });
        checklistBulletPoints.push({
            name: 'Compression was applied',
            passed: checklist.usesCompression.value,
        });
        return `${this.#lcpMetricSharedContext()}

${this.#traceFormatter.formatNetworkRequests([documentRequest], {
            verbose: true,
            customTitle: 'Document network request'
        })}

The result of the checks for this insight are:
${checklistBulletPoints.map(point => `- ${point.name}: ${point.passed ? 'PASSED' : 'FAILED'}`).join('\n')}`;
    }
    formatDomSizeInsight(insight) {
        if (insight.state === 'pass') {
            return 'No DOM size issues were detected.';
        }
        let output = UIStrings$H.description + '\n';
        if (insight.maxDOMStats) {
            output += '\n' + UIStrings$H.statistic + ':\n\n';
            const maxDepthStats = insight.maxDOMStats.args.data.maxDepth;
            const maxChildrenStats = insight.maxDOMStats.args.data.maxChildren;
            output += UIStrings$H.totalElements + ': ' +
                insight.maxDOMStats.args.data.totalElements + '.\n';
            if (maxDepthStats) {
                output += UIStrings$H.maxDOMDepth + ': ' + maxDepthStats.depth +
                    ` nodes, starting with element '${maxDepthStats.nodeName}'` +
                    ' (node id: ' + maxDepthStats.nodeId + ').\n';
            }
            if (maxChildrenStats) {
                output += UIStrings$H.maxChildren + ': ' + maxChildrenStats.numChildren +
                    `, for parent '${maxChildrenStats.nodeName}'` +
                    ' (node id: ' + maxChildrenStats.nodeId + ').\n';
            }
        }
        if (insight.largeLayoutUpdates.length > 0 || insight.largeStyleRecalcs.length > 0) {
            output += `\nLarge layout updates/style calculations:\n`;
        }
        if (insight.largeLayoutUpdates.length > 0) {
            for (const update of insight.largeLayoutUpdates) {
                output += `\n  - Layout update: Duration: ${this.#formatMicro(update.dur)},`;
                output += ` with ${update.args.beginData.dirtyObjects} of ${update.args.beginData.totalObjects} nodes needing layout.`;
            }
        }
        if (insight.largeStyleRecalcs.length > 0) {
            for (const recalc of insight.largeStyleRecalcs) {
                output += `\n  - Style recalculation: Duration: ${this.#formatMicro(recalc.dur)}, `;
                output += `with ${recalc.args.elementCount} elements affected.`;
            }
        }
        return output;
    }
    formatDuplicatedJavaScriptInsight(insight) {
        const totalWastedBytes = insight.wastedBytes;
        const duplicatedScriptsByModule = insight.duplicationGroupedByNodeModules;
        if (duplicatedScriptsByModule.size === 0) {
            return 'There is no duplicated JavaScript in the page modules';
        }
        const filesFormatted = Array.from(duplicatedScriptsByModule)
            .map(([module, duplication]) => `- Source: ${module} - Duplicated bytes: ${duplication.estimatedDuplicateBytes} bytes`)
            .join('\n');
        return `Total wasted bytes: ${totalWastedBytes} bytes.

Duplication grouped by Node modules: ${filesFormatted}`;
    }
    formatFontDisplayInsight(insight) {
        if (insight.fonts.length === 0) {
            return 'No font display issues were detected.';
        }
        let output = 'The following font display issues were found:\n';
        for (const font of insight.fonts) {
            let fontName = font.name;
            if (!fontName) {
                const url = new ParsedURL(font.request.args.data.url);
                fontName = url.isValid ? url.lastPathComponent : '(not available)';
            }
            output += `\n - Font name: ${fontName}, URL: ${this.#formatRequestUrl(font.request)}, Property 'font-display' set to: '${font.display}', Wasted time: ${this.#formatMilli(font.wastedTime)}.`;
        }
        output += '\n\n' + UIStrings$F.description;
        return output;
    }
    formatForcedReflowInsight(insight) {
        let output = UIStrings$E.description + '\n\n';
        if (insight.topLevelFunctionCallData || insight.aggregatedBottomUpData.length > 0) {
            output += 'The forced reflow checks revealed one or more problems.\n\n';
        }
        else {
            output += 'The forced reflow checks revealed no problems.';
            return output;
        }
        function callFrameToString(frame) {
            if (frame === null) {
                return UIStrings$E.unattributed;
            }
            let result = `${frame.functionName || UIStrings$E.anonymous}`;
            if (frame.url) {
                result += ` @ ${frame.url}:${frame.lineNumber}:${frame.columnNumber}`;
            }
            else {
                result += ' @ unknown location';
            }
            return result;
        }
        if (insight.topLevelFunctionCallData) {
            output += 'The following is the top function call that caused forced reflow(s):\n\n';
            output += ' - ' + callFrameToString(insight.topLevelFunctionCallData.topLevelFunctionCall);
            output += `\n\n${UIStrings$E.totalReflowTime}: ${this.#formatMicro(insight.topLevelFunctionCallData.totalReflowTime)}\n`;
        }
        else {
            output += 'No top-level functions causing forced reflows were identified.\n';
        }
        if (insight.aggregatedBottomUpData.length > 0) {
            output += '\n' + UIStrings$E.reflowCallFrames + ' (including total time):\n';
            for (const data of insight.aggregatedBottomUpData) {
                output += `\n - ${this.#formatMicro(data.totalTime)} in ${callFrameToString(data.bottomUpData)}`;
            }
        }
        else {
            output += '\nNo aggregated bottom-up causes of forced reflows were identified.';
        }
        return output;
    }
    formatImageDeliveryInsight(insight) {
        const optimizableImages = insight.optimizableImages;
        if (optimizableImages.length === 0) {
            return 'There are no unoptimized images on this page.';
        }
        const imageDetails = optimizableImages
            .map(image => {
            const optimizations = image.optimizations
                .map(optimization => {
                const message = getOptimizationMessage(optimization);
                const byteSavings = bytes(optimization.byteSavings);
                return `${message} (Est ${byteSavings})`;
            })
                .join('\n');
            return `### ${this.#formatRequestUrl(image.request)}
- Potential savings: ${bytes(image.byteSavings)}
- Optimizations:\n${optimizations}`;
        })
            .join('\n\n');
        return `Total potential savings: ${bytes(insight.wastedBytes)}

The following images could be optimized:\n\n${imageDetails}`;
    }
    formatInpBreakdownInsight(insight) {
        const event = insight.longestInteractionEvent;
        if (!event) {
            return '';
        }
        const inpInfoForEvent = `The longest interaction on the page was a \`${event.type}\` which had a total duration of \`${this.#formatMicro(event.dur)}\`. The timings of each of the three phases were:

1. Input delay: ${this.#formatMicro(event.inputDelay)}
2. Processing duration: ${this.#formatMicro(event.mainThreadHandling)}
3. Presentation delay: ${this.#formatMicro(event.presentationDelay)}.`;
        return inpInfoForEvent;
    }
    formatLcpBreakdownInsight(insight) {
        const { subparts, lcpMs } = insight;
        if (!lcpMs || !subparts) {
            return '';
        }
        const phaseBulletPoints = [];
        Object.values(subparts).forEach((subpart) => {
            const phaseMilli = microToMilli(subpart.range);
            const percentage = (phaseMilli / lcpMs * 100).toFixed(1);
            phaseBulletPoints.push({ name: subpart.label, value: this.#formatMilli(phaseMilli), percentage });
        });
        return `${this.#lcpMetricSharedContext()}

We can break this time down into the ${phaseBulletPoints.length} phases that combine to make the LCP time:

${phaseBulletPoints.map(phase => `- ${phase.name}: ${phase.value} (${phase.percentage}% of total LCP time)`)
            .join('\n')}`;
    }
    formatLcpDiscoveryInsight(insight) {
        const { checklist, lcpEvent, lcpRequest, earliestDiscoveryTimeTs } = insight;
        if (!checklist || !lcpEvent || !lcpRequest || !earliestDiscoveryTimeTs) {
            return '';
        }
        const checklistBulletPoints = [];
        checklistBulletPoints.push({
            name: checklist.priorityHinted.label,
            passed: checklist.priorityHinted.value,
        });
        checklistBulletPoints.push({
            name: checklist.eagerlyLoaded.label,
            passed: checklist.eagerlyLoaded.value,
        });
        checklistBulletPoints.push({
            name: checklist.requestDiscoverable.label,
            passed: checklist.requestDiscoverable.value,
        });
        return `${this.#lcpMetricSharedContext()}

The result of the checks for this insight are:
${checklistBulletPoints.map(point => `- ${point.name}: ${point.passed ? 'PASSED' : 'FAILED'}`).join('\n')}`;
    }
    formatLegacyJavaScriptInsight(insight) {
        const legacyJavaScriptResults = insight.legacyJavaScriptResults;
        if (legacyJavaScriptResults.size === 0) {
            return 'There is no significant amount of legacy JavaScript on the page.';
        }
        const filesFormatted = Array.from(legacyJavaScriptResults)
            .map(([script, result]) => `\n- Script: ${this.#formatScriptUrl(script)} - Wasted bytes: ${result.estimatedByteSavings} bytes
Matches:
${result.matches.map(match => `Line: ${match.line}, Column: ${match.column}, Name: ${match.name}`).join('\n')}`)
            .join('\n');
        return `Total legacy JavaScript: ${legacyJavaScriptResults.size} files.

Legacy JavaScript by file:
${filesFormatted}`;
    }
    formatModernHttpInsight(insight) {
        const requestSummary = (insight.http1Requests.length === 1) ?
            this.#traceFormatter.formatNetworkRequests(insight.http1Requests, { verbose: true }) :
            this.#traceFormatter.formatNetworkRequests(insight.http1Requests);
        if (requestSummary.length === 0) {
            return 'There are no requests that were served over a legacy HTTP protocol.';
        }
        return `Here is a list of the network requests that were served over a legacy HTTP protocol:
${requestSummary}`;
    }
    formatNetworkDependencyTreeInsight(insight) {
        let output = insight.fail ?
            'The network dependency tree checks found one or more problems.\n\n' :
            'The network dependency tree checks revealed no problems, but optimization suggestions may be available.\n\n';
        const rootNodes = insight.rootNodes;
        if (rootNodes.length > 0) {
            output += `Max critical path latency is ${this.#formatMicro(insight.maxTime)}\n\n`;
            output += 'The following is the critical request chain:\n';
            function formatNode(node, indent) {
                const url = this.#formatRequestUrl(node.request);
                const time = this.#formatMicro(node.timeFromInitialRequest);
                const isLongest = node.isLongest ? ' (longest chain)' : '';
                let nodeString = `${indent}- ${url} (${time})${isLongest}\n`;
                for (const child of node.children) {
                    nodeString += formatNode.call(this, child, indent + '  ');
                }
                return nodeString;
            }
            for (const rootNode of rootNodes) {
                output += formatNode.call(this, rootNode, '');
            }
            output += '\n';
        }
        else {
            output += `${UIStrings$x.noNetworkDependencyTree}.\n\n`;
        }
        if (insight.preconnectedOrigins?.length > 0) {
            output += `${UIStrings$x.preconnectOriginsTableTitle}:\n`;
            output += `${UIStrings$x.preconnectOriginsTableDescription}\n`;
            for (const origin of insight.preconnectedOrigins) {
                const headerText = 'headerText' in origin ? `'${origin.headerText}'` : ``;
                output += `
  - ${origin.url}
    - ${UIStrings$x.columnSource}: '${origin.source}'`;
                if (headerText) {
                    output += `\n   - Header: ${headerText}`;
                }
                if (origin.unused) {
                    output += `\n   - Warning: ${UIStrings$x.unusedWarning}`;
                }
                if (origin.crossorigin) {
                    output += `\n   - Warning: ${UIStrings$x.crossoriginWarning}`;
                }
            }
            if (insight.preconnectedOrigins.length >
                TOO_MANY_PRECONNECTS_THRESHOLD) {
                output +=
                    `\n\n**Warning**: ${UIStrings$x.tooManyPreconnectLinksWarning}`;
            }
        }
        else {
            output += `${UIStrings$x.noPreconnectOrigins}.`;
        }
        if (insight.preconnectCandidates.length > 0 &&
            insight.preconnectedOrigins.length <
                TOO_MANY_PRECONNECTS_THRESHOLD) {
            output += `\n\n${UIStrings$x.estSavingTableTitle}:\n${UIStrings$x.estSavingTableDescription}\n`;
            for (const candidate of insight.preconnectCandidates) {
                output += `\nAdding [preconnect] to origin '${candidate.origin}' would save ${this.#formatMilli(candidate.wastedMs)}.`;
            }
        }
        return output;
    }
    formatRenderBlockingInsight(insight) {
        const requestSummary = this.#traceFormatter.formatNetworkRequests(insight.renderBlockingRequests);
        if (requestSummary.length === 0) {
            return 'There are no network requests that are render-blocking.';
        }
        return `Here is a list of the network requests that were render-blocking on this page and their duration:

${requestSummary}`;
    }
    formatSlowCssSelectorsInsight(insight) {
        let output = '';
        if (!insight.topSelectorElapsedMs && !insight.topSelectorMatchAttempts) {
            return UIStrings$v.enableSelectorData;
        }
        output += 'One or more slow CSS selectors were identified as negatively affecting page performance:\n\n';
        if (insight.topSelectorElapsedMs) {
            output += `${UIStrings$v.topSelectorElapsedTime} (as ranked by elapsed time in ms):\n`;
            output += `${this.#formatMicro(insight.topSelectorElapsedMs['elapsed (us)'])}: ${insight.topSelectorElapsedMs.selector}\n\n`;
        }
        if (insight.topSelectorMatchAttempts) {
            output += UIStrings$v.topSelectorMatchAttempt + ':\n';
            output += `${insight.topSelectorMatchAttempts.match_attempts} attempts for selector: '${insight.topSelectorMatchAttempts.selector}'\n\n`;
        }
        output += `${UIStrings$v.total}:\n`;
        output +=
            `${UIStrings$v.elapsed}: ${this.#formatMicro(insight.totalElapsedMs)}\n`;
        output += `${UIStrings$v.matchAttempts}: ${insight.totalMatchAttempts}\n`;
        output += `${UIStrings$v.matchCount}: ${insight.totalMatchCount}\n\n`;
        output += UIStrings$v.description;
        return output;
    }
    formatThirdPartiesInsight(insight) {
        let output = '';
        const entitySummaries = insight.entitySummaries ?? [];
        const firstPartyEntity = insight.firstPartyEntity;
        const thirdPartyTransferSizeEntries = entitySummaries.filter(s => s.entity !== firstPartyEntity).toSorted((a, b) => b.transferSize - a.transferSize);
        const thirdPartyMainThreadTimeEntries = entitySummaries.filter(s => s.entity !== firstPartyEntity)
            .toSorted((a, b) => b.mainThreadTime - a.mainThreadTime);
        if (!thirdPartyTransferSizeEntries.length && !thirdPartyMainThreadTimeEntries.length) {
            return `No 3rd party scripts were found on this page.`;
        }
        if (thirdPartyTransferSizeEntries.length) {
            output += `The following list contains the largest transfer sizes by a 3rd party script:\n\n`;
            for (const entry of thirdPartyTransferSizeEntries) {
                if (entry.transferSize > 0) {
                    output += `- ${entry.entity.name}: ${bytes(entry.transferSize)}\n`;
                }
            }
            output += '\n';
        }
        if (thirdPartyMainThreadTimeEntries.length) {
            output += `The following list contains the largest amount spent by a 3rd party script on the main thread:\n\n`;
            for (const entry of thirdPartyMainThreadTimeEntries) {
                if (entry.mainThreadTime > 0) {
                    output += `- ${entry.entity.name}: ${this.#formatMilli(entry.mainThreadTime)}\n`;
                }
            }
            output += '\n';
        }
        output += UIStrings$u.description;
        return output;
    }
    formatViewportInsight(insight) {
        let output = '';
        output += 'The webpage is ' + (insight.mobileOptimized ? 'already' : 'not') + ' optimized for mobile viewing.\n';
        const hasMetaTag = insight.viewportEvent;
        if (hasMetaTag) {
            output += `\nThe viewport meta tag was found: \`${insight.viewportEvent?.args?.data.content}\`.`;
        }
        else {
            output += `\nThe viewport meta tag is missing.`;
        }
        if (!hasMetaTag) {
            output += '\n\n' + UIStrings$t.description;
        }
        return output;
    }
    formatInsight(opts = { headingLevel: 2 }) {
        const header = '#'.repeat(opts.headingLevel);
        const { title } = this.#insight;
        return `${header} Insight Title: ${title}

${header} Insight Summary:
${this.#description()}

${header} Detailed analysis:
${this.#details()}

${header} Estimated savings: ${this.estimatedSavings() || 'none'}

${header} External resources:
${this.#links()}`;
    }
    #details() {
        if (isCacheInsight(this.#insight)) {
            return this.formatCacheInsight(this.#insight);
        }
        if (isCLSCulpritsInsight(this.#insight)) {
            return this.formatClsCulpritsInsight(this.#insight);
        }
        if (isDocumentLatencyInsight(this.#insight)) {
            return this.formatDocumentLatencyInsight(this.#insight);
        }
        if (isDomSizeInsight(this.#insight)) {
            return this.formatDomSizeInsight(this.#insight);
        }
        if (isDuplicatedJavaScriptInsight(this.#insight)) {
            return this.formatDuplicatedJavaScriptInsight(this.#insight);
        }
        if (isFontDisplayInsight(this.#insight)) {
            return this.formatFontDisplayInsight(this.#insight);
        }
        if (isForcedReflowInsight(this.#insight)) {
            return this.formatForcedReflowInsight(this.#insight);
        }
        if (isImageDeliveryInsight(this.#insight)) {
            return this.formatImageDeliveryInsight(this.#insight);
        }
        if (isINPBreakdownInsight(this.#insight)) {
            return this.formatInpBreakdownInsight(this.#insight);
        }
        if (isLCPBreakdownInsight(this.#insight)) {
            return this.formatLcpBreakdownInsight(this.#insight);
        }
        if (isLCPDiscoveryInsight(this.#insight)) {
            return this.formatLcpDiscoveryInsight(this.#insight);
        }
        if (isLegacyJavaScript(this.#insight)) {
            return this.formatLegacyJavaScriptInsight(this.#insight);
        }
        if (isModernHTTPInsight(this.#insight)) {
            return this.formatModernHttpInsight(this.#insight);
        }
        if (isNetworkDependencyTreeInsight(this.#insight)) {
            return this.formatNetworkDependencyTreeInsight(this.#insight);
        }
        if (isRenderBlockingInsight(this.#insight)) {
            return this.formatRenderBlockingInsight(this.#insight);
        }
        if (isSlowCSSSelectorInsight(this.#insight)) {
            return this.formatSlowCssSelectorsInsight(this.#insight);
        }
        if (isThirdPartyInsight(this.#insight)) {
            return this.formatThirdPartiesInsight(this.#insight);
        }
        if (isViewportInsight(this.#insight)) {
            return this.formatViewportInsight(this.#insight);
        }
        return '';
    }
    estimatedSavings() {
        return Object.entries(this.#insight.metricSavings ?? {})
            .map(([k, v]) => {
            if (k === 'CLS') {
                return `${k} ${v.toFixed(2)}`;
            }
            return `${k} ${Math.round(v)} ms`;
        })
            .join(', ');
    }
    #links() {
        const links = [];
        if (this.#insight.docs) {
            links.push(this.#insight.docs);
        }
        switch (this.#insight.insightKey) {
            case 'CLSCulprits':
                links.push('https://web.dev/articles/cls');
                links.push('https://web.dev/articles/optimize-cls');
                break;
            case 'DocumentLatency':
                links.push('https://web.dev/articles/optimize-ttfb');
                break;
            case 'DOMSize':
                links.push('https://developer.chrome.com/docs/lighthouse/performance/dom-size/');
                break;
            case 'FontDisplay':
                links.push('https://web.dev/articles/preload-optional-fonts');
                links.push('https://fonts.google.com/knowledge/glossary/foit');
                links.push('https://developer.chrome.com/blog/font-fallbacks');
                break;
            case 'ForcedReflow':
                links.push('https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing#avoid-forced-synchronous-layouts');
                break;
            case 'ImageDelivery':
                links.push('https://developer.chrome.com/docs/lighthouse/performance/uses-optimized-images/');
                break;
            case 'INPBreakdown':
                links.push('https://web.dev/articles/inp');
                links.push('https://web.dev/explore/how-to-optimize-inp');
                links.push('https://web.dev/articles/optimize-long-tasks');
                links.push('https://web.dev/articles/avoid-large-complex-layouts-and-layout-thrashing');
                break;
            case 'LCPBreakdown':
            case 'LCPDiscovery':
            case 'RenderBlocking':
                links.push('https://web.dev/articles/lcp');
                links.push('https://web.dev/articles/optimize-lcp');
                break;
            case 'NetworkDependencyTree':
                links.push('https://web.dev/learn/performance/understanding-the-critical-path');
                links.push('https://developer.chrome.com/docs/lighthouse/performance/uses-rel-preconnect/');
                break;
            case 'SlowCSSSelector':
                links.push('https://developer.chrome.com/docs/devtools/performance/selector-stats');
                break;
            case 'ThirdParties':
                links.push('https://web.dev/articles/optimizing-content-efficiency-loading-third-party-javascript/');
                break;
            case 'Viewport':
                links.push('https://developer.chrome.com/blog/300ms-tap-delay-gone-away/');
                break;
            case 'Cache':
                links.push('https://web.dev/uses-long-cache-ttl/');
                break;
            case 'ModernHTTP':
                links.push('https://developer.chrome.com/docs/lighthouse/best-practices/uses-http2');
                break;
            case 'LegacyJavaScript':
                links.push('https://web.dev/articles/baseline-and-polyfills');
                links.push('https://philipwalton.com/articles/the-state-of-es5-on-the-web/');
                break;
        }
        return links.map(link => '- ' + link).join('\n');
    }
    #description() {
        switch (this.#insight.insightKey) {
            case 'CLSCulprits':
                return `Cumulative Layout Shifts (CLS) is a measure of the largest burst of layout shifts for every unexpected layout shift that occurs during the lifecycle of a page. This is a Core Web Vital and the thresholds for categorizing a score are:
- Good: 0.1 or less
- Needs improvement: more than 0.1 and less than or equal to 0.25
- Bad: over 0.25`;
            case 'DocumentLatency':
                return `This insight checks that the first request is responded to promptly. We use the following criteria to check this:
1. Was the initial request redirected?
2. Did the server respond in 600ms or less? We want developers to aim for as close to 100ms as possible, but our threshold for this insight is 600ms.
3. Was there compression applied to the response to minimize the transfer size?`;
            case 'DOMSize':
                return `This insight evaluates some key metrics about the Document Object Model (DOM) and identifies excess in the DOM tree, for example:
- The maximum number of elements within the DOM.
- The maximum number of children for any given element.
- Excessive depth of the DOM structure.
- The largest layout and style recalculation events.`;
            case 'DuplicatedJavaScript':
                return `This insight identifies large, duplicated JavaScript modules that are present in your application and create redundant code.
  This wastes network bandwidth and slows down your page, as the user's browser must download and process the same code multiple times.`;
            case 'FontDisplay':
                return 'This insight identifies font issues when a webpage uses custom fonts, for example when font-display is not set to `swap`, `fallback` or `optional`, causing the "Flash of Invisible Text" problem (FOIT).';
            case 'ForcedReflow':
                return `This insight identifies forced synchronous layouts (also known as forced reflows) and layout thrashing caused by JavaScript accessing layout properties at suboptimal points in time.`;
            case 'ImageDelivery':
                return 'This insight identifies unoptimized images that are downloaded at a much higher resolution than they are displayed. Properly sizing and compressing these assets will decrease their download time, directly improving the perceived page load time and LCP';
            case 'INPBreakdown':
                return `Interaction to Next Paint (INP) is a metric that tracks the responsiveness of the page when the user interacts with it. INP is a Core Web Vital and the thresholds for how we categorize a score are:
- Good: 200 milliseconds or less.
- Needs improvement: more than 200 milliseconds and 500 milliseconds or less.
- Bad: over 500 milliseconds.

For a given slow interaction, we can break it down into 3 phases:
1. Input delay: starts when the user initiates an interaction with the page, and ends when the event callbacks for the interaction begin to run.
2. Processing duration: the time it takes for the event callbacks to run to completion.
3. Presentation delay: the time it takes for the browser to present the next frame which contains the visual result of the interaction.

The sum of these three phases is the total latency. It is important to optimize each of these phases to ensure interactions take as little time as possible. Focusing on the phase that has the largest score is a good way to start optimizing.`;
            case 'LCPDiscovery':
                return `This insight analyzes the time taken to discover the LCP resource and request it on the network. It only applies if the LCP element was a resource like an image that has to be fetched over the network. There are 3 checks this insight makes:
1. Did the resource have \`fetchpriority=high\` applied?
2. Was the resource discoverable in the initial document, rather than injected from a script or stylesheet?
3. The resource was not lazy loaded as this can delay the browser loading the resource.

It is important that all of these checks pass to minimize the delay between the initial page load and the LCP resource being loaded.`;
            case 'LCPBreakdown':
                return 'This insight is used to analyze the time spent that contributed to the final LCP time and identify which of the 4 phases (or 2 if there was no LCP resource) are contributing most to the delay in rendering the LCP element.';
            case 'NetworkDependencyTree':
                return `This insight analyzes the network dependency tree to identify:
- The maximum critical path latency (the longest chain of network requests that the browser must download before it can render the page).
- Whether current [preconnect] tags are appropriate, according to the following rules:
   1. They should all be in use (no unnecessary preconnects).
   2. All preconnects should specify cross-origin correctly.
   3. The maximum of 4 preconnects should be respected.
- Opportunities to add [preconnect] for a faster loading experience.`;
            case 'RenderBlocking':
                return 'This insight identifies network requests that were render-blocking. Render-blocking requests are impactful because they are deemed critical to the page and therefore the browser stops rendering the page until it has dealt with these resources. For this insight make sure you fully inspect the details of each render-blocking network request and prioritize your suggestions to the user based on the impact of each render-blocking request.';
            case 'SlowCSSSelector':
                return `This insight identifies CSS selectors that are slowing down your page's rendering performance.`;
            case 'ThirdParties':
                return 'This insight analyzes the performance impact of resources loaded from third-party servers and aggregates the performance cost, in terms of download transfer sizes and total amount of time that third party scripts spent executing on the main thread.';
            case 'Viewport':
                return 'The insight identifies web pages that are not specifying the viewport meta tag for mobile devies, which avoids the artificial 300-350ms delay designed to help differentiate between tap and double-click.';
            case 'Cache':
                return 'This insight identifies static resources that are not cached effectively by the browser.';
            case 'ModernHTTP':
                return `Modern HTTP protocols, such as HTTP/2, are more efficient than older versions like HTTP/1.1 because they allow for multiple requests and responses to be sent over a single network connection, significantly improving page load performance by reducing latency and overhead. This insight identifies requests that can be upgraded to a modern HTTP protocol.

We apply a conservative approach when flagging HTTP/1.1 usage. This insight will only flag requests that meet all of the following criteria:
1.  Were served over HTTP/1.1 or an earlier protocol.
2.  Originate from an origin that serves at least 6 static asset requests, as the benefits of multiplexing are less significant with fewer requests.
3.  Are not served from 'localhost' or coming from a third-party source, where developers have no control over the server's protocol.

To pass this insight, ensure your server supports and prioritizes a modern HTTP protocol (like HTTP/2) for static assets, especially when serving a substantial number of them.`;
            case 'LegacyJavaScript':
                return `This insight identified legacy JavaScript in your application's modules that may be creating unnecessary code.

Polyfills and transforms enable older browsers to use new JavaScript features. However, many are not necessary for modern browsers. Consider modifying your JavaScript build process to not transpile Baseline features, unless you know you must support older browsers.`;
        }
    }
}

// Copyright 2025 The Chromium Authors
function getPrimaryInsightSet(insights) {
    const insightSets = Array.from(insights.values());
    if (insightSets.length === 0) {
        return null;
    }
    if (insightSets.length === 1) {
        return insightSets[0];
    }
    return insightSets.filter(set => set.navigation).at(0) ?? insightSets.at(0) ?? null;
}
class AgentFocus {
    static fromParsedTrace(parsedTrace) {
        if (!parsedTrace.insights) {
            throw new Error('missing insights');
        }
        return new AgentFocus({
            parsedTrace,
            event: null,
            callTree: null,
            insight: null,
        });
    }
    static fromInsight(parsedTrace, insight) {
        if (!parsedTrace.insights) {
            throw new Error('missing insights');
        }
        return new AgentFocus({
            parsedTrace,
            event: null,
            callTree: null,
            insight,
        });
    }
    static fromEvent(parsedTrace, event) {
        if (!parsedTrace.insights) {
            throw new Error('missing insights');
        }
        const result = AgentFocus.#getCallTreeOrEvent(parsedTrace, event);
        return new AgentFocus({ parsedTrace, event: result.event, callTree: result.callTree, insight: null });
    }
    static fromCallTree(callTree) {
        return new AgentFocus({ parsedTrace: callTree.parsedTrace, event: null, callTree, insight: null });
    }
    #data;
    #primaryInsightSet;
    eventsSerializer = new EventsSerializer();
    constructor(data) {
        if (!data.parsedTrace.insights) {
            throw new Error('missing insights');
        }
        this.#data = data;
        this.#primaryInsightSet = getPrimaryInsightSet(data.parsedTrace.insights);
    }
    get parsedTrace() {
        return this.#data.parsedTrace;
    }
    get primaryInsightSet() {
        return this.#primaryInsightSet;
    }
    get event() {
        return this.#data.event;
    }
    get callTree() {
        return this.#data.callTree;
    }
    get insight() {
        return this.#data.insight;
    }
    withInsight(insight) {
        const focus = new AgentFocus(this.#data);
        focus.#data.insight = insight;
        return focus;
    }
    withEvent(event) {
        const focus = new AgentFocus(this.#data);
        const result = AgentFocus.#getCallTreeOrEvent(this.#data.parsedTrace, event);
        focus.#data.callTree = result.callTree;
        focus.#data.event = result.event;
        return focus;
    }
    lookupEvent(key) {
        try {
            return this.eventsSerializer.eventForKey(key, this.#data.parsedTrace);
        }
        catch (err) {
            if (err.toString().includes('Unknown trace event') || err.toString().includes('Unknown profile call')) {
                return null;
            }
            throw err;
        }
    }
    static #getCallTreeOrEvent(parsedTrace, event) {
        const callTree = event && AICallTree.fromEvent(event, parsedTrace);
        if (callTree) {
            return { callTree, event: null };
        }
        if (event && isSyntheticNetworkRequest(event)) {
            return { callTree: null, event };
        }
        return { callTree: null, event: null };
    }
}

// Copyright 2020 The Chromium Authors
const UIStrings$l = {
    improvements: 'Improvements',
    pageErrors: 'Page Errors',
    breakingChanges: 'Breaking Changes',
    pageErrorIssue: 'A page error issue: the page is not working correctly',
    breakingChangeIssue: 'A breaking change issue: the page may stop working in an upcoming version of Chrome',
    improvementIssue: 'An improvement issue: there is an opportunity to improve the page',
};
const str_$k = registerUIStrings('models/issues_manager/Issue.ts', UIStrings$l);
getLocalizedString.bind(undefined, str_$k);
function unionIssueKind(a, b) {
    if (a === "PageError"  || b === "PageError" ) {
        return "PageError" ;
    }
    if (a === "BreakingChange"  || b === "BreakingChange" ) {
        return "BreakingChange" ;
    }
    return "Improvement" ;
}
class Issue {
    #issueCode;
    #issuesModel;
    issueId = undefined;
    #issueDetails;
    #hidden;
    constructor(code, issueDetails, issuesModel = null, issueId) {
        this.#issueCode = typeof code === 'object' ? code.code : code;
        this.#issueDetails = issueDetails;
        this.#issuesModel = issuesModel;
        this.issueId = issueId;
        userMetrics.issueCreated(typeof code === 'string' ? code : code.umaCode);
        this.#hidden = false;
    }
    code() {
        return this.#issueCode;
    }
    details() {
        return this.#issueDetails;
    }
    getBlockedByResponseDetails() {
        return [];
    }
    cookies() {
        return [];
    }
    rawCookieLines() {
        return [];
    }
    elements() {
        return [];
    }
    requests() {
        return [];
    }
    sources() {
        return [];
    }
    trackingSites() {
        return [];
    }
    isAssociatedWithRequestId(requestId) {
        for (const request of this.requests()) {
            if (request.requestId === requestId) {
                return true;
            }
        }
        return false;
    }
    model() {
        return this.#issuesModel;
    }
    isCausedByThirdParty() {
        return false;
    }
    getIssueId() {
        return this.issueId;
    }
    isHidden() {
        return this.#hidden;
    }
    setHidden(hidden) {
        this.#hidden = hidden;
    }
    maybeCreateConsoleMessage() {
        return;
    }
}
function toZeroBasedLocation(location) {
    if (!location) {
        return undefined;
    }
    return {
        url: location.url,
        scriptId: location.scriptId,
        lineNumber: location.lineNumber,
        columnNumber: location.columnNumber === 0 ? undefined : location.columnNumber - 1,
    };
}

// Copyright 2021 The Chromium Authors
function getIssueCode$2(details) {
    switch (details.violationType) {
        case "PermissionPolicyDisabled" :
            return "AttributionReportingIssue::PermissionPolicyDisabled" ;
        case "UntrustworthyReportingOrigin" :
            return "AttributionReportingIssue::UntrustworthyReportingOrigin" ;
        case "InsecureContext" :
            return "AttributionReportingIssue::InsecureContext" ;
        case "InvalidHeader" :
            return "AttributionReportingIssue::InvalidRegisterSourceHeader" ;
        case "InvalidRegisterTriggerHeader" :
            return "AttributionReportingIssue::InvalidRegisterTriggerHeader" ;
        case "SourceAndTriggerHeaders" :
            return "AttributionReportingIssue::SourceAndTriggerHeaders" ;
        case "SourceIgnored" :
            return "AttributionReportingIssue::SourceIgnored" ;
        case "TriggerIgnored" :
            return "AttributionReportingIssue::TriggerIgnored" ;
        case "OsSourceIgnored" :
            return "AttributionReportingIssue::OsSourceIgnored" ;
        case "OsTriggerIgnored" :
            return "AttributionReportingIssue::OsTriggerIgnored" ;
        case "InvalidRegisterOsSourceHeader" :
            return "AttributionReportingIssue::InvalidRegisterOsSourceHeader" ;
        case "InvalidRegisterOsTriggerHeader" :
            return "AttributionReportingIssue::InvalidRegisterOsTriggerHeader" ;
        case "WebAndOsHeaders" :
            return "AttributionReportingIssue::WebAndOsHeaders" ;
        case "NoWebOrOsSupport" :
            return "AttributionReportingIssue::NoWebOrOsSupport" ;
        case "NavigationRegistrationWithoutTransientUserActivation" :
            return "AttributionReportingIssue::NavigationRegistrationWithoutTransientUserActivation" ;
        case "InvalidInfoHeader" :
            return "AttributionReportingIssue::InvalidInfoHeader" ;
        case "NoRegisterSourceHeader" :
            return "AttributionReportingIssue::NoRegisterSourceHeader" ;
        case "NoRegisterTriggerHeader" :
            return "AttributionReportingIssue::NoRegisterTriggerHeader" ;
        case "NoRegisterOsSourceHeader" :
            return "AttributionReportingIssue::NoRegisterOsSourceHeader" ;
        case "NoRegisterOsTriggerHeader" :
            return "AttributionReportingIssue::NoRegisterOsTriggerHeader" ;
        case "NavigationRegistrationUniqueScopeAlreadySet" :
            return "AttributionReportingIssue::NavigationRegistrationUniqueScopeAlreadySet" ;
        default:
            return "AttributionReportingIssue::Unknown" ;
    }
}
const structuredHeaderLink = {
    link: 'https://tools.ietf.org/id/draft-ietf-httpbis-header-structure-15.html#rfc.section.4.2.2',
    linkTitle: 'Structured Headers RFC',
};
class AttributionReportingIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super(getIssueCode$2(issueDetails), issueDetails, issuesModel);
    }
    getCategory() {
        return "AttributionReporting" ;
    }
    getHeaderValidatorLink(name) {
        const url = new URL('https://wicg.github.io/attribution-reporting-api/validate-headers');
        url.searchParams.set('header', name);
        const details = this.details();
        if (details.invalidParameter) {
            url.searchParams.set('json', details.invalidParameter);
        }
        return {
            link: url.toString(),
            linkTitle: 'Header Validator',
        };
    }
    getDescription() {
        switch (this.code()) {
            case "AttributionReportingIssue::PermissionPolicyDisabled" :
                return {
                    file: 'arPermissionPolicyDisabled.md',
                    links: [],
                };
            case "AttributionReportingIssue::UntrustworthyReportingOrigin" :
                return {
                    file: 'arUntrustworthyReportingOrigin.md',
                    links: [],
                };
            case "AttributionReportingIssue::InsecureContext" :
                return {
                    file: 'arInsecureContext.md',
                    links: [],
                };
            case "AttributionReportingIssue::InvalidRegisterSourceHeader" :
                return {
                    file: 'arInvalidRegisterSourceHeader.md',
                    links: [this.getHeaderValidatorLink('source')],
                };
            case "AttributionReportingIssue::InvalidRegisterTriggerHeader" :
                return {
                    file: 'arInvalidRegisterTriggerHeader.md',
                    links: [this.getHeaderValidatorLink('trigger')],
                };
            case "AttributionReportingIssue::InvalidRegisterOsSourceHeader" :
                return {
                    file: 'arInvalidRegisterOsSourceHeader.md',
                    links: [this.getHeaderValidatorLink('os-source')],
                };
            case "AttributionReportingIssue::InvalidRegisterOsTriggerHeader" :
                return {
                    file: 'arInvalidRegisterOsTriggerHeader.md',
                    links: [this.getHeaderValidatorLink('os-trigger')],
                };
            case "AttributionReportingIssue::SourceAndTriggerHeaders" :
                return {
                    file: 'arSourceAndTriggerHeaders.md',
                    links: [],
                };
            case "AttributionReportingIssue::WebAndOsHeaders" :
                return {
                    file: 'arWebAndOsHeaders.md',
                    links: [],
                };
            case "AttributionReportingIssue::SourceIgnored" :
                return {
                    file: 'arSourceIgnored.md',
                    links: [structuredHeaderLink],
                };
            case "AttributionReportingIssue::TriggerIgnored" :
                return {
                    file: 'arTriggerIgnored.md',
                    links: [structuredHeaderLink],
                };
            case "AttributionReportingIssue::OsSourceIgnored" :
                return {
                    file: 'arOsSourceIgnored.md',
                    links: [structuredHeaderLink],
                };
            case "AttributionReportingIssue::OsTriggerIgnored" :
                return {
                    file: 'arOsTriggerIgnored.md',
                    links: [structuredHeaderLink],
                };
            case "AttributionReportingIssue::NavigationRegistrationWithoutTransientUserActivation" :
                return {
                    file: 'arNavigationRegistrationWithoutTransientUserActivation.md',
                    links: [],
                };
            case "AttributionReportingIssue::NoWebOrOsSupport" :
                return {
                    file: 'arNoWebOrOsSupport.md',
                    links: [],
                };
            case "AttributionReportingIssue::InvalidInfoHeader" :
                return {
                    file: 'arInvalidInfoHeader.md',
                    links: [],
                };
            case "AttributionReportingIssue::NoRegisterSourceHeader" :
                return {
                    file: 'arNoRegisterSourceHeader.md',
                    links: [],
                };
            case "AttributionReportingIssue::NoRegisterTriggerHeader" :
                return {
                    file: 'arNoRegisterTriggerHeader.md',
                    links: [],
                };
            case "AttributionReportingIssue::NoRegisterOsSourceHeader" :
                return {
                    file: 'arNoRegisterOsSourceHeader.md',
                    links: [],
                };
            case "AttributionReportingIssue::NoRegisterOsTriggerHeader" :
                return {
                    file: 'arNoRegisterOsTriggerHeader.md',
                    links: [],
                };
            case "AttributionReportingIssue::NavigationRegistrationUniqueScopeAlreadySet" :
                return {
                    file: 'arNavigationRegistrationUniqueScopeAlreadySet.md',
                    links: [],
                };
            case "AttributionReportingIssue::Unknown" :
                return null;
        }
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getKind() {
        return "PageError" ;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const { attributionReportingIssueDetails } = inspectorIssue.details;
        if (!attributionReportingIssueDetails) {
            console.warn('Attribution Reporting issue without details received.');
            return [];
        }
        return [new AttributionReportingIssue(attributionReportingIssueDetails, issuesModel)];
    }
}

/**
 * marked v13.0.1 - a markdown parser
 * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed)
 * https://github.com/markedjs/marked
 */
function _getDefaults() {
    return {
        async: false,
        breaks: false,
        extensions: null,
        gfm: true,
        hooks: null,
        pedantic: false,
        renderer: null,
        silent: false,
        tokenizer: null,
        walkTokens: null
    };
}
let _defaults = _getDefaults();
function changeDefaults(newDefaults) {
    _defaults = newDefaults;
}
const escapeTest = /[&<>"']/;
const escapeReplace = new RegExp(escapeTest.source, 'g');
const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, 'g');
const escapeReplacements = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
};
const getEscapeReplacement = (ch) => escapeReplacements[ch];
function escape$1(html, encode) {
    if (encode) {
        if (escapeTest.test(html)) {
            return html.replace(escapeReplace, getEscapeReplacement);
        }
    }
    else {
        if (escapeTestNoEncode.test(html)) {
            return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
        }
    }
    return html;
}
const unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
function unescape$1(html) {
    return html.replace(unescapeTest, (_, n) => {
        n = n.toLowerCase();
        if (n === 'colon')
            return ':';
        if (n.charAt(0) === '#') {
            return n.charAt(1) === 'x'
                ? String.fromCharCode(parseInt(n.substring(2), 16))
                : String.fromCharCode(+n.substring(1));
        }
        return '';
    });
}
const caret = /(^|[^\[])\^/g;
function edit(regex, opt) {
    let source = typeof regex === 'string' ? regex : regex.source;
    opt = opt || '';
    const obj = {
        replace: (name, val) => {
            let valSource = typeof val === 'string' ? val : val.source;
            valSource = valSource.replace(caret, '$1');
            source = source.replace(name, valSource);
            return obj;
        },
        getRegex: () => {
            return new RegExp(source, opt);
        }
    };
    return obj;
}
function cleanUrl(href) {
    try {
        href = encodeURI(href).replace(/%25/g, '%');
    }
    catch (e) {
        return null;
    }
    return href;
}
const noopTest = { exec: () => null };
function splitCells(tableRow, count) {
    const row = tableRow.replace(/\|/g, (match, offset, str) => {
        let escaped = false;
        let curr = offset;
        while (--curr >= 0 && str[curr] === '\\')
            escaped = !escaped;
        if (escaped) {
            return '|';
        }
        else {
            return ' |';
        }
    }), cells = row.split(/ \|/);
    let i = 0;
    if (!cells[0].trim()) {
        cells.shift();
    }
    if (cells.length > 0 && !cells[cells.length - 1].trim()) {
        cells.pop();
    }
    if (count) {
        if (cells.length > count) {
            cells.splice(count);
        }
        else {
            while (cells.length < count)
                cells.push('');
        }
    }
    for (; i < cells.length; i++) {
        cells[i] = cells[i].trim().replace(/\\\|/g, '|');
    }
    return cells;
}
function rtrim(str, c, invert) {
    const l = str.length;
    if (l === 0) {
        return '';
    }
    let suffLen = 0;
    while (suffLen < l) {
        const currChar = str.charAt(l - suffLen - 1);
        if (currChar === c && true) {
            suffLen++;
        }
        else {
            break;
        }
    }
    return str.slice(0, l - suffLen);
}
function findClosingBracket(str, b) {
    if (str.indexOf(b[1]) === -1) {
        return -1;
    }
    let level = 0;
    for (let i = 0; i < str.length; i++) {
        if (str[i] === '\\') {
            i++;
        }
        else if (str[i] === b[0]) {
            level++;
        }
        else if (str[i] === b[1]) {
            level--;
            if (level < 0) {
                return i;
            }
        }
    }
    return -1;
}
function outputLink(cap, link, raw, lexer) {
    const href = link.href;
    const title = link.title ? escape$1(link.title) : null;
    const text = cap[1].replace(/\\([\[\]])/g, '$1');
    if (cap[0].charAt(0) !== '!') {
        lexer.state.inLink = true;
        const token = {
            type: 'link',
            raw,
            href,
            title,
            text,
            tokens: lexer.inlineTokens(text)
        };
        lexer.state.inLink = false;
        return token;
    }
    return {
        type: 'image',
        raw,
        href,
        title,
        text: escape$1(text)
    };
}
function indentCodeCompensation(raw, text) {
    const matchIndentToCode = raw.match(/^(\s+)(?:```)/);
    if (matchIndentToCode === null) {
        return text;
    }
    const indentToCode = matchIndentToCode[1];
    return text
        .split('\n')
        .map(node => {
        const matchIndentInNode = node.match(/^\s+/);
        if (matchIndentInNode === null) {
            return node;
        }
        const [indentInNode] = matchIndentInNode;
        if (indentInNode.length >= indentToCode.length) {
            return node.slice(indentToCode.length);
        }
        return node;
    })
        .join('\n');
}
class _Tokenizer {
    options;
    rules;
    lexer;
    constructor(options) {
        this.options = options || _defaults;
    }
    space(src) {
        const cap = this.rules.block.newline.exec(src);
        if (cap && cap[0].length > 0) {
            return {
                type: 'space',
                raw: cap[0]
            };
        }
    }
    code(src) {
        const cap = this.rules.block.code.exec(src);
        if (cap) {
            const text = cap[0].replace(/^ {1,4}/gm, '');
            return {
                type: 'code',
                raw: cap[0],
                codeBlockStyle: 'indented',
                text: !this.options.pedantic
                    ? rtrim(text, '\n')
                    : text
            };
        }
    }
    fences(src) {
        const cap = this.rules.block.fences.exec(src);
        if (cap) {
            const raw = cap[0];
            const text = indentCodeCompensation(raw, cap[3] || '');
            return {
                type: 'code',
                raw,
                lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],
                text
            };
        }
    }
    heading(src) {
        const cap = this.rules.block.heading.exec(src);
        if (cap) {
            let text = cap[2].trim();
            if (/#$/.test(text)) {
                const trimmed = rtrim(text, '#');
                if (this.options.pedantic) {
                    text = trimmed.trim();
                }
                else if (!trimmed || / $/.test(trimmed)) {
                    text = trimmed.trim();
                }
            }
            return {
                type: 'heading',
                raw: cap[0],
                depth: cap[1].length,
                text,
                tokens: this.lexer.inline(text)
            };
        }
    }
    hr(src) {
        const cap = this.rules.block.hr.exec(src);
        if (cap) {
            return {
                type: 'hr',
                raw: rtrim(cap[0], '\n')
            };
        }
    }
    blockquote(src) {
        const cap = this.rules.block.blockquote.exec(src);
        if (cap) {
            let lines = rtrim(cap[0], '\n').split('\n');
            let raw = '';
            let text = '';
            const tokens = [];
            while (lines.length > 0) {
                let inBlockquote = false;
                const currentLines = [];
                let i;
                for (i = 0; i < lines.length; i++) {
                    if (/^ {0,3}>/.test(lines[i])) {
                        currentLines.push(lines[i]);
                        inBlockquote = true;
                    }
                    else if (!inBlockquote) {
                        currentLines.push(lines[i]);
                    }
                    else {
                        break;
                    }
                }
                lines = lines.slice(i);
                const currentRaw = currentLines.join('\n');
                const currentText = currentRaw
                    .replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, '\n    $1')
                    .replace(/^ {0,3}>[ \t]?/gm, '');
                raw = raw ? `${raw}\n${currentRaw}` : currentRaw;
                text = text ? `${text}\n${currentText}` : currentText;
                const top = this.lexer.state.top;
                this.lexer.state.top = true;
                this.lexer.blockTokens(currentText, tokens, true);
                this.lexer.state.top = top;
                if (lines.length === 0) {
                    break;
                }
                const lastToken = tokens[tokens.length - 1];
                if (lastToken?.type === 'code') {
                    break;
                }
                else if (lastToken?.type === 'blockquote') {
                    const oldToken = lastToken;
                    const newText = oldToken.raw + '\n' + lines.join('\n');
                    const newToken = this.blockquote(newText);
                    tokens[tokens.length - 1] = newToken;
                    raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;
                    text = text.substring(0, text.length - oldToken.text.length) + newToken.text;
                    break;
                }
                else if (lastToken?.type === 'list') {
                    const oldToken = lastToken;
                    const newText = oldToken.raw + '\n' + lines.join('\n');
                    const newToken = this.list(newText);
                    tokens[tokens.length - 1] = newToken;
                    raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;
                    text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;
                    lines = newText.substring(tokens[tokens.length - 1].raw.length).split('\n');
                    continue;
                }
            }
            return {
                type: 'blockquote',
                raw,
                tokens,
                text
            };
        }
    }
    list(src) {
        let cap = this.rules.block.list.exec(src);
        if (cap) {
            let bull = cap[1].trim();
            const isordered = bull.length > 1;
            const list = {
                type: 'list',
                raw: '',
                ordered: isordered,
                start: isordered ? +bull.slice(0, -1) : '',
                loose: false,
                items: []
            };
            bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
            if (this.options.pedantic) {
                bull = isordered ? bull : '[*+-]';
            }
            const itemRegex = new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`);
            let raw = '';
            let itemContents = '';
            let endsWithBlankLine = false;
            while (src) {
                let endEarly = false;
                if (!(cap = itemRegex.exec(src))) {
                    break;
                }
                if (this.rules.block.hr.test(src)) {
                    break;
                }
                raw = cap[0];
                src = src.substring(raw.length);
                let line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t) => ' '.repeat(3 * t.length));
                let nextLine = src.split('\n', 1)[0];
                let indent = 0;
                if (this.options.pedantic) {
                    indent = 2;
                    itemContents = line.trimStart();
                }
                else {
                    indent = cap[2].search(/[^ ]/);
                    indent = indent > 4 ? 1 : indent;
                    itemContents = line.slice(indent);
                    indent += cap[1].length;
                }
                let blankLine = false;
                if (!line && /^ *$/.test(nextLine)) {
                    raw += nextLine + '\n';
                    src = src.substring(nextLine.length + 1);
                    endEarly = true;
                }
                if (!endEarly) {
                    const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`);
                    const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
                    const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
                    const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
                    while (src) {
                        const rawLine = src.split('\n', 1)[0];
                        nextLine = rawLine;
                        if (this.options.pedantic) {
                            nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, '  ');
                        }
                        if (fencesBeginRegex.test(nextLine)) {
                            break;
                        }
                        if (headingBeginRegex.test(nextLine)) {
                            break;
                        }
                        if (nextBulletRegex.test(nextLine)) {
                            break;
                        }
                        if (hrRegex.test(src)) {
                            break;
                        }
                        if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) {
                            itemContents += '\n' + nextLine.slice(indent);
                        }
                        else {
                            if (blankLine) {
                                break;
                            }
                            if (line.search(/[^ ]/) >= 4) {
                                break;
                            }
                            if (fencesBeginRegex.test(line)) {
                                break;
                            }
                            if (headingBeginRegex.test(line)) {
                                break;
                            }
                            if (hrRegex.test(line)) {
                                break;
                            }
                            itemContents += '\n' + nextLine;
                        }
                        if (!blankLine && !nextLine.trim()) {
                            blankLine = true;
                        }
                        raw += rawLine + '\n';
                        src = src.substring(rawLine.length + 1);
                        line = nextLine.slice(indent);
                    }
                }
                if (!list.loose) {
                    if (endsWithBlankLine) {
                        list.loose = true;
                    }
                    else if (/\n *\n *$/.test(raw)) {
                        endsWithBlankLine = true;
                    }
                }
                let istask = null;
                let ischecked;
                if (this.options.gfm) {
                    istask = /^\[[ xX]\] /.exec(itemContents);
                    if (istask) {
                        ischecked = istask[0] !== '[ ] ';
                        itemContents = itemContents.replace(/^\[[ xX]\] +/, '');
                    }
                }
                list.items.push({
                    type: 'list_item',
                    raw,
                    task: !!istask,
                    checked: ischecked,
                    loose: false,
                    text: itemContents,
                    tokens: []
                });
                list.raw += raw;
            }
            list.items[list.items.length - 1].raw = raw.trimEnd();
            (list.items[list.items.length - 1]).text = itemContents.trimEnd();
            list.raw = list.raw.trimEnd();
            for (let i = 0; i < list.items.length; i++) {
                this.lexer.state.top = false;
                list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);
                if (!list.loose) {
                    const spacers = list.items[i].tokens.filter(t => t.type === 'space');
                    const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => /\n.*\n/.test(t.raw));
                    list.loose = hasMultipleLineBreaks;
                }
            }
            if (list.loose) {
                for (let i = 0; i < list.items.length; i++) {
                    list.items[i].loose = true;
                }
            }
            return list;
        }
    }
    html(src) {
        const cap = this.rules.block.html.exec(src);
        if (cap) {
            const token = {
                type: 'html',
                block: true,
                raw: cap[0],
                pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',
                text: cap[0]
            };
            return token;
        }
    }
    def(src) {
        const cap = this.rules.block.def.exec(src);
        if (cap) {
            const tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
            const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';
            const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];
            return {
                type: 'def',
                tag,
                raw: cap[0],
                href,
                title
            };
        }
    }
    table(src) {
        const cap = this.rules.block.table.exec(src);
        if (!cap) {
            return;
        }
        if (!/[:|]/.test(cap[2])) {
            return;
        }
        const headers = splitCells(cap[1]);
        const aligns = cap[2].replace(/^\||\| *$/g, '').split('|');
        const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : [];
        const item = {
            type: 'table',
            raw: cap[0],
            header: [],
            align: [],
            rows: []
        };
        if (headers.length !== aligns.length) {
            return;
        }
        for (const align of aligns) {
            if (/^ *-+: *$/.test(align)) {
                item.align.push('right');
            }
            else if (/^ *:-+: *$/.test(align)) {
                item.align.push('center');
            }
            else if (/^ *:-+ *$/.test(align)) {
                item.align.push('left');
            }
            else {
                item.align.push(null);
            }
        }
        for (let i = 0; i < headers.length; i++) {
            item.header.push({
                text: headers[i],
                tokens: this.lexer.inline(headers[i]),
                header: true,
                align: item.align[i]
            });
        }
        for (const row of rows) {
            item.rows.push(splitCells(row, item.header.length).map((cell, i) => {
                return {
                    text: cell,
                    tokens: this.lexer.inline(cell),
                    header: false,
                    align: item.align[i]
                };
            }));
        }
        return item;
    }
    lheading(src) {
        const cap = this.rules.block.lheading.exec(src);
        if (cap) {
            return {
                type: 'heading',
                raw: cap[0],
                depth: cap[2].charAt(0) === '=' ? 1 : 2,
                text: cap[1],
                tokens: this.lexer.inline(cap[1])
            };
        }
    }
    paragraph(src) {
        const cap = this.rules.block.paragraph.exec(src);
        if (cap) {
            const text = cap[1].charAt(cap[1].length - 1) === '\n'
                ? cap[1].slice(0, -1)
                : cap[1];
            return {
                type: 'paragraph',
                raw: cap[0],
                text,
                tokens: this.lexer.inline(text)
            };
        }
    }
    text(src) {
        const cap = this.rules.block.text.exec(src);
        if (cap) {
            return {
                type: 'text',
                raw: cap[0],
                text: cap[0],
                tokens: this.lexer.inline(cap[0])
            };
        }
    }
    escape(src) {
        const cap = this.rules.inline.escape.exec(src);
        if (cap) {
            return {
                type: 'escape',
                raw: cap[0],
                text: escape$1(cap[1])
            };
        }
    }
    tag(src) {
        const cap = this.rules.inline.tag.exec(src);
        if (cap) {
            if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
                this.lexer.state.inLink = true;
            }
            else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
                this.lexer.state.inLink = false;
            }
            if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
                this.lexer.state.inRawBlock = true;
            }
            else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
                this.lexer.state.inRawBlock = false;
            }
            return {
                type: 'html',
                raw: cap[0],
                inLink: this.lexer.state.inLink,
                inRawBlock: this.lexer.state.inRawBlock,
                block: false,
                text: cap[0]
            };
        }
    }
    link(src) {
        const cap = this.rules.inline.link.exec(src);
        if (cap) {
            const trimmedUrl = cap[2].trim();
            if (!this.options.pedantic && /^</.test(trimmedUrl)) {
                if (!(/>$/.test(trimmedUrl))) {
                    return;
                }
                const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\');
                if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
                    return;
                }
            }
            else {
                const lastParenIndex = findClosingBracket(cap[2], '()');
                if (lastParenIndex > -1) {
                    const start = cap[0].indexOf('!') === 0 ? 5 : 4;
                    const linkLen = start + cap[1].length + lastParenIndex;
                    cap[2] = cap[2].substring(0, lastParenIndex);
                    cap[0] = cap[0].substring(0, linkLen).trim();
                    cap[3] = '';
                }
            }
            let href = cap[2];
            let title = '';
            if (this.options.pedantic) {
                const link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
                if (link) {
                    href = link[1];
                    title = link[3];
                }
            }
            else {
                title = cap[3] ? cap[3].slice(1, -1) : '';
            }
            href = href.trim();
            if (/^</.test(href)) {
                if (this.options.pedantic && !(/>$/.test(trimmedUrl))) {
                    href = href.slice(1);
                }
                else {
                    href = href.slice(1, -1);
                }
            }
            return outputLink(cap, {
                href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,
                title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title
            }, cap[0], this.lexer);
        }
    }
    reflink(src, links) {
        let cap;
        if ((cap = this.rules.inline.reflink.exec(src))
            || (cap = this.rules.inline.nolink.exec(src))) {
            const linkString = (cap[2] || cap[1]).replace(/\s+/g, ' ');
            const link = links[linkString.toLowerCase()];
            if (!link) {
                const text = cap[0].charAt(0);
                return {
                    type: 'text',
                    raw: text,
                    text
                };
            }
            return outputLink(cap, link, cap[0], this.lexer);
        }
    }
    emStrong(src, maskedSrc, prevChar = '') {
        let match = this.rules.inline.emStrongLDelim.exec(src);
        if (!match)
            return;
        if (match[3] && prevChar.match(/[\p{L}\p{N}]/u))
            return;
        const nextChar = match[1] || match[2] || '';
        if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
            const lLength = [...match[0]].length - 1;
            let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
            const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
            endReg.lastIndex = 0;
            maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
            while ((match = endReg.exec(maskedSrc)) != null) {
                rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
                if (!rDelim)
                    continue;
                rLength = [...rDelim].length;
                if (match[3] || match[4]) {
                    delimTotal += rLength;
                    continue;
                }
                else if (match[5] || match[6]) {
                    if (lLength % 3 && !((lLength + rLength) % 3)) {
                        midDelimTotal += rLength;
                        continue;
                    }
                }
                delimTotal -= rLength;
                if (delimTotal > 0)
                    continue;
                rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
                const lastCharLength = [...match[0]][0].length;
                const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);
                if (Math.min(lLength, rLength) % 2) {
                    const text = raw.slice(1, -1);
                    return {
                        type: 'em',
                        raw,
                        text,
                        tokens: this.lexer.inlineTokens(text)
                    };
                }
                const text = raw.slice(2, -2);
                return {
                    type: 'strong',
                    raw,
                    text,
                    tokens: this.lexer.inlineTokens(text)
                };
            }
        }
    }
    codespan(src) {
        const cap = this.rules.inline.code.exec(src);
        if (cap) {
            let text = cap[2].replace(/\n/g, ' ');
            const hasNonSpaceChars = /[^ ]/.test(text);
            const hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);
            if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
                text = text.substring(1, text.length - 1);
            }
            text = escape$1(text, true);
            return {
                type: 'codespan',
                raw: cap[0],
                text
            };
        }
    }
    br(src) {
        const cap = this.rules.inline.br.exec(src);
        if (cap) {
            return {
                type: 'br',
                raw: cap[0]
            };
        }
    }
    del(src) {
        const cap = this.rules.inline.del.exec(src);
        if (cap) {
            return {
                type: 'del',
                raw: cap[0],
                text: cap[2],
                tokens: this.lexer.inlineTokens(cap[2])
            };
        }
    }
    autolink(src) {
        const cap = this.rules.inline.autolink.exec(src);
        if (cap) {
            let text, href;
            if (cap[2] === '@') {
                text = escape$1(cap[1]);
                href = 'mailto:' + text;
            }
            else {
                text = escape$1(cap[1]);
                href = text;
            }
            return {
                type: 'link',
                raw: cap[0],
                text,
                href,
                tokens: [
                    {
                        type: 'text',
                        raw: text,
                        text
                    }
                ]
            };
        }
    }
    url(src) {
        let cap;
        if (cap = this.rules.inline.url.exec(src)) {
            let text, href;
            if (cap[2] === '@') {
                text = escape$1(cap[0]);
                href = 'mailto:' + text;
            }
            else {
                let prevCapZero;
                do {
                    prevCapZero = cap[0];
                    cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';
                } while (prevCapZero !== cap[0]);
                text = escape$1(cap[0]);
                if (cap[1] === 'www.') {
                    href = 'http://' + cap[0];
                }
                else {
                    href = cap[0];
                }
            }
            return {
                type: 'link',
                raw: cap[0],
                text,
                href,
                tokens: [
                    {
                        type: 'text',
                        raw: text,
                        text
                    }
                ]
            };
        }
    }
    inlineText(src) {
        const cap = this.rules.inline.text.exec(src);
        if (cap) {
            let text;
            if (this.lexer.state.inRawBlock) {
                text = cap[0];
            }
            else {
                text = escape$1(cap[0]);
            }
            return {
                type: 'text',
                raw: cap[0],
                text
            };
        }
    }
}
const newline = /^(?: *(?:\n|$))+/;
const blockCode = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/;
const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
const bullet = /(?:[*+-]|\d{1,9}[.)])/;
const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/)
    .replace(/bull/g, bullet)
    .replace(/blockCode/g, / {4}/)
    .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/)
    .replace(/blockquote/g, / {0,3}>/)
    .replace(/heading/g, / {0,3}#{1,6}/)
    .replace(/html/g, / {0,3}<[^\n>]+>\n/)
    .getRegex();
const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
const blockText = /^[^\n]+/;
const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
const def = edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/)
    .replace('label', _blockLabel)
    .replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/)
    .getRegex();
const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/)
    .replace(/bull/g, bullet)
    .getRegex();
const _tag = 'address|article|aside|base|basefont|blockquote|body|caption'
    + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'
    + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'
    + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'
    + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'
    + '|tr|track|ul';
const _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
const html = edit('^ {0,3}(?:'
    + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)'
    + '|comment[^\\n]*(\\n+|$)'
    + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)'
    + '|<![A-Z][\\s\\S]*?(?:>\\n*|$)'
    + '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)'
    + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)'
    + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)'
    + '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)'
    + ')', 'i')
    .replace('comment', _comment)
    .replace('tag', _tag)
    .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/)
    .getRegex();
const paragraph = edit(_paragraph)
    .replace('hr', hr)
    .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
    .replace('|lheading', '')
    .replace('|table', '')
    .replace('blockquote', ' {0,3}>')
    .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
    .replace('list', ' {0,3}(?:[*+-]|1[.)]) ')
    .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
    .replace('tag', _tag)
    .getRegex();
const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/)
    .replace('paragraph', paragraph)
    .getRegex();
const blockNormal = {
    blockquote,
    code: blockCode,
    def,
    fences,
    heading,
    hr,
    html,
    lheading,
    list,
    newline,
    paragraph,
    table: noopTest,
    text: blockText
};
const gfmTable = edit('^ *([^\\n ].*)\\n'
    + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)'
    + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)')
    .replace('hr', hr)
    .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
    .replace('blockquote', ' {0,3}>')
    .replace('code', ' {4}[^\\n]')
    .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
    .replace('list', ' {0,3}(?:[*+-]|1[.)]) ')
    .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
    .replace('tag', _tag)
    .getRegex();
const blockGfm = {
    ...blockNormal,
    table: gfmTable,
    paragraph: edit(_paragraph)
        .replace('hr', hr)
        .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
        .replace('|lheading', '')
        .replace('table', gfmTable)
        .replace('blockquote', ' {0,3}>')
        .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
        .replace('list', ' {0,3}(?:[*+-]|1[.)]) ')
        .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
        .replace('tag', _tag)
        .getRegex()
};
const blockPedantic = {
    ...blockNormal,
    html: edit('^ *(?:comment *(?:\\n|\\s*$)'
        + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)'
        + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))')
        .replace('comment', _comment)
        .replace(/tag/g, '(?!(?:'
        + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'
        + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'
        + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b')
        .getRegex(),
    def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
    heading: /^(#{1,6})(.*)(?:\n+|$)/,
    fences: noopTest,
    lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
    paragraph: edit(_paragraph)
        .replace('hr', hr)
        .replace('heading', ' *#{1,6} *[^\n]')
        .replace('lheading', lheading)
        .replace('|table', '')
        .replace('blockquote', ' {0,3}>')
        .replace('|fences', '')
        .replace('|list', '')
        .replace('|html', '')
        .replace('|tag', '')
        .getRegex()
};
const escape$2 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
const br = /^( {2,}|\\)\n(?!\s*$)/;
const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
const _punctuation = '\\p{P}\\p{S}';
const punctuation = edit(/^((?![*_])[\spunctuation])/, 'u')
    .replace(/punctuation/g, _punctuation).getRegex();
const blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g;
const emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, 'u')
    .replace(/punct/g, _punctuation)
    .getRegex();
const emStrongRDelimAst = edit('^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)'
    + '|[^*]+(?=[^*])'
    + '|(?!\\*)[punct](\\*+)(?=[\\s]|$)'
    + '|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)'
    + '|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])'
    + '|[\\s](\\*+)(?!\\*)(?=[punct])'
    + '|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])'
    + '|[^punct\\s](\\*+)(?=[^punct\\s])', 'gu')
    .replace(/punct/g, _punctuation)
    .getRegex();
const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)'
    + '|[^_]+(?=[^_])'
    + '|(?!_)[punct](_+)(?=[\\s]|$)'
    + '|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)'
    + '|(?!_)[punct\\s](_+)(?=[^punct\\s])'
    + '|[\\s](_+)(?!_)(?=[punct])'
    + '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu')
    .replace(/punct/g, _punctuation)
    .getRegex();
const anyPunctuation = edit(/\\([punct])/, 'gu')
    .replace(/punct/g, _punctuation)
    .getRegex();
const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/)
    .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)
    .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)
    .getRegex();
const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();
const tag = edit('^comment'
    + '|^</[a-zA-Z][\\w:-]*\\s*>'
    + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>'
    + '|^<\\?[\\s\\S]*?\\?>'
    + '|^<![a-zA-Z]+\\s[\\s\\S]*?>'
    + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>')
    .replace('comment', _inlineComment)
    .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/)
    .getRegex();
const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/)
    .replace('label', _inlineLabel)
    .replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/)
    .replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/)
    .getRegex();
const reflink = edit(/^!?\[(label)\]\[(ref)\]/)
    .replace('label', _inlineLabel)
    .replace('ref', _blockLabel)
    .getRegex();
const nolink = edit(/^!?\[(ref)\](?:\[\])?/)
    .replace('ref', _blockLabel)
    .getRegex();
const reflinkSearch = edit('reflink|nolink(?!\\()', 'g')
    .replace('reflink', reflink)
    .replace('nolink', nolink)
    .getRegex();
const inlineNormal = {
    _backpedal: noopTest,
    anyPunctuation,
    autolink,
    blockSkip,
    br,
    code: inlineCode,
    del: noopTest,
    emStrongLDelim,
    emStrongRDelimAst,
    emStrongRDelimUnd,
    escape: escape$2,
    link,
    nolink,
    punctuation,
    reflink,
    reflinkSearch,
    tag,
    text: inlineText,
    url: noopTest
};
const inlinePedantic = {
    ...inlineNormal,
    link: edit(/^!?\[(label)\]\((.*?)\)/)
        .replace('label', _inlineLabel)
        .getRegex(),
    reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/)
        .replace('label', _inlineLabel)
        .getRegex()
};
const inlineGfm = {
    ...inlineNormal,
    escape: edit(escape$2).replace('])', '~|])').getRegex(),
    url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i')
        .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)
        .getRegex(),
    _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
    del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
    text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
};
const inlineBreaks = {
    ...inlineGfm,
    br: edit(br).replace('{2,}', '*').getRegex(),
    text: edit(inlineGfm.text)
        .replace('\\b_', '\\b_| {2,}\\n')
        .replace(/\{2,\}/g, '*')
        .getRegex()
};
const block = {
    normal: blockNormal,
    gfm: blockGfm,
    pedantic: blockPedantic
};
const inline = {
    normal: inlineNormal,
    gfm: inlineGfm,
    breaks: inlineBreaks,
    pedantic: inlinePedantic
};
class _Lexer {
    tokens;
    options;
    state;
    tokenizer;
    inlineQueue;
    constructor(options) {
        this.tokens = [];
        this.tokens.links = Object.create(null);
        this.options = options || _defaults;
        this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
        this.tokenizer = this.options.tokenizer;
        this.tokenizer.options = this.options;
        this.tokenizer.lexer = this;
        this.inlineQueue = [];
        this.state = {
            inLink: false,
            inRawBlock: false,
            top: true
        };
        const rules = {
            block: block.normal,
            inline: inline.normal
        };
        if (this.options.pedantic) {
            rules.block = block.pedantic;
            rules.inline = inline.pedantic;
        }
        else if (this.options.gfm) {
            rules.block = block.gfm;
            if (this.options.breaks) {
                rules.inline = inline.breaks;
            }
            else {
                rules.inline = inline.gfm;
            }
        }
        this.tokenizer.rules = rules;
    }
    static get rules() {
        return {
            block,
            inline
        };
    }
    static lex(src, options) {
        const lexer = new _Lexer(options);
        return lexer.lex(src);
    }
    static lexInline(src, options) {
        const lexer = new _Lexer(options);
        return lexer.inlineTokens(src);
    }
    lex(src) {
        src = src
            .replace(/\r\n|\r/g, '\n');
        this.blockTokens(src, this.tokens);
        for (let i = 0; i < this.inlineQueue.length; i++) {
            const next = this.inlineQueue[i];
            this.inlineTokens(next.src, next.tokens);
        }
        this.inlineQueue = [];
        return this.tokens;
    }
    blockTokens(src, tokens = [], lastParagraphClipped = false) {
        if (this.options.pedantic) {
            src = src.replace(/\t/g, '    ').replace(/^ +$/gm, '');
        }
        else {
            src = src.replace(/^( *)(\t+)/gm, (_, leading, tabs) => {
                return leading + '    '.repeat(tabs.length);
            });
        }
        let token;
        let lastToken;
        let cutSrc;
        while (src) {
            if (this.options.extensions
                && this.options.extensions.block
                && this.options.extensions.block.some((extTokenizer) => {
                    if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
                        src = src.substring(token.raw.length);
                        tokens.push(token);
                        return true;
                    }
                    return false;
                })) {
                continue;
            }
            if (token = this.tokenizer.space(src)) {
                src = src.substring(token.raw.length);
                if (token.raw.length === 1 && tokens.length > 0) {
                    tokens[tokens.length - 1].raw += '\n';
                }
                else {
                    tokens.push(token);
                }
                continue;
            }
            if (token = this.tokenizer.code(src)) {
                src = src.substring(token.raw.length);
                lastToken = tokens[tokens.length - 1];
                if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
                    lastToken.raw += '\n' + token.raw;
                    lastToken.text += '\n' + token.text;
                    this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
                }
                else {
                    tokens.push(token);
                }
                continue;
            }
            if (token = this.tokenizer.fences(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.heading(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.hr(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.blockquote(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.list(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.html(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.def(src)) {
                src = src.substring(token.raw.length);
                lastToken = tokens[tokens.length - 1];
                if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
                    lastToken.raw += '\n' + token.raw;
                    lastToken.text += '\n' + token.raw;
                    this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
                }
                else if (!this.tokens.links[token.tag]) {
                    this.tokens.links[token.tag] = {
                        href: token.href,
                        title: token.title
                    };
                }
                continue;
            }
            if (token = this.tokenizer.table(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.lheading(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            cutSrc = src;
            if (this.options.extensions && this.options.extensions.startBlock) {
                let startIndex = Infinity;
                const tempSrc = src.slice(1);
                let tempStart;
                this.options.extensions.startBlock.forEach((getStartIndex) => {
                    tempStart = getStartIndex.call({ lexer: this }, tempSrc);
                    if (typeof tempStart === 'number' && tempStart >= 0) {
                        startIndex = Math.min(startIndex, tempStart);
                    }
                });
                if (startIndex < Infinity && startIndex >= 0) {
                    cutSrc = src.substring(0, startIndex + 1);
                }
            }
            if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
                lastToken = tokens[tokens.length - 1];
                if (lastParagraphClipped && lastToken?.type === 'paragraph') {
                    lastToken.raw += '\n' + token.raw;
                    lastToken.text += '\n' + token.text;
                    this.inlineQueue.pop();
                    this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
                }
                else {
                    tokens.push(token);
                }
                lastParagraphClipped = (cutSrc.length !== src.length);
                src = src.substring(token.raw.length);
                continue;
            }
            if (token = this.tokenizer.text(src)) {
                src = src.substring(token.raw.length);
                lastToken = tokens[tokens.length - 1];
                if (lastToken && lastToken.type === 'text') {
                    lastToken.raw += '\n' + token.raw;
                    lastToken.text += '\n' + token.text;
                    this.inlineQueue.pop();
                    this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
                }
                else {
                    tokens.push(token);
                }
                continue;
            }
            if (src) {
                const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
                if (this.options.silent) {
                    console.error(errMsg);
                    break;
                }
                else {
                    throw new Error(errMsg);
                }
            }
        }
        this.state.top = true;
        return tokens;
    }
    inline(src, tokens = []) {
        this.inlineQueue.push({ src, tokens });
        return tokens;
    }
    inlineTokens(src, tokens = []) {
        let token, lastToken, cutSrc;
        let maskedSrc = src;
        let match;
        let keepPrevChar, prevChar;
        if (this.tokens.links) {
            const links = Object.keys(this.tokens.links);
            if (links.length > 0) {
                while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
                    if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
                        maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
                    }
                }
            }
        }
        while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
            maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
        }
        while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
            maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
        }
        while (src) {
            if (!keepPrevChar) {
                prevChar = '';
            }
            keepPrevChar = false;
            if (this.options.extensions
                && this.options.extensions.inline
                && this.options.extensions.inline.some((extTokenizer) => {
                    if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
                        src = src.substring(token.raw.length);
                        tokens.push(token);
                        return true;
                    }
                    return false;
                })) {
                continue;
            }
            if (token = this.tokenizer.escape(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.tag(src)) {
                src = src.substring(token.raw.length);
                lastToken = tokens[tokens.length - 1];
                if (lastToken && token.type === 'text' && lastToken.type === 'text') {
                    lastToken.raw += token.raw;
                    lastToken.text += token.text;
                }
                else {
                    tokens.push(token);
                }
                continue;
            }
            if (token = this.tokenizer.link(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.reflink(src, this.tokens.links)) {
                src = src.substring(token.raw.length);
                lastToken = tokens[tokens.length - 1];
                if (lastToken && token.type === 'text' && lastToken.type === 'text') {
                    lastToken.raw += token.raw;
                    lastToken.text += token.text;
                }
                else {
                    tokens.push(token);
                }
                continue;
            }
            if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.codespan(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.br(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.del(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (token = this.tokenizer.autolink(src)) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            if (!this.state.inLink && (token = this.tokenizer.url(src))) {
                src = src.substring(token.raw.length);
                tokens.push(token);
                continue;
            }
            cutSrc = src;
            if (this.options.extensions && this.options.extensions.startInline) {
                let startIndex = Infinity;
                const tempSrc = src.slice(1);
                let tempStart;
                this.options.extensions.startInline.forEach((getStartIndex) => {
                    tempStart = getStartIndex.call({ lexer: this }, tempSrc);
                    if (typeof tempStart === 'number' && tempStart >= 0) {
                        startIndex = Math.min(startIndex, tempStart);
                    }
                });
                if (startIndex < Infinity && startIndex >= 0) {
                    cutSrc = src.substring(0, startIndex + 1);
                }
            }
            if (token = this.tokenizer.inlineText(cutSrc)) {
                src = src.substring(token.raw.length);
                if (token.raw.slice(-1) !== '_') {
                    prevChar = token.raw.slice(-1);
                }
                keepPrevChar = true;
                lastToken = tokens[tokens.length - 1];
                if (lastToken && lastToken.type === 'text') {
                    lastToken.raw += token.raw;
                    lastToken.text += token.text;
                }
                else {
                    tokens.push(token);
                }
                continue;
            }
            if (src) {
                const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
                if (this.options.silent) {
                    console.error(errMsg);
                    break;
                }
                else {
                    throw new Error(errMsg);
                }
            }
        }
        return tokens;
    }
}
class _Renderer {
    options;
    parser;
    constructor(options) {
        this.options = options || _defaults;
    }
    space(token) {
        return '';
    }
    code({ text, lang, escaped }) {
        const langString = (lang || '').match(/^\S*/)?.[0];
        const code = text.replace(/\n$/, '') + '\n';
        if (!langString) {
            return '<pre><code>'
                + (escaped ? code : escape$1(code, true))
                + '</code></pre>\n';
        }
        return '<pre><code class="language-'
            + escape$1(langString)
            + '">'
            + (escaped ? code : escape$1(code, true))
            + '</code></pre>\n';
    }
    blockquote({ tokens }) {
        const body = this.parser.parse(tokens);
        return `<blockquote>\n${body}</blockquote>\n`;
    }
    html({ text }) {
        return text;
    }
    heading({ tokens, depth }) {
        return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\n`;
    }
    hr(token) {
        return '<hr>\n';
    }
    list(token) {
        const ordered = token.ordered;
        const start = token.start;
        let body = '';
        for (let j = 0; j < token.items.length; j++) {
            const item = token.items[j];
            body += this.listitem(item);
        }
        const type = ordered ? 'ol' : 'ul';
        const startAttr = (ordered && start !== 1) ? (' start="' + start + '"') : '';
        return '<' + type + startAttr + '>\n' + body + '</' + type + '>\n';
    }
    listitem(item) {
        let itemBody = '';
        if (item.task) {
            const checkbox = this.checkbox({ checked: !!item.checked });
            if (item.loose) {
                if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
                    item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
                    if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
                        item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
                    }
                }
                else {
                    item.tokens.unshift({
                        type: 'text',
                        raw: checkbox + ' ',
                        text: checkbox + ' '
                    });
                }
            }
            else {
                itemBody += checkbox + ' ';
            }
        }
        itemBody += this.parser.parse(item.tokens, !!item.loose);
        return `<li>${itemBody}</li>\n`;
    }
    checkbox({ checked }) {
        return '<input '
            + (checked ? 'checked="" ' : '')
            + 'disabled="" type="checkbox">';
    }
    paragraph({ tokens }) {
        return `<p>${this.parser.parseInline(tokens)}</p>\n`;
    }
    table(token) {
        let header = '';
        let cell = '';
        for (let j = 0; j < token.header.length; j++) {
            cell += this.tablecell(token.header[j]);
        }
        header += this.tablerow({ text: cell });
        let body = '';
        for (let j = 0; j < token.rows.length; j++) {
            const row = token.rows[j];
            cell = '';
            for (let k = 0; k < row.length; k++) {
                cell += this.tablecell(row[k]);
            }
            body += this.tablerow({ text: cell });
        }
        if (body)
            body = `<tbody>${body}</tbody>`;
        return '<table>\n'
            + '<thead>\n'
            + header
            + '</thead>\n'
            + body
            + '</table>\n';
    }
    tablerow({ text }) {
        return `<tr>\n${text}</tr>\n`;
    }
    tablecell(token) {
        const content = this.parser.parseInline(token.tokens);
        const type = token.header ? 'th' : 'td';
        const tag = token.align
            ? `<${type} align="${token.align}">`
            : `<${type}>`;
        return tag + content + `</${type}>\n`;
    }
    strong({ tokens }) {
        return `<strong>${this.parser.parseInline(tokens)}</strong>`;
    }
    em({ tokens }) {
        return `<em>${this.parser.parseInline(tokens)}</em>`;
    }
    codespan({ text }) {
        return `<code>${text}</code>`;
    }
    br(token) {
        return '<br>';
    }
    del({ tokens }) {
        return `<del>${this.parser.parseInline(tokens)}</del>`;
    }
    link({ href, title, tokens }) {
        const text = this.parser.parseInline(tokens);
        const cleanHref = cleanUrl(href);
        if (cleanHref === null) {
            return text;
        }
        href = cleanHref;
        let out = '<a href="' + href + '"';
        if (title) {
            out += ' title="' + title + '"';
        }
        out += '>' + text + '</a>';
        return out;
    }
    image({ href, title, text }) {
        const cleanHref = cleanUrl(href);
        if (cleanHref === null) {
            return text;
        }
        href = cleanHref;
        let out = `<img src="${href}" alt="${text}"`;
        if (title) {
            out += ` title="${title}"`;
        }
        out += '>';
        return out;
    }
    text(token) {
        return 'tokens' in token && token.tokens ? this.parser.parseInline(token.tokens) : token.text;
    }
}
class _TextRenderer {
    strong({ text }) {
        return text;
    }
    em({ text }) {
        return text;
    }
    codespan({ text }) {
        return text;
    }
    del({ text }) {
        return text;
    }
    html({ text }) {
        return text;
    }
    text({ text }) {
        return text;
    }
    link({ text }) {
        return '' + text;
    }
    image({ text }) {
        return '' + text;
    }
    br() {
        return '';
    }
}
class _Parser {
    options;
    renderer;
    textRenderer;
    constructor(options) {
        this.options = options || _defaults;
        this.options.renderer = this.options.renderer || new _Renderer();
        this.renderer = this.options.renderer;
        this.renderer.options = this.options;
        this.renderer.parser = this;
        this.textRenderer = new _TextRenderer();
    }
    static parse(tokens, options) {
        const parser = new _Parser(options);
        return parser.parse(tokens);
    }
    static parseInline(tokens, options) {
        const parser = new _Parser(options);
        return parser.parseInline(tokens);
    }
    parse(tokens, top = true) {
        let out = '';
        for (let i = 0; i < tokens.length; i++) {
            const anyToken = tokens[i];
            if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
                const genericToken = anyToken;
                const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
                if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(genericToken.type)) {
                    out += ret || '';
                    continue;
                }
            }
            const token = anyToken;
            switch (token.type) {
                case 'space': {
                    out += this.renderer.space(token);
                    continue;
                }
                case 'hr': {
                    out += this.renderer.hr(token);
                    continue;
                }
                case 'heading': {
                    out += this.renderer.heading(token);
                    continue;
                }
                case 'code': {
                    out += this.renderer.code(token);
                    continue;
                }
                case 'table': {
                    out += this.renderer.table(token);
                    continue;
                }
                case 'blockquote': {
                    out += this.renderer.blockquote(token);
                    continue;
                }
                case 'list': {
                    out += this.renderer.list(token);
                    continue;
                }
                case 'html': {
                    out += this.renderer.html(token);
                    continue;
                }
                case 'paragraph': {
                    out += this.renderer.paragraph(token);
                    continue;
                }
                case 'text': {
                    let textToken = token;
                    let body = this.renderer.text(textToken);
                    while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {
                        textToken = tokens[++i];
                        body += '\n' + this.renderer.text(textToken);
                    }
                    if (top) {
                        out += this.renderer.paragraph({
                            type: 'paragraph',
                            raw: body,
                            text: body,
                            tokens: [{ type: 'text', raw: body, text: body }]
                        });
                    }
                    else {
                        out += body;
                    }
                    continue;
                }
                default: {
                    const errMsg = 'Token with "' + token.type + '" type was not found.';
                    if (this.options.silent) {
                        console.error(errMsg);
                        return '';
                    }
                    else {
                        throw new Error(errMsg);
                    }
                }
            }
        }
        return out;
    }
    parseInline(tokens, renderer) {
        renderer = renderer || this.renderer;
        let out = '';
        for (let i = 0; i < tokens.length; i++) {
            const anyToken = tokens[i];
            if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
                const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
                if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {
                    out += ret || '';
                    continue;
                }
            }
            const token = anyToken;
            switch (token.type) {
                case 'escape': {
                    out += renderer.text(token);
                    break;
                }
                case 'html': {
                    out += renderer.html(token);
                    break;
                }
                case 'link': {
                    out += renderer.link(token);
                    break;
                }
                case 'image': {
                    out += renderer.image(token);
                    break;
                }
                case 'strong': {
                    out += renderer.strong(token);
                    break;
                }
                case 'em': {
                    out += renderer.em(token);
                    break;
                }
                case 'codespan': {
                    out += renderer.codespan(token);
                    break;
                }
                case 'br': {
                    out += renderer.br(token);
                    break;
                }
                case 'del': {
                    out += renderer.del(token);
                    break;
                }
                case 'text': {
                    out += renderer.text(token);
                    break;
                }
                default: {
                    const errMsg = 'Token with "' + token.type + '" type was not found.';
                    if (this.options.silent) {
                        console.error(errMsg);
                        return '';
                    }
                    else {
                        throw new Error(errMsg);
                    }
                }
            }
        }
        return out;
    }
}
class _Hooks {
    options;
    constructor(options) {
        this.options = options || _defaults;
    }
    static passThroughHooks = new Set([
        'preprocess',
        'postprocess',
        'processAllTokens'
    ]);
    preprocess(markdown) {
        return markdown;
    }
    postprocess(html) {
        return html;
    }
    processAllTokens(tokens) {
        return tokens;
    }
}
class Marked {
    defaults = _getDefaults();
    options = this.setOptions;
    parse = this.#parseMarkdown(_Lexer.lex, _Parser.parse);
    parseInline = this.#parseMarkdown(_Lexer.lexInline, _Parser.parseInline);
    Parser = _Parser;
    Renderer = _Renderer;
    TextRenderer = _TextRenderer;
    Lexer = _Lexer;
    Tokenizer = _Tokenizer;
    Hooks = _Hooks;
    constructor(...args) {
        this.use(...args);
    }
    walkTokens(tokens, callback) {
        let values = [];
        for (const token of tokens) {
            values = values.concat(callback.call(this, token));
            switch (token.type) {
                case 'table': {
                    const tableToken = token;
                    for (const cell of tableToken.header) {
                        values = values.concat(this.walkTokens(cell.tokens, callback));
                    }
                    for (const row of tableToken.rows) {
                        for (const cell of row) {
                            values = values.concat(this.walkTokens(cell.tokens, callback));
                        }
                    }
                    break;
                }
                case 'list': {
                    const listToken = token;
                    values = values.concat(this.walkTokens(listToken.items, callback));
                    break;
                }
                default: {
                    const genericToken = token;
                    if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
                        this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
                            const tokens = genericToken[childTokens].flat(Infinity);
                            values = values.concat(this.walkTokens(tokens, callback));
                        });
                    }
                    else if (genericToken.tokens) {
                        values = values.concat(this.walkTokens(genericToken.tokens, callback));
                    }
                }
            }
        }
        return values;
    }
    use(...args) {
        const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
        args.forEach((pack) => {
            const opts = { ...pack };
            opts.async = this.defaults.async || opts.async || false;
            if (pack.extensions) {
                pack.extensions.forEach((ext) => {
                    if (!ext.name) {
                        throw new Error('extension name required');
                    }
                    if ('renderer' in ext) {
                        const prevRenderer = extensions.renderers[ext.name];
                        if (prevRenderer) {
                            extensions.renderers[ext.name] = function (...args) {
                                let ret = ext.renderer.apply(this, args);
                                if (ret === false) {
                                    ret = prevRenderer.apply(this, args);
                                }
                                return ret;
                            };
                        }
                        else {
                            extensions.renderers[ext.name] = ext.renderer;
                        }
                    }
                    if ('tokenizer' in ext) {
                        if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {
                            throw new Error("extension level must be 'block' or 'inline'");
                        }
                        const extLevel = extensions[ext.level];
                        if (extLevel) {
                            extLevel.unshift(ext.tokenizer);
                        }
                        else {
                            extensions[ext.level] = [ext.tokenizer];
                        }
                        if (ext.start) {
                            if (ext.level === 'block') {
                                if (extensions.startBlock) {
                                    extensions.startBlock.push(ext.start);
                                }
                                else {
                                    extensions.startBlock = [ext.start];
                                }
                            }
                            else if (ext.level === 'inline') {
                                if (extensions.startInline) {
                                    extensions.startInline.push(ext.start);
                                }
                                else {
                                    extensions.startInline = [ext.start];
                                }
                            }
                        }
                    }
                    if ('childTokens' in ext && ext.childTokens) {
                        extensions.childTokens[ext.name] = ext.childTokens;
                    }
                });
                opts.extensions = extensions;
            }
            if (pack.renderer) {
                const renderer = this.defaults.renderer || new _Renderer(this.defaults);
                for (const prop in pack.renderer) {
                    if (!(prop in renderer)) {
                        throw new Error(`renderer '${prop}' does not exist`);
                    }
                    if (['options', 'parser'].includes(prop)) {
                        continue;
                    }
                    const rendererProp = prop;
                    let rendererFunc = pack.renderer[rendererProp];
                    const prevRenderer = renderer[rendererProp];
                    renderer[rendererProp] = (...args) => {
                        if (!pack.useNewRenderer) {
                            rendererFunc = this.#convertRendererFunction(rendererFunc, rendererProp, renderer);
                        }
                        let ret = rendererFunc.apply(renderer, args);
                        if (ret === false) {
                            ret = prevRenderer.apply(renderer, args);
                        }
                        return ret || '';
                    };
                }
                opts.renderer = renderer;
            }
            if (pack.tokenizer) {
                const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
                for (const prop in pack.tokenizer) {
                    if (!(prop in tokenizer)) {
                        throw new Error(`tokenizer '${prop}' does not exist`);
                    }
                    if (['options', 'rules', 'lexer'].includes(prop)) {
                        continue;
                    }
                    const tokenizerProp = prop;
                    const tokenizerFunc = pack.tokenizer[tokenizerProp];
                    const prevTokenizer = tokenizer[tokenizerProp];
                    tokenizer[tokenizerProp] = (...args) => {
                        let ret = tokenizerFunc.apply(tokenizer, args);
                        if (ret === false) {
                            ret = prevTokenizer.apply(tokenizer, args);
                        }
                        return ret;
                    };
                }
                opts.tokenizer = tokenizer;
            }
            if (pack.hooks) {
                const hooks = this.defaults.hooks || new _Hooks();
                for (const prop in pack.hooks) {
                    if (!(prop in hooks)) {
                        throw new Error(`hook '${prop}' does not exist`);
                    }
                    if (prop === 'options') {
                        continue;
                    }
                    const hooksProp = prop;
                    const hooksFunc = pack.hooks[hooksProp];
                    const prevHook = hooks[hooksProp];
                    if (_Hooks.passThroughHooks.has(prop)) {
                        hooks[hooksProp] = (arg) => {
                            if (this.defaults.async) {
                                return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {
                                    return prevHook.call(hooks, ret);
                                });
                            }
                            const ret = hooksFunc.call(hooks, arg);
                            return prevHook.call(hooks, ret);
                        };
                    }
                    else {
                        hooks[hooksProp] = (...args) => {
                            let ret = hooksFunc.apply(hooks, args);
                            if (ret === false) {
                                ret = prevHook.apply(hooks, args);
                            }
                            return ret;
                        };
                    }
                }
                opts.hooks = hooks;
            }
            if (pack.walkTokens) {
                const walkTokens = this.defaults.walkTokens;
                const packWalktokens = pack.walkTokens;
                opts.walkTokens = function (token) {
                    let values = [];
                    values.push(packWalktokens.call(this, token));
                    if (walkTokens) {
                        values = values.concat(walkTokens.call(this, token));
                    }
                    return values;
                };
            }
            this.defaults = { ...this.defaults, ...opts };
        });
        return this;
    }
    #convertRendererFunction(func, prop, renderer) {
        switch (prop) {
            case 'heading':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, renderer.parser.parseInline(token.tokens), token.depth, unescape$1(renderer.parser.parseInline(token.tokens, renderer.parser.textRenderer)));
                };
            case 'code':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, token.text, token.lang, !!token.escaped);
                };
            case 'table':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    let header = '';
                    let cell = '';
                    for (let j = 0; j < token.header.length; j++) {
                        cell += this.tablecell({
                            text: token.header[j].text,
                            tokens: token.header[j].tokens,
                            header: true,
                            align: token.align[j]
                        });
                    }
                    header += this.tablerow({ text: cell });
                    let body = '';
                    for (let j = 0; j < token.rows.length; j++) {
                        const row = token.rows[j];
                        cell = '';
                        for (let k = 0; k < row.length; k++) {
                            cell += this.tablecell({
                                text: row[k].text,
                                tokens: row[k].tokens,
                                header: false,
                                align: token.align[k]
                            });
                        }
                        body += this.tablerow({ text: cell });
                    }
                    return func.call(this, header, body);
                };
            case 'blockquote':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    const body = this.parser.parse(token.tokens);
                    return func.call(this, body);
                };
            case 'list':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    const ordered = token.ordered;
                    const start = token.start;
                    const loose = token.loose;
                    let body = '';
                    for (let j = 0; j < token.items.length; j++) {
                        const item = token.items[j];
                        const checked = item.checked;
                        const task = item.task;
                        let itemBody = '';
                        if (item.task) {
                            const checkbox = this.checkbox({ checked: !!checked });
                            if (loose) {
                                if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
                                    item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
                                    if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
                                        item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
                                    }
                                }
                                else {
                                    item.tokens.unshift({
                                        type: 'text',
                                        text: checkbox + ' '
                                    });
                                }
                            }
                            else {
                                itemBody += checkbox + ' ';
                            }
                        }
                        itemBody += this.parser.parse(item.tokens, loose);
                        body += this.listitem({
                            type: 'list_item',
                            raw: itemBody,
                            text: itemBody,
                            task,
                            checked: !!checked,
                            loose,
                            tokens: item.tokens
                        });
                    }
                    return func.call(this, body, ordered, start);
                };
            case 'html':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, token.text, token.block);
                };
            case 'paragraph':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, this.parser.parseInline(token.tokens));
                };
            case 'escape':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, token.text);
                };
            case 'link':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, token.href, token.title, this.parser.parseInline(token.tokens));
                };
            case 'image':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, token.href, token.title, token.text);
                };
            case 'strong':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, this.parser.parseInline(token.tokens));
                };
            case 'em':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, this.parser.parseInline(token.tokens));
                };
            case 'codespan':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, token.text);
                };
            case 'del':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, this.parser.parseInline(token.tokens));
                };
            case 'text':
                return function (token) {
                    if (!token.type || token.type !== prop) {
                        return func.apply(this, arguments);
                    }
                    return func.call(this, token.text);
                };
        }
        return func;
    }
    setOptions(opt) {
        this.defaults = { ...this.defaults, ...opt };
        return this;
    }
    lexer(src, options) {
        return _Lexer.lex(src, options ?? this.defaults);
    }
    parser(tokens, options) {
        return _Parser.parse(tokens, options ?? this.defaults);
    }
    #parseMarkdown(lexer, parser) {
        return (src, options) => {
            const origOpt = { ...options };
            const opt = { ...this.defaults, ...origOpt };
            if (this.defaults.async === true && origOpt.async === false) {
                if (!opt.silent) {
                    console.warn('marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored.');
                }
                opt.async = true;
            }
            const throwError = this.#onError(!!opt.silent, !!opt.async);
            if (typeof src === 'undefined' || src === null) {
                return throwError(new Error('marked(): input parameter is undefined or null'));
            }
            if (typeof src !== 'string') {
                return throwError(new Error('marked(): input parameter is of type '
                    + Object.prototype.toString.call(src) + ', string expected'));
            }
            if (opt.hooks) {
                opt.hooks.options = opt;
            }
            if (opt.async) {
                return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src)
                    .then(src => lexer(src, opt))
                    .then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens)
                    .then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens)
                    .then(tokens => parser(tokens, opt))
                    .then(html => opt.hooks ? opt.hooks.postprocess(html) : html)
                    .catch(throwError);
            }
            try {
                if (opt.hooks) {
                    src = opt.hooks.preprocess(src);
                }
                let tokens = lexer(src, opt);
                if (opt.hooks) {
                    tokens = opt.hooks.processAllTokens(tokens);
                }
                if (opt.walkTokens) {
                    this.walkTokens(tokens, opt.walkTokens);
                }
                let html = parser(tokens, opt);
                if (opt.hooks) {
                    html = opt.hooks.postprocess(html);
                }
                return html;
            }
            catch (e) {
                return throwError(e);
            }
        };
    }
    #onError(silent, async) {
        return (e) => {
            e.message += '\nPlease report this to https://github.com/markedjs/marked.';
            if (silent) {
                const msg = '<p>An error occurred:</p><pre>'
                    + escape$1(e.message + '', true)
                    + '</pre>';
                if (async) {
                    return Promise.resolve(msg);
                }
                return msg;
            }
            if (async) {
                return Promise.reject(e);
            }
            throw e;
        };
    }
}
const markedInstance = new Marked();
function marked$1(src, opt) {
    return markedInstance.parse(src, opt);
}
marked$1.options =
    marked$1.setOptions = function (options) {
        markedInstance.setOptions(options);
        marked$1.defaults = markedInstance.defaults;
        changeDefaults(marked$1.defaults);
        return marked$1;
    };
marked$1.getDefaults = _getDefaults;
marked$1.defaults = _defaults;
marked$1.use = function (...args) {
    markedInstance.use(...args);
    marked$1.defaults = markedInstance.defaults;
    changeDefaults(marked$1.defaults);
    return marked$1;
};
marked$1.walkTokens = function (tokens, callback) {
    return markedInstance.walkTokens(tokens, callback);
};
marked$1.parseInline = markedInstance.parseInline;
marked$1.Parser = _Parser;
marked$1.parser = _Parser.parse;
marked$1.Renderer = _Renderer;
marked$1.TextRenderer = _TextRenderer;
marked$1.Lexer = _Lexer;
marked$1.lexer = _Lexer.lex;
marked$1.Tokenizer = _Tokenizer;
marked$1.Hooks = _Hooks;
marked$1.parse = marked$1;
const options = marked$1.options;
const setOptions = marked$1.setOptions;
const use = marked$1.use;
const walkTokens = marked$1.walkTokens;
const parseInline = marked$1.parseInline;
const parse = marked$1;
const parser = _Parser.parse;
const lexer = _Lexer.lex;

var marked_esm = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Hooks: _Hooks,
	Lexer: _Lexer,
	Marked: Marked,
	Parser: _Parser,
	Renderer: _Renderer,
	TextRenderer: _TextRenderer,
	Tokenizer: _Tokenizer,
	get defaults () { return _defaults; },
	getDefaults: _getDefaults,
	lexer: lexer,
	marked: marked$1,
	options: options,
	parse: parse,
	parseInline: parseInline,
	parser: parser,
	setOptions: setOptions,
	use: use,
	walkTokens: walkTokens
});

var marked = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Marked: marked_esm
});

// Copyright 2020 The Chromium Authors
function resolveLazyDescription(lazyDescription) {
    function linksMap(currentLink) {
        return { link: currentLink.link, linkTitle: currentLink.linkTitle() };
    }
    const substitutionMap = new Map();
    lazyDescription.substitutions?.forEach((value, key) => {
        substitutionMap.set(key, value());
    });
    const description = {
        file: lazyDescription.file,
        links: lazyDescription.links.map(linksMap),
        substitutions: substitutionMap,
    };
    return description;
}
async function getFileContent(url) {
    try {
        const response = await fetch(url.toString());
        return await response.text();
    }
    catch {
        throw new Error(`Markdown file ${url.toString()} not found. Make sure it is correctly listed in the relevant BUILD.gn files.`);
    }
}
async function getMarkdownFileContent(filename) {
    return await getFileContent(new URL(`descriptions/${filename}`, import.meta.url));
}
async function createIssueDescriptionFromMarkdown(description) {
    const rawMarkdown = await getMarkdownFileContent(description.file);
    const rawMarkdownWithPlaceholdersReplaced = substitutePlaceholders(rawMarkdown, description.substitutions);
    return createIssueDescriptionFromRawMarkdown(rawMarkdownWithPlaceholdersReplaced, description);
}
function createIssueDescriptionFromRawMarkdown(markdown, description) {
    const markdownAst = lexer(markdown);
    const title = findTitleFromMarkdownAst(markdownAst);
    if (!title) {
        throw new Error('Markdown issue descriptions must start with a heading');
    }
    return {
        title,
        markdown: markdownAst.slice(1),
        links: description.links,
    };
}
const validPlaceholderMatchPattern = /\{(PLACEHOLDER_[a-zA-Z][a-zA-Z0-9]*)\}/g;
const validPlaceholderNamePattern = /PLACEHOLDER_[a-zA-Z][a-zA-Z0-9]*/;
function substitutePlaceholders(markdown, substitutions) {
    const unusedPlaceholders = new Set(substitutions ? substitutions.keys() : []);
    validatePlaceholders(unusedPlaceholders);
    const result = markdown.replace(validPlaceholderMatchPattern, (_, placeholder) => {
        const replacement = substitutions ? substitutions.get(placeholder) : undefined;
        if (replacement === undefined) {
            throw new Error(`No replacement provided for placeholder '${placeholder}'.`);
        }
        unusedPlaceholders.delete(placeholder);
        return replacement;
    });
    if (unusedPlaceholders.size > 0) {
        throw new Error(`Unused replacements provided: ${[...unusedPlaceholders]}`);
    }
    return result;
}
function validatePlaceholders(placeholders) {
    const invalidPlaceholders = [...placeholders].filter(placeholder => !validPlaceholderNamePattern.test(placeholder));
    if (invalidPlaceholders.length > 0) {
        throw new Error(`Invalid placeholders provided in the substitutions map: ${invalidPlaceholders}`);
    }
}
function findTitleFromMarkdownAst(markdownAst) {
    if (markdownAst.length === 0 || markdownAst[0].type !== 'heading' || markdownAst[0].depth !== 1) {
        return null;
    }
    return markdownAst[0].text;
}
async function getIssueTitleFromMarkdownDescription(description) {
    const rawMarkdown = await getMarkdownFileContent(description.file);
    const markdownAst = lexer(rawMarkdown);
    return findTitleFromMarkdownAst(markdownAst);
}

var MarkdownIssueDescription = /*#__PURE__*/Object.freeze({
	__proto__: null,
	createIssueDescriptionFromMarkdown: createIssueDescriptionFromMarkdown,
	createIssueDescriptionFromRawMarkdown: createIssueDescriptionFromRawMarkdown,
	findTitleFromMarkdownAst: findTitleFromMarkdownAst,
	getFileContent: getFileContent,
	getIssueTitleFromMarkdownDescription: getIssueTitleFromMarkdownDescription,
	getMarkdownFileContent: getMarkdownFileContent,
	resolveLazyDescription: resolveLazyDescription,
	substitutePlaceholders: substitutePlaceholders
});

// Copyright 2020 The Chromium Authors
const UIStrings$k = {
    contentSecurityPolicySource: 'Content Security Policy - Source Allowlists',
    contentSecurityPolicyInlineCode: 'Content Security Policy - Inline Code',
    contentSecurityPolicyEval: 'Content Security Policy - Eval',
    trustedTypesFixViolations: 'Trusted Types - Fix violations',
    trustedTypesPolicyViolation: 'Trusted Types - Policy violation',
};
const str_$j = registerUIStrings('models/issues_manager/ContentSecurityPolicyIssue.ts', UIStrings$k);
const i18nLazyString$a = getLazilyComputedLocalizedString.bind(undefined, str_$j);
class ContentSecurityPolicyIssue extends Issue {
    constructor(issueDetails, issuesModel, issueId) {
        const issueCode = [
            "ContentSecurityPolicyIssue" ,
            issueDetails.contentSecurityPolicyViolationType,
        ].join('::');
        super(issueCode, issueDetails, issuesModel, issueId);
    }
    getCategory() {
        return "ContentSecurityPolicy" ;
    }
    primaryKey() {
        return JSON.stringify(this.details(), [
            'blockedURL',
            'contentSecurityPolicyViolationType',
            'violatedDirective',
            'isReportOnly',
            'sourceCodeLocation',
            'url',
            'lineNumber',
            'columnNumber',
            'violatingNodeId',
        ]);
    }
    getDescription() {
        const description = issueDescriptions$7.get(this.details().contentSecurityPolicyViolationType);
        if (!description) {
            return null;
        }
        return resolveLazyDescription(description);
    }
    getKind() {
        if (this.details().isReportOnly) {
            return "Improvement" ;
        }
        return "PageError" ;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const cspDetails = inspectorIssue.details.contentSecurityPolicyIssueDetails;
        if (!cspDetails) {
            console.warn('Content security policy issue without details received.');
            return [];
        }
        return [new ContentSecurityPolicyIssue(cspDetails, issuesModel, inspectorIssue.issueId)];
    }
}
const cspURLViolation = {
    file: 'cspURLViolation.md',
    links: [{
            link: 'https://developers.google.com/web/fundamentals/security/csp#source_allowlists',
            linkTitle: i18nLazyString$a(UIStrings$k.contentSecurityPolicySource),
        }],
};
const cspInlineViolation = {
    file: 'cspInlineViolation.md',
    links: [{
            link: 'https://developers.google.com/web/fundamentals/security/csp#inline_code_is_considered_harmful',
            linkTitle: i18nLazyString$a(UIStrings$k.contentSecurityPolicyInlineCode),
        }],
};
const cspEvalViolation = {
    file: 'cspEvalViolation.md',
    links: [{
            link: 'https://developers.google.com/web/fundamentals/security/csp#eval_too',
            linkTitle: i18nLazyString$a(UIStrings$k.contentSecurityPolicyEval),
        }],
};
const cspTrustedTypesSinkViolation = {
    file: 'cspTrustedTypesSinkViolation.md',
    links: [{
            link: 'https://web.dev/trusted-types/#fix-the-violations',
            linkTitle: i18nLazyString$a(UIStrings$k.trustedTypesFixViolations),
        }],
};
const cspTrustedTypesPolicyViolation = {
    file: 'cspTrustedTypesPolicyViolation.md',
    links: [{ link: 'https://web.dev/trusted-types/', linkTitle: i18nLazyString$a(UIStrings$k.trustedTypesPolicyViolation) }],
};
const trustedTypesSinkViolationCode = [
    "ContentSecurityPolicyIssue" ,
    "kTrustedTypesSinkViolation" ,
].join('::');
const trustedTypesPolicyViolationCode = [
    "ContentSecurityPolicyIssue" ,
    "kTrustedTypesPolicyViolation" ,
].join('::');
const issueDescriptions$7 = new Map([
    ["kURLViolation" , cspURLViolation],
    ["kInlineViolation" , cspInlineViolation],
    ["kEvalViolation" , cspEvalViolation],
    ["kTrustedTypesSinkViolation" , cspTrustedTypesSinkViolation],
    ["kTrustedTypesPolicyViolation" , cspTrustedTypesPolicyViolation],
]);

// Copyright 2023 The Chromium Authors
const UIStrings$j = {
    thirdPartyPhaseoutExplained: 'Changes to Chrome\'s treatment of third-party cookies',
};
const str_$i = registerUIStrings('models/issues_manager/CookieDeprecationMetadataIssue.ts', UIStrings$j);
const i18nString$8 = getLocalizedString.bind(undefined, str_$i);
class CookieDeprecationMetadataIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        const issueCode = "CookieDeprecationMetadataIssue"  + '_' + issueDetails.operation;
        super(issueCode, issueDetails, issuesModel);
    }
    getCategory() {
        return "Other" ;
    }
    getDescription() {
        const fileName = this.details().operation === 'SetCookie' ? 'cookieWarnMetadataGrantSet.md' : 'cookieWarnMetadataGrantRead.md';
        let optOutText = '';
        if (this.details().isOptOutTopLevel) {
            optOutText = '\n\n (Top level site opt-out: ' + this.details().optOutPercentage +
                '% - [learn more](gracePeriodStagedControlExplainer))';
        }
        return {
            file: fileName,
            substitutions: new Map([
                ['PLACEHOLDER_topleveloptout', optOutText],
            ]),
            links: [
                {
                    link: 'https://goo.gle/changes-to-chrome-browsing',
                    linkTitle: i18nString$8(UIStrings$j.thirdPartyPhaseoutExplained),
                },
            ],
        };
    }
    getKind() {
        return "BreakingChange" ;
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const details = inspectorIssue.details.cookieDeprecationMetadataIssueDetails;
        if (!details) {
            console.warn('Cookie deprecation metadata issue without details received.');
            return [];
        }
        return [new CookieDeprecationMetadataIssue(details, issuesModel)];
    }
}

// Copyright 2020 The Chromium Authors
const UIStrings$i = {
    samesiteCookiesExplained: 'SameSite cookies explained',
    howSchemefulSamesiteWorks: 'How Schemeful Same-Site Works',
    fileCrosSiteRedirectBug: 'File a bug',
    consoleTpcdErrorMessage: 'Third-party cookie is blocked in Chrome either because of Chrome flags or browser configuration.',
};
const str_$h = registerUIStrings('models/issues_manager/CookieIssue.ts', UIStrings$i);
const i18nLazyString$9 = getLazilyComputedLocalizedString.bind(undefined, str_$h);
class CookieIssue extends Issue {
    cookieId() {
        const details = this.details();
        if (details.cookie) {
            const { domain, path, name } = details.cookie;
            const cookieId = `${domain};${path};${name}`;
            return cookieId;
        }
        return this.details().rawCookieLine ?? 'no-cookie-info';
    }
    primaryKey() {
        const details = this.details();
        const requestId = details.request ? details.request.requestId : 'no-request';
        return `${this.code()}-(${this.cookieId()})-(${requestId})`;
    }
    static createIssuesFromCookieIssueDetails(cookieIssueDetails, issuesModel, issueId) {
        const issues = [];
        if (cookieIssueDetails.cookieExclusionReasons && cookieIssueDetails.cookieExclusionReasons.length > 0) {
            for (const exclusionReason of cookieIssueDetails.cookieExclusionReasons) {
                const code = CookieIssue.codeForCookieIssueDetails(exclusionReason, cookieIssueDetails.cookieWarningReasons, cookieIssueDetails.operation, cookieIssueDetails.cookieUrl);
                if (code) {
                    issues.push(new CookieIssue(code, cookieIssueDetails, issuesModel, issueId));
                }
            }
            return issues;
        }
        if (cookieIssueDetails.cookieWarningReasons) {
            for (const warningReason of cookieIssueDetails.cookieWarningReasons) {
                const code = CookieIssue.codeForCookieIssueDetails(warningReason, [], cookieIssueDetails.operation, cookieIssueDetails.cookieUrl);
                if (code) {
                    issues.push(new CookieIssue(code, cookieIssueDetails, issuesModel, issueId));
                }
            }
        }
        return issues;
    }
    static codeForCookieIssueDetails(reason, warningReasons, operation, cookieUrl) {
        const isURLSecure = cookieUrl && (schemeIs(cookieUrl, 'https:') || schemeIs(cookieUrl, 'wss:'));
        const secure = isURLSecure ? 'Secure' : 'Insecure';
        if (reason === "ExcludeSameSiteStrict"  ||
            reason === "ExcludeSameSiteLax"  ||
            reason === "ExcludeSameSiteUnspecifiedTreatedAsLax" ) {
            if (warningReasons && warningReasons.length > 0) {
                if (warningReasons.includes("WarnSameSiteStrictLaxDowngradeStrict" )) {
                    return [
                        "CookieIssue" ,
                        'ExcludeNavigationContextDowngrade',
                        secure,
                    ].join('::');
                }
                if (warningReasons.includes("WarnSameSiteStrictCrossDowngradeStrict" ) ||
                    warningReasons.includes("WarnSameSiteStrictCrossDowngradeLax" ) ||
                    warningReasons.includes("WarnSameSiteLaxCrossDowngradeStrict" ) ||
                    warningReasons.includes("WarnSameSiteLaxCrossDowngradeLax" )) {
                    return [
                        "CookieIssue" ,
                        'ExcludeContextDowngrade',
                        operation,
                        secure,
                    ].join('::');
                }
            }
            if (warningReasons.includes("WarnCrossSiteRedirectDowngradeChangesInclusion" )) {
                return [
                    "CookieIssue" ,
                    'CrossSiteRedirectDowngradeChangesInclusion',
                ].join('::');
            }
            if (reason === "ExcludeSameSiteUnspecifiedTreatedAsLax" ) {
                return ["CookieIssue" , reason, operation].join('::');
            }
            return null;
        }
        if (reason === "WarnSameSiteStrictLaxDowngradeStrict" ) {
            return ["CookieIssue" , reason, secure].join('::');
        }
        if (reason === "WarnSameSiteStrictCrossDowngradeStrict"  ||
            reason === "WarnSameSiteStrictCrossDowngradeLax"  ||
            reason === "WarnSameSiteLaxCrossDowngradeLax"  ||
            reason === "WarnSameSiteLaxCrossDowngradeStrict" ) {
            return ["CookieIssue" , 'WarnCrossDowngrade', operation, secure].join('::');
        }
        if (reason === "ExcludePortMismatch" ) {
            return ["CookieIssue" , 'ExcludePortMismatch'].join('::');
        }
        if (reason === "ExcludeSchemeMismatch" ) {
            return ["CookieIssue" , 'ExcludeSchemeMismatch'].join('::');
        }
        return ["CookieIssue" , reason, operation].join('::');
    }
    cookies() {
        const details = this.details();
        if (details.cookie) {
            return [details.cookie];
        }
        return [];
    }
    rawCookieLines() {
        const details = this.details();
        if (details.rawCookieLine) {
            return [details.rawCookieLine];
        }
        return [];
    }
    requests() {
        const details = this.details();
        if (details.request) {
            return [details.request];
        }
        return [];
    }
    getCategory() {
        return "Cookie" ;
    }
    getDescription() {
        const description = issueDescriptions$6.get(this.code());
        if (!description) {
            return null;
        }
        return resolveLazyDescription(description);
    }
    isCausedByThirdParty() {
        const outermostFrame = FrameManager.instance().getOutermostFrame();
        return isCausedByThirdParty(outermostFrame, this.details().cookieUrl, this.details().siteForCookies);
    }
    getKind() {
        if (this.details().cookieExclusionReasons?.length > 0) {
            return "PageError" ;
        }
        return "BreakingChange" ;
    }
    static getCookieStatus(cookieIssueDetails) {
        if (cookieIssueDetails.cookieExclusionReasons.includes("ExcludeThirdPartyPhaseout" )) {
            return 0 ;
        }
        if (cookieIssueDetails.cookieWarningReasons.includes("WarnDeprecationTrialMetadata" )) {
            return 2 ;
        }
        if (cookieIssueDetails.cookieWarningReasons.includes("WarnThirdPartyCookieHeuristic" )) {
            return 3 ;
        }
        if (cookieIssueDetails.cookieWarningReasons.includes("WarnThirdPartyPhaseout" )) {
            return 1 ;
        }
        return;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const cookieIssueDetails = inspectorIssue.details.cookieIssueDetails;
        if (!cookieIssueDetails) {
            console.warn('Cookie issue without details received.');
            return [];
        }
        return CookieIssue.createIssuesFromCookieIssueDetails(cookieIssueDetails, issuesModel, inspectorIssue.issueId);
    }
    static getSubCategory(code) {
        if (code.includes('SameSite') || code.includes('Downgrade')) {
            return "SameSiteCookie" ;
        }
        if (code.includes('ThirdPartyPhaseout')) {
            return "ThirdPartyPhaseoutCookie" ;
        }
        return "GenericCookie" ;
    }
    static isThirdPartyCookiePhaseoutRelatedIssue(issue) {
        const excludeFromAggregate = [
            "WarnThirdPartyCookieHeuristic" ,
            "WarnDeprecationTrialMetadata" ,
            "WarnThirdPartyPhaseout" ,
            "ExcludeThirdPartyPhaseout" ,
        ];
        return (excludeFromAggregate.some(exclude => issue.code().includes(exclude)));
    }
    maybeCreateConsoleMessage() {
        const issuesModel = this.model();
        if (issuesModel && this.code().includes("ExcludeThirdPartyPhaseout" )) {
            return new ConsoleMessage(issuesModel.target().model(RuntimeModel), FrontendMessageSource.ISSUE_PANEL, "warning" , UIStrings$i.consoleTpcdErrorMessage, {
                url: this.details().request?.url,
                affectedResources: { requestId: this.details().request?.requestId, issueId: this.issueId },
            });
        }
        return;
    }
}
function isCausedByThirdParty(outermostFrame, cookieUrl, siteForCookies) {
    if (!outermostFrame) {
        return true;
    }
    if (!siteForCookies) {
        return true;
    }
    if (!cookieUrl || outermostFrame.domainAndRegistry() === '') {
        return false;
    }
    const parsedCookieUrl = ParsedURL.fromString(cookieUrl);
    if (!parsedCookieUrl) {
        return false;
    }
    return !isSubdomainOf(parsedCookieUrl.domain(), outermostFrame.domainAndRegistry());
}
function isSubdomainOf(subdomain, superdomain) {
    if (subdomain.length <= superdomain.length) {
        return subdomain === superdomain;
    }
    if (!subdomain.endsWith(superdomain)) {
        return false;
    }
    const subdomainWithoutSuperdomian = subdomain.substr(0, subdomain.length - superdomain.length);
    return subdomainWithoutSuperdomian.endsWith('.');
}
const sameSiteUnspecifiedWarnRead = {
    file: 'SameSiteUnspecifiedLaxAllowUnsafeRead.md',
    links: [
        {
            link: 'https://web.dev/samesite-cookies-explained/',
            linkTitle: i18nLazyString$9(UIStrings$i.samesiteCookiesExplained),
        },
    ],
};
const sameSiteUnspecifiedWarnSet = {
    file: 'SameSiteUnspecifiedLaxAllowUnsafeSet.md',
    links: [
        {
            link: 'https://web.dev/samesite-cookies-explained/',
            linkTitle: i18nLazyString$9(UIStrings$i.samesiteCookiesExplained),
        },
    ],
};
const sameSiteNoneInsecureErrorRead = {
    file: 'SameSiteNoneInsecureErrorRead.md',
    links: [
        {
            link: 'https://web.dev/samesite-cookies-explained/',
            linkTitle: i18nLazyString$9(UIStrings$i.samesiteCookiesExplained),
        },
    ],
};
const sameSiteNoneInsecureErrorSet = {
    file: 'SameSiteNoneInsecureErrorSet.md',
    links: [
        {
            link: 'https://web.dev/samesite-cookies-explained/',
            linkTitle: i18nLazyString$9(UIStrings$i.samesiteCookiesExplained),
        },
    ],
};
const sameSiteNoneInsecureWarnRead = {
    file: 'SameSiteNoneInsecureWarnRead.md',
    links: [
        {
            link: 'https://web.dev/samesite-cookies-explained/',
            linkTitle: i18nLazyString$9(UIStrings$i.samesiteCookiesExplained),
        },
    ],
};
const sameSiteNoneInsecureWarnSet = {
    file: 'SameSiteNoneInsecureWarnSet.md',
    links: [
        {
            link: 'https://web.dev/samesite-cookies-explained/',
            linkTitle: i18nLazyString$9(UIStrings$i.samesiteCookiesExplained),
        },
    ],
};
const schemefulSameSiteArticles = [{ link: 'https://web.dev/schemeful-samesite/', linkTitle: i18nLazyString$9(UIStrings$i.howSchemefulSamesiteWorks) }];
function schemefulSameSiteSubstitutions({ isDestinationSecure, isOriginSecure }) {
    return new Map([
        ['PLACEHOLDER_destination', () => isDestinationSecure ? 'a secure' : 'an insecure'],
        ['PLACEHOLDER_origin', () => isOriginSecure ? 'a secure' : 'an insecure'],
    ]);
}
function sameSiteWarnStrictLaxDowngradeStrict(isSecure) {
    return {
        file: 'SameSiteWarnStrictLaxDowngradeStrict.md',
        substitutions: schemefulSameSiteSubstitutions({ isDestinationSecure: isSecure, isOriginSecure: !isSecure }),
        links: schemefulSameSiteArticles,
    };
}
function sameSiteExcludeNavigationContextDowngrade(isSecure) {
    return {
        file: 'SameSiteExcludeNavigationContextDowngrade.md',
        substitutions: schemefulSameSiteSubstitutions({ isDestinationSecure: isSecure, isOriginSecure: !isSecure }),
        links: schemefulSameSiteArticles,
    };
}
function sameSiteWarnCrossDowngradeRead(isSecure) {
    return {
        file: 'SameSiteWarnCrossDowngradeRead.md',
        substitutions: schemefulSameSiteSubstitutions({ isDestinationSecure: isSecure, isOriginSecure: !isSecure }),
        links: schemefulSameSiteArticles,
    };
}
function sameSiteExcludeContextDowngradeRead(isSecure) {
    return {
        file: 'SameSiteExcludeContextDowngradeRead.md',
        substitutions: schemefulSameSiteSubstitutions({ isDestinationSecure: isSecure, isOriginSecure: !isSecure }),
        links: schemefulSameSiteArticles,
    };
}
function sameSiteWarnCrossDowngradeSet(isSecure) {
    return {
        file: 'SameSiteWarnCrossDowngradeSet.md',
        substitutions: schemefulSameSiteSubstitutions({ isDestinationSecure: !isSecure, isOriginSecure: isSecure }),
        links: schemefulSameSiteArticles,
    };
}
function sameSiteExcludeContextDowngradeSet(isSecure) {
    return {
        file: 'SameSiteExcludeContextDowngradeSet.md',
        substitutions: schemefulSameSiteSubstitutions({ isDestinationSecure: isSecure, isOriginSecure: !isSecure }),
        links: schemefulSameSiteArticles,
    };
}
const attributeValueExceedsMaxSize = {
    file: 'CookieAttributeValueExceedsMaxSize.md',
    links: [],
};
const warnDomainNonAscii = {
    file: 'cookieWarnDomainNonAscii.md',
    links: [],
};
const excludeDomainNonAscii = {
    file: 'cookieExcludeDomainNonAscii.md',
    links: [],
};
const excludeBlockedWithinRelatedWebsiteSet = {
    file: 'cookieExcludeBlockedWithinRelatedWebsiteSet.md',
    links: [],
};
const cookieCrossSiteRedirectDowngrade = {
    file: 'cookieCrossSiteRedirectDowngrade.md',
    links: [{
            link: 'https://bugs.chromium.org/p/chromium/issues/entry?template=Defect%20report%20from%20user&summary=[Cross-Site Redirect Chain] <INSERT BUG SUMMARY HERE>&comment=Chrome Version: (copy from chrome://version)%0AChannel: (e.g. Canary, Dev, Beta, Stable)%0A%0AAffected URLs:%0A%0AWhat is the expected result?%0A%0AWhat happens instead?%0A%0AWhat is the purpose of the cross-site redirect?:%0A%0AWhat steps will reproduce the problem?:%0A(1)%0A(2)%0A(3)%0A%0APlease provide any additional information below.&components=Internals%3ENetwork%3ECookies',
            linkTitle: i18nLazyString$9(UIStrings$i.fileCrosSiteRedirectBug),
        }],
};
const ExcludePortMismatch = {
    file: 'cookieExcludePortMismatch.md',
    links: [],
};
const ExcludeSchemeMismatch = {
    file: 'cookieExcludeSchemeMismatch.md',
    links: [],
};
const placeholderDescriptionForInvisibleIssues = {
    file: 'placeholderDescriptionForInvisibleIssues.md',
    links: [],
};
const issueDescriptions$6 = new Map([
    ['CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::ReadCookie', sameSiteUnspecifiedWarnRead],
    ['CookieIssue::WarnSameSiteUnspecifiedLaxAllowUnsafe::SetCookie', sameSiteUnspecifiedWarnSet],
    ['CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::ReadCookie', sameSiteUnspecifiedWarnRead],
    ['CookieIssue::WarnSameSiteUnspecifiedCrossSiteContext::SetCookie', sameSiteUnspecifiedWarnSet],
    ['CookieIssue::ExcludeSameSiteNoneInsecure::ReadCookie', sameSiteNoneInsecureErrorRead],
    ['CookieIssue::ExcludeSameSiteNoneInsecure::SetCookie', sameSiteNoneInsecureErrorSet],
    ['CookieIssue::WarnSameSiteNoneInsecure::ReadCookie', sameSiteNoneInsecureWarnRead],
    ['CookieIssue::WarnSameSiteNoneInsecure::SetCookie', sameSiteNoneInsecureWarnSet],
    ['CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Secure', sameSiteWarnStrictLaxDowngradeStrict(true)],
    ['CookieIssue::WarnSameSiteStrictLaxDowngradeStrict::Insecure', sameSiteWarnStrictLaxDowngradeStrict(false)],
    ['CookieIssue::WarnCrossDowngrade::ReadCookie::Secure', sameSiteWarnCrossDowngradeRead(true)],
    ['CookieIssue::WarnCrossDowngrade::ReadCookie::Insecure', sameSiteWarnCrossDowngradeRead(false)],
    ['CookieIssue::WarnCrossDowngrade::SetCookie::Secure', sameSiteWarnCrossDowngradeSet(true)],
    ['CookieIssue::WarnCrossDowngrade::SetCookie::Insecure', sameSiteWarnCrossDowngradeSet(false)],
    ['CookieIssue::ExcludeNavigationContextDowngrade::Secure', sameSiteExcludeNavigationContextDowngrade(true)],
    [
        'CookieIssue::ExcludeNavigationContextDowngrade::Insecure',
        sameSiteExcludeNavigationContextDowngrade(false),
    ],
    ['CookieIssue::ExcludeContextDowngrade::ReadCookie::Secure', sameSiteExcludeContextDowngradeRead(true)],
    ['CookieIssue::ExcludeContextDowngrade::ReadCookie::Insecure', sameSiteExcludeContextDowngradeRead(false)],
    ['CookieIssue::ExcludeContextDowngrade::SetCookie::Secure', sameSiteExcludeContextDowngradeSet(true)],
    ['CookieIssue::ExcludeContextDowngrade::SetCookie::Insecure', sameSiteExcludeContextDowngradeSet(false)],
    ['CookieIssue::WarnAttributeValueExceedsMaxSize::ReadCookie', attributeValueExceedsMaxSize],
    ['CookieIssue::WarnAttributeValueExceedsMaxSize::SetCookie', attributeValueExceedsMaxSize],
    ['CookieIssue::WarnDomainNonASCII::ReadCookie', warnDomainNonAscii],
    ['CookieIssue::WarnDomainNonASCII::SetCookie', warnDomainNonAscii],
    ['CookieIssue::ExcludeDomainNonASCII::ReadCookie', excludeDomainNonAscii],
    ['CookieIssue::ExcludeDomainNonASCII::SetCookie', excludeDomainNonAscii],
    [
        'CookieIssue::ExcludeThirdPartyCookieBlockedInRelatedWebsiteSet::ReadCookie',
        excludeBlockedWithinRelatedWebsiteSet,
    ],
    [
        'CookieIssue::ExcludeThirdPartyCookieBlockedInRelatedWebsiteSet::SetCookie',
        excludeBlockedWithinRelatedWebsiteSet,
    ],
    ['CookieIssue::WarnThirdPartyPhaseout::ReadCookie', placeholderDescriptionForInvisibleIssues],
    ['CookieIssue::WarnThirdPartyPhaseout::SetCookie', placeholderDescriptionForInvisibleIssues],
    ['CookieIssue::WarnDeprecationTrialMetadata::ReadCookie', placeholderDescriptionForInvisibleIssues],
    ['CookieIssue::WarnDeprecationTrialMetadata::SetCookie', placeholderDescriptionForInvisibleIssues],
    ['CookieIssue::WarnThirdPartyCookieHeuristic::ReadCookie', placeholderDescriptionForInvisibleIssues],
    ['CookieIssue::WarnThirdPartyCookieHeuristic::SetCookie', placeholderDescriptionForInvisibleIssues],
    ['CookieIssue::ExcludeThirdPartyPhaseout::ReadCookie', placeholderDescriptionForInvisibleIssues],
    ['CookieIssue::ExcludeThirdPartyPhaseout::SetCookie', placeholderDescriptionForInvisibleIssues],
    ['CookieIssue::CrossSiteRedirectDowngradeChangesInclusion', cookieCrossSiteRedirectDowngrade],
    ['CookieIssue::ExcludePortMismatch', ExcludePortMismatch],
    ['CookieIssue::ExcludeSchemeMismatch', ExcludeSchemeMismatch],
]);

// Copyright 2020 The Chromium Authors
const UIStrings$h = {
    corsLocalNetworkAccess: 'Local Network Access',
    CORS: 'Cross-Origin Resource Sharing (`CORS`)',
};
const str_$g = registerUIStrings('models/issues_manager/CorsIssue.ts', UIStrings$h);
const i18nString$7 = getLocalizedString.bind(undefined, str_$g);
function getIssueCode$1(details) {
    switch (details.corsErrorStatus.corsError) {
        case "InvalidAllowMethodsPreflightResponse" :
        case "InvalidAllowHeadersPreflightResponse" :
        case "PreflightMissingAllowOriginHeader" :
        case "PreflightMultipleAllowOriginValues" :
        case "PreflightInvalidAllowOriginValue" :
        case "MissingAllowOriginHeader" :
        case "MultipleAllowOriginValues" :
        case "InvalidAllowOriginValue" :
            return "CorsIssue::InvalidHeaders" ;
        case "PreflightWildcardOriginNotAllowed" :
        case "WildcardOriginNotAllowed" :
            return "CorsIssue::WildcardOriginWithCredentials" ;
        case "PreflightInvalidStatus" :
        case "PreflightDisallowedRedirect" :
        case "InvalidResponse" :
            return "CorsIssue::PreflightResponseInvalid" ;
        case "AllowOriginMismatch" :
        case "PreflightAllowOriginMismatch" :
            return "CorsIssue::OriginMismatch" ;
        case "InvalidAllowCredentials" :
        case "PreflightInvalidAllowCredentials" :
            return "CorsIssue::AllowCredentialsRequired" ;
        case "MethodDisallowedByPreflightResponse" :
            return "CorsIssue::MethodDisallowedByPreflightResponse" ;
        case "HeaderDisallowedByPreflightResponse" :
            return "CorsIssue::HeaderDisallowedByPreflightResponse" ;
        case "RedirectContainsCredentials" :
            return "CorsIssue::RedirectContainsCredentials" ;
        case "DisallowedByMode" :
            return "CorsIssue::DisallowedByMode" ;
        case "CorsDisabledScheme" :
            return "CorsIssue::CorsDisabledScheme" ;
        case "PreflightMissingAllowExternal" :
            return "CorsIssue::PreflightMissingAllowExternal" ;
        case "PreflightInvalidAllowExternal" :
            return "CorsIssue::PreflightInvalidAllowExternal" ;
        case "InsecureLocalNetwork" :
            return "CorsIssue::InsecureLocalNetwork" ;
        case "NoCorsRedirectModeNotFollow" :
            return "CorsIssue::NoCorsRedirectModeNotFollow" ;
        case "InvalidLocalNetworkAccess" :
            return "CorsIssue::InvalidLocalNetworkAccess" ;
        case "LocalNetworkAccessPermissionDenied" :
            return "CorsIssue::LocalNetworkAccessPermissionDenied" ;
    }
}
class CorsIssue extends Issue {
    constructor(issueDetails, issuesModel, issueId) {
        super(getIssueCode$1(issueDetails), issueDetails, issuesModel, issueId);
    }
    getCategory() {
        return "Cors" ;
    }
    getDescription() {
        switch (getIssueCode$1(this.details())) {
            case "CorsIssue::InvalidHeaders" :
                return {
                    file: 'corsInvalidHeaderValues.md',
                    links: [{
                            link: 'https://web.dev/cross-origin-resource-sharing',
                            linkTitle: i18nString$7(UIStrings$h.CORS),
                        }],
                };
            case "CorsIssue::WildcardOriginWithCredentials" :
                return {
                    file: 'corsWildcardOriginNotAllowed.md',
                    links: [{
                            link: 'https://web.dev/cross-origin-resource-sharing',
                            linkTitle: i18nString$7(UIStrings$h.CORS),
                        }],
                };
            case "CorsIssue::PreflightResponseInvalid" :
                return {
                    file: 'corsPreflightResponseInvalid.md',
                    links: [{
                            link: 'https://web.dev/cross-origin-resource-sharing',
                            linkTitle: i18nString$7(UIStrings$h.CORS),
                        }],
                };
            case "CorsIssue::OriginMismatch" :
                return {
                    file: 'corsOriginMismatch.md',
                    links: [{
                            link: 'https://web.dev/cross-origin-resource-sharing',
                            linkTitle: i18nString$7(UIStrings$h.CORS),
                        }],
                };
            case "CorsIssue::AllowCredentialsRequired" :
                return {
                    file: 'corsAllowCredentialsRequired.md',
                    links: [{
                            link: 'https://web.dev/cross-origin-resource-sharing',
                            linkTitle: i18nString$7(UIStrings$h.CORS),
                        }],
                };
            case "CorsIssue::MethodDisallowedByPreflightResponse" :
                return {
                    file: 'corsMethodDisallowedByPreflightResponse.md',
                    links: [{
                            link: 'https://web.dev/cross-origin-resource-sharing',
                            linkTitle: i18nString$7(UIStrings$h.CORS),
                        }],
                };
            case "CorsIssue::HeaderDisallowedByPreflightResponse" :
                return {
                    file: 'corsHeaderDisallowedByPreflightResponse.md',
                    links: [{
                            link: 'https://web.dev/cross-origin-resource-sharing',
                            linkTitle: i18nString$7(UIStrings$h.CORS),
                        }],
                };
            case "CorsIssue::RedirectContainsCredentials" :
                return {
                    file: 'corsRedirectContainsCredentials.md',
                    links: [{
                            link: 'https://web.dev/cross-origin-resource-sharing',
                            linkTitle: i18nString$7(UIStrings$h.CORS),
                        }],
                };
            case "CorsIssue::DisallowedByMode" :
                return {
                    file: 'corsDisallowedByMode.md',
                    links: [{
                            link: 'https://web.dev/cross-origin-resource-sharing',
                            linkTitle: i18nString$7(UIStrings$h.CORS),
                        }],
                };
            case "CorsIssue::CorsDisabledScheme" :
                return {
                    file: 'corsDisabledScheme.md',
                    links: [{
                            link: 'https://web.dev/cross-origin-resource-sharing',
                            linkTitle: i18nString$7(UIStrings$h.CORS),
                        }],
                };
            case "CorsIssue::NoCorsRedirectModeNotFollow" :
                return {
                    file: 'corsNoCorsRedirectModeNotFollow.md',
                    links: [{
                            link: 'https://web.dev/cross-origin-resource-sharing',
                            linkTitle: i18nString$7(UIStrings$h.CORS),
                        }],
                };
            case "CorsIssue::InsecureLocalNetwork" :
            case "CorsIssue::LocalNetworkAccessPermissionDenied" :
                return {
                    file: 'corsLocalNetworkAccessPermissionDenied.md',
                    links: [{
                            link: 'https://developer.chrome.com/blog/local-network-access',
                            linkTitle: i18nString$7(UIStrings$h.corsLocalNetworkAccess),
                        }],
                };
            case "CorsIssue::PreflightMissingAllowExternal" :
            case "CorsIssue::PreflightInvalidAllowExternal" :
            case "CorsIssue::InvalidLocalNetworkAccess" :
                return null;
        }
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getKind() {
        if (this.details().isWarning &&
            this.details().corsErrorStatus.corsError === "InsecureLocalNetwork" ) {
            return "BreakingChange" ;
        }
        return "PageError" ;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const corsIssueDetails = inspectorIssue.details.corsIssueDetails;
        if (!corsIssueDetails) {
            console.warn('Cors issue without details received.');
            return [];
        }
        return [new CorsIssue(corsIssueDetails, issuesModel, inspectorIssue.issueId)];
    }
}

// Copyright 2026 The Chromium Authors
const UIStrings$g = {
    AttributionReporting: "Attribution Reporting is deprecated and will be removed. See https://goo.gle/ps-status for details.",
    AuthorizationCoveredByWildcard: "Authorization will not be covered by the wildcard symbol (*) in CORS `Access-Control-Allow-Headers` handling.",
    CanRequestURLHTTPContainingNewline: "Resource requests whose URLs contained both removed whitespace `\\(n|r|t)` characters and less-than characters (`<`) are blocked. Please remove newlines and encode less-than characters from places like element attribute values in order to load these resources.",
    ChromeLoadTimesConnectionInfo: "`chrome.loadTimes()` is deprecated, instead use standardized API: Navigation Timing 2.",
    ChromeLoadTimesFirstPaintAfterLoadTime: "`chrome.loadTimes()` is deprecated, instead use standardized API: Paint Timing.",
    ChromeLoadTimesWasAlternateProtocolAvailable: "`chrome.loadTimes()` is deprecated, instead use standardized API: `nextHopProtocol` in Navigation Timing 2.",
    CrossOriginAccessBasedOnDocumentDomain: "Relaxing the same-origin policy by setting `document.domain` is deprecated, and will be disabled by default. This deprecation warning is for a cross-origin access that was enabled by setting `document.domain`.",
    CrossOriginWindowAlert: "Triggering window.alert from cross origin iframes has been deprecated and will be removed in the future.",
    CrossOriginWindowConfirm: "Triggering window.confirm from cross origin iframes has been deprecated and will be removed in the future.",
    CSSSelectorInternalMediaControlsOverlayCastButton: "The `disableRemotePlayback` attribute should be used in order to disable the default Cast integration instead of using `-internal-media-controls-overlay-cast-button` selector.",
    CSSValueAppearanceSliderVertical: "CSS appearance value `slider-vertical` is not standardized and will be removed.",
    DataUrlInSvgUse: "Support for data: URLs in SVGUseElement is deprecated and it will be removed in the future.",
    ExampleBrowserProcessDeprecation: "This is an example for showing the code required for a browser process reported deprecation.",
    Fledge: "The Protected Audience API is deprecated and will be removed in a future release.",
    GeolocationInsecureOrigin: "`getCurrentPosition()` and `watchPosition()` no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://www.chromium.org/Home/chromium-security/deprecating-powerful-features-on-insecure-origins/ for more details.",
    GeolocationInsecureOriginDeprecatedNotRemoved: "`getCurrentPosition()` and `watchPosition()` are deprecated on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://www.chromium.org/Home/chromium-security/deprecating-powerful-features-on-insecure-origins/ for more details.",
    GetUserMediaInsecureOrigin: "`getUserMedia()` no longer works on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://www.chromium.org/Home/chromium-security/deprecating-powerful-features-on-insecure-origins/ for more details.",
    HostCandidateAttributeGetter: "`RTCPeerConnectionIceErrorEvent.hostCandidate` is deprecated. Please use `RTCPeerConnectionIceErrorEvent.address` or `RTCPeerConnectionIceErrorEvent.port` instead.",
    IdentityInCanMakePaymentEvent: "The merchant origin and arbitrary data from the `canmakepayment` service worker event are deprecated and will be removed: `topOrigin`, `paymentRequestOrigin`, `methodData`, `modifiers`.",
    InsecurePrivateNetworkSubresourceRequest: "The website requested a subresource from a network that it could only access because of its users' privileged network position. These requests expose non-public devices and servers to the internet, increasing the risk of a cross-site request forgery (CSRF) attack, and/or information leakage. To mitigate these risks, Chrome deprecates requests to non-public subresources when initiated from non-secure contexts, and will start blocking them.",
    InterestGroupDailyUpdateUrl: "The `dailyUpdateUrl` field of `InterestGroups` passed to `joinAdInterestGroup()` has been renamed to `updateUrl`, to more accurately reflect its behavior.",
    IntlV8BreakIterator: "`Intl.v8BreakIterator` is deprecated. Please use `Intl.Segmenter` instead.",
    LanguageModel_InputQuota: "LanguageModel.inputQuota is deprecated. Please use LanguageModel.contextWindow instead. This alias is only available in extensions.",
    LanguageModel_InputUsage: "LanguageModel.inputUsage is deprecated. Please use LanguageModel.contextUsage instead. This alias is only available in extensions.",
    LanguageModel_MeasureInputUsage: "LanguageModel.measureInputUsage() is deprecated. Please use LanguageModel.measureContextUsage() instead. This alias is only available in extensions.",
    LanguageModel_OnQuotaOverflow: "LanguageModel.onquotaoverflow is deprecated. Please use LanguageModel.oncontextoverflow instead. The LanguageModel.onquotaoverflow alias is only available in extensions.",
    LanguageModelParams: "LanguageModel.params() is deprecated and now only available in extension contexts. The topK and temperature related fields within its result are also deprecated.",
    LanguageModelTemperature: "The 'temperature' parameter/attribute for LanguageModel is deprecated. It is only functional within extensions and may be removed in the future.",
    LanguageModelTopK: "The 'topK' parameter/attribute for LanguageModel is deprecated. It is only functional within extensions and may be removed in the future.",
    LocalCSSFileExtensionRejected: "CSS cannot be loaded from `file:` URLs unless they end in a `.css` file extension.",
    NoSysexWebMIDIWithoutPermission: "Web MIDI will ask a permission to use even if the sysex is not specified in the `MIDIOptions`.",
    NotificationInsecureOrigin: "The Notification API may no longer be used from insecure origins. You should consider switching your application to a secure origin, such as HTTPS. See https://www.chromium.org/Home/chromium-security/deprecating-powerful-features-on-insecure-origins/ for more details.",
    NotificationPermissionRequestedIframe: "Permission for the Notification API may no longer be requested from a cross-origin iframe. You should consider requesting permission from a top-level frame or opening a new window instead.",
    ObsoleteCreateImageBitmapImageOrientationNone: "Option `imageOrientation: 'none'` in createImageBitmap is deprecated. Please use createImageBitmap with option '{imageOrientation: 'from-image'}' instead.",
    ObsoleteWebRtcCipherSuite: "Your partner is negotiating an obsolete (D)TLS version. Please check with your partner to have this fixed.",
    OverflowVisibleOnReplacedElement: "Specifying `overflow: visible` on img, video and canvas tags may cause them to produce visual content outside of the element bounds. See https://github.com/WICG/shared-element-transitions/blob/main/debugging_overflow_on_images.md.",
    OverrideFlashEmbedwithHTML: "Legacy flash video embed has been rewritten to HTML iframe. Flash is long gone, this rewriting hack is deprecated and may be removed in the future.",
    PaymentInstruments: "`paymentManager.instruments` is deprecated. Please use just-in-time install for payment handlers instead.",
    PaymentRequestCSPViolation: "Your `PaymentRequest` call bypassed Content-Security-Policy (CSP) `connect-src` directive. This bypass is deprecated. Please add the payment method identifier from the `PaymentRequest` API (in `supportedMethods` field) to your CSP `connect-src` directive.",
    PersistentQuotaType: "`StorageType.persistent` is deprecated. Please use standardized `navigator.storage` instead.",
    PictureSourceSrc: "`<source src>` with a `<picture>` parent is invalid and therefore ignored. Please use `<source srcset>` instead.",
    PrefixedCancelAnimationFrame: "webkitCancelAnimationFrame is vendor-specific. Please use the standard cancelAnimationFrame instead.",
    PrefixedRequestAnimationFrame: "webkitRequestAnimationFrame is vendor-specific. Please use the standard requestAnimationFrame instead.",
    PrefixedVideoDisplayingFullscreen: "HTMLVideoElement.webkitDisplayingFullscreen is deprecated. Please use Document.fullscreenElement instead.",
    PrefixedVideoEnterFullScreen: "HTMLVideoElement.webkitEnterFullScreen() is deprecated. Please use Element.requestFullscreen() instead.",
    PrefixedVideoEnterFullscreen: "HTMLVideoElement.webkitEnterFullscreen() is deprecated. Please use Element.requestFullscreen() instead.",
    PrefixedVideoExitFullScreen: "HTMLVideoElement.webkitExitFullScreen() is deprecated. Please use Document.exitFullscreen() instead.",
    PrefixedVideoExitFullscreen: "HTMLVideoElement.webkitExitFullscreen() is deprecated. Please use Document.exitFullscreen() instead.",
    PrefixedVideoSupportsFullscreen: "HTMLVideoElement.webkitSupportsFullscreen is deprecated. Please use Document.fullscreenEnabled instead.",
    RangeExpand: "Range.expand() is deprecated. Please use Selection.modify() instead.",
    RelatedWebsiteSets: "`Related Website Sets` is deprecated and will be removed. See https://privacysandbox.com/news/update-on-plans-for-privacy-sandbox-technologies/ for more details.",
    RequestedSubresourceWithEmbeddedCredentials: "Subresource requests whose URLs contain embedded credentials (e.g. `https://user:pass@host/`) are blocked.",
    RTCConstraintEnableDtlsSrtpFalse: "The constraint `DtlsSrtpKeyAgreement` is removed. You have specified a `false` value for this constraint, which is interpreted as an attempt to use the removed `SDES key negotiation` method. This functionality is removed; use a service that supports `DTLS key negotiation` instead.",
    RTCConstraintEnableDtlsSrtpTrue: "The constraint `DtlsSrtpKeyAgreement` is removed. You have specified a `true` value for this constraint, which had no effect, but you can remove this constraint for tidiness.",
    RTCPeerConnectionGetStatsLegacyNonCompliant: "The callback-based getStats() is deprecated and will be removed. Use the spec-compliant getStats() instead.",
    RtcpMuxPolicyNegotiate: "The `rtcpMuxPolicy` option is deprecated and will be removed.",
    SharedArrayBufferConstructedWithoutIsolation: "`SharedArrayBuffer` will require cross-origin isolation. See https://developer.chrome.com/blog/enabling-shared-array-buffer/ for more details.",
    SharedStorage: "The Shared Storage API is deprecated and will be removed in a future release.",
    StorageAccessAPI_requestStorageAccessFor_Method: "`document.requestStorageAccessFor` is deprecated and will be removed. See https://privacysandbox.com/news/update-on-plans-for-privacy-sandbox-technologies/ for more details.",
    TextToSpeech_DisallowedByAutoplay: "`speechSynthesis.speak()` without user activation is deprecated and will be removed.",
    Topics: "The Topics API is deprecated and will be removed in a future release.",
    UnloadHandler: "Unload event listeners are deprecated and will be removed.",
    V8SharedArrayBufferConstructedInExtensionWithoutIsolation: "Extensions should opt into cross-origin isolation to continue using `SharedArrayBuffer`. See https://developer.chrome.com/docs/extensions/mv3/cross-origin-isolation/.",
    WebBluetoothRemoteCharacteristicWriteValue: "`BluetoothRemoteGATTCharacteristic.writeValue()` is deprecated. Use `writeValueWithResponse()` or `writeValueWithoutResponse()` instead.",
    XHRJSONEncodingDetection: "UTF-16 is not supported by response json in `XMLHttpRequest`",
    XMLHttpRequestSynchronousInNonWorkerOutsideBeforeUnload: "Synchronous `XMLHttpRequest` on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.",
    XSLT: "XSLTProcessor and XSLT Processing Instructions have been deprecated by all browsers. These features will be removed from this browser soon.",
};
const DEPRECATIONS_METADATA = {
    "AttributionReporting": {
        "chromeStatusFeature": 6320639375966208
    },
    "AuthorizationCoveredByWildcard": {
        "milestone": 97
    },
    "CSSSelectorInternalMediaControlsOverlayCastButton": {
        "chromeStatusFeature": 5714245488476160
    },
    "CSSValueAppearanceSliderVertical": {
        "chromeStatusFeature": 6001359429566464
    },
    "CanRequestURLHTTPContainingNewline": {
        "chromeStatusFeature": 5735596811091968
    },
    "ChromeLoadTimesConnectionInfo": {
        "chromeStatusFeature": 5637885046816768
    },
    "ChromeLoadTimesFirstPaintAfterLoadTime": {
        "chromeStatusFeature": 5637885046816768
    },
    "ChromeLoadTimesWasAlternateProtocolAvailable": {
        "chromeStatusFeature": 5637885046816768
    },
    "CrossOriginAccessBasedOnDocumentDomain": {
        "milestone": 115
    },
    "DataUrlInSvgUse": {
        "chromeStatusFeature": 5128825141198848,
        "milestone": 119
    },
    "IdentityInCanMakePaymentEvent": {
        "chromeStatusFeature": 5190978431352832
    },
    "InsecurePrivateNetworkSubresourceRequest": {
        "chromeStatusFeature": 5436853517811712,
        "milestone": 92
    },
    "LanguageModelParams": {
        "chromeStatusFeature": 5134603979063296
    },
    "LanguageModelTemperature": {
        "chromeStatusFeature": 5134603979063296
    },
    "LanguageModelTopK": {
        "chromeStatusFeature": 5134603979063296
    },
    "LanguageModel_InputQuota": {
        "chromeStatusFeature": 5134603979063296
    },
    "LanguageModel_InputUsage": {
        "chromeStatusFeature": 5134603979063296
    },
    "LanguageModel_MeasureInputUsage": {
        "chromeStatusFeature": 5134603979063296
    },
    "LanguageModel_OnQuotaOverflow": {
        "chromeStatusFeature": 5134603979063296
    },
    "LocalCSSFileExtensionRejected": {
        "milestone": 64
    },
    "NoSysexWebMIDIWithoutPermission": {
        "chromeStatusFeature": 5138066234671104,
        "milestone": 82
    },
    "NotificationPermissionRequestedIframe": {
        "chromeStatusFeature": 6451284559265792
    },
    "ObsoleteCreateImageBitmapImageOrientationNone": {
        "milestone": 111
    },
    "ObsoleteWebRtcCipherSuite": {
        "milestone": 81
    },
    "OverflowVisibleOnReplacedElement": {
        "chromeStatusFeature": 5137515594383360,
        "milestone": 108
    },
    "OverrideFlashEmbedwithHTML": {
        "milestone": 140
    },
    "PaymentInstruments": {
        "chromeStatusFeature": 5099285054488576
    },
    "PaymentRequestCSPViolation": {
        "chromeStatusFeature": 6286595631087616
    },
    "PersistentQuotaType": {
        "chromeStatusFeature": 5176235376246784,
        "milestone": 106
    },
    "RTCConstraintEnableDtlsSrtpFalse": {
        "milestone": 97
    },
    "RTCConstraintEnableDtlsSrtpTrue": {
        "milestone": 97
    },
    "RTCPeerConnectionGetStatsLegacyNonCompliant": {
        "chromeStatusFeature": 4631626228695040,
        "milestone": 117
    },
    "RelatedWebsiteSets": {
        "chromeStatusFeature": 5194473869017088
    },
    "RequestedSubresourceWithEmbeddedCredentials": {
        "chromeStatusFeature": 5669008342777856
    },
    "RtcpMuxPolicyNegotiate": {
        "chromeStatusFeature": 5654810086866944,
        "milestone": 62
    },
    "SharedArrayBufferConstructedWithoutIsolation": {
        "milestone": 106
    },
    "SharedStorage": {
        "chromeStatusFeature": 5076349064708096
    },
    "StorageAccessAPI_requestStorageAccessFor_Method": {
        "chromeStatusFeature": 5162221567082496
    },
    "TextToSpeech_DisallowedByAutoplay": {
        "chromeStatusFeature": 5687444770914304,
        "milestone": 71
    },
    "UnloadHandler": {
        "chromeStatusFeature": 5579556305502208
    },
    "V8SharedArrayBufferConstructedInExtensionWithoutIsolation": {
        "milestone": 96
    },
    "WebBluetoothRemoteCharacteristicWriteValue": {
        "chromeStatusFeature": 5088568590598144
    },
    "XHRJSONEncodingDetection": {
        "milestone": 93
    },
    "XSLT": {
        "chromeStatusFeature": 4709671889534976,
        "milestone": 143
    }
};

// Copyright 2021 The Chromium Authors
const UIStrings$f = {
    feature: 'Check the feature status page for more details.',
    milestone: 'This change will go into effect with milestone {milestone}.',
    title: 'Deprecated feature used',
};
const str_$f = registerUIStrings('models/issues_manager/DeprecationIssue.ts', UIStrings$f);
const i18nLazyString$8 = getLazilyComputedLocalizedString.bind(undefined, str_$f);
const strDeprecation = registerUIStrings('generated/Deprecation.ts', UIStrings$g);
const i18nLazyDeprecationString = getLazilyComputedLocalizedString.bind(undefined, strDeprecation);
class DeprecationIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        const issueCode = [
            "DeprecationIssue" ,
            issueDetails.type,
        ].join('::');
        super({ code: issueCode, umaCode: 'DeprecationIssue' }, issueDetails, issuesModel);
    }
    getCategory() {
        return "Other" ;
    }
    getDescription() {
        let messageFunction = () => '';
        const maybeEnglishMessage = UIStrings$g[this.details().type];
        if (maybeEnglishMessage) {
            messageFunction = i18nLazyDeprecationString(maybeEnglishMessage);
        }
        const links = [];
        const deprecationMeta = DEPRECATIONS_METADATA[this.details().type];
        const feature = deprecationMeta?.chromeStatusFeature ?? 0;
        if (feature !== 0) {
            links.push({
                link: `https://chromestatus.com/feature/${feature}`,
                linkTitle: i18nLazyString$8(UIStrings$f.feature),
            });
        }
        const milestone = deprecationMeta?.milestone ?? 0;
        if (milestone !== 0) {
            links.push({
                link: 'https://chromiumdash.appspot.com/schedule',
                linkTitle: i18nLazyString$8(UIStrings$f.milestone, { milestone }),
            });
        }
        return resolveLazyDescription({
            file: 'deprecation.md',
            substitutions: new Map([
                ['PLACEHOLDER_title', i18nLazyString$8(UIStrings$f.title)],
                ['PLACEHOLDER_message', messageFunction],
            ]),
            links,
        });
    }
    sources() {
        if (this.details().sourceCodeLocation) {
            return [this.details().sourceCodeLocation];
        }
        return [];
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getKind() {
        return "BreakingChange" ;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const details = inspectorIssue.details.deprecationIssueDetails;
        if (!details) {
            console.warn('Deprecation issue without details received.');
            return [];
        }
        return [new DeprecationIssue(details, issuesModel)];
    }
}

// Copyright 2025 The Chromium Authors
class ElementAccessibilityIssue extends Issue {
    constructor(issueDetails, issuesModel, issueId) {
        const issueCode = [
            "ElementAccessibilityIssue" ,
            issueDetails.elementAccessibilityIssueReason,
        ].join('::');
        super(issueCode, issueDetails, issuesModel, issueId);
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getDescription() {
        if (this.isInteractiveContentAttributesSelectDescendantIssue()) {
            return {
                file: 'selectElementAccessibilityInteractiveContentAttributesSelectDescendant.md',
                links: [],
            };
        }
        const description = issueDescriptions$5.get(this.details().elementAccessibilityIssueReason);
        if (!description) {
            return null;
        }
        return resolveLazyDescription(description);
    }
    getKind() {
        return "PageError" ;
    }
    getCategory() {
        return "Other" ;
    }
    isInteractiveContentAttributesSelectDescendantIssue() {
        return this.details().hasDisallowedAttributes &&
            (this.details().elementAccessibilityIssueReason !==
                "InteractiveContentOptionChild"  &&
                this.details().elementAccessibilityIssueReason !==
                    "InteractiveContentSummaryDescendant" );
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const elementAccessibilityIssueDetails = inspectorIssue.details.elementAccessibilityIssueDetails;
        if (!elementAccessibilityIssueDetails) {
            console.warn('Element Accessibility issue without details received.');
            return [];
        }
        return [new ElementAccessibilityIssue(elementAccessibilityIssueDetails, issuesModel, inspectorIssue.issueId)];
    }
}
const issueDescriptions$5 = new Map([
    [
        "DisallowedSelectChild" ,
        {
            file: 'selectElementAccessibilityDisallowedSelectChild.md',
            links: [],
        },
    ],
    [
        "DisallowedOptGroupChild" ,
        {
            file: 'selectElementAccessibilityDisallowedOptGroupChild.md',
            links: [],
        },
    ],
    [
        "NonPhrasingContentOptionChild" ,
        {
            file: 'selectElementAccessibilityNonPhrasingContentOptionChild.md',
            links: [],
        },
    ],
    [
        "InteractiveContentOptionChild" ,
        {
            file: 'selectElementAccessibilityInteractiveContentOptionChild.md',
            links: [],
        },
    ],
    [
        "InteractiveContentLegendChild" ,
        {
            file: 'selectElementAccessibilityInteractiveContentLegendChild.md',
            links: [],
        },
    ],
    [
        "InteractiveContentSummaryDescendant" ,
        {
            file: 'summaryElementAccessibilityInteractiveContentSummaryDescendant.md',
            links: [],
        },
    ],
]);

// Copyright 2021 The Chromium Authors
const UIStrings$e = {
    howDoesAutofillWorkPageTitle: 'How does autofill work?',
    labelFormlementsPageTitle: 'The label elements',
    inputFormElementPageTitle: 'The form input element',
    autocompleteAttributePageTitle: 'HTML attribute: autocomplete',
    corbExplainerPageTitle: 'CORB explainer',
    historyManipulationInterventionPageTitle: 'History manipulation intervention explainer'
};
const str_$e = registerUIStrings('models/issues_manager/GenericIssue.ts', UIStrings$e);
const i18nLazyString$7 = getLazilyComputedLocalizedString.bind(undefined, str_$e);
class GenericIssue extends Issue {
    constructor(issueDetails, issuesModel, issueId) {
        const issueCode = [
            "GenericIssue" ,
            issueDetails.errorType,
        ].join('::');
        super(issueCode, issueDetails, issuesModel, issueId);
    }
    requests() {
        const details = this.details();
        if (details.request) {
            return [details.request];
        }
        return [];
    }
    getCategory() {
        return "Generic" ;
    }
    primaryKey() {
        const details = this.details();
        const requestId = details.request ? details.request.requestId : 'no-request';
        return `${this.code()}-(${details.frameId})-(${details.violatingNodeId})-(${details.violatingNodeAttribute})-(${requestId})`;
    }
    getDescription() {
        const description = issueDescriptions$4.get(this.details().errorType);
        if (!description) {
            return null;
        }
        return resolveLazyDescription(description);
    }
    getKind() {
        return issueTypes.get(this.details().errorType) || "Improvement" ;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const genericDetails = inspectorIssue.details.genericIssueDetails;
        if (!genericDetails) {
            console.warn('Generic issue without details received.');
            return [];
        }
        return [new GenericIssue(genericDetails, issuesModel, inspectorIssue.issueId)];
    }
}
const genericFormLabelForNameError = {
    file: 'genericFormLabelForNameError.md',
    links: [{
            link: 'https://html.spec.whatwg.org/multipage/forms.html#attr-label-for',
            linkTitle: lockedLazyString('HTML Standard'),
        }],
};
const genericFormInputWithNoLabelError = {
    file: 'genericFormInputWithNoLabelError.md',
    links: [],
};
const genericFormAutocompleteAttributeEmptyError = {
    file: 'genericFormAutocompleteAttributeEmptyError.md',
    links: [],
};
const genericFormDuplicateIdForInputError = {
    file: 'genericFormDuplicateIdForInputError.md',
    links: [{
            link: 'https://web.dev/learn/forms/autofill/#how-does-autofill-work',
            linkTitle: i18nLazyString$7(UIStrings$e.howDoesAutofillWorkPageTitle),
        }],
};
const genericFormAriaLabelledByToNonExistingIdError = {
    file: 'genericFormAriaLabelledByToNonExistingIdError.md',
    links: [{
            link: 'https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label',
            linkTitle: i18nLazyString$7(UIStrings$e.labelFormlementsPageTitle),
        }],
};
const genericFormEmptyIdAndNameAttributesForInputError = {
    file: 'genericFormEmptyIdAndNameAttributesForInputError.md',
    links: [{
            link: 'https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input',
            linkTitle: i18nLazyString$7(UIStrings$e.inputFormElementPageTitle),
        }],
};
const genericFormInputAssignedAutocompleteValueToIdOrNameAttributeError = {
    file: 'genericFormInputAssignedAutocompleteValueToIdOrNameAttributeError.md',
    links: [{
            link: 'https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete#values',
            linkTitle: i18nLazyString$7(UIStrings$e.autocompleteAttributePageTitle),
        }],
};
const genericFormInputHasWrongButWellIntendedAutocompleteValue = {
    file: 'genericFormInputHasWrongButWellIntendedAutocompleteValueError.md',
    links: [{
            link: 'https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete#values',
            linkTitle: i18nLazyString$7(UIStrings$e.autocompleteAttributePageTitle),
        }],
};
const genericFormLabelForMatchesNonExistingIdError = {
    file: 'genericFormLabelForMatchesNonExistingIdError.md',
    links: [{
            link: 'https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label',
            linkTitle: i18nLazyString$7(UIStrings$e.labelFormlementsPageTitle),
        }],
};
const genericFormLabelHasNeitherForNorNestedInputError = {
    file: 'genericFormLabelHasNeitherForNorNestedInputError.md',
    links: [{
            link: 'https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label',
            linkTitle: i18nLazyString$7(UIStrings$e.labelFormlementsPageTitle),
        }],
};
const genericResponseWasBlockedbyORB = {
    file: 'genericResponseWasBlockedByORB.md',
    links: [{
            link: 'https://www.chromium.org/Home/chromium-security/corb-for-developers/',
            linkTitle: i18nLazyString$7(UIStrings$e.corbExplainerPageTitle),
        }],
};
const genericNavigationEntryMarkedSkippable = {
    file: 'genericNavigationEntryMarkedSkippable.md',
    links: [{
            link: 'https://chromium.googlesource.com/chromium/src/+/main/docs/history_manipulation_intervention.md',
            linkTitle: i18nLazyString$7(UIStrings$e.historyManipulationInterventionPageTitle),
        }],
};
const issueDescriptions$4 = new Map([
    ["FormLabelForNameError" , genericFormLabelForNameError],
    ["FormInputWithNoLabelError" , genericFormInputWithNoLabelError],
    [
        "FormAutocompleteAttributeEmptyError" ,
        genericFormAutocompleteAttributeEmptyError,
    ],
    ["FormDuplicateIdForInputError" , genericFormDuplicateIdForInputError],
    [
        "FormAriaLabelledByToNonExistingIdError" ,
        genericFormAriaLabelledByToNonExistingIdError
    ],
    [
        "FormEmptyIdAndNameAttributesForInputError" ,
        genericFormEmptyIdAndNameAttributesForInputError,
    ],
    [
        "FormInputAssignedAutocompleteValueToIdOrNameAttributeError" ,
        genericFormInputAssignedAutocompleteValueToIdOrNameAttributeError,
    ],
    [
        "FormLabelForMatchesNonExistingIdError" ,
        genericFormLabelForMatchesNonExistingIdError,
    ],
    [
        "FormLabelHasNeitherForNorNestedInputError" ,
        genericFormLabelHasNeitherForNorNestedInputError,
    ],
    [
        "FormInputHasWrongButWellIntendedAutocompleteValueError" ,
        genericFormInputHasWrongButWellIntendedAutocompleteValue,
    ],
    [
        "ResponseWasBlockedByORB" ,
        genericResponseWasBlockedbyORB,
    ],
    [
        "NavigationEntryMarkedSkippable" ,
        genericNavigationEntryMarkedSkippable,
    ],
]);
const issueTypes = new Map([
    ["FormLabelForNameError" , "PageError" ],
    ["FormInputWithNoLabelError" , "Improvement" ],
    ["FormAutocompleteAttributeEmptyError" , "PageError" ],
    ["FormDuplicateIdForInputError" , "PageError" ],
    ["FormAriaLabelledByToNonExistingIdError" , "Improvement" ],
    ["FormEmptyIdAndNameAttributesForInputError" , "Improvement" ],
    [
        "FormInputAssignedAutocompleteValueToIdOrNameAttributeError" ,
        "Improvement" ,
    ],
    ["FormLabelForMatchesNonExistingIdError" , "PageError" ],
    ["FormLabelHasNeitherForNorNestedInputError" , "Improvement" ],
    ["FormInputHasWrongButWellIntendedAutocompleteValueError" , "Improvement" ],
]);

// Copyright 2020 The Chromium Authors
const UIStrings$d = {
    handlingHeavyAdInterventions: 'Handling Heavy Ad Interventions',
};
const str_$d = registerUIStrings('models/issues_manager/HeavyAdIssue.ts', UIStrings$d);
const i18nString$6 = getLocalizedString.bind(undefined, str_$d);
class HeavyAdIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        const umaCode = ["HeavyAdIssue" , issueDetails.reason].join('::');
        super({ code: "HeavyAdIssue" , umaCode }, issueDetails, issuesModel);
    }
    primaryKey() {
        return `${"HeavyAdIssue" }-${JSON.stringify(this.details())}`;
    }
    getDescription() {
        return {
            file: 'heavyAd.md',
            links: [
                {
                    link: 'https://developers.google.com/web/updates/2020/05/heavy-ad-interventions',
                    linkTitle: i18nString$6(UIStrings$d.handlingHeavyAdInterventions),
                },
            ],
        };
    }
    getCategory() {
        return "HeavyAd" ;
    }
    getKind() {
        switch (this.details().resolution) {
            case "HeavyAdBlocked" :
                return "PageError" ;
            case "HeavyAdWarning" :
                return "BreakingChange" ;
        }
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const heavyAdIssueDetails = inspectorIssue.details.heavyAdIssueDetails;
        if (!heavyAdIssueDetails) {
            console.warn('Heavy Ad issue without details received.');
            return [];
        }
        return [new HeavyAdIssue(heavyAdIssueDetails, issuesModel)];
    }
}

// Copyright 2020 The Chromium Authors
const UIStrings$c = {
    colorAndContrastAccessibility: 'Color and contrast accessibility',
};
const str_$c = registerUIStrings('models/issues_manager/LowTextContrastIssue.ts', UIStrings$c);
const i18nString$5 = getLocalizedString.bind(undefined, str_$c);
class LowTextContrastIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super('LowTextContrastIssue', issueDetails, issuesModel);
    }
    primaryKey() {
        return `${this.code()}-(${this.details().violatingNodeId})`;
    }
    getCategory() {
        return "LowTextContrast" ;
    }
    getDescription() {
        return {
            file: 'LowTextContrast.md',
            links: [
                {
                    link: 'https://web.dev/color-and-contrast-accessibility/',
                    linkTitle: i18nString$5(UIStrings$c.colorAndContrastAccessibility),
                },
            ],
        };
    }
    getKind() {
        return "Improvement" ;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const lowTextContrastIssueDetails = inspectorIssue.details.lowTextContrastIssueDetails;
        if (!lowTextContrastIssueDetails) {
            console.warn('LowTextContrast issue without details received.');
            return [];
        }
        return [new LowTextContrastIssue(lowTextContrastIssueDetails, issuesModel)];
    }
}

// Copyright 2020 The Chromium Authors
const UIStrings$b = {
    preventingMixedContent: 'Preventing mixed content',
};
const str_$b = registerUIStrings('models/issues_manager/MixedContentIssue.ts', UIStrings$b);
const i18nString$4 = getLocalizedString.bind(undefined, str_$b);
class MixedContentIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super("MixedContentIssue" , issueDetails, issuesModel);
    }
    requests() {
        const details = this.details();
        if (details.request) {
            return [details.request];
        }
        return [];
    }
    getCategory() {
        return "MixedContent" ;
    }
    getDescription() {
        return {
            file: 'mixedContent.md',
            links: [{ link: 'https://web.dev/what-is-mixed-content/', linkTitle: i18nString$4(UIStrings$b.preventingMixedContent) }],
        };
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getKind() {
        switch (this.details().resolutionStatus) {
            case "MixedContentAutomaticallyUpgraded" :
                return "Improvement" ;
            case "MixedContentBlocked" :
                return "PageError" ;
            case "MixedContentWarning" :
                return "Improvement" ;
        }
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const mixedContentDetails = inspectorIssue.details.mixedContentIssueDetails;
        if (!mixedContentDetails) {
            console.warn('Mixed content issue without details received.');
            return [];
        }
        return [new MixedContentIssue(mixedContentDetails, issuesModel)];
    }
}

// Copyright 2025 The Chromium Authors
const UIStrings$a = {
    partitioningBlobURL: 'Partitioning BlobURL',
    chromeStatusEntry: 'Chrome Status Entry'
};
const str_$a = registerUIStrings('models/issues_manager/PartitioningBlobURLIssue.ts', UIStrings$a);
const i18nString$3 = getLocalizedString.bind(undefined, str_$a);
class PartitioningBlobURLIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super("PartitioningBlobURLIssue" , issueDetails, issuesModel);
    }
    getCategory() {
        return "Other" ;
    }
    getDescription() {
        const fileName = this.details().partitioningBlobURLInfo ===
            "BlockedCrossPartitionFetching"  ?
            'fetchingPartitionedBlobURL.md' :
            'navigatingPartitionedBlobURL.md';
        return {
            file: fileName,
            links: [
                {
                    link: 'https://developers.google.com/privacy-sandbox/cookies/storage-partitioning',
                    linkTitle: i18nString$3(UIStrings$a.partitioningBlobURL),
                },
                {
                    link: 'https://chromestatus.com/feature/5130361898795008',
                    linkTitle: i18nString$3(UIStrings$a.chromeStatusEntry),
                },
            ],
        };
    }
    getKind() {
        return "BreakingChange" ;
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const details = inspectorIssue.details.partitioningBlobURLIssueDetails;
        if (!details) {
            console.warn('Partitioning BlobURL issue without details received.');
            return [];
        }
        return [new PartitioningBlobURLIssue(details, issuesModel)];
    }
}

// Copyright 2025 The Chromium Authors
class PermissionElementIssue extends Issue {
    #issueDetails;
    constructor(issueDetails, issuesModel) {
        const issueCode = [
            "PermissionElementIssue" ,
            issueDetails.issueType,
        ].join('::');
        super(issueCode, issueDetails, issuesModel);
        this.#issueDetails = issueDetails;
    }
    getCategory() {
        return "PermissionElement" ;
    }
    getDescription() {
        const issueType = this.#issueDetails.issueType;
        switch (issueType) {
            case "InvalidType" :
                return {
                    file: 'permissionElementInvalidType.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "FencedFrameDisallowed" :
                return {
                    file: 'permissionElementFencedFrameDisallowed.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "CspFrameAncestorsMissing" :
                return {
                    file: 'permissionElementCspFrameAncestorsMissing.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "PermissionsPolicyBlocked" :
                return {
                    file: 'permissionElementPermissionsPolicyBlocked.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                        ['PLACEHOLDER_PermissionName', this.#issueDetails.permissionName || ''],
                    ]),
                    links: [],
                };
            case "PaddingRightUnsupported" :
                return {
                    file: 'permissionElementPaddingRightUnsupported.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "PaddingBottomUnsupported" :
                return {
                    file: 'permissionElementPaddingBottomUnsupported.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "InsetBoxShadowUnsupported" :
                return {
                    file: 'permissionElementInsetBoxShadowUnsupported.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "RequestInProgress" :
                return {
                    file: 'permissionElementRequestInProgress.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "UntrustedEvent" :
                return {
                    file: 'permissionElementUntrustedEvent.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "RegistrationFailed" :
                return {
                    file: 'permissionElementRegistrationFailed.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "TypeNotSupported" :
                return {
                    file: 'permissionElementTypeNotSupported.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "InvalidTypeActivation" :
                return {
                    file: 'permissionElementInvalidTypeActivation.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "SecurityChecksFailed" :
                return {
                    file: 'permissionElementSecurityChecksFailed.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "ActivationDisabled" : {
                if (this.#issueDetails.occluderNodeInfo && this.#issueDetails.occluderParentNodeInfo) {
                    return {
                        file: 'permissionElementActivationDisabledWithOccluderParent.md',
                        substitutions: new Map([
                            ['PLACEHOLDER_DisableReason', this.#issueDetails.disableReason || ''],
                            ['PLACEHOLDER_OccluderInfo', this.#issueDetails.occluderNodeInfo || ''],
                            ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                            ['PLACEHOLDER_OccluderParentInfo', this.#issueDetails.occluderParentNodeInfo || ''],
                        ]),
                        links: [],
                    };
                }
                if (this.#issueDetails.occluderNodeInfo) {
                    return {
                        file: 'permissionElementActivationDisabledWithOccluder.md',
                        substitutions: new Map([
                            ['PLACEHOLDER_DisableReason', this.#issueDetails.disableReason || ''],
                            ['PLACEHOLDER_OccluderInfo', this.#issueDetails.occluderNodeInfo || ''],
                            ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                        ]),
                        links: [],
                    };
                }
                return {
                    file: 'permissionElementActivationDisabled.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_DisableReason', this.#issueDetails.disableReason || ''],
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            }
            case "GeolocationDeprecated" :
                return {
                    file: 'permissionElementGeolocationDeprecated.md',
                    links: [],
                };
            case "InvalidDisplayStyle" :
                return {
                    file: 'permissionElementInvalidDisplayStyle.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "NonOpaqueColor" :
                return {
                    file: 'permissionElementNonOpaqueColor.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "LowContrast" :
                return {
                    file: 'permissionElementLowContrast.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "FontSizeTooSmall" :
                return {
                    file: 'permissionElementFontSizeTooSmall.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "FontSizeTooLarge" :
                return {
                    file: 'permissionElementFontSizeTooLarge.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            case "InvalidSizeValue" :
                return {
                    file: 'permissionElementInvalidSizeValue.md',
                    substitutions: new Map([
                        ['PLACEHOLDER_Type', this.#issueDetails.type || ''],
                    ]),
                    links: [],
                };
            default:
                console.warn('Unknown PermissionElementIssueType:', issueType);
                return null;
        }
    }
    elements() {
        if (this.#issueDetails.nodeId) {
            const target = this.model()?.target();
            const result = [{
                    backendNodeId: this.#issueDetails.nodeId,
                    nodeName: this.#issueDetails.type || 'Affected element',
                    target: target || null,
                }];
            return result;
        }
        return [];
    }
    getKind() {
        return this.#issueDetails.isWarning ? "Improvement"  : "PageError" ;
    }
    primaryKey() {
        return `${"PermissionElementIssue" }-${JSON.stringify(this.#issueDetails)}`;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const permissionElementIssueDetails = inspectorIssue.details.permissionElementIssueDetails;
        if (!permissionElementIssueDetails) {
            console.warn('Permission element issue without details received.');
            return [];
        }
        return [new PermissionElementIssue(permissionElementIssueDetails, issuesModel)];
    }
}

// Copyright 2021 The Chromium Authors
const UIStrings$9 = {
    documentCompatibilityMode: 'Document compatibility mode',
};
const str_$9 = registerUIStrings('models/issues_manager/QuirksModeIssue.ts', UIStrings$9);
const i18nString$2 = getLocalizedString.bind(undefined, str_$9);
class QuirksModeIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        const mode = issueDetails.isLimitedQuirksMode ? 'LimitedQuirksMode' : 'QuirksMode';
        const umaCode = ["QuirksModeIssue" , mode].join('::');
        super({ code: "QuirksModeIssue" , umaCode }, issueDetails, issuesModel);
    }
    primaryKey() {
        return `${this.code()}-(${this.details().documentNodeId})-(${this.details().url})`;
    }
    getCategory() {
        return "QuirksMode" ;
    }
    getDescription() {
        return {
            file: 'CompatibilityModeQuirks.md',
            links: [
                {
                    link: 'https://web.dev/doctype/',
                    linkTitle: i18nString$2(UIStrings$9.documentCompatibilityMode),
                },
            ],
        };
    }
    getKind() {
        return "Improvement" ;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const quirksModeIssueDetails = inspectorIssue.details.quirksModeIssueDetails;
        if (!quirksModeIssueDetails) {
            console.warn('Quirks Mode issue without details received.');
            return [];
        }
        return [new QuirksModeIssue(quirksModeIssueDetails, issuesModel)];
    }
}

// Copyright 2020 The Chromium Authors
const UIStrings$8 = {
    enablingSharedArrayBuffer: 'Enabling `SharedArrayBuffer`',
};
const str_$8 = registerUIStrings('models/issues_manager/SharedArrayBufferIssue.ts', UIStrings$8);
const i18nString$1 = getLocalizedString.bind(undefined, str_$8);
class SharedArrayBufferIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        const umaCode = ["SharedArrayBufferIssue" , issueDetails.type].join('::');
        super({ code: "SharedArrayBufferIssue" , umaCode }, issueDetails, issuesModel);
    }
    getCategory() {
        return "Other" ;
    }
    getDescription() {
        return {
            file: 'sharedArrayBuffer.md',
            links: [{
                    link: 'https://developer.chrome.com/blog/enabling-shared-array-buffer/',
                    linkTitle: i18nString$1(UIStrings$8.enablingSharedArrayBuffer),
                }],
        };
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getKind() {
        if (this.details().isWarning) {
            return "BreakingChange" ;
        }
        return "PageError" ;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const sabIssueDetails = inspectorIssue.details.sharedArrayBufferIssueDetails;
        if (!sabIssueDetails) {
            console.warn('SAB transfer issue without details received.');
            return [];
        }
        return [new SharedArrayBufferIssue(sabIssueDetails, issuesModel)];
    }
}

// Copyright 2020 The Chromium Authors
class AggregatedIssue extends Issue {
    #allIssues = new Set();
    #affectedCookies = new Map();
    #affectedRawCookieLines = new Map();
    #affectedRequests = [];
    #affectedRequestIds = new Set();
    #affectedLocations = new Map();
    #heavyAdIssues = new Set();
    #blockedByResponseDetails = new Map();
    #bounceTrackingSites = new Set();
    #corsIssues = new Set();
    #cspIssues = new Set();
    #deprecationIssues = new Set();
    #issueKind = "Improvement" ;
    #lowContrastIssues = new Set();
    #cookieDeprecationMetadataIssues = new Set();
    #mixedContentIssues = new Set();
    #partitioningBlobURLIssues = new Set();
    #permissionElementIssues = new Set();
    #sharedArrayBufferIssues = new Set();
    #quirksModeIssues = new Set();
    #attributionReportingIssues = new Set();
    #genericIssues = new Set();
    #elementAccessibilityIssues = new Set();
    #representative;
    #aggregatedIssuesCount = 0;
    #key;
    constructor(code, aggregationKey) {
        super(code, null);
        this.#key = aggregationKey;
    }
    primaryKey() {
        throw new Error('This should never be called');
    }
    aggregationKey() {
        return this.#key;
    }
    getBlockedByResponseDetails() {
        return this.#blockedByResponseDetails.values();
    }
    cookies() {
        return Array.from(this.#affectedCookies.values()).map(x => x.cookie);
    }
    getRawCookieLines() {
        return this.#affectedRawCookieLines.values();
    }
    sources() {
        return this.#affectedLocations.values();
    }
    getBounceTrackingSites() {
        return this.#bounceTrackingSites.values();
    }
    cookiesWithRequestIndicator() {
        return this.#affectedCookies.values();
    }
    getHeavyAdIssues() {
        return this.#heavyAdIssues;
    }
    getCookieDeprecationMetadataIssues() {
        return this.#cookieDeprecationMetadataIssues;
    }
    getMixedContentIssues() {
        return this.#mixedContentIssues;
    }
    getCorsIssues() {
        return this.#corsIssues;
    }
    getCspIssues() {
        return this.#cspIssues;
    }
    getDeprecationIssues() {
        return this.#deprecationIssues;
    }
    getLowContrastIssues() {
        return this.#lowContrastIssues;
    }
    requests() {
        return this.#affectedRequests.values();
    }
    getSharedArrayBufferIssues() {
        return this.#sharedArrayBufferIssues;
    }
    getQuirksModeIssues() {
        return this.#quirksModeIssues;
    }
    getAttributionReportingIssues() {
        return this.#attributionReportingIssues;
    }
    getGenericIssues() {
        return this.#genericIssues;
    }
    getElementAccessibilityIssues() {
        return this.#elementAccessibilityIssues;
    }
    getDescription() {
        if (this.#representative) {
            return this.#representative.getDescription();
        }
        return null;
    }
    getCategory() {
        if (this.#representative) {
            return this.#representative.getCategory();
        }
        return "Other" ;
    }
    getAggregatedIssuesCount() {
        return this.#aggregatedIssuesCount;
    }
    getPartitioningBlobURLIssues() {
        return this.#partitioningBlobURLIssues;
    }
    getPermissionElementIssues() {
        return this.#permissionElementIssues;
    }
    #keyForCookie(cookie) {
        const { domain, path, name } = cookie;
        return `${domain};${path};${name}`;
    }
    addInstance(issue) {
        this.#aggregatedIssuesCount++;
        if (!this.#representative) {
            this.#representative = issue;
        }
        this.#allIssues.add(issue);
        this.#issueKind = unionIssueKind(this.#issueKind, issue.getKind());
        let hasRequest = false;
        for (const request of issue.requests()) {
            const { requestId } = request;
            hasRequest = true;
            if (requestId === undefined) {
                this.#affectedRequests.push(request);
            }
            else if (!this.#affectedRequestIds.has(requestId)) {
                this.#affectedRequests.push(request);
                this.#affectedRequestIds.add(requestId);
            }
        }
        for (const cookie of issue.cookies()) {
            const key = this.#keyForCookie(cookie);
            if (!this.#affectedCookies.has(key)) {
                this.#affectedCookies.set(key, { cookie, hasRequest });
            }
        }
        for (const rawCookieLine of issue.rawCookieLines()) {
            if (!this.#affectedRawCookieLines.has(rawCookieLine)) {
                this.#affectedRawCookieLines.set(rawCookieLine, { rawCookieLine, hasRequest });
            }
        }
        for (const site of issue.trackingSites()) {
            if (!this.#bounceTrackingSites.has(site)) {
                this.#bounceTrackingSites.add(site);
            }
        }
        for (const location of issue.sources()) {
            const key = JSON.stringify(location);
            if (!this.#affectedLocations.has(key)) {
                this.#affectedLocations.set(key, location);
            }
        }
        if (issue instanceof CookieDeprecationMetadataIssue) {
            this.#cookieDeprecationMetadataIssues.add(issue);
        }
        if (issue instanceof MixedContentIssue) {
            this.#mixedContentIssues.add(issue);
        }
        if (issue instanceof HeavyAdIssue) {
            this.#heavyAdIssues.add(issue);
        }
        for (const details of issue.getBlockedByResponseDetails()) {
            const key = JSON.stringify(details, ['parentFrame', 'blockedFrame', 'requestId', 'frameId', 'reason', 'request']);
            this.#blockedByResponseDetails.set(key, details);
        }
        if (issue instanceof ContentSecurityPolicyIssue) {
            this.#cspIssues.add(issue);
        }
        if (issue instanceof DeprecationIssue) {
            this.#deprecationIssues.add(issue);
        }
        if (issue instanceof SharedArrayBufferIssue) {
            this.#sharedArrayBufferIssues.add(issue);
        }
        if (issue instanceof LowTextContrastIssue) {
            this.#lowContrastIssues.add(issue);
        }
        if (issue instanceof CorsIssue) {
            this.#corsIssues.add(issue);
        }
        if (issue instanceof QuirksModeIssue) {
            this.#quirksModeIssues.add(issue);
        }
        if (issue instanceof AttributionReportingIssue) {
            this.#attributionReportingIssues.add(issue);
        }
        if (issue instanceof GenericIssue) {
            this.#genericIssues.add(issue);
        }
        if (issue instanceof ElementAccessibilityIssue) {
            this.#elementAccessibilityIssues.add(issue);
        }
        if (issue instanceof PartitioningBlobURLIssue) {
            this.#partitioningBlobURLIssues.add(issue);
        }
        if (issue instanceof PermissionElementIssue) {
            this.#permissionElementIssues.add(issue);
        }
    }
    getKind() {
        return this.#issueKind;
    }
    getAllIssues() {
        return Array.from(this.#allIssues);
    }
    isHidden() {
        return this.#representative?.isHidden() || false;
    }
    setHidden(_value) {
        throw new Error('Should not call setHidden on aggregatedIssue');
    }
}
class IssueAggregator extends ObjectWrapper {
    issuesManager;
    #aggregatedIssuesByKey = new Map();
    #hiddenAggregatedIssuesByKey = new Map();
    constructor(issuesManager) {
        super();
        this.issuesManager = issuesManager;
        this.issuesManager.addEventListener("IssueAdded" , this.#onIssueAdded, this);
        this.issuesManager.addEventListener("FullUpdateRequired" , this.#onFullUpdateRequired, this);
        for (const issue of this.issuesManager.issues()) {
            this.#aggregateIssue(issue);
        }
    }
    #onIssueAdded(event) {
        this.#aggregateIssue(event.data.issue);
    }
    #onFullUpdateRequired() {
        this.#aggregatedIssuesByKey.clear();
        this.#hiddenAggregatedIssuesByKey.clear();
        for (const issue of this.issuesManager.issues()) {
            this.#aggregateIssue(issue);
        }
        this.dispatchEventToListeners("FullUpdateRequired" );
    }
    #aggregateIssue(issue) {
        if (CookieIssue.isThirdPartyCookiePhaseoutRelatedIssue(issue)) {
            return;
        }
        const map = issue.isHidden() ? this.#hiddenAggregatedIssuesByKey : this.#aggregatedIssuesByKey;
        const aggregatedIssue = this.#aggregateIssueByStatus(map, issue);
        this.dispatchEventToListeners("AggregatedIssueUpdated" , aggregatedIssue);
        return aggregatedIssue;
    }
    #aggregateIssueByStatus(aggregatedIssuesMap, issue) {
        const key = issue.code();
        let aggregatedIssue = aggregatedIssuesMap.get(key);
        if (!aggregatedIssue) {
            aggregatedIssue = new AggregatedIssue(issue.code(), key);
            aggregatedIssuesMap.set(key, aggregatedIssue);
        }
        aggregatedIssue.addInstance(issue);
        return aggregatedIssue;
    }
    aggregatedIssues() {
        return [...this.#aggregatedIssuesByKey.values(), ...this.#hiddenAggregatedIssuesByKey.values()];
    }
    aggregatedIssueCodes() {
        return new Set([...this.#aggregatedIssuesByKey.keys(), ...this.#hiddenAggregatedIssuesByKey.keys()]);
    }
    aggregatedIssueCategories() {
        const result = new Set();
        for (const issue of this.#aggregatedIssuesByKey.values()) {
            result.add(issue.getCategory());
        }
        return result;
    }
    aggregatedIssueKinds() {
        const result = new Set();
        for (const issue of this.#aggregatedIssuesByKey.values()) {
            result.add(issue.getKind());
        }
        return result;
    }
    numberOfAggregatedIssues() {
        return this.#aggregatedIssuesByKey.size;
    }
    numberOfHiddenAggregatedIssues() {
        return this.#hiddenAggregatedIssuesByKey.size;
    }
    keyForIssue(issue) {
        return issue.code();
    }
}

// Copyright 2023 The Chromium Authors
const UIStrings$7 = {
    bounceTrackingMitigations: 'Bounce tracking mitigations',
};
const str_$7 = registerUIStrings('models/issues_manager/BounceTrackingIssue.ts', UIStrings$7);
const i18nString = getLocalizedString.bind(undefined, str_$7);
class BounceTrackingIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super("BounceTrackingIssue" , issueDetails, issuesModel);
    }
    getCategory() {
        return "Other" ;
    }
    getDescription() {
        return {
            file: 'bounceTrackingMitigations.md',
            links: [
                {
                    link: 'https://privacycg.github.io/nav-tracking-mitigations/#bounce-tracking-mitigations',
                    linkTitle: i18nString(UIStrings$7.bounceTrackingMitigations),
                },
            ],
        };
    }
    getKind() {
        return "BreakingChange" ;
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    trackingSites() {
        return this.details().trackingSites;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const details = inspectorIssue.details.bounceTrackingIssueDetails;
        if (!details) {
            console.warn('Bounce tracking issue without details received.');
            return [];
        }
        return [new BounceTrackingIssue(details, issuesModel)];
    }
}

// Copyright 2021 The Chromium Authors
const UIStrings$6 = {
    clientHintsInfrastructure: 'Client Hints Infrastructure',
};
const str_$6 = registerUIStrings('models/issues_manager/ClientHintIssue.ts', UIStrings$6);
const i18nLazyString$6 = getLazilyComputedLocalizedString.bind(undefined, str_$6);
class ClientHintIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super({
            code: "ClientHintIssue" ,
            umaCode: ["ClientHintIssue" , issueDetails.clientHintIssueReason].join('::'),
        }, issueDetails, issuesModel);
    }
    getCategory() {
        return "Other" ;
    }
    getDescription() {
        const description = issueDescriptions$3.get(this.details().clientHintIssueReason);
        if (!description) {
            return null;
        }
        return resolveLazyDescription(description);
    }
    sources() {
        return [this.details().sourceCodeLocation];
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getKind() {
        return "BreakingChange" ;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const details = inspectorIssue.details.clientHintIssueDetails;
        if (!details) {
            console.warn('Client Hint issue without details received.');
            return [];
        }
        return [new ClientHintIssue(details, issuesModel)];
    }
}
const issueDescriptions$3 = new Map([
    [
        "MetaTagAllowListInvalidOrigin" ,
        {
            file: 'clientHintMetaTagAllowListInvalidOrigin.md',
            links: [{
                    link: 'https://wicg.github.io/client-hints-infrastructure/',
                    linkTitle: i18nLazyString$6(UIStrings$6.clientHintsInfrastructure),
                }],
        },
    ],
    [
        "MetaTagModifiedHTML" ,
        {
            file: 'clientHintMetaTagModifiedHTML.md',
            links: [{
                    link: 'https://wicg.github.io/client-hints-infrastructure/',
                    linkTitle: i18nLazyString$6(UIStrings$6.clientHintsInfrastructure),
                }],
        },
    ],
]);

// Copyright 2026 The Chromium Authors
const UIStrings$5 = {
    connectionAllowlistHeader: 'Connection-Allowlist specification',
};
const str_$5 = registerUIStrings('models/issues_manager/ConnectionAllowlistIssue.ts', UIStrings$5);
const i18nLazyString$5 = getLazilyComputedLocalizedString.bind(undefined, str_$5);
class ConnectionAllowlistIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super({
            code: `${"ConnectionAllowlistIssue" }::${issueDetails.error}`,
            umaCode: `${"ConnectionAllowlistIssue" }::${issueDetails.error}`,
        }, issueDetails, issuesModel);
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getDescription() {
        const description = {
            file: `connectionAllowlist${this.details().error}.md`,
            links: [
                {
                    link: 'https://wicg.github.io/private-network-access/#connection-allowlist',
                    linkTitle: i18nLazyString$5(UIStrings$5.connectionAllowlistHeader),
                },
            ],
        };
        return resolveLazyDescription(description);
    }
    getCategory() {
        return "Other" ;
    }
    getKind() {
        return "PageError" ;
    }
    requests() {
        return this.details().request ? [this.details().request] : [];
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const details = inspectorIssue.details.connectionAllowlistIssueDetails;
        if (!details) {
            console.warn('Connection-Allowlist issue without details received.');
            return [];
        }
        return [new ConnectionAllowlistIssue(details, issuesModel)];
    }
}

// Copyright 2020 The Chromium Authors
const UIStrings$4 = {
    coopAndCoep: 'COOP and COEP',
    samesiteAndSameorigin: 'Same-Site and Same-Origin',
};
const str_$4 = registerUIStrings('models/issues_manager/CrossOriginEmbedderPolicyIssue.ts', UIStrings$4);
const i18nLazyString$4 = getLazilyComputedLocalizedString.bind(undefined, str_$4);
function isCrossOriginEmbedderPolicyIssue(reason) {
    switch (reason) {
        case "CoepFrameResourceNeedsCoepHeader" :
            return true;
        case "CoopSandboxedIFrameCannotNavigateToCoopPage" :
            return true;
        case "CorpNotSameOrigin" :
            return true;
        case "CorpNotSameOriginAfterDefaultedToSameOriginByCoep" :
            return true;
        case "CorpNotSameSite" :
            return true;
    }
    return false;
}
class CrossOriginEmbedderPolicyIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super(`CrossOriginEmbedderPolicyIssue::${issueDetails.reason}`, issueDetails, issuesModel);
    }
    primaryKey() {
        return `${this.code()}-(${this.details().request.requestId})`;
    }
    getBlockedByResponseDetails() {
        return [this.details()];
    }
    requests() {
        return [this.details().request];
    }
    getCategory() {
        return "CrossOriginEmbedderPolicy" ;
    }
    getDescription() {
        const description = issueDescriptions$2.get(this.code());
        if (!description) {
            return null;
        }
        return resolveLazyDescription(description);
    }
    getKind() {
        return "PageError" ;
    }
}
const issueDescriptions$2 = new Map([
    [
        'CrossOriginEmbedderPolicyIssue::CorpNotSameOriginAfterDefaultedToSameOriginByCoep',
        {
            file: 'CoepCorpNotSameOriginAfterDefaultedToSameOriginByCoep.md',
            links: [
                { link: 'https://web.dev/coop-coep/', linkTitle: i18nLazyString$4(UIStrings$4.coopAndCoep) },
                { link: 'https://web.dev/same-site-same-origin/', linkTitle: i18nLazyString$4(UIStrings$4.samesiteAndSameorigin) },
            ],
        },
    ],
    [
        'CrossOriginEmbedderPolicyIssue::CoepFrameResourceNeedsCoepHeader',
        {
            file: 'CoepFrameResourceNeedsCoepHeader.md',
            links: [
                { link: 'https://web.dev/coop-coep/', linkTitle: i18nLazyString$4(UIStrings$4.coopAndCoep) },
            ],
        },
    ],
    [
        'CrossOriginEmbedderPolicyIssue::CoopSandboxedIframeCannotNavigateToCoopPage',
        {
            file: 'CoepCoopSandboxedIframeCannotNavigateToCoopPage.md',
            links: [
                { link: 'https://web.dev/coop-coep/', linkTitle: i18nLazyString$4(UIStrings$4.coopAndCoep) },
            ],
        },
    ],
    [
        'CrossOriginEmbedderPolicyIssue::CorpNotSameSite',
        {
            file: 'CoepCorpNotSameSite.md',
            links: [
                { link: 'https://web.dev/coop-coep/', linkTitle: i18nLazyString$4(UIStrings$4.coopAndCoep) },
                { link: 'https://web.dev/same-site-same-origin/', linkTitle: i18nLazyString$4(UIStrings$4.samesiteAndSameorigin) },
            ],
        },
    ],
    [
        'CrossOriginEmbedderPolicyIssue::CorpNotSameOrigin',
        {
            file: 'CoepCorpNotSameOrigin.md',
            links: [
                { link: 'https://web.dev/coop-coep/', linkTitle: i18nLazyString$4(UIStrings$4.coopAndCoep) },
                { link: 'https://web.dev/same-site-same-origin/', linkTitle: i18nLazyString$4(UIStrings$4.samesiteAndSameorigin) },
            ],
        },
    ],
]);

// Copyright 2022 The Chromium Authors
const UIStrings$3 = {
    fedCm: 'Federated Credential Management API',
};
const str_$3 = registerUIStrings('models/issues_manager/FederatedAuthRequestIssue.ts', UIStrings$3);
const i18nLazyString$3 = getLazilyComputedLocalizedString.bind(undefined, str_$3);
class FederatedAuthRequestIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super({
            code: "FederatedAuthRequestIssue" ,
            umaCode: [
                "FederatedAuthRequestIssue" ,
                issueDetails.federatedAuthRequestIssueReason,
            ].join('::'),
        }, issueDetails, issuesModel);
    }
    getCategory() {
        return "Other" ;
    }
    getDescription() {
        const description = issueDescriptions$1.get(this.details().federatedAuthRequestIssueReason);
        if (!description) {
            return null;
        }
        return resolveLazyDescription(description);
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getKind() {
        return "PageError" ;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const details = inspectorIssue.details.federatedAuthRequestIssueDetails;
        if (!details) {
            console.warn('Federated auth request issue without details received.');
            return [];
        }
        return [new FederatedAuthRequestIssue(details, issuesModel)];
    }
}
const issueDescriptions$1 = new Map([
    [
        "TooManyRequests" ,
        {
            file: 'federatedAuthRequestTooManyRequests.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "ConfigHttpNotFound" ,
        {
            file: 'federatedAuthRequestManifestHttpNotFound.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "ConfigNoResponse" ,
        {
            file: 'federatedAuthRequestManifestNoResponse.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "ConfigInvalidResponse" ,
        {
            file: 'federatedAuthRequestManifestInvalidResponse.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "ErrorFetchingSignin" ,
        {
            file: 'federatedAuthRequestErrorFetchingSignin.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "InvalidSigninResponse" ,
        {
            file: 'federatedAuthRequestInvalidSigninResponse.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "AccountsHttpNotFound" ,
        {
            file: 'federatedAuthRequestAccountsHttpNotFound.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "AccountsNoResponse" ,
        {
            file: 'federatedAuthRequestAccountsNoResponse.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "AccountsInvalidResponse" ,
        {
            file: 'federatedAuthRequestAccountsInvalidResponse.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "IdTokenHttpNotFound" ,
        {
            file: 'federatedAuthRequestIdTokenHttpNotFound.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "IdTokenNoResponse" ,
        {
            file: 'federatedAuthRequestIdTokenNoResponse.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "IdTokenInvalidResponse" ,
        {
            file: 'federatedAuthRequestIdTokenInvalidResponse.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "IdTokenInvalidRequest" ,
        {
            file: 'federatedAuthRequestIdTokenInvalidRequest.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "ErrorIdToken" ,
        {
            file: 'federatedAuthRequestErrorIdToken.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
    [
        "Canceled" ,
        {
            file: 'federatedAuthRequestCanceled.md',
            links: [{
                    link: 'https://fedidcg.github.io/FedCM/',
                    linkTitle: i18nLazyString$3(UIStrings$3.fedCm),
                }],
        },
    ],
]);

// Copyright 2023 The Chromium Authors
class PropertyRuleIssue extends Issue {
    #primaryKey;
    constructor(issueDetails, issuesModel) {
        const code = JSON.stringify(issueDetails);
        super(code, issueDetails, issuesModel);
        this.#primaryKey = code;
    }
    sources() {
        return [this.details().sourceCodeLocation];
    }
    primaryKey() {
        return this.#primaryKey;
    }
    getPropertyName() {
        switch (this.details().propertyRuleIssueReason) {
            case "InvalidInherits" :
                return 'inherits';
            case "InvalidInitialValue" :
                return 'initial-value';
            case "InvalidSyntax" :
                return 'syntax';
        }
        return '';
    }
    getDescription() {
        if (this.details().propertyRuleIssueReason === "InvalidName" ) {
            return {
                file: 'propertyRuleInvalidNameIssue.md',
                links: [],
            };
        }
        const value = this.details().propertyValue ? `: ${this.details().propertyValue}` : '';
        const property = `${this.getPropertyName()}${value}`;
        return {
            file: 'propertyRuleIssue.md',
            substitutions: new Map([['PLACEHOLDER_property', property]]),
            links: [],
        };
    }
    getCategory() {
        return "Other" ;
    }
    getKind() {
        return "PageError" ;
    }
    static fromInspectorIssue(issueModel, inspectorIssue) {
        const propertyRuleIssueDetails = inspectorIssue.details.propertyRuleIssueDetails;
        if (!propertyRuleIssueDetails) {
            console.warn('Property rule issue without details received');
            return [];
        }
        return [new PropertyRuleIssue(propertyRuleIssueDetails, issueModel)];
    }
}

// Copyright 2023 The Chromium Authors
const UIStrings$2 = {
    compressionDictionaryTransport: 'Compression Dictionary Transport',
};
const str_$2 = registerUIStrings('models/issues_manager/SharedDictionaryIssue.ts', UIStrings$2);
const i18nLazyString$2 = getLazilyComputedLocalizedString.bind(undefined, str_$2);
function getIssueCode(details) {
    switch (details.sharedDictionaryError) {
        case "UseErrorCrossOriginNoCorsRequest" :
            return "SharedDictionaryIssue::UseErrorCrossOriginNoCorsRequest" ;
        case "UseErrorDictionaryLoadFailure" :
            return "SharedDictionaryIssue::UseErrorDictionaryLoadFailure" ;
        case "UseErrorMatchingDictionaryNotUsed" :
            return "SharedDictionaryIssue::UseErrorMatchingDictionaryNotUsed" ;
        case "UseErrorUnexpectedContentDictionaryHeader" :
            return "SharedDictionaryIssue::UseErrorUnexpectedContentDictionaryHeader" ;
        case "WriteErrorCossOriginNoCorsRequest" :
            return "SharedDictionaryIssue::WriteErrorCossOriginNoCorsRequest" ;
        case "WriteErrorDisallowedBySettings" :
            return "SharedDictionaryIssue::WriteErrorDisallowedBySettings" ;
        case "WriteErrorExpiredResponse" :
            return "SharedDictionaryIssue::WriteErrorExpiredResponse" ;
        case "WriteErrorFeatureDisabled" :
            return "SharedDictionaryIssue::WriteErrorFeatureDisabled" ;
        case "WriteErrorInsufficientResources" :
            return "SharedDictionaryIssue::WriteErrorInsufficientResources" ;
        case "WriteErrorInvalidMatchField" :
            return "SharedDictionaryIssue::WriteErrorInvalidMatchField" ;
        case "WriteErrorInvalidStructuredHeader" :
            return "SharedDictionaryIssue::WriteErrorInvalidStructuredHeader" ;
        case "WriteErrorInvalidTTLField" :
            return "SharedDictionaryIssue::WriteErrorInvalidTTLField" ;
        case "WriteErrorNavigationRequest" :
            return "SharedDictionaryIssue::WriteErrorNavigationRequest" ;
        case "WriteErrorNoMatchField" :
            return "SharedDictionaryIssue::WriteErrorNoMatchField" ;
        case "WriteErrorNonIntegerTTLField" :
            return "SharedDictionaryIssue::WriteErrorNonIntegerTTLField" ;
        case "WriteErrorNonListMatchDestField" :
            return "SharedDictionaryIssue::WriteErrorNonListMatchDestField" ;
        case "WriteErrorNonSecureContext" :
            return "SharedDictionaryIssue::WriteErrorNonSecureContext" ;
        case "WriteErrorNonStringIdField" :
            return "SharedDictionaryIssue::WriteErrorNonStringIdField" ;
        case "WriteErrorNonStringInMatchDestList" :
            return "SharedDictionaryIssue::WriteErrorNonStringInMatchDestList" ;
        case "WriteErrorNonStringMatchField" :
            return "SharedDictionaryIssue::WriteErrorNonStringMatchField" ;
        case "WriteErrorNonTokenTypeField" :
            return "SharedDictionaryIssue::WriteErrorNonTokenTypeField" ;
        case "WriteErrorRequestAborted" :
            return "SharedDictionaryIssue::WriteErrorRequestAborted" ;
        case "WriteErrorShuttingDown" :
            return "SharedDictionaryIssue::WriteErrorShuttingDown" ;
        case "WriteErrorTooLongIdField" :
            return "SharedDictionaryIssue::WriteErrorTooLongIdField" ;
        case "WriteErrorUnsupportedType" :
            return "SharedDictionaryIssue::WriteErrorUnsupportedType" ;
        default:
            return "SharedDictionaryIssue::WriteErrorUnknown" ;
    }
}
class SharedDictionaryIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super({
            code: getIssueCode(issueDetails),
            umaCode: [
                "SharedDictionaryIssue" ,
                issueDetails.sharedDictionaryError,
            ].join('::'),
        }, issueDetails, issuesModel);
    }
    requests() {
        if (this.details().request) {
            return [this.details().request];
        }
        return [];
    }
    getCategory() {
        return "Other" ;
    }
    getDescription() {
        const description = issueDescriptions.get(this.details().sharedDictionaryError);
        if (!description) {
            return null;
        }
        return resolveLazyDescription(description);
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getKind() {
        return "PageError" ;
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const details = inspectorIssue.details.sharedDictionaryIssueDetails;
        if (!details) {
            console.warn('Shared Dictionary issue without details received.');
            return [];
        }
        return [new SharedDictionaryIssue(details, issuesModel)];
    }
}
const specLinks = [{
        link: 'https://datatracker.ietf.org/doc/draft-ietf-httpbis-compression-dictionary/',
        linkTitle: i18nLazyString$2(UIStrings$2.compressionDictionaryTransport),
    }];
const issueDescriptions = new Map([
    [
        "UseErrorCrossOriginNoCorsRequest" ,
        {
            file: 'sharedDictionaryUseErrorCrossOriginNoCorsRequest.md',
            links: specLinks,
        },
    ],
    [
        "UseErrorDictionaryLoadFailure" ,
        {
            file: 'sharedDictionaryUseErrorDictionaryLoadFailure.md',
            links: specLinks,
        },
    ],
    [
        "UseErrorMatchingDictionaryNotUsed" ,
        {
            file: 'sharedDictionaryUseErrorMatchingDictionaryNotUsed.md',
            links: specLinks,
        },
    ],
    [
        "UseErrorUnexpectedContentDictionaryHeader" ,
        {
            file: 'sharedDictionaryUseErrorUnexpectedContentDictionaryHeader.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorCossOriginNoCorsRequest" ,
        {
            file: 'sharedDictionaryWriteErrorCossOriginNoCorsRequest.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorDisallowedBySettings" ,
        {
            file: 'sharedDictionaryWriteErrorDisallowedBySettings.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorExpiredResponse" ,
        {
            file: 'sharedDictionaryWriteErrorExpiredResponse.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorFeatureDisabled" ,
        {
            file: 'sharedDictionaryWriteErrorFeatureDisabled.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorInsufficientResources" ,
        {
            file: 'sharedDictionaryWriteErrorInsufficientResources.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorInvalidMatchField" ,
        {
            file: 'sharedDictionaryWriteErrorInvalidMatchField.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorInvalidStructuredHeader" ,
        {
            file: 'sharedDictionaryWriteErrorInvalidStructuredHeader.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorInvalidTTLField" ,
        {
            file: 'sharedDictionaryWriteErrorInvalidTTLField.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorNavigationRequest" ,
        {
            file: 'sharedDictionaryWriteErrorNavigationRequest.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorNoMatchField" ,
        {
            file: 'sharedDictionaryWriteErrorNoMatchField.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorNonIntegerTTLField" ,
        {
            file: 'sharedDictionaryWriteErrorNonIntegerTTLField.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorNonListMatchDestField" ,
        {
            file: 'sharedDictionaryWriteErrorNonListMatchDestField.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorNonSecureContext" ,
        {
            file: 'sharedDictionaryWriteErrorNonSecureContext.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorNonStringIdField" ,
        {
            file: 'sharedDictionaryWriteErrorNonStringIdField.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorNonStringInMatchDestList" ,
        {
            file: 'sharedDictionaryWriteErrorNonStringInMatchDestList.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorNonStringMatchField" ,
        {
            file: 'sharedDictionaryWriteErrorNonStringMatchField.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorNonTokenTypeField" ,
        {
            file: 'sharedDictionaryWriteErrorNonTokenTypeField.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorRequestAborted" ,
        {
            file: 'sharedDictionaryWriteErrorRequestAborted.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorShuttingDown" ,
        {
            file: 'sharedDictionaryWriteErrorShuttingDown.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorTooLongIdField" ,
        {
            file: 'sharedDictionaryWriteErrorTooLongIdField.md',
            links: specLinks,
        },
    ],
    [
        "WriteErrorUnsupportedType" ,
        {
            file: 'sharedDictionaryWriteErrorUnsupportedType.md',
            links: specLinks,
        },
    ],
]);

// Copyright 2023 The Chromium Authors
const lateImportStylesheetLoadingCode = [
    "StylesheetLoadingIssue" ,
    "LateImportRule" ,
].join('::');
class StylesheetLoadingIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        const code = `${"StylesheetLoadingIssue" }::${issueDetails.styleSheetLoadingIssueReason}`;
        super(code, issueDetails, issuesModel);
    }
    sources() {
        return [this.details().sourceCodeLocation];
    }
    requests() {
        const details = this.details();
        if (!details.failedRequestInfo) {
            return [];
        }
        const { url, requestId } = details.failedRequestInfo;
        if (!requestId) {
            return [];
        }
        return [{ url, requestId }];
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getDescription() {
        switch (this.details().styleSheetLoadingIssueReason) {
            case "LateImportRule" :
                return {
                    file: 'stylesheetLateImport.md',
                    links: [],
                };
            case "RequestFailed" :
                return {
                    file: 'stylesheetRequestFailed.md',
                    links: [],
                };
        }
    }
    getCategory() {
        return "Other" ;
    }
    getKind() {
        return "PageError" ;
    }
    static fromInspectorIssue(issueModel, inspectorIssue) {
        const stylesheetLoadingDetails = inspectorIssue.details.stylesheetLoadingIssueDetails;
        if (!stylesheetLoadingDetails) {
            console.warn('Stylesheet loading issue without details received');
            return [];
        }
        return [new StylesheetLoadingIssue(stylesheetLoadingDetails, issueModel)];
    }
}

// Copyright 2020 The Chromium Authors
class SourceFrameIssuesManager {
    issuesManager;
    #sourceFrameMessageManager = new PresentationSourceFrameMessageManager();
    constructor(issuesManager) {
        this.issuesManager = issuesManager;
        this.issuesManager.addEventListener("IssueAdded" , this.#onIssueAdded, this);
        this.issuesManager.addEventListener("FullUpdateRequired" , this.#onFullUpdateRequired, this);
    }
    #onIssueAdded(event) {
        const { issue } = event.data;
        void this.#addIssue(issue);
    }
    async #addIssue(issue) {
        if (!this.#isTrustedTypeIssue(issue) && !this.#isLateImportIssue(issue) && !this.#isPropertyRuleIssue(issue)) {
            return;
        }
        const issuesModel = issue.model();
        if (!issuesModel) {
            return;
        }
        const srcLocation = toZeroBasedLocation(issue.details().sourceCodeLocation);
        const description = issue.getDescription();
        if (!description || !srcLocation) {
            return;
        }
        const messageText = await getIssueTitleFromMarkdownDescription(description);
        if (!messageText) {
            return;
        }
        const clickHandler = () => {
            void reveal(issue);
        };
        this.#sourceFrameMessageManager.addMessage(new IssueMessage(messageText, issue.getKind(), clickHandler), {
            line: srcLocation.lineNumber,
            column: srcLocation.columnNumber ?? -1,
            url: srcLocation.url,
            scriptId: srcLocation.scriptId,
        }, issuesModel.target());
    }
    #onFullUpdateRequired() {
        this.#resetMessages();
        const issues = this.issuesManager.issues();
        for (const issue of issues) {
            void this.#addIssue(issue);
        }
    }
    #isTrustedTypeIssue(issue) {
        return issue instanceof ContentSecurityPolicyIssue && issue.code() === trustedTypesSinkViolationCode ||
            issue.code() === trustedTypesPolicyViolationCode;
    }
    #isPropertyRuleIssue(issue) {
        return issue instanceof PropertyRuleIssue;
    }
    #isLateImportIssue(issue) {
        return issue.code() === lateImportStylesheetLoadingCode;
    }
    #resetMessages() {
        this.#sourceFrameMessageManager.clear();
    }
}
class IssueMessage extends Message {
    #kind;
    constructor(title, kind, clickHandler) {
        super("Issue" , title, clickHandler);
        this.#kind = kind;
    }
    getIssueKind() {
        return this.#kind;
    }
}

// Copyright 2025 The Chromium Authors
const UIStrings$1 = {
    httpMessageSignatures: 'HTTP Message Signatures (RFC9421)',
    signatureBasedIntegrity: 'Signature-based Integrity',
};
const str_$1 = registerUIStrings('models/issues_manager/SRIMessageSignatureIssue.ts', UIStrings$1);
const i18nLazyString$1 = getLazilyComputedLocalizedString.bind(undefined, str_$1);
function generateGroupingIssueCode(details) {
    const issueCode = `${"SRIMessageSignatureIssue" }::${details.error}`;
    if (details.error === "ValidationFailedSignatureMismatch" ) {
        return issueCode + details.signatureBase;
    }
    if (details.error === "ValidationFailedIntegrityMismatch" ) {
        return issueCode + details.integrityAssertions.join();
    }
    return issueCode;
}
class SRIMessageSignatureIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super({
            code: generateGroupingIssueCode(issueDetails),
            umaCode: `${"SRIMessageSignatureIssue" }::${issueDetails.error}`,
        }, issueDetails, issuesModel);
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getDescription() {
        const details = this.details();
        const description = {
            file: `sri${details.error}.md`,
            links: [
                {
                    link: 'https://www.rfc-editor.org/rfc/rfc9421.html',
                    linkTitle: i18nLazyString$1(UIStrings$1.httpMessageSignatures),
                },
                {
                    link: 'https://wicg.github.io/signature-based-sri/',
                    linkTitle: i18nLazyString$1(UIStrings$1.signatureBasedIntegrity),
                }
            ],
            substitutions: new Map()
        };
        if (details.error === "ValidationFailedSignatureMismatch" ) {
            description.substitutions?.set('PLACEHOLDER_signatureBase', () => details.signatureBase);
        }
        if (details.error === "ValidationFailedIntegrityMismatch" ) {
            description.substitutions?.set('PLACEHOLDER_integrityAssertions', () => {
                const prefix = '\n* ';
                return prefix + this.details().integrityAssertions.join(prefix);
            });
        }
        return resolveLazyDescription(description);
    }
    getCategory() {
        return "Other" ;
    }
    getKind() {
        return "PageError" ;
    }
    requests() {
        return this.details().request ? [this.details().request] : [];
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const details = inspectorIssue.details.sriMessageSignatureIssueDetails;
        if (!details) {
            console.warn('SRI Message Signature issue without details received.');
            return [];
        }
        return [new SRIMessageSignatureIssue(details, issuesModel)];
    }
}

// Copyright 2025 The Chromium Authors
const UIStrings = {
    unencodedDigestHeader: 'HTTP Unencoded Digest specification',
    integrityIntegration: 'Server-Initiated Integrity Checks',
};
const str_ = registerUIStrings('models/issues_manager/UnencodedDigestIssue.ts', UIStrings);
const i18nLazyString = getLazilyComputedLocalizedString.bind(undefined, str_);
class UnencodedDigestIssue extends Issue {
    constructor(issueDetails, issuesModel) {
        super({
            code: `${"UnencodedDigestIssue" }::${issueDetails.error}`,
            umaCode: `${"UnencodedDigestIssue" }::${issueDetails.error}`,
        }, issueDetails, issuesModel);
    }
    primaryKey() {
        return JSON.stringify(this.details());
    }
    getDescription() {
        const description = {
            file: `unencodedDigest${this.details().error}.md`,
            links: [
                {
                    link: 'https://www.ietf.org/archive/id/draft-ietf-httpbis-unencoded-digest-01.html',
                    linkTitle: i18nLazyString(UIStrings.unencodedDigestHeader),
                },
                {
                    link: 'https://wicg.github.io/signature-based-sri/#unencoded-digest-validation',
                    linkTitle: i18nLazyString(UIStrings.integrityIntegration),
                },
            ],
        };
        return resolveLazyDescription(description);
    }
    getCategory() {
        return "Other" ;
    }
    getKind() {
        return "PageError" ;
    }
    requests() {
        return this.details().request ? [this.details().request] : [];
    }
    static fromInspectorIssue(issuesModel, inspectorIssue) {
        const details = inspectorIssue.details.unencodedDigestIssueDetails;
        if (!details) {
            console.warn('Unencoded-Digest issue without details received.');
            return [];
        }
        return [new UnencodedDigestIssue(details, issuesModel)];
    }
}

// Copyright 2020 The Chromium Authors
let issuesManagerInstance = null;
function createIssuesForBlockedByResponseIssue(issuesModel, inspectorIssue) {
    const blockedByResponseIssueDetails = inspectorIssue.details.blockedByResponseIssueDetails;
    if (!blockedByResponseIssueDetails) {
        console.warn('BlockedByResponse issue without details received.');
        return [];
    }
    if (isCrossOriginEmbedderPolicyIssue(blockedByResponseIssueDetails.reason)) {
        return [new CrossOriginEmbedderPolicyIssue(blockedByResponseIssueDetails, issuesModel)];
    }
    return [];
}
const issueCodeHandlers = new Map([
    [
        "CookieIssue" ,
        CookieIssue.fromInspectorIssue,
    ],
    [
        "MixedContentIssue" ,
        MixedContentIssue.fromInspectorIssue,
    ],
    [
        "HeavyAdIssue" ,
        HeavyAdIssue.fromInspectorIssue,
    ],
    [
        "ContentSecurityPolicyIssue" ,
        ContentSecurityPolicyIssue.fromInspectorIssue,
    ],
    ["BlockedByResponseIssue" , createIssuesForBlockedByResponseIssue],
    [
        "SharedArrayBufferIssue" ,
        SharedArrayBufferIssue.fromInspectorIssue,
    ],
    [
        "SharedDictionaryIssue" ,
        SharedDictionaryIssue.fromInspectorIssue,
    ],
    [
        "LowTextContrastIssue" ,
        LowTextContrastIssue.fromInspectorIssue,
    ],
    [
        "CorsIssue" ,
        CorsIssue.fromInspectorIssue,
    ],
    [
        "QuirksModeIssue" ,
        QuirksModeIssue.fromInspectorIssue,
    ],
    [
        "AttributionReportingIssue" ,
        AttributionReportingIssue.fromInspectorIssue,
    ],
    [
        "GenericIssue" ,
        GenericIssue.fromInspectorIssue,
    ],
    [
        "DeprecationIssue" ,
        DeprecationIssue.fromInspectorIssue,
    ],
    [
        "ClientHintIssue" ,
        ClientHintIssue.fromInspectorIssue,
    ],
    [
        "FederatedAuthRequestIssue" ,
        FederatedAuthRequestIssue.fromInspectorIssue,
    ],
    [
        "BounceTrackingIssue" ,
        BounceTrackingIssue.fromInspectorIssue,
    ],
    [
        "StylesheetLoadingIssue" ,
        StylesheetLoadingIssue.fromInspectorIssue,
    ],
    [
        "PartitioningBlobURLIssue" ,
        PartitioningBlobURLIssue.fromInspectorIssue,
    ],
    [
        "PropertyRuleIssue" ,
        PropertyRuleIssue.fromInspectorIssue,
    ],
    [
        "CookieDeprecationMetadataIssue" ,
        CookieDeprecationMetadataIssue.fromInspectorIssue,
    ],
    [
        "ElementAccessibilityIssue" ,
        ElementAccessibilityIssue.fromInspectorIssue,
    ],
    [
        "SRIMessageSignatureIssue" ,
        SRIMessageSignatureIssue.fromInspectorIssue,
    ],
    [
        "UnencodedDigestIssue" ,
        UnencodedDigestIssue.fromInspectorIssue,
    ],
    [
        "ConnectionAllowlistIssue" ,
        ConnectionAllowlistIssue.fromInspectorIssue,
    ],
    [
        "PermissionElementIssue" ,
        PermissionElementIssue.fromInspectorIssue,
    ],
]);
function createIssuesFromProtocolIssue(issuesModel, inspectorIssue) {
    const handler = issueCodeHandlers.get(inspectorIssue.code);
    if (handler) {
        return handler(issuesModel, inspectorIssue);
    }
    console.warn(`No handler registered for issue code ${inspectorIssue.code}`);
    return [];
}
function defaultHideIssueByCodeSetting() {
    const setting = {};
    return setting;
}
class IssuesManager extends ObjectWrapper {
    showThirdPartyIssuesSetting;
    hideIssueSetting;
    #eventListeners = new WeakMap();
    #allIssues = new Map();
    #filteredIssues = new Map();
    #issueCounts = new Map();
    #hiddenIssueCount = new Map();
    #thirdPartyCookiePhaseoutIssueCount = new Map();
    #issuesById = new Map();
    #issuesByOutermostTarget = new Map();
    constructor(showThirdPartyIssuesSetting, hideIssueSetting) {
        super();
        this.showThirdPartyIssuesSetting = showThirdPartyIssuesSetting;
        this.hideIssueSetting = hideIssueSetting;
        new SourceFrameIssuesManager(this);
        TargetManager.instance().observeModels(IssuesModel, this);
        TargetManager.instance().addModelListener(ResourceTreeModel, Events$6.PrimaryPageChanged, this.#onPrimaryPageChanged, this);
        FrameManager.instance().addEventListener("FrameAddedToTarget" , this.#onFrameAddedToTarget, this);
        this.showThirdPartyIssuesSetting?.addChangeListener(() => this.#updateFilteredIssues());
        this.hideIssueSetting?.addChangeListener(() => this.#updateFilteredIssues());
        TargetManager.instance().observeTargets({
            targetAdded: (target) => {
                if (target.outermostTarget() === target) {
                    this.#updateFilteredIssues();
                }
            },
            targetRemoved: (_) => { },
        }, { scoped: true });
    }
    static instance(opts = {
        forceNew: false,
        ensureFirst: false,
    }) {
        if (issuesManagerInstance && opts.ensureFirst) {
            throw new Error('IssuesManager was already created. Either set "ensureFirst" to false or make sure that this invocation is really the first one.');
        }
        if (!issuesManagerInstance || opts.forceNew) {
            issuesManagerInstance = new IssuesManager(opts.showThirdPartyIssuesSetting, opts.hideIssueSetting);
        }
        return issuesManagerInstance;
    }
    static removeInstance() {
        issuesManagerInstance = null;
    }
    #onPrimaryPageChanged(event) {
        const { frame, type } = event.data;
        const keptIssues = new Map();
        for (const [key, issue] of this.#allIssues.entries()) {
            if (issue.isAssociatedWithRequestId(frame.loaderId)) {
                keptIssues.set(key, issue);
            }
            else if ((type === "Activation" ) &&
                (frame.resourceTreeModel().target() === issue.model()?.target())) {
                keptIssues.set(key, issue);
            }
            else if (issue.code() === "BounceTrackingIssue"  ||
                issue.code() === "CookieIssue" ) {
                const networkManager = frame.resourceTreeModel().target().model(NetworkManager);
                if (networkManager?.requestForLoaderId(frame.loaderId)?.hasUserGesture() === false) {
                    keptIssues.set(key, issue);
                }
            }
        }
        this.#allIssues = keptIssues;
        this.#updateFilteredIssues();
    }
    #onFrameAddedToTarget(event) {
        const { frame } = event.data;
        if (frame.isOutermostFrame() && TargetManager.instance().isInScope(frame.resourceTreeModel())) {
            this.#updateFilteredIssues();
        }
    }
    modelAdded(issuesModel) {
        const listener = issuesModel.addEventListener("IssueAdded" , this.#onIssueAddedEvent, this);
        this.#eventListeners.set(issuesModel, listener);
    }
    modelRemoved(issuesModel) {
        const listener = this.#eventListeners.get(issuesModel);
        if (listener) {
            removeEventListeners([listener]);
        }
    }
    #onIssueAddedEvent(event) {
        const { issuesModel, inspectorIssue } = event.data;
        const issues = createIssuesFromProtocolIssue(issuesModel, inspectorIssue);
        for (const issue of issues) {
            this.addIssue(issuesModel, issue);
            const message = issue.maybeCreateConsoleMessage();
            if (!message) {
                continue;
            }
            issuesModel.target().model(ConsoleModel)?.addMessage(message);
        }
    }
    addIssue(issuesModel, issue) {
        if (!issue.getDescription()) {
            return;
        }
        const primaryKey = issue.primaryKey();
        if (this.#allIssues.has(primaryKey)) {
            return;
        }
        this.#allIssues.set(primaryKey, issue);
        const outermostTarget = issuesModel.target().outermostTarget();
        if (outermostTarget) {
            let issuesForTarget = this.#issuesByOutermostTarget.get(outermostTarget);
            if (!issuesForTarget) {
                issuesForTarget = new Set();
                this.#issuesByOutermostTarget.set(outermostTarget, issuesForTarget);
            }
            issuesForTarget.add(issue);
        }
        if (this.#issueFilter(issue)) {
            this.#filteredIssues.set(primaryKey, issue);
            this.#issueCounts.set(issue.getKind(), 1 + (this.#issueCounts.get(issue.getKind()) || 0));
            const issueId = issue.getIssueId();
            if (issueId) {
                this.#issuesById.set(issueId, issue);
            }
            const values = this.hideIssueSetting?.get();
            this.#updateIssueHiddenStatus(issue, values);
            if (CookieIssue.isThirdPartyCookiePhaseoutRelatedIssue(issue)) {
                this.#thirdPartyCookiePhaseoutIssueCount.set(issue.getKind(), 1 + (this.#thirdPartyCookiePhaseoutIssueCount.get(issue.getKind()) || 0));
            }
            else if (issue.isHidden()) {
                this.#hiddenIssueCount.set(issue.getKind(), 1 + (this.#hiddenIssueCount.get(issue.getKind()) || 0));
            }
            this.dispatchEventToListeners("IssueAdded" , { issuesModel, issue });
        }
        this.dispatchEventToListeners("IssuesCountUpdated" );
    }
    issues() {
        return this.#filteredIssues.values();
    }
    numberOfIssues(kind) {
        if (kind) {
            return (this.#issueCounts.get(kind) ?? 0) - this.numberOfHiddenIssues(kind) -
                this.numberOfThirdPartyCookiePhaseoutIssues(kind);
        }
        return this.#filteredIssues.size - this.numberOfHiddenIssues() - this.numberOfThirdPartyCookiePhaseoutIssues();
    }
    numberOfHiddenIssues(kind) {
        if (kind) {
            return this.#hiddenIssueCount.get(kind) ?? 0;
        }
        let count = 0;
        for (const num of this.#hiddenIssueCount.values()) {
            count += num;
        }
        return count;
    }
    numberOfThirdPartyCookiePhaseoutIssues(kind) {
        if (kind) {
            return this.#thirdPartyCookiePhaseoutIssueCount.get(kind) ?? 0;
        }
        let count = 0;
        for (const num of this.#thirdPartyCookiePhaseoutIssueCount.values()) {
            count += num;
        }
        return count;
    }
    numberOfAllStoredIssues() {
        return this.#allIssues.size;
    }
    #issueFilter(issue) {
        const scopeTarget = TargetManager.instance().scopeTarget();
        if (!scopeTarget) {
            return false;
        }
        if (!this.#issuesByOutermostTarget.get(scopeTarget)?.has(issue)) {
            return false;
        }
        return this.showThirdPartyIssuesSetting?.get() || !issue.isCausedByThirdParty();
    }
    #updateIssueHiddenStatus(issue, values) {
        const code = issue.code();
        if (values?.[code]) {
            if (values[code] === "Hidden" ) {
                issue.setHidden(true);
                return;
            }
            issue.setHidden(false);
            return;
        }
    }
    #updateFilteredIssues() {
        this.#filteredIssues.clear();
        this.#issueCounts.clear();
        this.#issuesById.clear();
        this.#hiddenIssueCount.clear();
        this.#thirdPartyCookiePhaseoutIssueCount.clear();
        const values = this.hideIssueSetting?.get();
        for (const [key, issue] of this.#allIssues) {
            if (this.#issueFilter(issue)) {
                this.#updateIssueHiddenStatus(issue, values);
                this.#filteredIssues.set(key, issue);
                this.#issueCounts.set(issue.getKind(), 1 + (this.#issueCounts.get(issue.getKind()) ?? 0));
                if (issue.isHidden()) {
                    this.#hiddenIssueCount.set(issue.getKind(), 1 + (this.#hiddenIssueCount.get(issue.getKind()) || 0));
                }
                const issueId = issue.getIssueId();
                if (issueId) {
                    this.#issuesById.set(issueId, issue);
                }
            }
        }
        this.dispatchEventToListeners("FullUpdateRequired" );
        this.dispatchEventToListeners("IssuesCountUpdated" );
    }
    unhideAllIssues() {
        for (const issue of this.#allIssues.values()) {
            issue.setHidden(false);
        }
        this.hideIssueSetting?.set(defaultHideIssueByCodeSetting());
    }
    getIssueById(id) {
        return this.#issuesById.get(id);
    }
}
globalThis.addIssueForTest = (issue) => {
    const mainTarget = TargetManager.instance().primaryPageTarget();
    const issuesModel = mainTarget?.model(IssuesModel);
    issuesModel?.issueAdded({ issue });
};

// Copyright 2025 The Chromium Authors
installInspectorFrontendHost(new McpHostBindings());

var mcp = /*#__PURE__*/Object.freeze({
	__proto__: null,
	AgentFocus: AgentFocus,
	AggregatedIssue: AggregatedIssue,
	Common: common,
	ConnectionTransport: ConnectionTransport,
	CrUXManager: CrUXManager,
	DebuggerModel: DebuggerModel,
	DebuggerWorkspaceBinding: DebuggerWorkspaceBinding,
	Formatter: formatter,
	Foundation: foundation,
	I18n: i18n,
	IgnoreListManager: IgnoreListManager,
	Issue: Issue,
	IssueAggregator: IssueAggregator,
	IssuesManager: IssuesManager,
	MarkdownIssueDescription: MarkdownIssueDescription,
	Marked: marked,
	PerformanceInsightFormatter: PerformanceInsightFormatter,
	PerformanceTraceFormatter: PerformanceTraceFormatter,
	Protocol: protocol,
	ProtocolClient: protocol_client,
	RuntimeModel: RuntimeModel,
	StackTrace: stack_trace,
	Target: Target,
	TargetManager: TargetManager,
	TraceEngine: trace,
	createIssuesFromProtocolIssue: createIssuesFromProtocolIssue
});

/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
const snapshot = snapshot$1;
const navigation = navigation$1;
const generateReport = generateReport$1;

export { Browser as BrowserEnum, CDPSessionEvent, Client$1 as Client, mcp as DevTools, KnownDevices, Locator, McpServer, PipeTransport, PredefinedNetworkConditions, SetLevelRequestSchema, StdioClientTransport, StdioServerTransport, debug$2 as debug, detectBrowserPlatform, generateReport, hideBin, navigation, puppeteer, resolveDefaultUserDataDir, snapshot, Yargs as yargs, z as zod };
